using System.IO;
using Microsoft.AspNetCore.Hosting;
using NLog;

namespace HelloWorldApp
{
    public class Program
    {
        // Entry point for the application.
        public static void Main(string[] args)
        {
            SetupNLog();

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseWebRoot(FindWebRoot())
                .UseStartup<Startup>()
                .Build();

           host.Run();
        }

        private static void SetupNLog()
        {
            var location = System.Reflection.Assembly.GetEntryAssembly().Location;
            location = location.Substring(0, location.LastIndexOf(Path.DirectorySeparatorChar));
            location = location + Path.DirectorySeparatorChar + "nlog.config";
            LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(location, true);
        }

        private static string FindWebRoot()
        {
            var currentDir = Directory.GetCurrentDirectory();

            var webRoot = currentDir + Path.DirectorySeparatorChar +
                            ".." + Path.DirectorySeparatorChar +
                            "wwwroot";

            if (!Directory.Exists(webRoot))
                webRoot = currentDir + Path.DirectorySeparatorChar +
                            "ui" + Path.DirectorySeparatorChar +
                            "wwwroot";

            if (!Directory.Exists(webRoot))
                webRoot = currentDir + Path.DirectorySeparatorChar +
                            ".." + Path.DirectorySeparatorChar +
                            "ui" + Path.DirectorySeparatorChar +
                            "wwwroot";

            if (!Directory.Exists(webRoot))
                webRoot = currentDir + Path.DirectorySeparatorChar +
                            "wwwroot";

            return webRoot;
        }
    }
}

using System.IO;
using Microsoft.AspNetCore.Hosting;
using NLog;

namespace HelloWorldApp
{
    public class Program
    {
        // Entry point for the application.
        public static void Main(string[] args)
        {
            SetupNLog();

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseWebRoot(FindWebRoot())
                .UseStartup<Startup>()
                .Build();

           host.Run();
        }

        private static void SetupNLog()
        {
            var location = System.Reflection.Assembly.GetEntryAssembly().Location;
            location = location.Substring(0, location.LastIndexOf(Path.DirectorySeparatorChar));
            location = location + Path.DirectorySeparatorChar + "nlog.config";
            LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(location, true);
        }

        private static string FindWebRoot()
        {
            var currentDir = Directory.GetCurrentDirectory();

            var webRoot = currentDir + Path.DirectorySeparatorChar +
                            ".." + Path.DirectorySeparatorChar +
                            "wwwroot";

            if (!Directory.Exists(webRoot))
                webRoot = currentDir + Path.DirectorySeparatorChar +
                            "ui" + Path.DirectorySeparatorChar +
                            "wwwroot";

            if (!Directory.Exists(webRoot))
                webRoot = currentDir + Path.DirectorySeparatorChar +
                            ".." + Path.DirectorySeparatorChar +
                            ".." + Path.DirectorySeparatorChar +
                            "ui" + Path.DirectorySeparatorChar +
                            "wwwroot";

            if (!Directory.Exists(webRoot))
                webRoot = currentDir + Path.DirectorySeparatorChar +
                            "wwwroot";

            return webRoot;
        }
    }
}

Adjust locations where to look for wwwroot.


using AutoMapper;
using Baskerville.App.App_Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Baskerville.App
{
    public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            Mapper.Initialize(c => c.AddProfile<MappingProfile>());
            GlobalConfiguration.Configure(WebApiConfig.Register);
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

using AutoMapper;
using Baskerville.App.App_Start;
using Baskerville.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Baskerville.App
{
    public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            Mapper.Initialize(p =>
            {
                p.AddProfile<MappingProfile>();
                p.AddProfile<ServiceMappingProfile>();
            });

            GlobalConfiguration.Configure(WebApiConfig.Register);
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

Update mapping config with service profile.


using System;
using System.Collections.Generic;

public class CircularBuffer<T>
{
    private readonly Queue<T> _buffer;
    private readonly int _capacity;
    public CircularBuffer(int capacity)
    {
        _buffer = new Queue<T>(capacity);
        _capacity = capacity;
    }

    public T Read()
    {
        return _buffer.Dequeue();
    }

    public void Write(T value)
    {
        _buffer.Enqueue(value);
        if (_buffer.Count > _capacity)
        {
            throw new InvalidOperationException();
        }
    }

    public void Overwrite(T value)
    {
        _buffer.Enqueue(value);
        if (_buffer.Count > _capacity)
        {
            _buffer.Dequeue();
        }
    }

    public void Clear()
    {
        _buffer.Clear();
    }
}

using System;
using System.Collections.Generic;

public class CircularBuffer<T>
{
    private readonly Queue<T> _buffer;
    private readonly int _capacity;
    public CircularBuffer(int capacity)
    {
        _buffer = new Queue<T>(capacity);
        _capacity = capacity;
    }

    public T Read() => _buffer.Dequeue();

    public void Write(T value)
    {
        if (_buffer.Count + 1 > _capacity)
        {
            throw new InvalidOperationException();
        }
        _buffer.Enqueue(value);
    }

    public void Overwrite(T value)
    {
        if (_buffer.Count + 1 > _capacity)
        {
            _buffer.Dequeue();
        }
        _buffer.Enqueue(value);
    }

    public void Clear() => _buffer.Clear();
}

Use Expression-bodied members and never execeeds its capacity


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using MongoDB.Bson.Serialization;
using MongoFramework.Attributes;

namespace MongoFramework.Infrastructure.Mapping.Processors
{
	public class IndexProcessor : IMappingProcessor
	{
		public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
		{
			definition.Indexes = definition.TraverseProperties().SelectMany(p =>
				p.PropertyInfo.GetCustomAttributes<IndexAttribute>().Select(a => new EntityIndex
				{
					Property = p,
					IndexName = a.Name,
					IsUnique = a.IsUnique,
					SortOrder = a.SortOrder,
					IndexPriority = a.IndexPriority,
					IndexType = a.IndexType
				})
			);
		}
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using MongoDB.Bson.Serialization;
using MongoFramework.Attributes;

namespace MongoFramework.Infrastructure.Mapping.Processors
{
	public class IndexProcessor : IMappingProcessor
	{
		public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
		{
			definition.Indexes = definition.TraverseProperties().SelectMany(p =>
				p.PropertyInfo.GetCustomAttributes<IndexAttribute>().Select(a => new EntityIndex
				{
					Property = p,
					IndexName = a.Name,
					IsUnique = a.IsUnique,
					SortOrder = a.SortOrder,
					IndexPriority = a.IndexPriority,
					IndexType = a.IndexType
				})
			).ToArray();
		}
	}
}

Index processor to store result, not enumerable, on definition


using System;
using Platform.Validation;
using Shaolinq;

namespace IdentityServer3.Shaolinq.DataModel
{
	[DataAccessObject(Name = "Scope")]
	public abstract class DbScope : DataAccessObject<Guid>
	{
		[PersistedMember]
		public abstract bool Enabled { get; set; }

		[PersistedMember]
		[ValueRequired]
		[SizeConstraint(MaximumLength = 200)]
		public abstract string Name { get; set; }

		[PersistedMember]
		[SizeConstraint(MaximumLength = 200)]
		public abstract string DisplayName { get; set; }

		[PersistedMember]
		[SizeConstraint(MaximumLength = 200)]
		public abstract string Description { get; set; }

		[PersistedMember]
		public abstract bool Required { get; set; }
		[PersistedMember]
		public abstract bool Emphasize { get; set; }
		[PersistedMember]
		public abstract int Type { get; set; }
		[RelatedDataAccessObjects]
		public abstract RelatedDataAccessObjects<DbScopeClaim> ScopeClaims { get; }
		[PersistedMember]
		public abstract bool IncludeAllClaimsForUser { get; set; }

		[PersistedMember]
		[SizeConstraint(MaximumLength = 200)]
		public abstract string ClaimsRule { get; set; }

		[PersistedMember]
		public abstract bool ShowInDiscoveryDocument { get; set; }
	}
}

using System;
using IdentityServer3.Core.Models;
using Platform.Validation;
using Shaolinq;

namespace IdentityServer3.Shaolinq.DataModel
{
	[DataAccessObject(Name = "Scope")]
	public abstract class DbScope : DataAccessObject<Guid>
	{
		[PersistedMember]
		public abstract bool Enabled { get; set; }

		[PersistedMember]
		[ValueRequired]
		[SizeConstraint(MaximumLength = 200)]
		public abstract string Name { get; set; }

		[PersistedMember]
		[SizeConstraint(MaximumLength = 200)]
		public abstract string DisplayName { get; set; }

		[PersistedMember]
		[SizeConstraint(MaximumLength = 200)]
		public abstract string Description { get; set; }

		[PersistedMember]
		public abstract bool Required { get; set; }
		[PersistedMember]
		public abstract bool Emphasize { get; set; }
		[PersistedMember]
		public abstract ScopeType Type { get; set; }
		[RelatedDataAccessObjects]
		public abstract RelatedDataAccessObjects<DbScopeClaim> ScopeClaims { get; }
		[PersistedMember]
		public abstract bool IncludeAllClaimsForUser { get; set; }

		[PersistedMember]
		[SizeConstraint(MaximumLength = 200)]
		public abstract string ClaimsRule { get; set; }

		[PersistedMember]
		public abstract bool ShowInDiscoveryDocument { get; set; }
	}
}

Use enum for scope type

Use enum for scope type


//
// Copyright (c) Microsoft.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

using System.Reflection;
using System.Resources;

[assembly: AssemblyTitle("Microsoft Azure Resource Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure resource management operations including Resource Groups.")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

//
// Copyright (c) Microsoft.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

using System.Reflection;
using System.Resources;

[assembly: AssemblyTitle("Microsoft Azure Resource Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure resource management operations including Resource Groups.")]

[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

Update ARM assembly and file version to 2.0.0


using System;
using System.Collections.Generic;
using System.Linq;

using PEPlugin;

namespace WeightedOffsetBlend
{
    public class Plugin : PEPluginClass
    {
        private static MainForm FormInstance { get; set; }

        public override string Name
        {
            get { return "重み付きオフセット付加"; }
        }

        public override IPEPluginOption Option
        {
            get
            {
                return new PEPluginOption(bootup: true);
            }
        }

        public override void Run(IPERunArgs args)
        {
            if (args.IsBootup)
            {
                FormInstance = new MainForm(args.Host);
                FormInstance.Visible = false;
                FormInstance.Show();
                return;
            }

            FormInstance.Visible = true;
            FormInstance.BringToFront();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;

using PEPlugin;

namespace WeightedOffsetBlend
{
    public class Plugin : PEPluginClass
    {
        private static MainForm FormInstance { get; set; }

        public override string Name
        {
            get { return "重み付きオフセット付加"; }
        }

        public override IPEPluginOption Option
        {
            get
            {
                return new PEPluginOption(bootup: true);
            }
        }

        public override void Run(IPERunArgs args)
        {
            if (args.IsBootup)
            {
                FormInstance = new MainForm(args.Host);
                FormInstance.Show();
                FormInstance.Visible = false;
                return;
            }

            FormInstance.Visible = true;
            FormInstance.BringToFront();
        }
    }
}

Fix showing window at boot

Fix showing window at boot


// Copyright © 2006 Paul Welter

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MSBuild.Community.Tasks")]
[assembly: AssemblyDescription("MSBuild community tasks library")]
[assembly: AssemblyCulture("")]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d038566a-1937-478a-b5c5-b79c4afb253d")]

[assembly: InternalsVisibleTo("MSBuild.Community.Tasks.Tests")]

// Copyright © 2006 Paul Welter

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MSBuild.Community.Tasks")]
[assembly: AssemblyDescription("MSBuild community tasks library")]
[assembly: AssemblyCulture("")]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d038566a-1937-478a-b5c5-b79c4afb253d")]

[assembly: InternalsVisibleTo("MSBuild.Community.Tasks.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cf82d03d9d827823ae8e4dc989a53a37a54029875ee9e45b08131024540a68d4a2130d82ffc1a35446c2cef805fefa179df6e99a5ec91d7cbf311605103a2b2f0002824b4bf68e36a5dd00a3d81af54408f7f53a66e2d6ab3866288cb2ef460e920f159176062a7d5a126fb5695e04738e1edfcb5b6e34557b1308aba9fda1dc")]

Update the argument of the InternalsVisibleTo attribute.


// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

namespace StyleCop.Analyzers.Test.CSharp7.MaintainabilityRules
{
    using StyleCop.Analyzers.Test.MaintainabilityRules;

    public class SA1400CSharp7UnitTests : SA1400UnitTests
    {
    }
}

// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

namespace StyleCop.Analyzers.Test.CSharp7.MaintainabilityRules
{
    using System.Threading;
    using System.Threading.Tasks;
    using StyleCop.Analyzers.Test.MaintainabilityRules;
    using Xunit;

    public class SA1400CSharp7UnitTests : SA1400UnitTests
    {
        /// <summary>
        /// Verifies that local functions, which do not support access modifiers, do not trigger SA1400.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
        [Fact]
        public async Task TestLocalFunctionAsync()
        {
            var testCode = @"
internal class ClassName
{
    public void MethodName()
    {
        void LocalFunction()
        {
        }
    }
}
";

            await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
        }
    }
}

Add SA1400 test for local functions

Add SA1400 test for local functions


// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Cloud.ClientTesting;
using System;
using Xunit;

// TODO: Use location instead of zone when building the request.
// The Container API config is being revisited to make all of this simpler.

namespace Google.Cloud.Container.V1.Snippets
{
    [SnippetOutputCollector]
    [Collection(nameof(ContainerSnippetFixture))]
    public class ClusterManagerClientSnippets
    {
        private readonly ContainerSnippetFixture _fixture;

        public ClusterManagerClientSnippets(ContainerSnippetFixture fixture) =>
            _fixture = fixture;

        [Fact]
        public void ListAllClusters()
        {
            string projectId = _fixture.ProjectId;
            // Sample: ListAllClusters
            ClusterManagerClient client = ClusterManagerClient.Create();
            // You can list clusters in a single zone, or specify "-" for all zones.
            ListClustersResponse zones = client.ListClusters(projectId, zone: "-");
            foreach (Cluster cluster in zones.Clusters)
            {
                Console.WriteLine($"Cluster {cluster.Name} in {cluster.Location}");
            }
            // End sample
        }
    }
}

// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Gax.ResourceNames;
using Google.Cloud.ClientTesting;
using System;
using Xunit;

namespace Google.Cloud.Container.V1.Snippets
{
    [SnippetOutputCollector]
    [Collection(nameof(ContainerSnippetFixture))]
    public class ClusterManagerClientSnippets
    {
        private readonly ContainerSnippetFixture _fixture;

        public ClusterManagerClientSnippets(ContainerSnippetFixture fixture) =>
            _fixture = fixture;

        [Fact]
        public void ListAllClusters()
        {
            string projectId = _fixture.ProjectId;
            // Sample: ListAllClusters
            ClusterManagerClient client = ClusterManagerClient.Create();
            // You can list clusters in a single zone, or specify "-" for all zones.
            LocationName location = new LocationName(projectId, locationId: "-");
            ListClustersResponse zones = client.ListClusters(location.ToString());
            foreach (Cluster cluster in zones.Clusters)
            {
                Console.WriteLine($"Cluster {cluster.Name} in {cluster.Location}");
            }
            // End sample
        }
    }
}

fix: Use a location name in ClusterManagerClient snippet

(This avoids calling a now-deprecated method.)


using System;

namespace Clarius.TransformOnBuild.MSBuild.Task
{
    public class TransformOnBuildTask : Microsoft.Build.Utilities.Task
    {
        public override bool Execute()
        {
            throw new NotImplementedException();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Build.Execution;

namespace Clarius.TransformOnBuild.MSBuild.Task
{
    public class TransformOnBuildTask : Microsoft.Build.Utilities.Task
    {
        private ProjectInstance _projectInstance;
        private Dictionary<string, string> _properties;
        const BindingFlags BindingFlags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public;

        public override bool Execute()
        {
            _projectInstance = GetProjectInstance();
            _properties = _projectInstance.Properties.ToDictionary(p => p.Name, p => p.EvaluatedValue);

            return true;
        }

        /// <summary>
        /// Inspired by http://stackoverflow.com/questions/3043531/when-implementing-a-microsoft-build-utilities-task-how-to-i-get-access-to-the-va
        /// </summary>
        /// <returns></returns>
        private ProjectInstance GetProjectInstance()
        {
            var buildEngineType = BuildEngine.GetType();
            var targetBuilderCallbackField = buildEngineType.GetField("targetBuilderCallback", BindingFlags);
            if (targetBuilderCallbackField == null)
                throw new Exception("Could not extract targetBuilderCallback from " + buildEngineType.FullName);
            var targetBuilderCallback = targetBuilderCallbackField.GetValue(BuildEngine);
            var targetCallbackType = targetBuilderCallback.GetType();
            var projectInstanceField = targetCallbackType.GetField("projectInstance", BindingFlags);
            if (projectInstanceField == null)
                throw new Exception("Could not extract projectInstance from " + targetCallbackType.FullName);
            return (ProjectInstance) projectInstanceField.GetValue(targetBuilderCallback);
        }
    }
}

Move GetProjectInstance to the task

Move GetProjectInstance to the task


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DotVVM.Samples.BasicSamples.ViewModels.ControlSamples.CheckBox
{
    public class CheckedItemsRepeaterViewModel
    {
        public Outer Data { get; set; }

        public class Outer
        {
            public IList<Inner> AllData { get; set; }

            public IList<int> SelectedDataTestsIds { get; set; }
        }

        public class Inner
        {
            public int Id { get; set; }

            public string Name { get; set; }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DotVVM.Samples.BasicSamples.ViewModels.ControlSamples.CheckBox
{
    public class CheckedItemsRepeaterViewModel
    {
        public Outer Data { get; set; } = new Outer();

        public class Outer
        {
            public IList<Inner> AllData { get; set; }

            public IList<int> SelectedDataTestsIds { get; set; }
        }

        public class Inner
        {
            public int Id { get; set; }

            public string Name { get; set; }
        }
    }
}

Make the sample actually test the issue

Make the sample actually test the issue

...this time for reals


using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Controllers
{
    [Authorize, ApiExplorerSettings(IgnoreApi = true)]
    public class AdminController : Controller
    {
        // Admin Tasks:

        // Add/Remove Users

        // Backup SQLite Db

        // Scrub Soldier Data

        private readonly Database db;

        public AdminController(Database db)
        {
            this.db = db;
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> Scrub()
        {
            // Go through each soldier and fix casing on their name

            foreach(var soldier in db.Soldiers)
            {
                soldier.FirstName = soldier.FirstName.ToTitleCase();
                soldier.MiddleName = soldier.MiddleName.ToTitleCase();
                soldier.LastName = soldier.LastName.ToTitleCase();
            }

            await db.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }

        public IActionResult Backup()
        {
            var data = System.IO.File.ReadAllBytes("Data.db");

            var mimeType = "application/octet-stream";

            return File(data, mimeType);
        }
    }
}

using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Controllers
{
    [Authorize, ApiExplorerSettings(IgnoreApi = true)]
    public class AdminController : Controller
    {
        // Admin Tasks:

        // Add/Remove Users

        // Backup SQLite Db

        // Scrub Soldier Data

        private readonly Database db;

        public AdminController(Database db)
        {
            this.db = db;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Backup()
        {
            var data = System.IO.File.ReadAllBytes("Data.db");

            var mimeType = "application/octet-stream";

            return File(data, mimeType);
        }

        public IActionResult Logs()
        {
            var data = System.IO.File.ReadAllBytes($@"logs\{DateTime.Today:yyyyMMdd}.log");

            var mimeType = "text/plain";

            return File(data, mimeType);
        }
    }
}

Add endpoint for getting log files

Add endpoint for getting log files


using System;
using System.Windows.Forms;

namespace HospitalAutomation.GUI
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormHomePage());
        }
    }
}

using System;
using System.Windows.Forms;

namespace HospitalAutomation.GUI
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new LoginForm());
        }
    }
}

Set login screen as main

Set login screen as main


using System;
using UIKit;

namespace FFImageLoading.Extensions
{
	public static class UnitsExtensions
	{
		private static nfloat _screenScale;

		static UnitsExtensions()
		{
			UIScreen.MainScreen.InvokeOnMainThread(() =>
				{
					_screenScale = _screenScale;
				});
		}

		public static int PointsToPixels(this double points)
		{
			return (int)Math.Floor(points * _screenScale);
		}

		public static int PixelsToPoints(this double px)
		{
			if (px == 0d)
				return 0;

			return (int)Math.Floor(px / UIScreen.MainScreen.Scale);
		}

		public static int PointsToPixels(this int points)
		{
			return PointsToPixels((double)points);
		}

		public static int PixelsToPoints(this int px)
		{
			return PixelsToPoints((double)px);
		}
	}
}

using System;
using UIKit;

namespace FFImageLoading.Extensions
{
	public static class UnitsExtensions
	{
		private static nfloat _screenScale;

		static UnitsExtensions()
		{
			UIScreen.MainScreen.InvokeOnMainThread(() =>
				{
					_screenScale = UIScreen.MainScreen.Scale;
				});
		}

		public static int PointsToPixels(this double points)
		{
			return (int)Math.Floor(points * _screenScale);
		}

		public static int PixelsToPoints(this double px)
		{
			if (px == 0d)
				return 0;

			return (int)Math.Floor(px / UIScreen.MainScreen.Scale);
		}

		public static int PointsToPixels(this int points)
		{
			return PointsToPixels((double)points);
		}

		public static int PixelsToPoints(this int px)
		{
			return PixelsToPoints((double)px);
		}
	}
}

Fix bug introduced with commit about screen scale


using System.Collections;

/// <summary>Contains commands for holdables (including the freeplay case and the missions binder).</summary>
public static class HoldableCommands
{
	#region Commands
	[Command("help")]
	public static bool Help(TwitchHoldable holdable, string user, bool isWhisper) => holdable.PrintHelp(user, isWhisper);

	[Command("(hold|pick up)")]
	public static IEnumerator Hold(TwitchHoldable holdable) => holdable.Hold();

	[Command("(drop|let go|put down)")]
	public static IEnumerator Drop(TwitchHoldable holdable) => holdable.Drop();

	[Command(@"(turn|turn round|turn around|rotate|flip|spin)")]
	public static IEnumerator Flip(TwitchHoldable holdable) => holdable.Turn();

	[Command(null)]
	public static IEnumerator DefaultCommand(TwitchHoldable holdable, string user, bool isWhisper, string cmd) => holdable.RespondToCommand(user, cmd, isWhisper);
	#endregion
}

using System.Collections;

/// <summary>Contains commands for holdables (including the freeplay case and the missions binder).</summary>
public static class HoldableCommands
{
	#region Commands
	[Command("help")]
	public static bool Help(TwitchHoldable holdable, string user, bool isWhisper) => holdable.PrintHelp(user, isWhisper);

	[Command("(hold|pick up)")]
	public static IEnumerator Hold(TwitchHoldable holdable) => holdable.Hold();

	[Command("(drop|let go|put down)")]
	public static IEnumerator Drop(TwitchHoldable holdable) => holdable.Drop();

	[Command(@"(turn|turn round|turn around|rotate|flip|spin)")]
	public static IEnumerator Flip(TwitchHoldable holdable) => holdable.Turn();

	[Command(null)]
	public static IEnumerator DefaultCommand(TwitchHoldable holdable, string user, bool isWhisper, string cmd)
	{
		if (holdable.CommandType == typeof(AlarmClockCommands))
			return AlarmClockCommands.Snooze(holdable, user, isWhisper);

		if (holdable.CommandType == typeof(IRCConnectionManagerCommands) ||
		    holdable.CommandType == typeof(MissionBinderCommands) ||
		    holdable.CommandType == typeof(FreeplayCommands))
			return holdable.RespondToCommand(user, isWhisper);

		return holdable.RespondToCommand(user, cmd, isWhisper);
	}
	#endregion
}

Add default handlers for built in holdables

* Freeplay / Binder / Alarm clock / IRC Manager no longer responds with
"Sorry @{user}, this holdable is not supported by Twitch Plays."
whenever an invalid command is entered.


using UnityEditor;
using UnityEngine;

public class PlayerPrefsEditor {

    [MenuItem("Tools/PlayerPrefs/DeleteAll")]
    static void DeleteAll(){
        PlayerPrefs.DeleteAll();
        Debug.Log("Delete All Data Of PlayerPrefs!!");
    }
}

using UnityEditor;
using UnityEngine;

public class PlayerPrefsEditor : EditorWindow {

    string stringKey = "";
    string intKey = "";
    string floatKey = "";

    [MenuItem("Tools/PlayerPrefs/DeleteAll")]
    static void DeleteAll(){
        PlayerPrefs.DeleteAll();
        Debug.Log("Delete All Data Of PlayerPrefs!!");
    }

    [MenuItem("Tools/PlayerPrefs/OpenEditor")]
    static void OpenEditor(){
        EditorWindow.GetWindow<PlayerPrefsEditor>("PlayrePrefsEditor");
    }

    void OnGUI(){
        GUILayout.Label( "Input PlayerPrefs Key Here" );
        GUILayout.Label( "String Value" );
        stringKey = GUILayout.TextField( stringKey );
        if(PlayerPrefs.HasKey(stringKey)){
            string data = PlayerPrefs.GetString(stringKey);
            GUILayout.Label(data);
        }

        GUILayout.Label("Int Value");
        intKey = GUILayout.TextField(intKey);
        if(PlayerPrefs.HasKey(intKey)){
            string data = PlayerPrefs.GetInt(intKey).ToString();
            GUILayout.Label(data);
        }

        GUILayout.Label("Float Value");
        floatKey = GUILayout.TextField(floatKey);
        if(PlayerPrefs.HasKey(floatKey)){
            string data = PlayerPrefs.GetFloat(floatKey).ToString();
            GUILayout.Label(data);
        }
    }
}

Add PlayerPrefs Value Search Func

Add PlayerPrefs Value Search Func


using System;

using System.Collections.Generic;
using System.IO;
using System.Linq;

using Microsoft.VisualStudio.TestTools.UnitTesting;
using NugetAuditor;

namespace NugetAuditor.Tests
{
    [TestClass]
    public class NugetAuditorLibTests
    {
        [TestMethod]
        public void CanAuditFiles()
        {
            var f3 = Path.Combine("TestFiles", "packages.config.example.3");
            Assert.IsTrue(File.Exists(f3));
            var results = Lib.NugetAuditor.AuditPackages(f3, 0);
            Assert.AreNotEqual(0, results.Count(r => r.MatchedVulnerabilities > 0));
        }
    }
}

using System;

using System.Collections.Generic;
using System.IO;
using System.Linq;

using Microsoft.VisualStudio.TestTools.UnitTesting;
using NugetAuditor;

namespace NugetAuditor.Tests
{
    [TestClass]
    public class NugetAuditorLibTests
    {
        [TestMethod]
        public void CanAuditFiles()
        {
            var f3 = Path.Combine("TestFiles", "packages.config.example.3");
            Assert.IsTrue(File.Exists(f3));
            var results = Lib.NugetAuditor.AuditPackages(f3, 0, new NuGet.Common.NullLogger());
            Assert.AreNotEqual(0, results.Count(r => r.MatchedVulnerabilities > 0));
        }
    }
}

Use correct Lib call in tests.

Use correct Lib call in tests.


using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBi.Core.Scalar.Presentation
{
    public class DateTimePresenter : BasePresenter
    {
        protected override string PresentNotNull(object value)
        {
            switch (value)
            {
                case DateTime x: return PresentDateTime(x);
                case string x: return PresentString(x);
                default:
                    return PresentString(value.ToString());
            }
        }

        protected string PresentDateTime(DateTime value)
        {
            if (value.TimeOfDay.Ticks == 0)
                return value.ToString("yyyy-MM-dd");
            else if (value.Millisecond == 0)
                return value.ToString("yyyy-MM-dd hh:mm:ss");
            else
                return value.ToString("yyyy-MM-dd hh:mm:ss.fff");
        }

        protected string PresentString(string value)
        {
            DateTime valueDateTime = DateTime.MinValue;
            if (DateTime.TryParse(value, out valueDateTime))
                return PresentDateTime(valueDateTime);
            else
                return value;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBi.Core.Scalar.Presentation
{
    public class DateTimePresenter : BasePresenter
    {
        protected override string PresentNotNull(object value)
        {
            switch (value)
            {
                case DateTime x: return PresentDateTime(x);
                case string x: return PresentString(x);
                default:
                    return PresentString(value.ToString());
            }
        }

        protected string PresentDateTime(DateTime value)
        {
            if (value.TimeOfDay.Ticks == 0)
                return value.ToString("yyyy-MM-dd");
            else if (value.Millisecond == 0)
                return value.ToString("yyyy-MM-dd HH:mm:ss");
            else
                return value.ToString("yyyy-MM-dd HH:mm:ss.fff");
        }

        protected string PresentString(string value)
        {
            DateTime valueDateTime = DateTime.MinValue;
            if (DateTime.TryParse(value, out valueDateTime))
                return PresentDateTime(valueDateTime);
            else
                return value;
        }
    }
}

Fix display issue for dateTime cells

Fix display issue for dateTime cells


using CertiPay.Common.Logging;
using System;
using System.Threading.Tasks;
using Twilio;

namespace CertiPay.Common.Notifications
{
    /// <summary>
    /// Send an SMS message to the given recipient.
    /// </summary>
    /// <remarks>
    /// Implementation may be sent into background processing.
    /// </remarks>
    public interface ISMSService : INotificationSender<SMSNotification>
    {
        // Task SendAsync(T notification);
    }

    public class SmsService : ISMSService
    {
        private static readonly ILog Log = LogManager.GetLogger<ISMSService>();

        private readonly String _twilioAccountSId;

        private readonly String _twilioAuthToken;

        private readonly String _twilioSourceNumber;

        public SmsService(TwilioConfig config)
        {
            this._twilioAccountSId = config.AccountSid;
            this._twilioAuthToken = config.AuthToken;
            this._twilioSourceNumber = config.SourceNumber;
        }

        public Task SendAsync(SMSNotification notification)
        {
            using (Log.Timer("SMSNotification.SendAsync"))
            {
                Log.Info("Sending SMSNotification {@Notification}", notification);

                // TODO Add error handling

                var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken);

                foreach (var recipient in notification.Recipients)
                {
                    client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content);
                }

                return Task.FromResult(0);
            }
        }

        public class TwilioConfig
        {
            public String AccountSid { get; set; }

            public String AuthToken { get; set; }

            public String SourceNumber { get; set; }
        }
    }
}

using CertiPay.Common.Logging;
using System;
using System.Threading.Tasks;
using Twilio;

namespace CertiPay.Common.Notifications
{
    /// <summary>
    /// Send an SMS message to the given recipient.
    /// </summary>
    /// <remarks>
    /// Implementation may be sent into background processing.
    /// </remarks>
    public interface ISMSService : INotificationSender<SMSNotification>
    {
        // Task SendAsync(T notification);
    }

    public class SmsService : ISMSService
    {
        private static readonly ILog Log = LogManager.GetLogger<ISMSService>();

        private readonly String _twilioAccountSId;

        private readonly String _twilioAuthToken;

        private readonly String _twilioSourceNumber;

        public SmsService(TwilioConfig config)
        {
            this._twilioAccountSId = config.AccountSid;
            this._twilioAuthToken = config.AuthToken;
            this._twilioSourceNumber = config.SourceNumber;
        }

        public Task SendAsync(SMSNotification notification)
        {
            using (Log.Timer("SMSNotification.SendAsync", context: notification))
            {
                // TODO Add error handling

                var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken);

                foreach (var recipient in notification.Recipients)
                {
                    client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content);
                }

                return Task.FromResult(0);
            }
        }

        public class TwilioConfig
        {
            public String AccountSid { get; set; }

            public String AuthToken { get; set; }

            public String SourceNumber { get; set; }
        }
    }
}

Include context in SMSService sending

Include context in SMSService sending


// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.

using System;

namespace Wangkanai.Detection.Models
{
    [Flags]
    public enum Device
    {
        Desktop = 0,      // Windows, Mac, Linux
        Tablet  = 1 << 0, // iPad, Android
        Mobile  = 1 << 1, // iPhone, Android
        Tv      = 1 << 2, // Samsung, LG
        Console = 1 << 3, // XBox, Play Station
        Car     = 1 << 4, // Ford, Toyota
        IoT     = 1 << 5  // Raspberry Pi
    }
}

// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.

using System;

namespace Wangkanai.Detection.Models
{
    [Flags]
    public enum Device
    {
        Desktop = 0,      // Windows, Mac, Linux
        Tablet  = 1 << 0, // iPad, Android
        Mobile  = 1 << 1, // iPhone, Android
        Watch   = 1 << 2, // Smart Watchs
        Tv      = 1 << 3, // Samsung, LG
        Console = 1 << 4, // XBox, Play Station
        Car     = 1 << 5, // Ford, Toyota
        IoT     = 1 << 6  // Raspberry Pi
    }
}

Add Smart Watch to device

Add Smart Watch to device


using EnvDTE;
using System;
using System.Linq;

namespace T4TS
{
    public class ProjectTraverser
    {
        public Action<CodeNamespace> WithNamespace { get; private set; }

        public ProjectTraverser(Project project, Action<CodeNamespace> withNamespace)
        {
            if (project == null)
                throw new ArgumentNullException("project");

            if (withNamespace == null)
                throw new ArgumentNullException("withNamespace");

            WithNamespace = withNamespace;

            if (project.ProjectItems != null)
                Traverse(project.ProjectItems);
        }

        private void Traverse(ProjectItems items)
        {
            foreach (ProjectItem pi in items)
            {
                if (pi.FileCodeModel != null)
                {
                    var codeElements = pi.FileCodeModel.CodeElements;
                    foreach (var ns in codeElements.OfType<CodeNamespace>())
                        WithNamespace(ns);
                }

                if (pi.ProjectItems != null)
                    Traverse(pi.ProjectItems);
            }
        }
    }
}

using EnvDTE;
using System;
using System.Linq;

namespace T4TS
{
    public class ProjectTraverser
    {
        public Action<CodeNamespace> WithNamespace { get; private set; }

        public ProjectTraverser(Project project, Action<CodeNamespace> withNamespace)
        {
            if (project == null)
                throw new ArgumentNullException("project");

            if (withNamespace == null)
                throw new ArgumentNullException("withNamespace");

            WithNamespace = withNamespace;

            if (project.ProjectItems != null)
                Traverse(project.ProjectItems);
        }

        private void Traverse(ProjectItems items)
        {
            foreach (ProjectItem pi in items)
            {
                if (pi.FileCodeModel != null)
                {
                    var codeElements = pi.FileCodeModel.CodeElements;
                    foreach (var ns in codeElements.OfType<CodeNamespace>())
                        WithNamespace(ns);
                }

                if (pi.ProjectItems != null)
                    Traverse(pi.ProjectItems);

                /* LionSoft: Process projects in solution folders */
                else if (pi.SubProject != null && pi.SubProject.ProjectItems != null)
                {
                    Traverse(pi.SubProject.ProjectItems);
                }
                /* --- */

            }
        }
    }
}

Add processing projects in solution folders


using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Security.Permissions;

[assembly: AssemblyProduct("Python for .NET")]
[assembly: AssemblyVersion("2.4.2.7")]
[assembly: AssemblyTitle("Python Console")]
[assembly: AssemblyDefaultAlias("python.exe")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: PermissionSet(SecurityAction.RequestMinimum, Name = "FullTrust")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCopyright("MIT License")]
[assembly: AssemblyFileVersion("2.0.0.4")]
[assembly: NeutralResourcesLanguage("en")]

using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Security.Permissions;

[assembly: AssemblyProduct("Python for .NET")]
[assembly: AssemblyVersion("2.4.2.7")]
[assembly: AssemblyTitle("Python Console")]
[assembly: AssemblyDefaultAlias("python.exe")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCopyright("MIT License")]
[assembly: AssemblyFileVersion("2.0.0.4")]
[assembly: NeutralResourcesLanguage("en")]

Remove obsoleted & Unenforced PermissionSet

See: http://stackoverflow.com/questions/11625447/securityaction-requestminimum-is-obsolete-in-net-4-0


using System;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Machine.Fakes.Sdk;
using NSubstitute;

namespace Machine.Fakes.Adapters.NSubstitute
{
    internal class NSubstituteMethodCallOccurance<TFake> : IMethodCallOccurance where TFake : class
    {
        private readonly TFake _fake;
        private readonly Expression<Action<TFake>> _func;

        public NSubstituteMethodCallOccurance(TFake fake, Expression<Action<TFake>> func)
        {
            Guard.AgainstArgumentNull(fake, "fake");
            Guard.AgainstArgumentNull(func, "func");

            _fake = fake;
            _func = func;

            _func.Compile().Invoke(_fake.Received());
        }

        #region IMethodCallOccurance Members

        public void Times(int numberOfTimesTheMethodShouldHaveBeenCalled)
        {
            if (CountCalls() < numberOfTimesTheMethodShouldHaveBeenCalled)
                throw new Exception();
        }

        public void OnlyOnce()
        {
            if (CountCalls() != 1)
                throw new Exception();
        }

        private int CountCalls()
        {
            var method = ((MethodCallExpression) _func.Body).Method;
            return _fake
                .ReceivedCalls()
                .Select(x => x.GetMethodInfo())
                .Where(x => x == method)
                .Count();
        }

        public void Twice()
        {
            Times(2);
        }

        #endregion
    }
}

using System;
using System.Linq;
using System.Linq.Expressions;
using Machine.Fakes.Sdk;
using NSubstitute;
using NSubstitute.Exceptions;

namespace Machine.Fakes.Adapters.NSubstitute
{
    internal class NSubstituteMethodCallOccurance<TFake> : IMethodCallOccurance where TFake : class
    {
        private readonly TFake _fake;
        private readonly Expression<Action<TFake>> _func;

        public NSubstituteMethodCallOccurance(TFake fake, Expression<Action<TFake>> func)
        {
            Guard.AgainstArgumentNull(fake, "fake");
            Guard.AgainstArgumentNull(func, "func");

            _fake = fake;
            _func = func;

            _func.Compile().Invoke(_fake.Received());
        }

        #region IMethodCallOccurance Members

        public void Times(int numberOfTimesTheMethodShouldHaveBeenCalled)
        {
            var calls = CountCalls();
            if (calls < numberOfTimesTheMethodShouldHaveBeenCalled)
                throw new CallNotReceivedException(
                    string.Format("Expected {0} calls to the method but received {1}",
                                  numberOfTimesTheMethodShouldHaveBeenCalled, calls));
        }

        public void OnlyOnce()
        {
            var calls = CountCalls();
            if (calls != 1)
                throw new CallReceivedException(
                    string.Format("Expected only 1 call to the method but received {0}", calls));
        }

        public void Twice()
        {
            Times(2);
        }

        #endregion

        private int CountCalls()
        {
            var method = ((MethodCallExpression) _func.Body).Method;
            return _fake
                .ReceivedCalls()
                .Select(x => x.GetMethodInfo())
                .Where(x => x == method)
                .Count();
        }
    }
}

Change default exception to CallNotReceivedException and CallReceivedException in NSubtitute adapter.


using System.Text;
using DesktopWidgets.Classes;
using DesktopWidgets.Properties;

namespace DesktopWidgets.Helpers
{
    public static class AboutHelper
    {
        public static string AboutText
        {
            get
            {
                var stringBuilder = new StringBuilder();

                stringBuilder.AppendLine($"{AssemblyInfo.Title} ({AssemblyInfo.Version})");
                stringBuilder.AppendLine();
                stringBuilder.AppendLine($"Project: {Resources.GitHubMainPage}");
                stringBuilder.AppendLine($"Changes: {Resources.GitHubCommits}");
                stringBuilder.AppendLine($"Issues: {Resources.GitHubIssues}");
                stringBuilder.AppendLine();
                stringBuilder.AppendLine($"Icon made by {IconCredits}");
                stringBuilder.AppendLine();
                stringBuilder.Append(AssemblyInfo.Copyright);

                return stringBuilder.ToString();
            }
        }

        private static string IconCredits { get; } =
            "Freepik (http://www.freepik.com) from www.flaticon.com" +
            " is licensed under CC BY 3.0 (http://creativecommons.org/licenses/by/3.0/)";
    }
}

using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesktopWidgets.Classes;
using DesktopWidgets.Properties;

namespace DesktopWidgets.Helpers
{
    public static class AboutHelper
    {
        public static string AboutText
        {
            get
            {
                var stringBuilder = new StringBuilder();

                stringBuilder.AppendLine($"{AssemblyInfo.Title} ({AssemblyInfo.Version})");
                stringBuilder.AppendLine();
                stringBuilder.AppendLine($"Project: {Resources.GitHubMainPage}");
                stringBuilder.AppendLine($"Changes: {Resources.GitHubCommits}");
                stringBuilder.AppendLine($"Issues: {Resources.GitHubIssues}");
                stringBuilder.AppendLine();
                stringBuilder.AppendLine($"Icon made by {IconCredits}");
                stringBuilder.AppendLine();
                stringBuilder.AppendLine("Libraries:");
                foreach (var library in Libraries
                    .Select(x => $"  {x.Key}: {x.Value}"))
                {
                    stringBuilder.AppendLine(library);
                }
                stringBuilder.AppendLine();
                stringBuilder.Append(AssemblyInfo.Copyright);

                return stringBuilder.ToString();
            }
        }

        private static string IconCredits { get; } =
            "Freepik (http://www.freepik.com) from www.flaticon.com" +
            " is licensed under CC BY 3.0 (http://creativecommons.org/licenses/by/3.0/)";

        private static Dictionary<string, string> Libraries => new Dictionary<string, string>
        {
            {"Common Service Locator", "commonservicelocator.codeplex.com"},
            {"Extended WPF Toolkit", "wpftoolkit.codeplex.com"},
            {"NotifyIcon", "hardcodet.net/projects/wpf-notifyicon"},
            {"MVVM Light", "galasoft.ch/mvvm"},
            {"Json.NET", "newtonsoft.com/json"},
            {"NHotkey", "github.com/thomaslevesque/NHotkey"},
            {"WpfAppBar", "github.com/PhilipRieck/WpfAppBar"}
        };
    }
}

Add library credits to "About" text

Add library credits to "About" text


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ClipPlane : MonoBehaviour
{
    // input objects
    public Slider slider;
    public Material clipPlaneMaterial;

    // private objects
    private Renderer cube;
    private float clipX;

    void Start()
    {
        cube = GetComponent<Renderer>();
    }

    public void ClipPlaneOnValueChanged(float value)
    {
        clipX = value - 0.5f;
        cube.sharedMaterial = clipPlaneMaterial;
        cube.sharedMaterial.SetFloat("_ClipX", clipX);
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ClipPlane : MonoBehaviour
{
    // input objects
    public Slider slider;
    public Material clipPlaneMaterial;

    // private objects
    private Renderer cube;
    private float clipX;

    void Start()
    {
        cube = GetComponent<Renderer>();
    }

    public void ClipPlaneOnValueChanged(float value)
    {
        clipX = value - 0.5f;
        if (cube != null)
        {
            cube.sharedMaterial = clipPlaneMaterial;
            cube.sharedMaterial.SetFloat("_ClipX", clipX);
        }
    }
}

Fix nullreference when try to call disabled component


using System;
using System.Collections.Generic;
using System.IO;

namespace CreateXMLFile
{
  internal static class Program
  {
    private static void Main()
    {
      const string fileName = "quotes.txt";
      Dictionary<string, string> dicoQuotes = new Dictionary<string, string>();
      List<string> quotesList = new List<string>();
      StreamReader sr = new StreamReader(fileName);
      string line = string.Empty;
      while ((line = sr.ReadLine()) != null)
      {
        //Console.WriteLine(line);
        quotesList.Add(line);
      }

      for (int i = 0; i < quotesList.Count; i = i + 2)
      {
        if (!dicoQuotes.ContainsKey(quotesList[i]))
        {
          dicoQuotes.Add(quotesList[i], quotesList[i + 1]);
        }
        else
        {
          Console.WriteLine(quotesList[i]);
        }
      }

      Console.WriteLine("Press a key to exit:");
      Console.ReadKey();
    }
  }
}

using System;
using System.Collections.Generic;
using System.IO;

namespace CreateXMLFile
{
  internal static class Program
  {
    private static void Main()
    {
      const string fileName = "quotes-cleaned.txt";
      const string XmlFileName = "quotes-XML.txt";
      Dictionary<string, string> dicoQuotes = new Dictionary<string, string>();
      dicoQuotes = LoadDictionary(fileName);
      // create XML file
      if (!File.Exists(XmlFileName))
      {
        StreamWriter sw2 = new StreamWriter(XmlFileName, false);
        sw2.WriteLine(string.Empty);
        sw2.Close();
      }

      StreamWriter sw = new StreamWriter(XmlFileName, false);
      foreach (KeyValuePair<string, string> keyValuePair in dicoQuotes)
      {
        sw.WriteLine(string.Empty);
      }

      sw.Close();

      Console.WriteLine("Press a key to exit:");
      Console.ReadKey();
    }

    private static string AddTag(string msg)
    {
      string result = string.Empty;
      /*
       *<Quote>
          <Author></Author>
          <Language>French</Language>
          <QuoteValue></QuoteValue>
        </Quote>
       */

      return result;
    }

    private static Dictionary<string, string> LoadDictionary(string fileName)
    {
      Dictionary<string, string> result = new Dictionary<string, string>();
      if (!File.Exists(fileName)) return result;
      List<string> quotesList = new List<string>();
      StreamReader sr = new StreamReader(fileName);
      string line = string.Empty;
      while ((line = sr.ReadLine()) != null)
      {
        quotesList.Add(line);
      }

      for (int i = 0; i < quotesList.Count; i = i + 2)
      {
        if (!result.ContainsKey(quotesList[i]))
        {
          result.Add(quotesList[i], quotesList[i + 1]);
        }
        //else
        //{
        //  Console.WriteLine(quotesList[i]);
        //}
      }

      return result;
    }
  }
}

Add code to create XML file

Add code to create XML file


using ESISharp.Web;

namespace ESISharp.ESIPath.Character
{
    /// Authenticated Character Wallet paths
    public class CharacterWallet
    {
        protected ESIEve EasyObject;

        internal CharacterWallet(ESIEve EasyEve)
        {
            EasyObject = EasyEve;
        }

        /// Get Character's wallets and balances
        /// <remarks>Requires SSO Authentication, using "read_character_wallet" scope</remarks>
        /// <param name="CharacterID">(Int32) Character ID</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetWallets(int CharacterID)
        {
            var Path = $"/characters/{CharacterID.ToString()}/wallets/";
            return new EsiRequest(EasyObject, Path, EsiWebMethod.AuthGet);
        }
    }
}

using ESISharp.Web;

namespace ESISharp.ESIPath.Character
{
    /// Authenticated Character Wallet paths
    public class CharacterWallet
    {
        protected ESIEve EasyObject;

        internal CharacterWallet(ESIEve EasyEve)
        {
            EasyObject = EasyEve;
        }

        /// Get Character's wallets and balances
        /// <remarks>Requires SSO Authentication, using "read_character_wallet" scope</remarks>
        /// <param name="CharacterID">(Int32) Character ID</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetWallets(int CharacterID)
        {
            var Path = $"/characters/{CharacterID.ToString()}/wallets/";
            return new EsiRequest(EasyObject, Path, EsiWebMethod.AuthGet);
        }

        /// Get Character's wallet journal
        /// <remarks>Requires SSO Authentication, using "read_character_wallet" scope</remarks>
        /// <param name="CharacterID">(Int32) Character ID</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetWalletJounal(int CharacterID)
        {
            var Path = $"/characters/{CharacterID.ToString()}/wallet/journal/";
            return new EsiRequest(EasyObject, Path, EsiWebMethod.AuthGet);
        }

        /// Get Character's wallet transactions
        /// <remarks>Requires SSO Authentication, using "read_character_wallet" scope</remarks>
        /// <param name="CharacterID">(Int32) Character ID</param>
        /// <returns>EsiRequest</returns>
        public EsiRequest GetWalletTransactions(int CharacterID)
        {
            var Path = $"/characters/{CharacterID.ToString()}/wallet/transactions/";
            return new EsiRequest(EasyObject, Path, EsiWebMethod.AuthGet);
        }
    }
}

Add wallet journal and transaction endpoints.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StackExchange.DataExplorer.Helpers;
using System.Text;

namespace StackExchange.DataExplorer.Models {
    public partial class Query {

        public string BodyWithoutComments {
            get {
                ParsedQuery pq = new ParsedQuery(this.QueryBody, null);
                return pq.ExecutionSql;
            }
        }

        public void UpdateQueryBodyComment() {
            StringBuilder buffer = new StringBuilder();

            if (Name != null) {
                buffer.Append(ToComment(Name));
                buffer.Append("\n");
            }

            if (Description != null) {
                buffer.Append(ToComment(Description));
                buffer.Append("\n");
            }

            buffer.Append("\n");
            buffer.Append(BodyWithoutComments);

            QueryBody = buffer.ToString();
        }

        private string ToComment(string text) {

            string rval = text.Replace("\r\n", "\n");
            rval = "-- " + rval;
            rval = rval.Replace("\n", "\n-- ");
            if (rval.Contains("\n--")) {
                rval = rval.Substring(0, rval.Length - 3);
            }
            return rval;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StackExchange.DataExplorer.Helpers;
using System.Text;

namespace StackExchange.DataExplorer.Models {
    public partial class Query {

        public string BodyWithoutComments {
            get {
                ParsedQuery pq = new ParsedQuery(this.QueryBody, null);
                return pq.ExecutionSql;
            }
        }

        public void UpdateQueryBodyComment() {
            StringBuilder buffer = new StringBuilder();

            if (Name != null) {
                buffer.Append(ToComment(Name));
                buffer.Append("\n");
            }

            if (Description != null) {
                buffer.Append(ToComment(Description));
                buffer.Append("\n");
            }

            buffer.Append("\n");
            buffer.Append(BodyWithoutComments);

            QueryBody = buffer.ToString();
        }

        private string ToComment(string text) {

            if (string.IsNullOrEmpty(text)) return "";
            if (text != null) text = text.Trim();

            string rval = text.Replace("\r\n", "\n");
            rval = "-- " + rval;
            rval = rval.Replace("\n", "\n-- ");

            return rval;
        }
    }
}

Clean up ToComment so it handles a few edge cases a bit better


namespace RangeIt.Tests.Ranges
{
    using FluentAssertions;
    using RangeIt.Ranges;
    using Xunit;

    [Collection("Range.Ints.Tests")]
    public class Range_Ints_Tests
    {
        [Fact]
        public void Test_Range_Ints()
        {
            var range = Range.Ints(10);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        }

        [Fact]
        public void Test_Range_Ints_WithZeroCount()
        {
            var range = Range.Ints(0);
            range.Should().NotBeNull().And.BeEmpty();
        }

        [Fact]
        public void Test_Range_Ints_WithStartValue()
        {
            var range = Range.Ints(5, 10);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
        }
    }
}

namespace RangeIt.Tests.Ranges
{
    using FluentAssertions;
    using RangeIt.Ranges;
    using Xunit;

    [Collection("Range.Ints.Tests")]
    public class Range_Ints_Tests
    {
        [Fact]
        public void Test_Range_Ints()
        {
            var range = Range.Ints(10);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        }

        [Fact]
        public void Test_Range_Ints_WithZeroCount()
        {
            var range = Range.Ints(0);
            range.Should().NotBeNull().And.BeEmpty();
        }

        [Fact]
        public void Test_Range_Ints_WithStartValue()
        {
            var range = Range.Ints(5, 10);

            range.Should().NotBeNull()
                          .And.NotBeEmpty()
                          .And.HaveCount(10)
                          .And.ContainInOrder(5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
        }

        [Fact]
        public void Test_Range_Ints_WithStartValue_WithZeroCount()
        {
            var range = Range.Ints(5, 0);
            range.Should().NotBeNull().And.BeEmpty();
        }
    }
}

Add new test case for Range.Ints()

Add new test case for Range.Ints()


using System;
using System.Collections.Generic;
using Nancy;
using Nancy.Hosting.Self;

namespace ChildProcessUtil
{
    public class Program
    {
        private const string HttpAddress = "http://localhost:";
        private static NancyHost host;
        private static void Main(string[] args)
        {
            StartServer(30197);
            new MainProcessWatcher(int.Parse(args[0]));
            Console.Read();
        }

        public static void StartServer(int port)
        {
            var hostConfigs = new HostConfiguration
            {
                UrlReservations = new UrlReservations {CreateAutomatically = true}
            };

            var uriString = HttpAddress + port;
            ProcessModule.ActiveProcesses = new List<int>();
            host = new NancyHost(new Uri(uriString), new DefaultNancyBootstrapper(), hostConfigs);
            host.Start();
        }

        public static void StopServer(int port)
        {
            host.Stop();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading;
using Nancy;
using Nancy.Hosting.Self;

namespace ChildProcessUtil
{
    public class Program
    {
        private const string HttpAddress = "http://localhost:";
        private static NancyHost host;
        private static void Main(string[] args)
        {
            StartServer(30197, int.Parse(args[0]));
        }

        public static void StartServer(int port, int mainProcessId)
        {
            var hostConfigs = new HostConfiguration
            {
                UrlReservations = new UrlReservations {CreateAutomatically = true}
            };

            var uriString = HttpAddress + port;
            ProcessModule.ActiveProcesses = new List<int>();
            host = new NancyHost(new Uri(uriString), new DefaultNancyBootstrapper(), hostConfigs);
            host.Start();
            new MainProcessWatcher(mainProcessId);
            Thread.Sleep(Timeout.Infinite);
        }

        internal static void StopServer(int port)
        {
            host.Stop();
        }
    }
}

Change StartServer signature to take mainprocess's id as parameter


using System.Linq;

namespace PinSharp.Api
{
    internal class PathBuilder
    {
        public static string BuildPath(string basePath, RequestOptions options)
        {
            var path = basePath;

            if (!path.EndsWith("/"))
                path += "/";

            if (options?.SearchQuery != null)
                path = path.AddQueryParam("query", options.SearchQuery);

            if (options?.Fields?.Any() == true)
            {
                var fields = string.Join(",", options.Fields);
                path = path.AddQueryParam("fields", fields);
            }
            if (options?.Limit > 0)
                path = path.AddQueryParam("limit", options.Limit);

            if (options?.Cursor != null)
                path = path.AddQueryParam("cursor", options.Cursor);

            return path;
        }
    }

    internal static class QueryStringExtensions
    {
        public static string AddQueryParam(this string original, string name, object value)
        {
            original += original.Contains("?") ? "&" : "?";
            original += $"{name}={value}";
            return original;
        }
    }
}

using System.Linq;

namespace PinSharp.Api
{
    internal class PathBuilder
    {
        public static string BuildPath(string basePath, RequestOptions options)
        {
            var path = basePath;

            if (!path.EndsWith("/"))
                path += "/";

            if (options?.SearchQuery != null)
                path = path.AddQueryParam("query", options.SearchQuery);

            if (options?.Fields?.Any() == true)
            {
                var fields = string.Join(",", options.Fields);
                path = path.AddQueryParam("fields", fields);
            }

            if (options?.Cursor != null)
                path = path.AddQueryParam("cursor", options.Cursor);

            if (options?.Limit > 0)
                path = path.AddQueryParam("limit", options.Limit);

            return path;
        }
    }

    internal static class QueryStringExtensions
    {
        public static string AddQueryParam(this string original, string name, object value)
        {
            original += original.Contains("?") ? "&" : "?";
            original += $"{name}={value}";
            return original;
        }
    }
}

Rearrange query string parameters limit and cursor


namespace ControlzEx.Internal
{
    using System.Reflection;
    using System.Windows.Automation.Peers;
    using System.Windows.Controls;

    internal static class SelectorAutomationPeerExtensions
    {
        private static readonly MethodInfo RaiseSelectionEventsMethodInfo = typeof(SelectorAutomationPeer).GetMethod("RaiseSelectionEventsMethodInfo", BindingFlags.NonPublic | BindingFlags.Instance);

        internal static void RaiseSelectionEvents(this SelectorAutomationPeer selectorAutomationPeer, SelectionChangedEventArgs e)
        {
            RaiseSelectionEventsMethodInfo.Invoke(selectorAutomationPeer, new[]
                                                                          {
                                                                              e
                                                                          });
        }
    }
}

namespace ControlzEx.Internal
{
    using System.Reflection;
    using System.Windows.Automation.Peers;
    using System.Windows.Controls;

    internal static class SelectorAutomationPeerExtensions
    {
        private static readonly MethodInfo RaiseSelectionEventsMethodInfo = typeof(SelectorAutomationPeer).GetMethod("RaiseSelectionEvents", BindingFlags.NonPublic | BindingFlags.Instance);

        internal static void RaiseSelectionEvents(this SelectorAutomationPeer selectorAutomationPeer, SelectionChangedEventArgs e)
        {
            RaiseSelectionEventsMethodInfo.Invoke(selectorAutomationPeer, new object[] {e});
        }
    }
}

TabControlEx: Fix wrong method info for RaiseSelectionEvents

Fix getting the wrong method info for RaiseSelectionEvents.


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace osu.Framework.Allocation
{
    /// <summary>
    /// A queue which batches object disposal on threadpool threads.
    /// </summary>
    internal static class AsyncDisposalQueue
    {
        private static readonly Queue<IDisposable> disposal_queue = new Queue<IDisposable>();

        private static Task runTask;

        public static void Enqueue(IDisposable disposable)
        {
            lock (disposal_queue)
                disposal_queue.Enqueue(disposable);

            if (runTask?.Status < TaskStatus.Running)
                return;

            runTask = Task.Run(() =>
            {
                lock (disposal_queue)
                {
                    while (disposal_queue.Count > 0)
                        disposal_queue.Dequeue().Dispose();
                }
            });
        }
    }
}

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using osu.Framework.Statistics;

namespace osu.Framework.Allocation
{
    /// <summary>
    /// A queue which batches object disposal on threadpool threads.
    /// </summary>
    internal static class AsyncDisposalQueue
    {
        private static readonly GlobalStatistic<string> last_disposal = GlobalStatistics.Get<string>("Drawable", "Last disposal");

        private static readonly Queue<IDisposable> disposal_queue = new Queue<IDisposable>();

        private static Task runTask;

        public static void Enqueue(IDisposable disposable)
        {
            lock (disposal_queue)
                disposal_queue.Enqueue(disposable);

            if (runTask?.Status < TaskStatus.Running)
                return;

            runTask = Task.Run(() =>
            {
                lock (disposal_queue)
                {
                    while (disposal_queue.Count > 0)
                    {
                        var toDispose = disposal_queue.Dequeue();
                        toDispose.Dispose();

                        last_disposal.Value = toDispose.ToString();
                    }
                }
            });
        }
    }
}

Add last disposed drawable to global statistics


// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System.ComponentModel;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;

namespace osu.Game.Graphics.UserInterface
{
    /// <summary>
    /// Adds hover sounds to a drawable.
    /// Does not draw anything.
    /// </summary>
    public class HoverSounds : CompositeDrawable
    {
        private SampleChannel sampleHover;

        protected readonly HoverSampleSet SampleSet;

        public HoverSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal)
        {
            SampleSet = sampleSet;
            RelativeSizeAxes = Axes.Both;
            AlwaysPresent = true;
        }

        protected override bool OnHover(InputState state)
        {
            sampleHover?.Play();
            return base.OnHover(state);
        }

        [BackgroundDependencyLoader]
        private void load(AudioManager audio)
        {
            sampleHover = audio.Sample.Get($@"UI/generic-hover{SampleSet.GetDescription()}");
        }
    }

    public enum HoverSampleSet
    {
        [Description("")]
        Loud,
        [Description("-soft")]
        Normal,
        [Description("-softer")]
        Soft
    }
}

// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System.ComponentModel;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;

namespace osu.Game.Graphics.UserInterface
{
    /// <summary>
    /// Adds hover sounds to a drawable.
    /// Does not draw anything.
    /// </summary>
    public class HoverSounds : CompositeDrawable
    {
        private SampleChannel sampleHover;

        protected readonly HoverSampleSet SampleSet;

        public HoverSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal)
        {
            SampleSet = sampleSet;
            RelativeSizeAxes = Axes.Both;
        }

        protected override bool OnHover(InputState state)
        {
            sampleHover?.Play();
            return base.OnHover(state);
        }

        [BackgroundDependencyLoader]
        private void load(AudioManager audio)
        {
            sampleHover = audio.Sample.Get($@"UI/generic-hover{SampleSet.GetDescription()}");
        }
    }

    public enum HoverSampleSet
    {
        [Description("")]
        Loud,
        [Description("-soft")]
        Normal,
        [Description("-softer")]
        Soft
    }
}

Remove AlwaysPresent (not actually required)


using Hearts.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using Hearts.Scoring;

namespace Hearts.Extensions
{
    public static class CardListExtensions
    {
        public static void Log(this IEnumerable<Card> self, string name)
        {
            int padToLength = 38;
            Logging.Log.ToBlue();
            Console.Write(" " + name.PadLeft(Logging.Log.Options.NamePad) + " ");

            foreach (var suit in new List<Suit> { Suit.Hearts, Suit.Spades, Suit.Diamonds, Suit.Clubs })
            {
                var cardsOfSuit = self.Where(i => i.Suit == suit);

                foreach (var card in cardsOfSuit.OrderBy(i => i.Kind))
                {
                    Logging.Log.Card(card);
                    Console.Write(" ");
                }

                Console.Write(new string(' ', padToLength - cardsOfSuit.Count() * 3));
            }

            Logging.Log.NewLine();
        }

        public static int Score(this IEnumerable<Card> self)
        {
            return new ScoreEvaluator().CalculateScore(self);
        }

        public static string ToDebugString(this IEnumerable<Card> self)
        {
            return string.Join(",", self);
        }
    }
}

using Hearts.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using Hearts.Scoring;

namespace Hearts.Extensions
{
    public static class CardListExtensions
    {
        public static void Log(this IEnumerable<Card> self, string name)
        {
            int padToLength = 38;
            Logging.Log.ToBlue();
            Console.Write(" " + name.PadLeft(Logging.Log.Options.NamePad) + " ");

            foreach (var suit in new List<Suit> { Suit.Hearts, Suit.Spades, Suit.Diamonds, Suit.Clubs })
            {
                var cardsOfSuit = self.OfSuit(suit);

                foreach (var card in cardsOfSuit.Ascending())
                {
                    Logging.Log.Card(card);
                    Console.Write(" ");
                }

                Console.Write(new string(' ', padToLength - cardsOfSuit.Count() * 3));
            }

            Logging.Log.NewLine();
        }

        public static int Score(this IEnumerable<Card> self)
        {
            return new ScoreEvaluator().CalculateScore(self);
        }

        public static string ToDebugString(this IEnumerable<Card> self)
        {
            return string.Join(",", self);
        }
    }
}

Refactor to use card extensions

Refactor to use card extensions


using NUnit.Framework;
using Pash.ParserIntrinsics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ParserTests
{
    [TestFixture]
    public class ParserTests
    {
        [Test]
        public void IfTest()
        {
            var parseTree = PowerShellGrammar.Parser.Parse(@"if ($true) {}");

            if (parseTree.HasErrors())
            {
                Assert.Fail(parseTree.ParserMessages[0].ToString());
            }
        }

        [Test]
        public void IfElseTest()
        {
            var parseTree = PowerShellGrammar.Parser.Parse(@"if ($true) {} else {}");

            if (parseTree.HasErrors())
            {
                Assert.Fail(parseTree.ParserMessages[0].ToString());
            }
        }

        [Test]
        public void IfElseIfTest()
        {
            var parseTree = PowerShellGrammar.Parser.Parse(@"if ($true) {} elseif ($true) {} ");

            if (parseTree.HasErrors())
            {
                Assert.Fail(parseTree.ParserMessages[0].ToString());
            }
        }

        [Test, Explicit("bug")]
        public void IfElseIfElseTest()
        {
            var parseTree = PowerShellGrammar.Parser.Parse(@"if ($true) {} elseif {$true) {} else {}");

            if (parseTree.HasErrors())
            {
                Assert.Fail(parseTree.ParserMessages[0].ToString());
            }
        }

        [Test, Explicit("bug")]
        public void IfElseifElseTest()
        {
            var parseTree = PowerShellGrammar.Parser.Parse(@"if ($true) {} elseif ($true) {} elseif ($true) else {}");

            if (parseTree.HasErrors())
            {
                Assert.Fail(parseTree.ParserMessages[0].ToString());
            }
        }
    }
}

using NUnit.Framework;
using Pash.ParserIntrinsics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ParserTests
{
    [TestFixture]
    public class ParserTests
    {
        [Test]
        [TestCase(@"if ($true) {} else {}")]
        [TestCase(@"if ($true) {} elseif ($true) {} ")]
        [TestCase(@"if ($true) {} elseif {$true) {} else {}", Explicit = true)]
        [TestCase(@"if ($true) {} elseif ($true) {} elseif ($true) else {}", Explicit = true)]
        public void IfElseSyntax(string input)
        {
            var parseTree = PowerShellGrammar.Parser.Parse(input);

            if (parseTree.HasErrors())
            {
                Assert.Fail(parseTree.ParserMessages[0].ToString());
            }
        }
    }
}

TEST: Use `TestCase` attribute in parser tests.


@page "{id}"
@model SessionModel

Agenda

Day @(Model.DayOffset + 1)

@Model.Session.Title

@Model.Session.Title

@Model.Session.Track?.Name

@foreach (var speaker in Model.Session.Speakers)
{
    @speaker.Name
}

@Html.Raw(Model.Session.Abstract)

<form method="post">
    <input type="hidden" name="sessionId" value="@Model.Session.ID" />

        Edit
        @if (Model.IsInPersonalAgenda)
        {
            <button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-primary">Remove from My Agenda</button>
        }
        else
        {
            <button authz="true" type="submit" class="btn btn-primary">Add to My Agenda</button>
        }

</form>

@page "{id}"
@model SessionModel

Agenda

Day @(Model.DayOffset + 1)

@Model.Session.Title

@Model.Session.Title

@Model.Session.Track?.Name

@foreach (var speaker in Model.Session.Speakers)
{
    @speaker.Name
}

@Html.Raw(Model.Session.Abstract)

<form method="post">
    <input type="hidden" name="sessionId" value="@Model.Session.ID" />

        Edit
        @if (Model.IsInPersonalAgenda)
        {
            <button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-default btn-sm"></button>
        }
        else
        {
            <button authz="true" type="submit" class="btn btn-default btn-sm"></button>
        }

</form>

Fix icons on session details page

Fix icons on session details page


using System.Linq;
using System.Reflection;
using NSpec;
using NSpec.Domain;
using NSpec.Domain.Formatters;
using Microsoft.VisualStudio.TestTools.UnitTesting;

/*
 * Howdy,
 *
 * This is NSpec's DebuggerShim.  It will allow you to use TestDriven.Net or Resharper's test runner to run
 * NSpec tests that are in the same Assembly as this class.
 *
 * It's DEFINITELY worth trying specwatchr (http://nspec.org/continuoustesting). Specwatchr automatically
 * runs tests for you.
 *
 * If you ever want to debug a test when using Specwatchr, simply put the following line in your test:
 *
 *     System.Diagnostics.Debugger.Launch()
 *
 * Visual Studio will detect this and will give you a window which you can use to attach a debugger.
 */

[TestClass]
public class DebuggerShim
{
    [TestMethod]
    public void debug()
    {
        var tagOrClassName = "class_or_tag_you_want_to_debug";

        var types = GetType().Assembly.GetTypes();
        // OR
        // var types = new Type[]{typeof(Some_Type_Containg_some_Specs)};
        var finder = new SpecFinder(types, "");
        var builder = new ContextBuilder(finder, new Tags().Parse(tagOrClassName), new DefaultConventions());
        var runner = new ContextRunner(builder, new ConsoleFormatter(), false);
        var results = runner.Run(builder.Contexts().Build());

        //assert that there aren't any failures
        Assert.AreEqual(0, results.Failures().Count());
    }
}

using System.Linq;
using System.Reflection;
using NSpec;
using NSpec.Domain;
using NSpec.Domain.Formatters;
using Microsoft.VisualStudio.TestTools.UnitTesting;

/*
 * Howdy,
 *
 * This is NSpec's DebuggerShim.  It will allow you to use TestDriven.Net or Resharper's test runner to run
 * NSpec tests that are in the same Assembly as this class.
 *
 * It's DEFINITELY worth trying specwatchr (http://nspec.org/continuoustesting). Specwatchr automatically
 * runs tests for you.
 *
 * If you ever want to debug a test when using Specwatchr, simply put the following line in your test:
 *
 *     System.Diagnostics.Debugger.Launch()
 *
 * Visual Studio will detect this and will give you a window which you can use to attach a debugger.
 */

[TestClass]
public class DebuggerShim
{
    [TestMethod]
    public void NSpec_Tests()
    {
        var tagOrClassName = "class_or_tag_you_want_to_debug";

        var types = GetType().Assembly.GetTypes();
        // OR
        // var types = new Type[]{typeof(Some_Type_Containg_some_Specs)};
        var finder = new SpecFinder(types, "");
        var builder = new ContextBuilder(finder, new Tags().Parse(tagOrClassName), new DefaultConventions());
        var runner = new ContextRunner(builder, new ConsoleFormatter(), false);
        var results = runner.Run(builder.Contexts().Build());

        //assert that there aren't any failures
        Assert.AreEqual(0, results.Failures().Count());
    }
}

Rename test shim method name

Rename test shim method name

Give it a more friendly name than "debug" so test output at least makes
sense


using System;
using System.Reflection;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using Swashbuckle.AspNetCore.SwaggerUi;

namespace Microsoft.AspNetCore.Builder
{
    public static class SwaggerUiBuilderExtensions
    {
        public static IApplicationBuilder UseSwaggerUi(
            this IApplicationBuilder app,
            Action<SwaggerUiOptions> setupAction = null)
        {
            var options = new SwaggerUiOptions();
            setupAction?.Invoke(options);

            // Enable redirect from basePath to indexPath
            app.UseMiddleware<RedirectMiddleware>(options.BaseRoute, options.IndexPath);

            // Serve indexPath via middleware
            app.UseMiddleware<SwaggerUiMiddleware>(options);

            // Serve everything else via static file server
            var fileServerOptions = new FileServerOptions
            {
                RequestPath = $"/{options.BaseRoute}",
                EnableDefaultFiles = false,
                FileProvider = new EmbeddedFileProvider(typeof(SwaggerUiBuilderExtensions).GetTypeInfo().Assembly,
                    "Swashbuckle.SwaggerUi.bower_components.swagger_ui.dist")
            };
            fileServerOptions.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider();
            app.UseFileServer(fileServerOptions);

            return app;
        }
    }
}

using System;
using System.Reflection;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using Swashbuckle.AspNetCore.SwaggerUi;

namespace Microsoft.AspNetCore.Builder
{
    public static class SwaggerUiBuilderExtensions
    {
        public static IApplicationBuilder UseSwaggerUi(
            this IApplicationBuilder app,
            Action<SwaggerUiOptions> setupAction = null)
        {
            var options = new SwaggerUiOptions();
            setupAction?.Invoke(options);

            // Enable redirect from basePath to indexPath
            app.UseMiddleware<RedirectMiddleware>(options.BaseRoute, options.IndexPath);

            // Serve indexPath via middleware
            app.UseMiddleware<SwaggerUiMiddleware>(options);

            // Serve everything else via static file server
            var fileServerOptions = new FileServerOptions
            {
                RequestPath = $"/{options.BaseRoute}",
                EnableDefaultFiles = false,
                FileProvider = new EmbeddedFileProvider(typeof(SwaggerUiBuilderExtensions).GetTypeInfo().Assembly,
                    "Swashbuckle.AspNetCore.SwaggerUi.bower_components.swagger_ui.dist")
            };
            fileServerOptions.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider();
            app.UseFileServer(fileServerOptions);

            return app;
        }
    }
}

Update EmbeddedFileProvider to reflect project name change


#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License

// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence

#endregion

using System;

namespace Lokad.Cqrs.Feature.StreamingStorage
{
    [Flags]
    public enum StreamingWriteOptions
    {
        None,
        /// <summary>
        /// We'll compress data if possible.
        /// </summary>
        CompressIfPossible = 0x01,
        /// <summary>
        /// Be default we are optimizing for small read operations. Use this as a hint
        /// </summary>
        OptimizeForLargeWrites = 0x02
    }
}

#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License

// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence

#endregion

using System;

namespace Lokad.Cqrs.Feature.StreamingStorage
{
    [Flags]
    public enum StreamingWriteOptions
    {
        None,
        /// <summary>
        /// We'll compress data if possible.
        /// </summary>
        CompressIfPossible = 0x01,
    }
}

Drop unused streaming write option.

Drop unused streaming write option.


#region Copyright and license
// // <copyright file="NullTests.cs" company="Oliver Zick">
// //     Copyright (c) 2016 Oliver Zick. All rights reserved.
// // </copyright>
// // <author>Oliver Zick</author>
// // <license>
// //     Licensed under the Apache License, Version 2.0 (the "License");
// //     you may not use this file except in compliance with the License.
// //     You may obtain a copy of the License at
// //
// //     http://www.apache.org/licenses/LICENSE-2.0
// //
// //     Unless required by applicable law or agreed to in writing, software
// //     distributed under the License is distributed on an "AS IS" BASIS,
// //     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// //     See the License for the specific language governing permissions and
// //     limitations under the License.
// // </license>
#endregion

namespace Delizious.Filtering
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public sealed class NullTests
    {
        [TestMethod]
        public void Succeed__When_Value_Is_Null()
        {
            Assert.IsTrue(Match.Null<GenericParameterHelper>().Matches(null));
        }

        [TestMethod]
        public void Fail__When_Value_Is_An_Instance()
        {
            Assert.IsFalse(Match.Null<GenericParameterHelper>().Matches(new GenericParameterHelper()));
        }
    }
}

#region Copyright and license
// // <copyright file="NullTests.cs" company="Oliver Zick">
// //     Copyright (c) 2016 Oliver Zick. All rights reserved.
// // </copyright>
// // <author>Oliver Zick</author>
// // <license>
// //     Licensed under the Apache License, Version 2.0 (the "License");
// //     you may not use this file except in compliance with the License.
// //     You may obtain a copy of the License at
// //
// //     http://www.apache.org/licenses/LICENSE-2.0
// //
// //     Unless required by applicable law or agreed to in writing, software
// //     distributed under the License is distributed on an "AS IS" BASIS,
// //     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// //     See the License for the specific language governing permissions and
// //     limitations under the License.
// // </license>
#endregion

namespace Delizious.Filtering
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public sealed class NullTests
    {
        [TestMethod]
        public void Match_Succeeds_When_Value_To_Match_Is_Null()
        {
            Assert.IsTrue(Match.Null<GenericParameterHelper>().Matches(null));
        }

        [TestMethod]
        public void Match_Fails_When_Value_To_Match_Is_An_Instance()
        {
            Assert.IsFalse(Match.Null<GenericParameterHelper>().Matches(new GenericParameterHelper()));
        }
    }
}

Improve naming of tests to clearly indicate the feature to be tested


using System;

public class Herp
{
    public Herp(int X)
    {
        this.X = X;
    }

    public int X { get; private set; }
}

public static class HerpExtensions
{
    public static void PrintX(this Herp Value)
    {
        Console.WriteLine(Value.X);
    }
}

public static class Program
{
    public static void Main()
    {
        var herp = new Herp(20);
        herp.PrintX();
    }
}

using System;
using System.Collections.Generic;
using System.Linq;

public class Herp
{
    public Herp(int X)
    {
        this.X = X;
    }

    public int X { get; private set; }
}

public static class HerpExtensions
{
    public static void PrintX(this Herp Value)
    {
        Console.WriteLine(Value.X);
    }
}

public static class Program
{
    public static void Main()
    {
        var herp = new Herp(20);
        herp.PrintX();

        var items = new List<int>();
        items.Add(10);
        items.Add(20);
        items.Add(30);
        // Note that ToArray<int> is actually a generic extension method:
        // Enumerable.ToArray<T>.
        foreach (var x in items.ToArray<int>())
        {
            Console.WriteLine(x);
        }
    }
}

Update the extension method test case

Update the extension method test case


using System;
using System.Reactive;
using System.Reactive.Linq;
using ReactiveUI;
using WalletWasabi.Gui.ViewModels;

namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
	public class DialogScreenViewModel : ViewModelBase, IScreen
	{
		private bool _isClosing;
		private bool _isDialogVisible;

		public DialogScreenViewModel()
		{
			Observable.FromEventPattern(Router.NavigationStack, nameof(Router.NavigationStack.CollectionChanged))
				.Subscribe(_ =>
				{
					if (!_isClosing)
					{
						IsDialogVisible = Router.NavigationStack.Count >= 1;
					}
				});

			this.WhenAnyValue(x => x.IsDialogVisible).Subscribe(x =>
			{
				if (!x)
				{
					// Reset navigation when Dialog is using IScreen for navigation instead of the default IDialogHost.
					Close();
				}
			});
		}

		public RoutingState Router { get; } = new RoutingState();

		public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;

		public bool IsDialogVisible
		{
			get => _isDialogVisible;
			set => this.RaiseAndSetIfChanged(ref _isDialogVisible, value);
		}

		public void Close()
		{
			if (!_isClosing)
			{
				_isClosing = true;
				if (Router.NavigationStack.Count >= 1)
				{
					Router.NavigationStack.Clear();
				}
				_isClosing = false;
			}
		}
	}
}

using System;
using System.Reactive;
using System.Reactive.Linq;
using ReactiveUI;
using WalletWasabi.Gui.ViewModels;

namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
	public class DialogScreenViewModel : ViewModelBase, IScreen
	{
		private bool _isClosing;
		private bool _isDialogVisible;

		public DialogScreenViewModel()
		{
			Observable.FromEventPattern(Router.NavigationStack, nameof(Router.NavigationStack.CollectionChanged))
				.Subscribe(_ =>
				{
					if (!_isClosing)
					{
						IsDialogVisible = Router.NavigationStack.Count >= 1;
					}
				});

			this.WhenAnyValue(x => x.IsDialogVisible).Subscribe(x =>
			{
				if (!x)
				{
					// Reset navigation when Dialog is using IScreen for navigation instead of the default IDialogHost.
					Close();
				}
			});
		}

		public RoutingState Router { get; } = new RoutingState();

		public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;

		public bool IsDialogVisible
		{
			get => _isDialogVisible;
			set => this.RaiseAndSetIfChanged(ref _isDialogVisible, value);
		}

		public void Close()
		{
			if (!_isClosing)
			{
				_isClosing = true;
				if (Router.NavigationStack.Count >= 1)
				{
					Router.NavigationStack.Clear();
					IsDialogVisible = false;
				}
				_isClosing = false;
			}
		}
	}
}

Set dialog flag as Router.NavigationStack.CollectionChanged observable in blocked by _isClosing