namespace SpiderCrab.Agent
{
    using Ninject;
    using Ninject.Web.Common.OwinHost;
    using Ninject.Web.WebApi.OwinHost;
    using Owin;
    using Properties;
    using System.Reflection;
    using System.Web.Http;

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "default",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            app.UseNinjectMiddleware(CreateKernel)
                .UseNinjectWebApi(config);
        }

        private IKernel CreateKernel()
        {
            var kernel = new StandardKernel(new ServiceModule(Settings.Default));
            kernel.Load(Assembly.GetExecutingAssembly());
            return kernel;
        }
    }
}

namespace SpiderCrab.Agent
{
    using Newtonsoft.Json.Serialization;
    using Ninject;
    using Ninject.Web.Common.OwinHost;
    using Ninject.Web.WebApi.OwinHost;
    using Owin;
    using Properties;
    using System;
    using System.Net;
    using System.Reflection;
    using System.Web.Http;

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var listenerKey = typeof(HttpListener).FullName;
            if (app.Properties==null || !app.Properties.ContainsKey(listenerKey))
            {
                throw new ArgumentOutOfRangeException(
                    nameof(app), "Cannnot access HTTP listener property");
            }

            // Authn; Authz
            var listener = (HttpListener)app.Properties[listenerKey];
            listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
            var config = new HttpConfiguration();
            config.Filters.Add(
                new AuthorizeAttribute { Roles = $"{Environment.MachineName}\\SpiderCrab Operators" });

            // Routes
            config.Routes.MapHttpRoute(
                name: "default",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            // Serialization
            config.Formatters.XmlFormatter.UseXmlSerializer = true;
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver
                = new CamelCasePropertyNamesContractResolver();

            // Dependency injection
            app.UseNinjectMiddleware(CreateKernel)
                .UseNinjectWebApi(config);
        }

        private IKernel CreateKernel()
        {
            var kernel = new StandardKernel(new ServiceModule(Settings.Default));
            kernel.Load(Assembly.GetExecutingAssembly());
            return kernel;
        }
    }
}

Add Windows auth to service, and authorize to the SpiderCrab Operators group


using Certify.Locales;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Certify.UI.Utils
{
    public class UpdateCheckUtils
    {
        public async Task<Models.UpdateCheck> UpdateWithDownload()
        {
            Mouse.OverrideCursor = Cursors.Wait;
            var updateCheck = await new Management.Util().DownloadUpdate();
            if (!string.IsNullOrEmpty(updateCheck.UpdateFilePath))
            {
                if (MessageBox.Show(SR.Update_ReadyToApply, ConfigResources.AppName, MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
                {
                    // file has been downloaded and verified
                    System.Diagnostics.Process p = new System.Diagnostics.Process();
                    p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    p.StartInfo.FileName = updateCheck.UpdateFilePath;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardError = true;
                    p.StartInfo.Arguments = "/SILENT";
                    p.Start();

                    //stop certify.service
                    /*ServiceController service = new ServiceController("ServiceName");
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped);*/

                    Application.Current.Shutdown();
                }
            }
            Mouse.OverrideCursor = Cursors.Arrow;
            return updateCheck;
        }
    }
}

using Certify.Locales;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Certify.UI.Utils
{
    public class UpdateCheckUtils
    {
        public async Task<Models.UpdateCheck> UpdateWithDownload()
        {
            Mouse.OverrideCursor = Cursors.Wait;
            Models.UpdateCheck updateCheck;

            try
            {
                updateCheck = await new Management.Util().DownloadUpdate();
            }
            catch (Exception exp)
            {
                //could not complete or verify download
                MessageBox.Show("Sorry, the update could not be downloaded. Please try again later.");
                System.Diagnostics.Debug.WriteLine(exp.ToString());
                return null;
            }

            if (!string.IsNullOrEmpty(updateCheck.UpdateFilePath))
            {
                if (MessageBox.Show(SR.Update_ReadyToApply, ConfigResources.AppName, MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
                {
                    // file has been downloaded and verified
                    System.Diagnostics.Process p = new System.Diagnostics.Process();
                    p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    p.StartInfo.FileName = updateCheck.UpdateFilePath;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardError = true;
                    p.StartInfo.Arguments = "/SILENT";
                    p.Start();

                    //stop certify.service
                    /*ServiceController service = new ServiceController("ServiceName");
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped);*/

                    Application.Current.Shutdown();
                }
            }
            Mouse.OverrideCursor = Cursors.Arrow;
            return updateCheck;
        }
    }
}

Handle download exceptions when attempting to fetch update


using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Newtonsoft.Json;

namespace DocNuget {
    public class Startup {
        public void ConfigureServices(IServiceCollection services) {
            services.AddMvc();
            services.ConfigureMvcJson(options => {
                options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All;
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
            });
        }

        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) {
            loggerFactory.MinimumLevel = LogLevel.Debug;
            loggerFactory.AddConsole(LogLevel.Debug);
            app.UseErrorPage();
            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions {
                ServeUnknownFileTypes = true,
            });
            app.UseMvc();
        }
    }
}

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Newtonsoft.Json;

namespace DocNuget {
    public class Startup {
        public void ConfigureServices(IServiceCollection services) {
            services.AddMvc();
            services.ConfigureMvcJson(options => {
                options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All;
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
            });
        }

        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) {
            loggerFactory.MinimumLevel = LogLevel.Debug;
            loggerFactory.AddConsole(LogLevel.Debug);

            app
                .UseErrorPage()
                .UseDefaultFiles()
                .UseStaticFiles(new StaticFileOptions {
                    ServeUnknownFileTypes = true,
                })
                .UseMvc()
                .UseSendFileFallback()
                .Use(async (context, next) => {
                    await context.Response.SendFileAsync("wwwroot/index.html");
                });
        }
    }
}

Send index.html for any unknown paths

Send index.html for any unknown paths


using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Voxels.SkiaSharp;

namespace Voxels.CommandLine {
    class Program {
        static void Main(string[] args) {
            var filename = args.Length == 1 ? args[0] : "monu9.vox"; // "3x3x3.vox";
            using (var stream = File.OpenRead(filename)) {
                var voxelData = MagicaVoxel.Read(stream);

                var guid = Guid.NewGuid();
                File.WriteAllBytes($"output{guid}.png", Renderer.RenderPng(512, voxelData));
                File.WriteAllBytes($"output{guid}.svg", Renderer.RenderSvg(512, voxelData));
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Voxels.SkiaSharp;

namespace Voxels.CommandLine {
    class Program {
        static void Main(string[] args) {
            var filename = args.Length == 1 ? args[0] : "3x3x3.vox";
            using (var stream = File.OpenRead(filename)) {
                var voxelData = MagicaVoxel.Read(stream);

                var guid = Guid.NewGuid();
                File.WriteAllBytes($"output{guid}.png", Renderer.RenderPng(512, voxelData));
                File.WriteAllBytes($"output{guid}.svg", Renderer.RenderSvg(512, voxelData));
            }
        }
    }
}

Use 3x3x3.vox as default example

Use 3x3x3.vox as default example

Checked in with monu9.vox as the test case by accident.


using System;
using System.IO;
using System.Runtime.InteropServices;

namespace Dbus
{
    public class ReceivedMessage : IDisposable
    {
        private readonly MessageHeader messageHeader;

        public ReceivedMessage(
            MessageHeader messageHeader,
            Decoder decoder
        )
        {
            this.messageHeader = messageHeader;
            Decoder = decoder;
        }

        public SafeHandle[]? UnixFds => messageHeader.UnixFds;
        public Stream GetStream(int index) => messageHeader.GetStream(index);
        public Decoder Decoder { get; }

        public void AssertSignature(Signature signature)
            => signature.AssertEqual(messageHeader.BodySignature!);

        public void Dispose() => Decoder.Dispose();
    }
}

using System;
using System.IO;
using System.Runtime.InteropServices;

namespace Dbus
{
    public class ReceivedMessage : IDisposable
    {
        private readonly MessageHeader messageHeader;

        public ReceivedMessage(
            MessageHeader messageHeader,
            Decoder decoder
        )
        {
            this.messageHeader = messageHeader;
            Decoder = decoder;
        }

        public SafeHandle[]? UnixFds => messageHeader.UnixFds;
        public Stream GetStream(int index) => messageHeader.GetStream(index);
        public Decoder Decoder { get; }

        public void AssertSignature(Signature expectedSignature)
            => messageHeader.BodySignature!.AssertEqual(expectedSignature);

        public void Dispose() => Decoder.Dispose();
    }
}

Fix the expected / actual order to correct the message


using System;

using Tamir.SharpSsh;

namespace MCloud {

	public class ScriptDeployment : SSHDeployment {

		public ScriptDeployment (string local_path) : this (local_path, String.Concat ("/root/", local_path))
		{
		}

		public ScriptDeployment (string local_path, string remote_path)
		{
			LocalScriptPath = local_path;
			RemoteScriptPath = remote_path;
		}

		public string LocalScriptPath {
			get;
			private set;
		}

		public string RemoteScriptPath {
			get;
			private set;
		}

		protected override void RunImpl (Node node, NodeAuth auth)
		{

			if (node == null)
				throw new ArgumentNullException ("node");
			if (auth == null)
				throw new ArgumentNullException ("auth");

			if (node.PublicIPs.Count < 1)
				throw new ArgumentException ("node", "No public IPs available on node.");

			string host = node.PublicIPs [0].ToString ();
			CopyScript (host, auth);
			RunCommand (RemoteScriptPath, host, auth);
		}

		private void CopyScript (string host, NodeAuth auth)
		{
			Scp scp = new Scp (host, auth.UserName);

			SetupSSH (scp, auth);

			scp.Put (LocalScriptPath, RemoteScriptPath);
			scp.Close ();
		}
	}
}

using System;

using Tamir.SharpSsh;

namespace MCloud {

	public class ScriptDeployment : PutFileDeployment {

		public ScriptDeployment (string local) : base (local)
		{
		}

		public ScriptDeployment (string local, string remote_dir) : base (local, remote_dir)
		{
		}

		protected override void RunImpl (Node node, NodeAuth auth)
		{
			string host = node.PublicIPs [0].ToString ();

			string remote = String.Concat (RemoteDirectory, FileName);
			PutFile (host, auth, FileName, remote);

			RunCommand (remote, host, auth);
		}
	}
}

Change the deployment structure a bit

Change the deployment structure a bit


using UnityEngine;

[CreateAssetMenu (menuName = "AI/Decisions/TargetReached")]
public class Decision_OnTargetReached : Decision {

	public bool overrideDistanceToReach;
	public float distanceToReach;

	public override bool Decide(StateController controller) {
		return isTargetReached(controller);
	}

	private bool isTargetReached(StateController controller) {
		var enemyControl = controller as Enemy_StateController;

		enemyControl.navMeshAgent.destination = enemyControl.chaseTarget.position;

		if(!overrideDistanceToReach)
			distanceToReach = enemyControl.navMeshAgent.stoppingDistance;

		if(enemyControl.navMeshAgent.remainingDistance <= distanceToReach && !enemyControl.navMeshAgent.pathPending) {
			enemyControl.navMeshAgent.isStopped = true;
			return true;
		} else {
			enemyControl.navMeshAgent.isStopped = false;
			return false;
		}
	}
}

using UnityEngine;

[CreateAssetMenu (menuName = "AI/Decisions/TargetReached")]
public class Decision_OnTargetReached : Decision {

	public bool overrideDistanceToReach;
	public float distanceToReach;

	public override bool Decide(StateController controller) {
		return isTargetReached(controller);
	}

	private bool isTargetReached(StateController controller) {
		var enemyControl = controller as Enemy_StateController;

		enemyControl.navMeshAgent.destination = enemyControl.chaseTarget.position;

		if(!overrideDistanceToReach)
			distanceToReach = enemyControl.navMeshAgent.stoppingDistance;

		if(enemyControl.navMeshAgent.remainingDistance <= distanceToReach && !enemyControl.navMeshAgent.pathPending) {
			return true;
		} else {
			return false;
		}
	}
}

Remove NavMeshAgent handling from decision script (not its role)


using System.Linq;
using Thinktecture.IdentityServer.Core.Services.Contrib;
using Xunit;

namespace Unittests
{
    public class AvailableTranslations
    {
        [Theory]
        [InlineData("Default")]
        [InlineData("pirate")]
        [InlineData("nb-NO")]
        [InlineData("tr-TR")]
        [InlineData("de-DE")]
        [InlineData("sv-SE")]
        [InlineData("es-AR")]
        public void ContainsLocales(string locale)
        {
            Assert.Contains(GlobalizedLocalizationService.GetAvailableLocales(), s => s.Equals(locale));
        }

        [Fact]
        public void HasCorrectCount()
        {
            Assert.Equal(6, GlobalizedLocalizationService.GetAvailableLocales().Count());
        }
    }
}

using System.Linq;
using Thinktecture.IdentityServer.Core.Services.Contrib;
using Xunit;

namespace Unittests
{
    public class AvailableTranslations
    {
        [Theory]
        [InlineData("Default")]
        [InlineData("pirate")]
        [InlineData("nb-NO")]
        [InlineData("tr-TR")]
        [InlineData("de-DE")]
        [InlineData("sv-SE")]
        [InlineData("es-AR")]
        public void ContainsLocales(string locale)
        {
            Assert.Contains(GlobalizedLocalizationService.GetAvailableLocales(), s => s.Equals(locale));
        }

        [Fact]
        public void HasCorrectCount()
        {
            Assert.Equal(7, GlobalizedLocalizationService.GetAvailableLocales().Count());
        }
    }
}

Fix correct count 6 -> 7

Fix correct count 6 -> 7


using ExRam.Gremlinq.Core.Serialization;
using ExRam.Gremlinq.Providers;
using LanguageExt;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ExRam.Gremlinq.Core
{
    public static class GremlinQueryExecutionPipelineBuilder
    {
        public static IGremlinQueryExecutionPipelineBuilderWithSerializer<GroovySerializedGremlinQuery> UseGroovySerialization(this IGremlinQueryExecutionPipelineBuilder builder)
        {
            return builder.UseSerializer(GremlinQuerySerializer<GroovySerializedGremlinQuery>.FromVisitor<GroovyGremlinQueryElementVisitor>());
        }

        public static IGremlinQueryExecutionPipeline UseGraphsonDeserialization<TSerializedQuery>(this IGremlinQueryExecutionPipelineBuilderWithExecutor<TSerializedQuery, JToken> builder, params JsonConverter[] additionalConverters)
        {
            return builder.UseDeserializerFactory(new GraphsonDeserializerFactory(additionalConverters));
        }

        public static readonly IGremlinQueryExecutionPipelineBuilder Default = new GremlinQueryExecutionPipeline<Unit, Unit>(
            GremlinQuerySerializer<Unit>.Invalid,
            GremlinQueryExecutor<Unit, Unit>.Invalid,
            GremlinQueryExecutionResultDeserializerFactory<Unit>.Invalid);
    }
}

using ExRam.Gremlinq.Core.Serialization;
using ExRam.Gremlinq.Providers;
using LanguageExt;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ExRam.Gremlinq.Core
{
    public static class GremlinQueryExecutionPipelineBuilder
    {
        public static IGremlinQueryExecutionPipelineBuilderWithSerializer<GroovySerializedGremlinQuery> UseGroovySerialization(this IGremlinQueryExecutionPipelineBuilder builder)
        {
            return builder.UseSerializer(GremlinQuerySerializer<GroovySerializedGremlinQuery>.FromVisitor<GroovyGremlinQueryElementVisitor>());
        }

        public static IGremlinQueryExecutionPipeline<TSerializedQuery, JToken> UseGraphsonDeserialization<TSerializedQuery>(this IGremlinQueryExecutionPipelineBuilderWithExecutor<TSerializedQuery, JToken> builder, params JsonConverter[] additionalConverters)
        {
            return builder.UseDeserializerFactory(new GraphsonDeserializerFactory(additionalConverters));
        }

        public static readonly IGremlinQueryExecutionPipelineBuilder Default = new GremlinQueryExecutionPipeline<Unit, Unit>(
            GremlinQuerySerializer<Unit>.Invalid,
            GremlinQueryExecutor<Unit, Unit>.Invalid,
            GremlinQueryExecutionResultDeserializerFactory<Unit>.Invalid);
    }
}

Use richer return type when possible.

Use richer return type when possible.


using System.IO;

namespace TestUtility
{
    public static class StringExtensions
    {
        /// <summary>
        /// Given a file or directory path, return a path where all directory separators
        /// are replaced with a forward slash (/) character.
        /// </summary>
        public static string EnsureForwardSlashes(this string path)
            => path.Replace(Path.DirectorySeparatorChar, '/');
    }
}

using System.IO;

namespace TestUtility
{
    public static class StringExtensions
    {
        /// <summary>
        /// Given a file or directory path, return a path where all directory separators
        /// are replaced with a forward slash (/) character.
        /// </summary>
        public static string EnsureForwardSlashes(this string path)
            => path.Replace('\\', '/');
    }
}

Fix MSBuild tests on macOS/Linux

Fix MSBuild tests on macOS/Linux


// 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.SpacingRules
{
    using Test.SpacingRules;

    public class SA1024CSharp7UnitTests : SA1024UnitTests
    {
    }
}

// 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.SpacingRules
{
    using System;
    using System.Linq;
    using System.Reflection;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.CodeAnalysis;
    using StyleCop.Analyzers.Test.SpacingRules;
    using TestHelper;
    using Xunit;

    public class SA1024CSharp7UnitTests : SA1024UnitTests
    {
        /// <summary>
        /// Verifies spacing around a <c>:</c> character in tuple expressions.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
        [Fact]
        public async Task TestSpacingAroundColonInTupleExpressionsAsync()
        {
            const string testCode = @"using System;

public class Foo
{
    public void TestMethod()
    {
        var values = (x :3, y :4);
    }
}";
            const string fixedCode = @"using System;

public class Foo
{
    public void TestMethod()
    {
        var values = (x: 3, y: 4);
    }
}";

            DiagnosticResult[] expected =
            {
                this.CSharpDiagnostic().WithLocation(7, 25).WithArguments(" not", "preceded", string.Empty),
                this.CSharpDiagnostic().WithLocation(7, 25).WithArguments(string.Empty, "followed", string.Empty),
                this.CSharpDiagnostic().WithLocation(7, 31).WithArguments(" not", "preceded", string.Empty),
                this.CSharpDiagnostic().WithLocation(7, 31).WithArguments(string.Empty, "followed", string.Empty),
            };

            await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
            await this.VerifyCSharpDiagnosticAsync(fixedCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
            await this.VerifyCSharpFixAsync(testCode, fixedCode, cancellationToken: CancellationToken.None).ConfigureAwait(false);
        }

        protected override Solution CreateSolution(ProjectId projectId, string language)
        {
            Solution solution = base.CreateSolution(projectId, language);
            Assembly systemRuntime = AppDomain.CurrentDomain.GetAssemblies().Single(x => x.GetName().Name == "System.Runtime");
            return solution
                .AddMetadataReference(projectId, MetadataReference.CreateFromFile(systemRuntime.Location))
                .AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(ValueTuple).Assembly.Location));
        }
    }
}

Add tests for SA1024 in tuple expressions


using System.Reflection;

[assembly: AssemblyCompany("Kentor")]
[assembly: AssemblyCopyright("Copyright  Kentor and contributors 2015")]

// Kentor.AuthServices uses semantic versioning in three parts
//
//      Major Version
//      Minor Version
//      Patch Number
//
// An odd patch number is a development version, an even patch number is
// a relased version.

[assembly: AssemblyVersion("0.0.31")]
[assembly: AssemblyFileVersion("0.0.31")]
[assembly: AssemblyInformationalVersion("0.0.31")]

using System.Reflection;

[assembly: AssemblyCompany("Kentor")]
[assembly: AssemblyCopyright("Copyright  Kentor and contributors 2015")]

// Kentor.PU-Adapter uses semantic versioning in three parts
//
//      Major Version
//      Minor Version
//      Patch Number
//
// An odd patch number is a development version, an even patch number is
// a released version.

[assembly: AssemblyVersion("0.0.31")]
[assembly: AssemblyFileVersion("0.0.31")]
[assembly: AssemblyInformationalVersion("0.0.31")]

Fix names and spelling in comments

Fix names and spelling in comments


// Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.OutputSinks;

namespace Nuke.Common.CI.AppVeyor
{
    [UsedImplicitly]
    [ExcludeFromCodeCoverage]
    internal class AppVeyorOutputSink : AnsiColorOutputSink
    {
        private readonly AppVeyor _appVeyor;

        internal AppVeyorOutputSink(AppVeyor appVeyor)
        {
            _appVeyor = appVeyor;
        }

        protected override string TraceCode => "90";
        protected override string InformationCode => "36;1";
        protected override string WarningCode => "33;1";
        protected override string ErrorCode => "31;1";
        protected override string SuccessCode => "32;1";

        protected override void ReportWarning(string text, string details = null)
        {
            _appVeyor.WriteWarning(text, details);
        }

        protected override void ReportError(string text, string details = null)
        {
            _appVeyor.WriteError(text, details);
        }
    }
}

// Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.OutputSinks;

namespace Nuke.Common.CI.AppVeyor
{
    [UsedImplicitly]
    [ExcludeFromCodeCoverage]
    internal class AppVeyorOutputSink : AnsiColorOutputSink
    {
        private readonly AppVeyor _appVeyor;
        private int _messageCount;

        internal AppVeyorOutputSink(AppVeyor appVeyor)
        {
            _appVeyor = appVeyor;
        }

        protected override string TraceCode => "90";
        protected override string InformationCode => "36;1";
        protected override string WarningCode => "33;1";
        protected override string ErrorCode => "31;1";
        protected override string SuccessCode => "32;1";

        protected override void ReportWarning(string text, string details = null)
        {
            IncreaseAndCheckMessageCount();
            _appVeyor.WriteWarning(text, details);
        }

        protected override void ReportError(string text, string details = null)
        {
            IncreaseAndCheckMessageCount();
            _appVeyor.WriteError(text, details);
        }

        private void IncreaseAndCheckMessageCount()
        {
            _messageCount++;

            if (_messageCount == 501)
            {
                base.WriteWarning("AppVeyor has a default limit of 500 messages. " +
                                  "If you're getting an exception from 'appveyor.exe' after this message, " +
                                  "contact https://appveyor.com/support to resolve this issue for your account.");
            }
        }
    }
}

Fix AppVeyor message limit by printing a warning for the 501st report message


using MonoMac.Foundation;
using MonoMac.AppKit;
using Cirrious.CrossCore;
using Cirrious.MvvmCross.Mac.Platform;
using Cirrious.MvvmCross.Mac.Views.Presenters;
using Cirrious.MvvmCross.ViewModels;
using System.Drawing;

namespace Pina.Mac
{
	public partial class AppDelegate : MvxApplicationDelegate
	{
		MainWindowController mainWindowController;

		public AppDelegate()
		{
		}

		public override void FinishedLaunching (NSObject notification)
		{
			mainWindowController = new MainWindowController ();

			var presenter = new MvxMacViewPresenter (this, mainWindowController.Window);
			var setup = new Setup (this, presenter);
			setup.Initialize ();

			var startup = Mvx.Resolve<IMvxAppStart> ();
			startup.Start ();

			mainWindowController.Window.MakeKeyAndOrderFront (this);

			return;
		}
	}
}

using MonoMac.Foundation;
using MonoMac.AppKit;
using Cirrious.CrossCore;
using Cirrious.MvvmCross.Mac.Platform;
using Cirrious.MvvmCross.Mac.Views.Presenters;
using Cirrious.MvvmCross.ViewModels;
using System.Drawing;

namespace Pina.Mac
{
	public partial class AppDelegate : MvxApplicationDelegate
	{
		MainWindowController mainWindowController;

		public AppDelegate()
		{
		}

		public override void FinishedLaunching (NSObject notification)
		{
			mainWindowController = new MainWindowController ();

			var setup = new Setup (this, mainWindowController.Window);
			setup.Initialize ();

			var startup = Mvx.Resolve<IMvxAppStart> ();
			startup.Start ();

			mainWindowController.Window.MakeKeyAndOrderFront (this);

			return;
		}
	}
}

Switch to using NSWindow instead of presenter


namespace VkApiGenerator.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            var methods = new[]
            {
                "notes.get",
                "notes.getById",
                "notes.getFriendsNotes",
                "notes.add",
                "notes.edit",
                "notes.delete",
                "notes.getComments",
                "notes.createComment",
                "notes.editComment",
                "notes.deleteComment",
                "notes.restoreComment"
            };
            var parser = new VkApiParser();

            foreach (string methodName in methods)
            {
                System.Console.WriteLine("*** {0} ***", methodName);
                var methodInfo = parser.Parse(methodName);
                System.Console.WriteLine("DESCRIPTION: {0}", methodInfo.Description);
                System.Console.WriteLine("RETURN TEXT: {0}", methodInfo.ReturnText);
                System.Console.WriteLine("RETURN TYPE: {0}", methodInfo.ReturnType);

                System.Console.WriteLine("PAPAMETERS:");
                foreach (var p in methodInfo.Params)
                {
                    System.Console.WriteLine("    {0} - {1}", p.Name, p.Description);
                }

                System.Console.WriteLine("\n========================================\n");
                System.Console.ReadLine();
            }

            System.Console.WriteLine("done.");
        }
    }
}

using System.Net;
using VkApiGenerator.Model;

namespace VkApiGenerator.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            var methods = new[]
            {
                "notes.get",
                "notes.getById",
                "notes.getFriendsNotes",
                "notes.add",
                "notes.edit",
                "notes.delete",
                "notes.getComments",
                "notes.createComment",
                "notes.editComment",
                "notes.deleteComment",
                "notes.restoreComment"
            };
            var parser = new VkApiParser();

            foreach (string methodName in methods)
            {
                System.Console.WriteLine("*** {0} ***", methodName);
                VkMethodInfo methodInfo;
                try
                {
                    methodInfo = parser.Parse(methodName);
                }
                catch (WebException ex)
                {
                    System.Console.WriteLine(ex.Message);
                    continue;
                }
                System.Console.WriteLine("DESCRIPTION: {0}", methodInfo.Description);
                System.Console.WriteLine("RETURN TEXT: {0}", methodInfo.ReturnText);
                System.Console.WriteLine("RETURN TYPE: {0}", methodInfo.ReturnType);

                System.Console.WriteLine("PAPAMETERS:");
                foreach (var p in methodInfo.Params)
                {
                    System.Console.WriteLine("    {0} - {1}", p.Name, p.Description);
                }

                System.Console.WriteLine("\n========================================\n");
                System.Console.ReadLine();
            }

            System.Console.WriteLine("done.");
        }
    }
}

Check when internet connection is disabled


using UnityEngine;
using System.Collections;
using ActionEngine;

public static class VeryAwesomeAEX {

	public static ActionBase Create (IAEScriptContext ctx) {
		var simpleAEX = ctx.GetAEScript("$simple");
		var cube = ctx.GetTransform("$cube");
		var sphere = ctx.GetTransform("$sphere");

		return
			AE.Sequence(
				AE.Parallel(
					// You can use another AEX
					simpleAEX.Create(),
					// Basic tweens
					cube.AEMove(new Vector3(0, -3, 0), 3.5f).Easing(Easings.BounceInOut),
					sphere.AEMove(new Vector3(0, 3, 0), 4.5f).Easing(Easings.ElasticOut)
                ),
				AE.Parallel(
					cube.AEMove(new Vector3(0, 3, 0), 2.5f).Relative(true).Easing(Easings.BackOut),
					sphere.AEMove(new Vector3(0, -3, 0), 3.5f).Relative(true).Easing(Easings.QuadOut)
				),
				AE.Delay(0.5f),
				AE.Debug("All Completed!")
			);
	}

}

using ActionEngine;
using System.Collections;
using UnityEngine;

public static class VeryAwesomeAEX {

	public static ActionBase Create (IAEScriptContext ctx) {
		var simpleAEX = ctx.GetAEScript("$simple");
		var cube = ctx.GetTransform("$cube");
		var sphere = ctx.GetTransform("$sphere");

		return
			AE.Sequence(
				AE.Parallel(
					// You can use another AEX
					simpleAEX.Create(),

					// Basic tweens
					cube.AEMove(new Vector3(0, -3, 0), 3.5f).Easing(Easings.BounceInOut),
					sphere.AEMove(new Vector3(0, 3, 0), 4.5f).Easing(Easings.ElasticOut)
				),
				AE.Parallel(
					cube.AEMove(new Vector3(0, 3, 0), 2.5f).Relative(true).Easing(Easings.BackOut),
					sphere.AEMove(new Vector3(0, -3, 0), 3.5f).Relative(true).Easing(Easings.QuadOut)
				),
				AE.Coroutine(() => ExampleCoroutine()),
				AE.Debug("All Completed!")
			);
	}

	private static IEnumerator ExampleCoroutine () {
		Debug.Log("Coroutine Started: " + Time.time);
		yield return new WaitForSeconds(2f);
		Debug.Log("Coroutine End: " + Time.time);
	}

}

Add coroutine usage in AEX

Add coroutine usage in AEX


namespace slang.Lexing.Rules.Core
{
    public abstract class Rule
    {
        public static Rule operator | (Rule left, Rule right)
        {
            return new Or (left, right);
        }

        public static Rule operator + (Rule left, Rule right)
        {
            return new And (left, right);
        }

        public static implicit operator Rule (char value)
        {
            return new Constant (value);
        }
    }
}

using slang.Lexing.Tokens;
using System;
namespace slang.Lexing.Rules.Core
{
    public abstract class Rule
    {
        public Func<Token> TokenCreator { get; set; }

        public static Rule operator | (Rule left, Rule right)
        {
            return new Or (left, right);
        }

        public static Rule operator + (Rule left, Rule right)
        {
            return new And (left, right);
        }

        public static implicit operator Rule (char value)
        {
            return new Constant (value);
        }

        public Rule Returns(Func<Token> tokenCreator = null)
        {
            TokenCreator = tokenCreator ?? new Func<Token>(() => Token.Empty);
            return this;
        }
    }
}

Add ability to return token from rule

Add ability to return token from rule


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace TodoList.Web
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.IO;

namespace TodoList.Web
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
      services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
      // Redirect any non-api calls to the Angular app.
      app.Use(async (context, next) => {
        await next();
        if (context.Response.StatusCode == 404 &&
           !Path.HasExtension(context.Request.Path.Value) &&
           !context.Request.Path.Value.StartsWith("/api/"))
        {
          context.Request.Path = "/index.html";
          await next();
        }
      });
      app.UseMvcWithDefaultRoute();
      app.UseDefaultFiles();
      app.UseStaticFiles();
    }
    }
}

Add MVC and middleware to listening only for 'api' requests


namespace Espera.Network
{
    public enum NetworkPlaybackState
    {
        None,
        Playing,
        Paused,
        Stopped,
        Finished
    }
}

namespace Espera.Network
{
    public enum NetworkPlaybackState
    {
        None = 0,
        Playing = 1,
        Paused = 2,
        Stopped = 3,
        Finished = 4
    }
}

Mark the playback states with integer values


using NUnit.Framework;

using System;
using System.Collections.Generic;

namespace NHibernate.Test.NHSpecificTest.NH1119
{
	[TestFixture]
	public class Fixture : BugTestCase
	{
		public override string BugNumber
		{
			get { return "NH1119"; }
		}

		[Test]
		public void SelectMinFromEmptyTable()
		{
			using (ISession s = OpenSession())
			{
				try
				{
					DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>();
					string msg = "Calling UniqueResult<T> where T is a value type"
						+ " should throw InvalidCastException when the result"
						+ " is null";
					Assert.Fail(msg);
				}
				catch (InvalidCastException) { }
			}
		}
	}
}

using System;
using NUnit.Framework;

namespace NHibernate.Test.NHSpecificTest.NH1119
{
	[TestFixture]
	public class Fixture : BugTestCase
	{
		public override string BugNumber
		{
			get { return "NH1119"; }
		}

		[Test]
		public void SelectMinFromEmptyTable()
		{
			using (ISession s = OpenSession())
			{
				DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>();
				Assert.AreEqual(default(DateTime), dt);
			}
		}
	}
}

Check the use of default(T) instead exception.

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@3062


using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using static Hellang.Middleware.ProblemDetails.ProblemDetailsOptionsSetup;
using MvcProblemDetails = Microsoft.AspNetCore.Mvc.ProblemDetails;
using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory;

namespace Hellang.Middleware.ProblemDetails.Mvc
{
    internal class ProblemDetailsResultFilter : IAlwaysRunResultFilter, IOrderedFilter
    {
        public ProblemDetailsResultFilter(MvcProblemDetailsFactory factory)
        {
            Factory = factory;
        }

        /// <summary>
        /// The same order as the built-in ClientErrorResultFilter.
        /// </summary>
        public int Order => -2000;

        private MvcProblemDetailsFactory Factory { get; }

        public void OnResultExecuting(ResultExecutingContext context)
        {
            // Only handle ObjectResult for now.
            if (context.Result is not ObjectResult result)
            {
                return;
            }

            // Make sure the result should be treated as a problem.
            if (!IsProblemStatusCode(result.StatusCode))
            {
                return;
            }

            // Only handle the string case for now.
            if (result.Value is not string title)
            {
                return;
            }

            var problemDetails = Factory.CreateProblemDetails(context.HttpContext, result.StatusCode, title);

            context.Result = new ObjectResult(problemDetails)
            {
                StatusCode = problemDetails.Status,
                ContentTypes = {
                    "application/problem+json",
                    "application/problem+xml",
                },
            };
        }

        void IResultFilter.OnResultExecuted(ResultExecutedContext context)
        {
            // Not needed.
        }
    }
}

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using static Hellang.Middleware.ProblemDetails.ProblemDetailsOptionsSetup;
using MvcProblemDetails = Microsoft.AspNetCore.Mvc.ProblemDetails;
using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory;

namespace Hellang.Middleware.ProblemDetails.Mvc
{
    internal class ProblemDetailsResultFilter : IAlwaysRunResultFilter, IOrderedFilter
    {
        public ProblemDetailsResultFilter(MvcProblemDetailsFactory factory)
        {
            Factory = factory;
        }

        /// <summary>
        /// The same order as the built-in ClientErrorResultFilter.
        /// </summary>
        public int Order => -2000;

        private MvcProblemDetailsFactory Factory { get; }

        public void OnResultExecuting(ResultExecutingContext context)
        {
            // Only handle ObjectResult for now.
            if (context.Result is not ObjectResult result)
            {
                return;
            }

            // Make sure the result should be treated as a problem.
            if (!IsProblemStatusCode(result.StatusCode))
            {
                return;
            }

            // Only handle the string case for now.
            if (result.Value is not string detail)
            {
                return;
            }

            var problemDetails = Factory.CreateProblemDetails(context.HttpContext, result.StatusCode, detail: detail);

            context.Result = new ObjectResult(problemDetails)
            {
                StatusCode = problemDetails.Status,
                ContentTypes = {
                    "application/problem+json",
                    "application/problem+xml",
                },
            };
        }

        void IResultFilter.OnResultExecuted(ResultExecutedContext context)
        {
            // Not needed.
        }
    }
}

Set the detail instead of the title

Set the detail instead of the title


// 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 UIKit;

namespace osu.Framework.Tests.iOS
{
    public class Application
    {
        // This is the main entry point of the application.
        public static void Main(string[] args)
        {
            // if you want to use a different Application Delegate class from "AppDelegate"
            // you can specify it here.
            UIApplication.Main(args, null, "AppDelegate");
        }
    }
}

// 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 UIKit;

namespace osu.Framework.Tests.iOS
{
    public class Application
    {
        // This is the main entry point of the application.
        public static void Main(string[] args)
        {
            // if you want to use a different Application Delegate class from "AppDelegate"
            // you can specify it here.
            UIApplication.Main(args, "GameUIApplication", "AppDelegate");
        }
    }
}

Fix iOS visual tests not using raw keyboard handler


using System;
using System.Collections.Generic;
using System.IO;
public class ConfigFileFinder
{
    public static List<string> FindWeaverConfigs(string solutionDirectoryPath, string projectDirectory)
    {
        var files = new List<string>();

        var solutionConfigFilePath = Path.Combine(solutionDirectoryPath, "FodyWeavers.xml");
        if (File.Exists(solutionConfigFilePath))
        {
            files.Add(solutionConfigFilePath);
            logger.LogDebug($"Found path to weavers file '{solutionConfigFilePath}'.");
        }

        var projectConfigFilePath = Path.Combine(projectDirectory, "FodyWeavers.xml");
        if (!File.Exists(projectConfigFilePath))
        {
            logger.LogDebug($@"Could not file a FodyWeavers.xml at the project level ({projectConfigFilePath}). Some project types do not support using NuGet to add content files e.g. netstandard projects. In these cases it is necessary to manually add a FodyWeavers.xml to the project. Example content:
  <Weavers>
    <WeaverName/>
  </Weavers>
  ");
        }
        else
        {
            files.Add(projectConfigFilePath);
            logger.LogDebug($"Found path to weavers file '{projectConfigFilePath}'.");
        }

        if (files.Count == 0)
        {
            // ReSharper disable once UnusedVariable
            var pathsSearched = string.Join("', '", solutionConfigFilePath, projectConfigFilePath);
            throw new WeavingException($"Could not find path to weavers file. Searched '{pathsSearched}'.");
        }
        return files;
    }
}

using System;
using System.Collections.Generic;
using System.IO;
public class ConfigFileFinder
{
    public static List<string> FindWeaverConfigs(string solutionDirectoryPath, string projectDirectory)
    {
        var files = new List<string>();

        var solutionConfigFilePath = Path.Combine(solutionDirectoryPath, "FodyWeavers.xml");
        if (File.Exists(solutionConfigFilePath))
        {
            files.Add(solutionConfigFilePath);
        }

        var projectConfigFilePath = Path.Combine(projectDirectory, "FodyWeavers.xml");
        if (File.Exists(projectConfigFilePath))
        {
            files.Add(projectConfigFilePath);
        }

        if (files.Count == 0)
        {
            // ReSharper disable once UnusedVariable
            var pathsSearched = string.Join("', '", solutionConfigFilePath, projectConfigFilePath);
            throw new WeavingException($@"Could not find path to weavers file. Searched '{pathsSearched}'. Some project types do not support using NuGet to add content files e.g. netstandard projects. In these cases it is necessary to manually add a FodyWeavers.xml to the project. Example content:
  <Weavers>
    <WeaverName/>
  </Weavers>
  ");
        }
        return files;
    }
}

Fix missing logger by moving the expanded detail to the exception


namespace Linterhub.Cli.Strategy
{
    using Runtime;
    using Engine;
    using Linterhub.Engine.Exceptions;

    public class LinterVersionStrategy : IStrategy
    {
        public object Run(RunContext context, LinterFactory factory, LogManager log)
        {
            if (string.IsNullOrEmpty(context.Linter))
            {
                throw new LinterEngineException("Linter is not specified: " + context.Linter);
            }
            var result = "";
            var versionCmd = factory.BuildVersionCommand(context.Linter);
            //System.Console.WriteLine(versionCmd);

            var version = string.IsNullOrEmpty(versionCmd) ? "Unknown" : new LinterhubWrapper(context).LinterVersion(context.Linter, versionCmd).Trim();
            result += $"\n{context.Linter}: {version}";

            return result;
        }
    }
}

namespace Linterhub.Cli.Strategy
{
    using Runtime;
    using Engine;
    using Linterhub.Engine.Exceptions;
    using Newtonsoft.Json;
    using System.Dynamic;

    public class LinterVersionStrategy : IStrategy
    {
        public object Run(RunContext context, LinterFactory factory, LogManager log)
        {
            if (string.IsNullOrEmpty(context.Linter))
            {
                throw new LinterEngineException("Linter is not specified: " + context.Linter);
            }
            dynamic result = new ExpandoObject();
            var versionCmd = factory.BuildVersionCommand(context.Linter);

            var version = new LinterhubWrapper(context).LinterVersion(context.Linter, versionCmd).Trim();

            result.LinterName = context.Linter;
            result.Installed = version.Contains("Can\'t find " + context.Linter) ? "No" : "Yes";
            result.Version = ((string)result.Installed).Contains("No") ? "Unknown" : version;

            return JsonConvert.SerializeObject(result);
        }

    }
}

Change LinterVersion output to json format


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34003
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

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

[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.FakeItEasy 3.0.0-beta")]

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18051
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

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

[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.FakeItEasy 3.0.0-beta")]

Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.


// 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;
using osu.Framework.Platform;
using osu.Framework.Testing;

namespace osu.Game.Tests.Visual
{
    public abstract class OsuTestCase : TestCase
    {
        public override void RunTest()
        {
            using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false))
            {
                host.Run(new OsuTestCaseTestRunner(this));
            }

            // clean up after each run
            //storage.DeleteDirectory(string.Empty);
        }

        public class OsuTestCaseTestRunner : OsuGameBase
        {
            private readonly OsuTestCase testCase;

            public OsuTestCaseTestRunner(OsuTestCase testCase)
            {
                this.testCase = testCase;
            }

            protected override void LoadComplete()
            {
                base.LoadComplete();
                Add(new TestCaseTestRunner.TestRunner(testCase));
            }
        }
    }
}

// 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;
using osu.Framework.Platform;
using osu.Framework.Testing;

namespace osu.Game.Tests.Visual
{
    public abstract class OsuTestCase : TestCase
    {
        public override void RunTest()
        {
            using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false))
            {
                host.Storage.DeleteDirectory(string.Empty);
                host.Run(new OsuTestCaseTestRunner(this));
            }
        }

        public class OsuTestCaseTestRunner : OsuGameBase
        {
            private readonly OsuTestCase testCase;

            public OsuTestCaseTestRunner(OsuTestCase testCase)
            {
                this.testCase = testCase;
            }

            protected override void LoadComplete()
            {
                base.LoadComplete();
                Add(new TestCaseTestRunner.TestRunner(testCase));
            }
        }
    }
}

Add back test cleanup before run

Add back test cleanup before run


using System;

namespace LunaClient.Extensions
{
    public static class CelestialBodyExtension
    {
        public static double SiderealDayLength(this CelestialBody body)
        {
            //Taken from CelestialBody.Start()

            if (body == null) return 0;

            var siderealOrbitalPeriod = 6.28318530717959 * Math.Sqrt(Math.Pow(Math.Abs(body.orbit.semiMajorAxis), 3) / body.orbit.referenceBody.gravParameter);
            return body.rotationPeriod * siderealOrbitalPeriod / (siderealOrbitalPeriod + body.rotationPeriod);
        }
    }
}

using System;

namespace LunaClient.Extensions
{
    public static class CelestialBodyExtension
    {
        public static double SiderealDayLength(this CelestialBody body)
        {
            //Taken from CelestialBody.Start()

            //body.solarRotationPeriod will be false if it's the sun!
            if (body == null || body.orbit == null || !body.solarRotationPeriod) return 0;

            var siderealOrbitalPeriod = 6.28318530717959 * Math.Sqrt(Math.Pow(Math.Abs(body.orbit.semiMajorAxis), 3) / body.orbit.referenceBody.gravParameter);
            return body.rotationPeriod * siderealOrbitalPeriod / (siderealOrbitalPeriod + body.rotationPeriod);
        }
    }
}

Fix sidereal calculations for sun

Fix sidereal calculations for sun


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using VORBS.Utils.interfaces;

namespace VORBS.Utils
{
    public class StubbedEmailClient : ISmtpClient
    {
        private NLog.Logger _logger;

        public StubbedEmailClient()
        {
            _logger = NLog.LogManager.GetCurrentClassLogger();

            _logger.Trace(LoggerHelper.InitializeClassMessage());
        }

        public LinkedResource GetLinkedResource(string path, string id)
        {
            LinkedResource resource = new LinkedResource(path);
            resource.ContentId = id;
            _logger.Trace(LoggerHelper.ExecutedFunctionMessage(resource, path, id));
            return resource;
        }

        public void Send(MailMessage message)
        {
            string rootDirectory = $@"{AppDomain.CurrentDomain.SetupInformation.ApplicationBase}Logs/{DateTime.Now.ToString("yyyy-MM-dd")}/EmailLogs/{message.To.FirstOrDefault().User}";
            if (!Directory.Exists(rootDirectory))
                Directory.CreateDirectory(rootDirectory);

            string fileName = $"{message.Subject}_{DateTime.Now.ToString("hh-mm-ss")}";
            using (FileStream fs = File.Create($"{rootDirectory}/{fileName}.html"))
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine($"From: {message.From}");
                builder.AppendLine($"To: {message.To}");
                builder.AppendLine($"BCC: {message.Bcc}");
                builder.AppendLine($"Subject: {message.Subject}");
                builder.AppendLine(message.Body);

                byte[] info = new UTF8Encoding(true).GetBytes(builder.ToString());
                fs.Write(info, 0, info.Length);

                // writing data in bytes already
                byte[] data = new byte[] { 0x0 };
                fs.Write(data, 0, data.Length);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using VORBS.Utils.interfaces;

namespace VORBS.Utils
{
    public class StubbedEmailClient : ISmtpClient
    {
        private NLog.Logger _logger;

        public StubbedEmailClient()
        {
            _logger = NLog.LogManager.GetCurrentClassLogger();

            _logger.Trace(LoggerHelper.InitializeClassMessage());
        }

        public LinkedResource GetLinkedResource(string path, string id)
        {
            LinkedResource resource = new LinkedResource(path);
            resource.ContentId = id;
            _logger.Trace(LoggerHelper.ExecutedFunctionMessage(resource, path, id));
            return resource;
        }

        public void Send(MailMessage message)
        {
            SmtpClient client = new SmtpClient("stubbedhostname");
            client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;

            string rootDirectory = $@"{AppDomain.CurrentDomain.SetupInformation.ApplicationBase}Logs/{DateTime.Now.ToString("yyyy-MM-dd")}/EmailLogs/{message.To.FirstOrDefault().User}";
            if (!Directory.Exists(rootDirectory))
                Directory.CreateDirectory(rootDirectory);

            client.PickupDirectoryLocation = rootDirectory;
            client.Send(message);
        }
    }
}

Use Smtp PickUp delivery for stubbing saving of emails locally


Add Google Plus +1 to AddThis defaults

Add Google Plus +1 to AddThis defaults


/* © 2019 Ivan Pointer
MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE
Source on GitHub: https://github.com/ivanpointer/NuLog */

using NuLog.Configuration;
using NuLog.LogEvents;
using System;

namespace NuLog.CLI.Benchmarking {

    /// <summary>
    /// A dummy target for performance testing - we need to see the raw results of the engine, not
    /// the individual target.
    /// </summary>
    public class DummyTarget : ITarget {
        public string Name { get; set; }

        public void Configure(TargetConfig config) {
            // noop
        }

        public void Dispose() {
            // noop
        }

        public void Write(LogEvent logEvent) {
            // noop
        }
    }
}

/* © 2019 Ivan Pointer
MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE
Source on GitHub: https://github.com/ivanpointer/NuLog */

using NuLog.Configuration;
using NuLog.LogEvents;
using System;

namespace NuLog.CLI.Benchmarking {

    /// <summary>
    /// A dummy target for performance testing - we need to see the raw results of the engine, not
    /// the individual target.
    /// </summary>
    public class DummyTarget : ITarget {
        public string Name { get; set; }

        public void Configure(TargetConfig config) {
            // noop
        }

        public void Write(LogEvent logEvent) {
            // noop
        }

        #region IDisposable Support

        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing) {
            if (!disposedValue) {
                if (disposing) {
                    // noop
                }

                // noop

                disposedValue = true;
            }
        }

        // This code added to correctly implement the disposable pattern.
        public void Dispose() {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion IDisposable Support
    }
}

Implement proper disposable pattern to satisfy sonarcloud's compaint of a code smell :/


#region Usings

using System;
using System.Collections.Generic;
using System.Windows.Input;
using ReactiveUI.Legacy;
using UI.WPF.Launcher.Common.Classes;

#endregion

namespace UI.WPF.Modules.Installation.ViewModels.Installation
{
    public class InstallationViewModel : ReactiveObjectBase
    {
        private InstallationItemParent _installationParent;

        private InstallationItemParent _uninstallationParent;

        public ICommand CloseCommand { get; private set; }

        public InstallationViewModel(Action closeAction)
        {
            var cmd = new ReactiveCommand();
            cmd.Subscribe(_ => closeAction());
            CloseCommand = cmd;
        }

        public InstallationItemParent InstallationParent
        {
            get { return _installationParent; }
            private set { RaiseAndSetIfPropertyChanged(ref _installationParent, value); }
        }

        public InstallationItemParent UninstallationParent
        {
            get { return _uninstallationParent; }
            private set { RaiseAndSetIfPropertyChanged(ref _uninstallationParent, value); }
        }

        public IEnumerable<InstallationItem> InstallationItems
        {
            set { InstallationParent = new InstallationItemParent(null, value); }
        }

        public IEnumerable<InstallationItem> UninstallationItems
        {
            set { UninstallationParent = new InstallationItemParent(null, value); }
        }
    }
}

#region Usings

using System;
using System.Collections.Generic;
using System.Windows.Input;
using ReactiveUI;
using UI.WPF.Launcher.Common.Classes;

#endregion

namespace UI.WPF.Modules.Installation.ViewModels.Installation
{
    public class InstallationViewModel : ReactiveObjectBase
    {
        private InstallationItemParent _installationParent;

        private InstallationItemParent _uninstallationParent;

        public ICommand CloseCommand { get; private set; }

        public InstallationViewModel(Action closeAction)
        {
            var cmd = ReactiveCommand.Create();
            cmd.Subscribe(_ => closeAction());
            CloseCommand = cmd;
        }

        public InstallationItemParent InstallationParent
        {
            get { return _installationParent; }
            private set { RaiseAndSetIfPropertyChanged(ref _installationParent, value); }
        }

        public InstallationItemParent UninstallationParent
        {
            get { return _uninstallationParent; }
            private set { RaiseAndSetIfPropertyChanged(ref _uninstallationParent, value); }
        }

        public IEnumerable<InstallationItem> InstallationItems
        {
            set { InstallationParent = new InstallationItemParent(null, value); }
        }

        public IEnumerable<InstallationItem> UninstallationItems
        {
            set { UninstallationParent = new InstallationItemParent(null, value); }
        }
    }
}

Remove usage of legacy code

Remove usage of legacy code


using System.Collections.Generic;
using System.Linq;
using Alensia.Core.Common;
using UnityEngine;

namespace Alensia.Core.UI.Cursor
{
    public class CursorSet : ScriptableObject, IDirectory<CursorDefinition>, IEditorSettings
    {
        protected IDictionary<string, CursorDefinition> CursorMap
        {
            get
            {
                lock (this)
                {
                    if (_cursorMap != null) return _cursorMap;

                    _cursorMap = new Dictionary<string, CursorDefinition>();

                    foreach (var cursor in _cursors.Concat<CursorDefinition>(_animatedCursors))
                    {
                        _cursorMap.Add(cursor.Name, cursor);
                    }

                    return _cursorMap;
                }
            }
        }

        [SerializeField] private StaticCursor[] _cursors;

        [SerializeField] private AnimatedCursor[] _animatedCursors;

        private IDictionary<string, CursorDefinition> _cursorMap;

        public bool Contains(string key) => CursorMap.ContainsKey(key);

        public CursorDefinition this[string key] => CursorMap[key];

        private void OnEnable()
        {
            _cursors = _cursors?.OrderBy(c => c.Name).ToArray();
            _animatedCursors = _animatedCursors?.OrderBy(c => c.Name).ToArray();
        }

        private void OnValidate() => _cursorMap = null;

        private void OnDestroy() => _cursorMap = null;
    }
}

using System.Collections.Generic;
using System.Linq;
using Alensia.Core.Common;
using UnityEngine;

namespace Alensia.Core.UI.Cursor
{
    public class CursorSet : ScriptableObject, INamed, IDirectory<CursorDefinition>, IEditorSettings
    {
        public string Name => name;

        protected IDictionary<string, CursorDefinition> CursorMap
        {
            get
            {
                lock (this)
                {
                    if (_cursorMap != null) return _cursorMap;

                    _cursorMap = new Dictionary<string, CursorDefinition>();

                    foreach (var cursor in _cursors.Concat<CursorDefinition>(_animatedCursors))
                    {
                        _cursorMap.Add(cursor.Name, cursor);
                    }

                    return _cursorMap;
                }
            }
        }

        [SerializeField] private StaticCursor[] _cursors;

        [SerializeField] private AnimatedCursor[] _animatedCursors;

        private IDictionary<string, CursorDefinition> _cursorMap;

        public bool Contains(string key) => CursorMap.ContainsKey(key);

        public CursorDefinition this[string key] => CursorMap[key];

        private void OnEnable()
        {
            _cursors = _cursors?.OrderBy(c => c.Name).ToArray();
            _animatedCursors = _animatedCursors?.OrderBy(c => c.Name).ToArray();
        }

        private void OnValidate() => _cursorMap = null;

        private void OnDestroy() => _cursorMap = null;
    }
}

Use file name as the name of a Cursor Set


using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace GUI.Utils
{
    internal class ConsoleTab
    {
        internal class MyLogger : TextWriter
        {
            private TextBox control;

            public MyLogger(TextBox control)
            {
                this.control = control;
            }

            public override Encoding Encoding => null;

            public override void WriteLine(string value)
            {
                var logLine = $"[{DateTime.Now.ToString("HH:mm:ss.fff")}] {value}\n";
                control.AppendText(logLine);
            }
        }

        public TabPage CreateTab()
        {
            var control = new TextBox
            {
                Dock = DockStyle.Fill,
                Multiline = true,
                ReadOnly = true,
                WordWrap = true,
                ScrollBars = ScrollBars.Vertical,
                BorderStyle = BorderStyle.None,
                BackColor = Color.Black,
                ForeColor = Color.WhiteSmoke,
            };

            var tab = new TabPage("Console");
            tab.Controls.Add(control);

            Console.SetOut(new MyLogger(control));

            return tab;
        }
    }
}

using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace GUI.Utils
{
    internal class ConsoleTab
    {
        internal class MyLogger : TextWriter
        {
            private TextBox control;

            public MyLogger(TextBox control)
            {
                this.control = control;
            }

            public override Encoding Encoding => null;

            public override void WriteLine(string value)
            {
                var logLine = $"[{DateTime.Now.ToString("HH:mm:ss.fff")}] {value}{Environment.NewLine}";
                control.AppendText(logLine);
            }
        }

        public TabPage CreateTab()
        {
            var control = new TextBox
            {
                Dock = DockStyle.Fill,
                Multiline = true,
                ReadOnly = true,
                WordWrap = true,
                ScrollBars = ScrollBars.Vertical,
                BorderStyle = BorderStyle.None,
                BackColor = Color.Black,
                ForeColor = Color.WhiteSmoke,
            };

            var tab = new TabPage("Console");
            tab.Controls.Add(control);

            Console.SetOut(new MyLogger(control));

            return tab;
        }
    }
}

Fix new lines in console

Fix new lines in console


using Avalonia.Controls;
using Avalonia.Markup.Xaml;
#pragma warning disable 4014

namespace ControlCatalog.Pages
{
    public class DialogsPage : UserControl
    {
        public DialogsPage()
        {
            this.InitializeComponent();
            this.FindControl<Button>("OpenFile").Click += delegate
            {
                new OpenFileDialog()
                {
                    Title = "Open file"
                }.ShowAsync(GetWindow());
            };
            this.FindControl<Button>("SaveFile").Click += delegate
            {
                new SaveFileDialog()
                {
                    Title = "Save file"
                }.ShowAsync(GetWindow());
            };
            this.FindControl<Button>("SelectFolder").Click += delegate
            {
                new OpenFolderDialog()
                {
                    Title = "Select folder"
                }.ShowAsync(GetWindow());
            };
            this.FindControl<Button>("DecoratedWindow").Click += delegate
            {
                new DecoratedWindow().Show();
            };
            this.FindControl<Button>("DecoratedWindowDialog").Click += delegate
            {
                new DecoratedWindow().ShowDialog(GetWindow());
            };
            this.FindControl<Button>("Dialog").Click += delegate
                {
                    new MainWindow().ShowDialog(GetWindow());
                };

        }

        Window GetWindow() => (Window)this.VisualRoot;

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    }
}

using Avalonia.Controls;
using Avalonia.Markup.Xaml;
#pragma warning disable 4014

namespace ControlCatalog.Pages
{
    public class DialogsPage : UserControl
    {
        public DialogsPage()
        {
            this.InitializeComponent();
            this.FindControl<Button>("OpenFile").Click += delegate
            {
                new OpenFileDialog()
                {
                    Title = "Open file"
                }.ShowAsync(GetWindow());
            };
            this.FindControl<Button>("SaveFile").Click += delegate
            {
                new SaveFileDialog()
                {
                    Title = "Save file"
                }.ShowAsync(GetWindow());
            };
            this.FindControl<Button>("SelectFolder").Click += delegate
            {
                new OpenFolderDialog()
                {
                    Title = "Select folder"
                }.ShowAsync(GetWindow());
            };
            this.FindControl<Button>("DecoratedWindow").Click += delegate
            {
                new DecoratedWindow().Show();
            };
            this.FindControl<Button>("DecoratedWindowDialog").Click += delegate
            {
                new DecoratedWindow().ShowDialog(GetWindow());
            };
            this.FindControl<Button>("Dialog").Click += delegate
                {
                    var window = new Window();
                    window.Height = 200;
                    window.Width = 200;
                    window.Content = new TextBlock { Text = "Hello world!" };
                    window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    window.ShowDialog(GetWindow());
                };
        }

        Window GetWindow() => (Window)this.VisualRoot;

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    }
}

Modify DialogsPage to allow testing of startup location.


// Copyright 2015 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.
namespace ShoutLib
{
    internal class Constants
    {
        public const string ProjectId = "YOUR-PROJECT-ID";
        public const string ServiceAccountEmail = "YOUR-SERVICE-ACCOUNT@developer.gserviceaccount.com";
        public const string ServiceAccountP12KeyPath = @"C:\PATH\TO\YOUR\FILE.p12";
        public const string Subscription = "shout-tasks-workers";
        public const string UserAgent = "Shouter";
    }
}

Add copyright to one more .cs source file.

Change-Id: I5e5e9b80ae3a14cdb64ebc368a880a4f09bdd453


// 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 osu.Framework.Localisation;
using osu.Game.Online.API.Requests;
using osu.Game.Overlays.Profile.Sections.Beatmaps;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.Profile.Sections
{
    public class BeatmapsSection : ProfileSection
    {
        public override LocalisableString Title => UsersStrings.ShowExtraBeatmapsTitle;

        public override string Identifier => @"beatmaps";

        public BeatmapsSection()
        {
            Children = new[]
            {
                new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, UsersStrings.ShowExtraBeatmapsFavouriteTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Ranked, User, UsersStrings.ShowExtraBeatmapsRankedTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Loved, User, UsersStrings.ShowExtraBeatmapsLovedTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Pending, User, UsersStrings.ShowExtraBeatmapsPendingTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Guest, User, "Guest Participation Beatmaps"),
                new PaginatedBeatmapContainer(BeatmapSetType.Graveyard, User, UsersStrings.ShowExtraBeatmapsGraveyardTitle)
            };
        }
    }
}

// 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 osu.Framework.Localisation;
using osu.Game.Online.API.Requests;
using osu.Game.Overlays.Profile.Sections.Beatmaps;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.Profile.Sections
{
    public class BeatmapsSection : ProfileSection
    {
        public override LocalisableString Title => UsersStrings.ShowExtraBeatmapsTitle;

        public override string Identifier => @"beatmaps";

        public BeatmapsSection()
        {
            Children = new[]
            {
                new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, UsersStrings.ShowExtraBeatmapsFavouriteTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Ranked, User, UsersStrings.ShowExtraBeatmapsRankedTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Loved, User, UsersStrings.ShowExtraBeatmapsLovedTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Pending, User, UsersStrings.ShowExtraBeatmapsPendingTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Guest, User, UsersStrings.ShowExtraBeatmapsGuestTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Graveyard, User, UsersStrings.ShowExtraBeatmapsGraveyardTitle)
            };
        }
    }
}

Use localised string for guest participation beatmaps header


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(String twilioAccountSid, String twilioAuthToken, String twilioSourceNumber)
        {
            this._twilioAccountSId = twilioAccountSid;
            this._twilioAuthToken = twilioAuthToken;
            this._twilioSourceNumber = twilioSourceNumber;
        }

        public Task SendAsync(SMSNotification notification)
        {
            // TODO Add logging

            // 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);
        }
    }
}

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(String twilioAccountSid, String twilioAuthToken, String twilioSourceNumber)
        {
            this._twilioAccountSId = twilioAccountSid;
            this._twilioAuthToken = twilioAuthToken;
            this._twilioSourceNumber = twilioSourceNumber;
        }

        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);
            }
        }
    }
}

Add a timer and log to sms sending

Add a timer and log to sms sending


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

namespace IPOCS_Programmer.ObjectTypes
{
    public class GenericInput : BasicObject
    {
        public override byte objectTypeId { get { return 11; } }

        public byte inputPin { get; set; }

        public byte debounceTime { get; set; }

        protected override void Serialize(List<byte> buffer)
        {
            buffer.Add(this.inputPin);
            buffer.Add(this.debounceTime);
        }
    }
}

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

namespace IPOCS_Programmer.ObjectTypes
{
    public class GenericInput : BasicObject
    {
        public override byte objectTypeId { get { return 11; } }

        public byte inputPin { get; set; }

        public byte debounceTime { get; set; }

        public byte releaseHoldTime { get; set; }

        protected override void Serialize(List<byte> buffer)
        {
            buffer.Add(this.inputPin);
            buffer.Add(this.debounceTime);
            buffer.Add(this.releaseHoldTime);
        }
    }
}

Fix support for input and fix some bugs

Fix support for input and fix some bugs


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

using Xunit;
using System.IO;

namespace ParkingSpace.Facts.Sample {
  public class SampleFileFacts {

    public static IEnumerable<object[]> getFilesFromCurrentFolder() {
      var di = new DirectoryInfo(Environment.CurrentDirectory);
      foreach(var file in di.EnumerateFiles()) {
        yield return new object[] { file.Name };
      }
    }

    [Trait("Category", "Sample")]
    [Theory]
    [MemberData("getFilesFromCurrentFolder")]
    //[InlineData("sample1.txt")]
    //[InlineData("sample20.exe")]
    public void FileNameMustHasThreeCharactersExtension(string fileName) {
      var length = Path.GetExtension(fileName).Length;

      Assert.Equal(4, length); // include 'dot' in front of the extension (.dll, .exe)
    }
  }
}

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

using Xunit;
using System.IO;

namespace ParkingSpace.Facts.Sample {
  public class SampleFileFacts {

    public static IEnumerable<object[]> getFilesFromCurrentFolder() {
      var di = new DirectoryInfo(Environment.CurrentDirectory);
      foreach(var file in di.EnumerateFiles()) {
        yield return new object[] { file.Name };
      }
    }

    //[Trait("Category", "Sample")]
    //[Theory]
    //[MemberData("getFilesFromCurrentFolder")]
    ////[InlineData("sample1.txt")]
    ////[InlineData("sample20.exe")]
    //public void FileNameMustHasThreeCharactersExtension(string fileName) {
    //  var length = Path.GetExtension(fileName).Length;

    //  Assert.Equal(4, length); // include 'dot' in front of the extension (.dll, .exe)
    //}
  }
}

Comment out the sample tests

Comment out the sample tests


using ReactiveMarrow;
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;

namespace Espera.Core
{
    internal static class ReactiveHelpers
    {
        /// <summary>
        /// Takes the left observable and combines it with the latest value of the right observable.
        /// This method is like <see cref="Observable.CombineLatest{TSource1,TSource2,TResult}"/>,
        /// except it propagates only when the value of the left observable sequence changes.
        /// </summary>
        public static IObservable<TResult> Left<TLeft, TRight, TResult>(this IObservable<TLeft> left, IObservable<TRight> right, Func<TLeft, TRight, TResult> resultSelector)
        {
            TRight latest = default(TRight);
            bool initialized = false;

            var disp = new CompositeDisposable(2);

            right.Subscribe(x =>
            {
                latest = x;
                initialized = true;
            }).DisposeWith(disp);

            return Observable.Create<TResult>(o =>
            {
                left.Subscribe(x =>
                {
                    if (initialized)
                    {
                        o.OnNext(resultSelector(x, latest));
                    }
                }, o.OnError, o.OnCompleted).DisposeWith(disp);

                return disp;
            });
        }
    }
}

using ReactiveMarrow;
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;

namespace Espera.Core
{
    internal static class ReactiveHelpers
    {
        /// <summary>
        /// Takes the left observable and combines it with the latest value of the right observable.
        /// This method is like <see cref="Observable.CombineLatest{TSource1,TSource2,TResult}"/>,
        /// except it propagates only when the value of the left observable sequence changes.
        /// </summary>
        public static IObservable<TResult> Left<TLeft, TRight, TResult>(this IObservable<TLeft> left, IObservable<TRight> right, Func<TLeft, TRight, TResult> resultSelector)
        {
            TRight latest = default(TRight);
            bool initialized = false;

            var disp = new CompositeDisposable(2);

            right.Subscribe(x =>
            {
                latest = x;
                initialized = true;
            }).DisposeWith(disp);

            return Observable.Create<TResult>(o =>
            {
                left.Where(_ => initialized)
                    .Subscribe(x => o.OnNext(resultSelector(x, latest)),
                        o.OnError, o.OnCompleted)
                    .DisposeWith(disp);

                return disp;
            });
        }
    }
}

Save all the lines of code!

Save all the lines of code!


/*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestUsefullFunctions
{
  [TestClass]
  public class UnitTest1
  {
    [TestMethod]
    public void TestMethod1()
    {
      Assert.IsTrue(true);
    }
  }
}

Add license to new unit test class file

Add license to new unit test class file


using System;
using System.IO;
using System.Linq;
using Mitternacht.Common.Collections;
using Newtonsoft.Json;
using NLog;

namespace Mitternacht.Resources
{
    public class CommandStrings
    {
        private static readonly Logger Log;
        private const string CmdStringPath = @"./_strings/commandstrings.json";
        private static ConcurrentHashSet<CommandStringsModel> _commandStrings;

        static CommandStrings() {
            Log = LogManager.GetCurrentClassLogger();
            LoadCommandStrings();
        }

        public static bool LoadCommandStrings() {
            try {
                var json = File.ReadAllText(CmdStringPath);
                _commandStrings = JsonConvert.DeserializeObject<ConcurrentHashSet<CommandStringsModel>>(json);
            }
            catch (Exception e) {
                Log.Error(e);
                return false;
            }
            return true;
        }

        public static CommandStringsModel GetCommandStringModel(string name)
            => _commandStrings.FirstOrDefault(c => c.Name == name) ?? new CommandStringsModel { Name = name, Command = name + "_cmd" };
    }
}

using System;
using System.IO;
using System.Linq;
using Mitternacht.Common.Collections;
using Newtonsoft.Json;
using NLog;

namespace Mitternacht.Resources
{
    public class CommandStrings
    {
        private static readonly Logger Log;
        private const string CmdStringPath = @"./_strings/commandstrings.json";
        private static ConcurrentHashSet<CommandStringsModel> _commandStrings;

        static CommandStrings() {
            Log = LogManager.GetCurrentClassLogger();
            LoadCommandStrings();
        }

        public static void LoadCommandStrings() {
            try {
                var json = File.ReadAllText(CmdStringPath);
                _commandStrings = JsonConvert.DeserializeObject<ConcurrentHashSet<CommandStringsModel>>(json);
            }
            catch (Exception e) {
				Log.Error(e);
			}
		}

        public static CommandStringsModel GetCommandStringModel(string name)
            => _commandStrings.FirstOrDefault(c => c.Name == name) ?? new CommandStringsModel { Name = name, Command = name + "_cmd" };
    }
}

Change return type from bool to void.

Change return type from bool to void.


using Serenity.ComponentModel;
using Serenity.Data;
using System;
using System.ComponentModel;
using System.Reflection;

namespace Serenity.PropertyGrid
{
    public partial class LocalizablePropertyProcessor : PropertyProcessor
    {
        private ILocalizationRowHandler localizationRowHandler;

        public override void Initialize()
        {
            if (BasedOnRow == null)
                return;

            var attr = BasedOnRow.GetType().GetCustomAttribute<LocalizationRowAttribute>(false);

            if (attr != null)
                localizationRowHandler = Activator.CreateInstance(typeof(LocalizationRowHandler<>)
                    .MakeGenericType(BasedOnRow.GetType())) as ILocalizationRowHandler;
        }

        public override void Process(IPropertySource source, PropertyItem item)
        {
            var attr = source.GetAttribute<LocalizableAttribute>();
            if (attr != null)
            {
                item.Localizable = true;
                return;
            }

            if (!ReferenceEquals(null, source.BasedOnField) &&
                localizationRowHandler != null &&
                localizationRowHandler.IsLocalized(source.BasedOnField))
            {
                item.Localizable = true;
            }
        }

        public override int Priority
        {
            get { return 15; }
        }
    }
}

using Serenity.ComponentModel;
using Serenity.Data;
using System;
using System.ComponentModel;
using System.Reflection;

namespace Serenity.PropertyGrid
{
    public partial class LocalizablePropertyProcessor : PropertyProcessor
    {
        private ILocalizationRowHandler localizationRowHandler;

        public override void Initialize()
        {
            if (BasedOnRow == null)
                return;

            var attr = BasedOnRow.GetType().GetCustomAttribute<LocalizationRowAttribute>(false);

            if (attr != null)
                localizationRowHandler = Activator.CreateInstance(typeof(LocalizationRowHandler<>)
                    .MakeGenericType(BasedOnRow.GetType())) as ILocalizationRowHandler;
        }

        public override void Process(IPropertySource source, PropertyItem item)
        {
            var attr = source.GetAttribute<LocalizableAttribute>();
            if (attr != null)
            {
                if (item.IsLocalizable)
                    item.Localizable = true;
                return;
            }

            if (!ReferenceEquals(null, source.BasedOnField) &&
                localizationRowHandler != null &&
                localizationRowHandler.IsLocalized(source.BasedOnField))
            {
                item.Localizable = true;
            }
        }

        public override int Priority
        {
            get { return 15; }
        }
    }
}

Set property item as localizable only if Localizable attribute value is true


using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;

namespace RohlikAPITests
{
    [TestClass]
    public class PersistentSessionHttpClientTests
    {
        [TestMethod]
        public void GetTest()
        {
            const string testCookieName = "testCookieName";
            const string testCookieValue = "testCookieValue";

            var client = new PersistentSessionHttpClient();

            client.Get($"http://httpbin.org/cookies/set/{testCookieName}/{testCookieValue}");
            var response = client.Get("http://httpbin.org/cookies");

            Assert.IsTrue(response.Contains(testCookieName) && response.Contains(testCookieValue), $"Response should contain both {testCookieName} and {testCookieValue}");
        }
    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;

namespace RohlikAPITests
{
    [TestClass]
    public class PersistentSessionHttpClientTests
    {
        [TestMethod]
        public void HTTPGet_PersistsCookies()
        {
            const string testCookieName = "testCookieName";
            const string testCookieValue = "testCookieValue";

            var client = new PersistentSessionHttpClient();

            client.Get($"http://httpbin.org/cookies/set/{testCookieName}/{testCookieValue}");
            var response = client.Get("http://httpbin.org/cookies");

            Assert.IsTrue(response.Contains(testCookieName) && response.Contains(testCookieValue), $"Response should contain both {testCookieName} and {testCookieValue}");
        }
    }
}

Improve persistent session client test

Improve persistent session client test


using System;
using System.Linq;

namespace MQTTnet.Extensions
{
    public static class UserPropertyExtension
    {
        public static string GetUserProperty(this MqttApplicationMessage message, string propertyName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
        {
            return message?.UserProperties?.SingleOrDefault(up => up.Name.Equals(propertyName, comparisonType))?.Value;
        }

        public static T GetUserProperty<T>(this MqttApplicationMessage message, string propertyName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
        {
            return (T) Convert.ChangeType(GetUserProperty(message, propertyName, comparisonType), typeof(T));
        }
    }
}

using System;
using System.Linq;

namespace MQTTnet.Extensions
{
    public static class UserPropertyExtension
    {
        public static string GetUserProperty(this MqttApplicationMessage message, string propertyName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
        {
            if (message == null) throw new ArgumentNullException(nameof(message));
            if (propertyName == null) throw new ArgumentNullException(nameof(propertyName));

            return message.UserProperties?.SingleOrDefault(up => up.Name.Equals(propertyName, comparisonType))?.Value;
        }

        public static T GetUserProperty<T>(this MqttApplicationMessage message, string propertyName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
        {
            var value = GetUserProperty(message, propertyName, comparisonType);

            try
            {
                return (T) Convert.ChangeType(value, typeof(T));
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Cannot convert value({value}) of UserProperty({propertyName}) to {typeof(T).FullName}.", ex);
            }
        }
    }
}

Check parameters and add friendly exceptions.


// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------

using System;
using System.Linq;

using Microsoft.WindowsAzure.MobileServices.Test.Functional;
using Microsoft.WindowsAzure.MobileServices.TestFramework;

namespace Microsoft.WindowsAzure.MobileServices.Test
{
    [Tag("push")]
    public class PushUnit : TestBase
    {
        [TestMethod]
        public void InvalidBodyTemplateIfNotXml()
        {
            try
            {
                var registration = new TemplateRegistration("uri", "junkBodyTemplate", "testName");
            }
            catch (ArgumentException e)
            {
                // PASSES
            }
        }

        [TestMethod]
        public void InvalidBodyTemplateIfImproperXml()
        {
            try
            {
                var registration = new TemplateRegistration(
                    "uri",
                    "<foo><visual><binding template=\"ToastText01\"><text id=\"1\">$(message)</text></binding></visual></foo>",
                    "testName");
            }
            catch (ArgumentException e)
            {
                // PASSES
            }
        }
    }
}

// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------

using System;
using System.Linq;

using Microsoft.WindowsAzure.MobileServices.Test.Functional;
using Microsoft.WindowsAzure.MobileServices.TestFramework;

namespace Microsoft.WindowsAzure.MobileServices.Test
{
    [Tag("push")]
    public class PushUnit : TestBase
    {
        [TestMethod]
        public void InvalidBodyTemplateIfNotXml()
        {
            try
            {
                var registration = new TemplateRegistration("uri", "junkBodyTemplate", "testName");
                Assert.Fail("Expected templateBody that is not XML to throw ArgumentException");
            }
            catch (ArgumentException e)
            {
                // PASSES
            }
        }

        [TestMethod]
        public void InvalidBodyTemplateIfImproperXml()
        {
            try
            {
                var registration = new TemplateRegistration(
                    "uri",
                    "<foo><visual><binding template=\"ToastText01\"><text id=\"1\">$(message)</text></binding></visual></foo>",
                    "testName");
                Assert.Fail("Expected templateBody with unexpected first XML node to throw ArgumentException");
            }
            catch (ArgumentException e)
            {
                // PASSES
            }
        }
    }
}

Fix new unit test to fail if it does not throw properly