using System;
using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;

// Simple example script that subscribes to primary pointer changes and applies a cursor highlight to the current one.
public class PrimaryPointerHandlerExample : MonoBehaviour
{
    public GameObject CursorHighlight;

    private void OnEnable()
    {
        MixedRealityToolkit.InputSystem?.FocusProvider?.SubscribeToPrimaryPointerChanged(OnPrimaryPointerChanged, true);
    }

    private void OnPrimaryPointerChanged(IMixedRealityPointer oldPointer, IMixedRealityPointer newPointer)
    {
        if (CursorHighlight != null)
        {
            if (newPointer != null)
            {
                Transform parentTransform = newPointer.BaseCursor?.GameObjectReference?.transform;

                // If there's no cursor try using the controller pointer transform instead
                if (parentTransform == null)
                {
                    var controllerPointer = newPointer as BaseControllerPointer;
                    parentTransform = controllerPointer?.transform;
                }

                if (parentTransform != null)
                {
                    CursorHighlight.transform.SetParent(parentTransform, false);
                    CursorHighlight.SetActive(true);
                    return;
                }
            }

            CursorHighlight.SetActive(false);
            CursorHighlight.transform.SetParent(null, false);
        }
    }

    private void OnDisable()
    {
        MixedRealityToolkit.InputSystem?.FocusProvider?.UnsubscribeFromPrimaryPointerChanged(OnPrimaryPointerChanged);
        OnPrimaryPointerChanged(null, null);
    }
}

using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.Examples.Demos
{
    // Simple example script that subscribes to primary pointer changes and applies a cursor highlight to the current one.
    public class PrimaryPointerHandlerExample : MonoBehaviour
    {
        public GameObject CursorHighlight;

        private void OnEnable()
        {
            MixedRealityToolkit.InputSystem?.FocusProvider?.SubscribeToPrimaryPointerChanged(OnPrimaryPointerChanged, true);
        }

        private void OnPrimaryPointerChanged(IMixedRealityPointer oldPointer, IMixedRealityPointer newPointer)
        {
            if (CursorHighlight != null)
            {
                if (newPointer != null)
                {
                    Transform parentTransform = newPointer.BaseCursor?.GameObjectReference?.transform;

                    // If there's no cursor try using the controller pointer transform instead
                    if (parentTransform == null)
                    {
                        var controllerPointer = newPointer as BaseControllerPointer;
                        parentTransform = controllerPointer?.transform;
                    }

                    if (parentTransform != null)
                    {
                        CursorHighlight.transform.SetParent(parentTransform, false);
                        CursorHighlight.SetActive(true);
                        return;
                    }
                }

                CursorHighlight.SetActive(false);
                CursorHighlight.transform.SetParent(null, false);
            }
        }

        private void OnDisable()
        {
            MixedRealityToolkit.InputSystem?.FocusProvider?.UnsubscribeFromPrimaryPointerChanged(OnPrimaryPointerChanged);
            OnPrimaryPointerChanged(null, null);
        }
    }
}

Fix the broken NuGet build.

Fix the broken NuGet build.

It's been a few days of us not building NuGet packages - here's what happened.

We hit a CI outage earlier in the week caused by an upstream Azure DevOps issue (a bad nuget push package was pushed out). Our build was broken for a couple of days, during which we still had changes going in (mostly we were judging by green-ness of mrtk_pr, which is identical to CI except it doesn't produce and publish NuGet packages).

The problem is, without coverage on the NuGet building, we didn't know that we broke the nuget packages until the upstream nuget push package got fixed.

This fix in particular is simply because the asset retargeter assumes that every single class/object in the MRTK is prefixed by the MRTK namespace. This is a fairly reasonable assumption to make, and it throws when it finds something that violates it (so that we can then fix it)

I will follow up here and do work to make sure that the build breaks when this happens, instead of just showing warnings.


using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Mollie.Api.Models.Payment {
    [JsonConverter(typeof(StringEnumConverter))]
    public enum PaymentMethod {
        [EnumMember(Value = "ideal")] Ideal,
        [EnumMember(Value = "creditcard")] CreditCard,
        [EnumMember(Value = "mistercash")] MisterCash,
        [EnumMember(Value = "sofort")] Sofort,
        [EnumMember(Value = "banktransfer")] BankTransfer,
        [EnumMember(Value = "directdebit")] DirectDebit,
        [EnumMember(Value = "belfius")] Belfius,
        [EnumMember(Value = "bitcoin")] Bitcoin,
        [EnumMember(Value = "podiumcadeaukaart")] PodiumCadeaukaart,
        [EnumMember(Value = "paypal")] PayPal,
        [EnumMember(Value = "paysafecard")] PaySafeCard,
        [EnumMember(Value = "kbc")] Kbc,
        [EnumMember(Value = "giftcard")] GiftCard,
        [EnumMember(Value = "inghomepay")] IngHomePay,
    }
}

using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Mollie.Api.Models.Payment {
    [JsonConverter(typeof(StringEnumConverter))]
    public enum PaymentMethod {
        [EnumMember(Value = "ideal")] Ideal,
        [EnumMember(Value = "creditcard")] CreditCard,
        [EnumMember(Value = "mistercash")] MisterCash,
        [EnumMember(Value = "sofort")] Sofort,
        [EnumMember(Value = "banktransfer")] BankTransfer,
        [EnumMember(Value = "directdebit")] DirectDebit,
        [EnumMember(Value = "belfius")] Belfius,
        [EnumMember(Value = "bitcoin")] Bitcoin,
        [EnumMember(Value = "podiumcadeaukaart")] PodiumCadeaukaart,
        [EnumMember(Value = "paypal")] PayPal,
        [EnumMember(Value = "paysafecard")] PaySafeCard,
        [EnumMember(Value = "kbc")] Kbc,
        [EnumMember(Value = "giftcard")] GiftCard,
        [EnumMember(Value = "inghomepay")] IngHomePay,
		[EnumMember(Value = "refund")] Refund,
    }
}

Add Refund as paymentmethod so we can use it in SettlementPeriodRevenue.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace KenticoInspector.WebApplication
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // 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();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace KenticoInspector.WebApplication
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSpaStaticFiles(configuration => {
                configuration.RootPath = "ClientApp/dist";
            });
        }

        // 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();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseMvc();
            app.UseSpa(spa => {
                spa.Options.SourcePath = "ClientApp";

                //if (env.IsDevelopment()) {
                //    spa.UseProxyToSpaDevelopmentServer("http://localhost:1234");
                //}
            });
        }
    }
}

Add basics to load compiled client app

Add basics to load compiled client app


@{
    var ownerName = Environment.GetEnvironmentVariable("WEBSITE_OWNER_NAME") ?? "";
    var subscriptionId = ownerName;
    var resourceGroup = Environment.GetEnvironmentVariable("WEBSITE_RESOURCE_GROUP") ?? "";
    var siteName = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "";

    var index = ownerName.IndexOf('+');
    if (index >= 0)
    {
        subscriptionId = ownerName.Substring(0, index);
    }

    string detectorPath;
    if (Kudu.Core.Helpers.OSDetector.IsOnWindows())
    {
        detectorPath = "diagnostics%2Favailability%2Fanalysis";
    }
    else
    {
        detectorPath = "detectors%2FLinuxAppDown";
    }

    var detectorDeepLink = "https://portal.azure.com/?websitesextension_ext=asd.featurePath%3D"
            + detectorPath
            + "#resource/subscriptions/" + subscriptionId
            + "/resourceGroups/" + resourceGroup
            + "/providers/Microsoft.Web/sites/"
            + siteName
            + "/troubleshoot";

    Response.Redirect(detectorDeepLink);
}

@{
    var ownerName = Environment.GetEnvironmentVariable("WEBSITE_OWNER_NAME") ?? "";
    var subscriptionId = ownerName;
    var resourceGroup = Environment.GetEnvironmentVariable("WEBSITE_RESOURCE_GROUP") ?? "";
    var siteName = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "";
    var hostName = Environment.GetEnvironmentVariable("HTTP_HOST") ?? "";

    var index = ownerName.IndexOf('+');
    if (index >= 0)
    {
        subscriptionId = ownerName.Substring(0, index);
    }

    string detectorPath;
    if (Kudu.Core.Helpers.OSDetector.IsOnWindows())
    {
        detectorPath = "diagnostics%2Favailability%2Fanalysis";
    }
    else
    {
        detectorPath = "detectors%2FLinuxAppDown";
    }

    var hostNameIndex = hostName.IndexOf('.');
    if (hostNameIndex >= 0)
    {
        hostName = hostName.Substring(0, hostNameIndex);
    }

    var runtimeSuffxIndex = siteName.IndexOf("__");
    if (runtimeSuffxIndex >= 0)
    {
        siteName = siteName.Substring(0, runtimeSuffxIndex);
    }

    // Get the slot name
    if (!hostName.Equals(siteName, StringComparison.CurrentCultureIgnoreCase))
    {
        var slotNameIndex = siteName.Length;
        if (hostName.Length > slotNameIndex && hostName[slotNameIndex] == '-')
        {
            // Fix up hostName by replacing "-SLOTNAME" with "/slots/SLOTNAME"
            var slotName = hostName.Substring(slotNameIndex + 1);
            hostName = hostName.Substring(0, slotNameIndex) + "/slots/" + slotName;
        }
    }

    var detectorDeepLink = "https://portal.azure.com/?websitesextension_ext=asd.featurePath%3D"
            + detectorPath
            + "#resource/subscriptions/" + subscriptionId
            + "/resourceGroups/" + resourceGroup
            + "/providers/Microsoft.Web/sites/"
            + hostName
            + "/troubleshoot";

    Response.Redirect(detectorDeepLink);
}

Fix detectors link to the slot

Fix detectors link to the slot


using System.Numerics;

namespace DynamixelServo.Quadruped
{
    public static class Vector3Extensions
    {
        public static Vector3 Normal(this Vector3 vector)
        {
            return Vector3.Normalize(vector);
        }

        public static bool Similar(this Vector3 a, Vector3 b, float marginOfError = float.Epsilon)
        {
            return Vector3.Distance(a, b) <= marginOfError;
        }
    }
}

using System.Numerics;

namespace DynamixelServo.Quadruped
{
    public static class Vector3Extensions
    {
        public static Vector3 Normal(this Vector3 vector)
        {
            return Vector3.Normalize(vector);
        }

        public static bool Similar(this Vector3 a, Vector3 b, float marginOfError = float.Epsilon)
        {
            return Vector3.Distance(a, b) <= marginOfError;
        }

        public static Vector3 MoveTowards(this Vector3 current, Vector3 target, float distance)
        {
            var transport = target - current;
            var len = transport.Length();
            if (len < distance)
            {
                return target;
            }
            return current + transport.Normal() * distance;
        }
    }
}

Add move towards method for vectors

Add move towards method for vectors


using System;
using System.Diagnostics;

namespace Spiffy.Monitoring
{
    public static class Behavior
    {
        static Action<Level, string> _loggingAction;

        ///
        /// Whether or not to remove newline characters from logged values.
        ///
        /// <returns>
        /// true if newline characters will be removed from logged
        /// values, false otherwise.
        /// </returns>
        public static bool RemoveNewlines { get; set; }

        public static void UseBuiltInLogging(BuiltInLogging behavior)
        {
            switch (behavior)
            {
                case Monitoring.BuiltInLogging.Console:
                    _loggingAction = (level, message) => Console.WriteLine(message);
                    break;
                case Monitoring.BuiltInLogging.Trace:
                    _loggingAction = (level, message) => Trace.WriteLine(message);
                    break;
                default:
                    throw new NotSupportedException($"{behavior} is not supported");
            }

        }

        public static void UseCustomLogging(Action<Level, string> loggingAction)
        {
            _loggingAction = loggingAction;
        }

        internal static Action<Level, string> GetLoggingAction()
        {
            return _loggingAction;
        }
    }

    public enum BuiltInLogging
    {
        Trace,
        Console
    }
}

using System;
using System.Diagnostics;

namespace Spiffy.Monitoring
{
    public static class Behavior
    {
        static Action<Level, string> _loggingAction;

        ///
        /// Whether or not to remove newline characters from logged values.
        ///
        /// <returns>
        /// true if newline characters will be removed from logged
        /// values, false otherwise.
        /// </returns>
        public static bool RemoveNewlines { get; set; }

        public static void UseBuiltInLogging(BuiltInLogging behavior)
        {
            switch (behavior)
            {
                case Monitoring.BuiltInLogging.Console:
                    _loggingAction = (level, message) =>
                    {
                        if (level == Level.Error)
                        {
                            Console.Error.WriteLine(message);
                        }
                        else
                        {
                            Console.WriteLine(message);
                        }
                    };
                    break;
                case Monitoring.BuiltInLogging.Trace:
                    _loggingAction = (level, message) =>
                    {
                        switch (level)
                        {
                            case Level.Info:
                                Trace.TraceInformation(message);
                                break;
                            case Level.Warning:
                                Trace.TraceWarning(message);
                                break;
                            case Level.Error:
                                Trace.TraceError(message);
                                break;
                            default:
                                Trace.WriteLine(message);
                                break;
                        }
                    };
                    break;
                default:
                    throw new NotSupportedException($"{behavior} is not supported");
            }
        }

        public static void UseCustomLogging(Action<Level, string> loggingAction)
        {
            _loggingAction = loggingAction;
        }

        internal static Action<Level, string> GetLoggingAction()
        {
            return _loggingAction;
        }
    }

    public enum BuiltInLogging
    {
        Trace,
        Console
    }
}

Update default logging behaviors to use functions that correspond to log level


//Copyright (c) 2016 Artem A. Mavrin and other contributors

using UnrealBuildTool;

public class DialogueSystem : ModuleRules
{
	public DialogueSystem(TargetInfo Target)
	{

		PrivateIncludePaths.AddRange(
			new string[] {"DialogueSystem/Private"});

        PublicDependencyModuleNames.AddRange(
			new string[]
			{
				"Core",
				"CoreUObject",
				"Engine",
                "UMG",
                "SlateCore",
                "Slate",
                "AIModule"
			}
		);
	}
}

//Copyright (c) 2016 Artem A. Mavrin and other contributors

using UnrealBuildTool;

public class DialogueSystem : ModuleRules
{
	public DialogueSystem(TargetInfo Target)
	{

		PrivateIncludePaths.AddRange(
			new string[] {"DialogueSystem/Private"});

        PublicDependencyModuleNames.AddRange(
			new string[]
			{
				"Core",
				"CoreUObject",
				"Engine",
                "UMG",
                "SlateCore",
                "Slate",
                "AIModule",
                "GameplayTasks"
			}
		);
	}
}

Fix build issues with 4.12

Fix build issues with 4.12


using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;

namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms
{
    public class DefaultSafeNamespaceValueFormModel : IValueForm
    {
        public DefaultSafeNamespaceValueFormModel()
        {
        }

        public static readonly string FormName = "safe_namespace";

        public virtual string Identifier => FormName;

        public string Name => Identifier;

        public IValueForm FromJObject(string name, JObject configuration)
        {
            throw new NotImplementedException();
        }

        public virtual string Process(IReadOnlyDictionary<string, IValueForm> forms, string value)
        {
            string workingValue = Regex.Replace(value, @"(^\s+|\s+$)", "");
            workingValue = Regex.Replace(workingValue, @"(((?<=\.)|^)(?=\d)|[^\w\.])", "_");

            return workingValue;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;

namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms
{
    public class DefaultSafeNamespaceValueFormModel : IValueForm
    {
        public DefaultSafeNamespaceValueFormModel()
        {
        }

        public static readonly string FormName = "safe_namespace";

        public virtual string Identifier => FormName;

        public string Name => Identifier;

        public IValueForm FromJObject(string name, JObject configuration)
        {
            throw new NotImplementedException();
        }

        public virtual string Process(IReadOnlyDictionary<string, IValueForm> forms, string value)
        {
            string workingValue = Regex.Replace(value, @"(^\s+|\s+$)", "");
            workingValue = Regex.Replace(workingValue, @"(((?<=\.)|^)((?=\d)|\.)|[^\w\.])", "_");

            return workingValue;
        }
    }
}

Update expression to match dots following dots


using System.Collections.Generic;

namespace SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration
{
    public class EmployerApprenticeshipsServiceConfiguration
    {
        public CompaniesHouseConfiguration CompaniesHouse { get; set; }
        public EmployerConfiguration Employer { get; set; }
        public string  ServiceBusConnectionString { get; set; }
        public IdentityServerConfiguration Identity { get; set; }
        public SmtpConfiguration SmtpServer { get; set; }

        public string DashboardUrl { get; set; }

        public HmrcConfiguration Hmrc { get; set; }
    }

    public class HmrcConfiguration
    {
        public string BaseUrl { get; set; }
        public string ClientId { get; set; }
        public string Scope { get; set; }
        public string ClientSecret { get; set; }
    }

    public class IdentityServerConfiguration
    {
        public bool UseFake { get; set; }
        public string ClientId { get; set; }
        public string ClientSecret { get; set; }
        public string BaseAddress { get; set; }
    }

    public class EmployerConfiguration
    {
        public string DatabaseConnectionString { get; set; }
    }

    public class CompaniesHouseConfiguration
    {
        public string ApiKey { get; set; }
    }

    public class SmtpConfiguration
    {
        public string ServerName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Port { get; set; }
    }
}

using System.Collections.Generic;

namespace SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration
{
    public class EmployerApprenticeshipsServiceConfiguration
    {
        public CompaniesHouseConfiguration CompaniesHouse { get; set; }
        public EmployerConfiguration Employer { get; set; }
        public string  ServiceBusConnectionString { get; set; }
        public IdentityServerConfiguration Identity { get; set; }
        public SmtpConfiguration SmtpServer { get; set; }

        public string DashboardUrl { get; set; }

        public HmrcConfiguration Hmrc { get; set; }
    }

    public class HmrcConfiguration
    {
        public string BaseUrl { get; set; }
        public string ClientId { get; set; }
        public string Scope { get; set; }
        public string ClientSecret { get; set; }

        public bool DuplicatesCheck { get; set; }
    }

    public class IdentityServerConfiguration
    {
        public bool UseFake { get; set; }
        public string ClientId { get; set; }
        public string ClientSecret { get; set; }
        public string BaseAddress { get; set; }
    }

    public class EmployerConfiguration
    {
        public string DatabaseConnectionString { get; set; }
    }

    public class CompaniesHouseConfiguration
    {
        public string ApiKey { get; set; }
    }

    public class SmtpConfiguration
    {
        public string ServerName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Port { get; set; }
    }
}

Add new config value for testing scenarios related to duplicate PAYE schemes. This will be deleted


namespace TestMoya.Runner.Runners
{
    using System;
    using System.Reflection;
    using Moq;
    using Moya.Attributes;
    using Moya.Models;
    using Moya.Runner.Runners;
    using Xunit;

    public class TimerDecoratorTests
    {
        private readonly Mock<ITestRunner> testRunnerMock;
        private TimerDecorator timerDecorator;

        public TimerDecoratorTests()
        {
            testRunnerMock = new Mock<ITestRunner>();
        }

        [Fact]
        public void TimerDecoratorExecuteRunsMethod()
        {
            timerDecorator = new TimerDecorator(testRunnerMock.Object);
            bool methodRun = false;
            MethodInfo method = ((Action)(() => methodRun = true)).Method;
            testRunnerMock
                .Setup(x => x.Execute(method))
                .Callback(() => methodRun = true)
                .Returns(new TestResult());

            timerDecorator.Execute(method);

            Assert.True(methodRun);
        }

        [Fact]
        public void TimerDecoratorExecuteAddsDurationToResult()
        {
            MethodInfo method = ((Action)TestClass.MethodWithMoyaAttribute).Method;
            timerDecorator = new TimerDecorator(new StressTestRunner());

            var result = timerDecorator.Execute(method);

            Assert.True(result.Duration > 0);
        }

        public class TestClass
        {
            [Stress]
            public static void MethodWithMoyaAttribute()
            {

            }
        }
    }
}

using System.Threading;

namespace TestMoya.Runner.Runners
{
    using System;
    using System.Reflection;
    using Moq;
    using Moya.Attributes;
    using Moya.Models;
    using Moya.Runner.Runners;
    using Xunit;

    public class TimerDecoratorTests
    {
        private readonly Mock<ITestRunner> testRunnerMock;
        private TimerDecorator timerDecorator;

        public TimerDecoratorTests()
        {
            testRunnerMock = new Mock<ITestRunner>();
        }

        [Fact]
        public void TimerDecoratorExecuteRunsMethod()
        {
            timerDecorator = new TimerDecorator(testRunnerMock.Object);
            bool methodRun = false;
            MethodInfo method = ((Action)(() => methodRun = true)).Method;
            testRunnerMock
                .Setup(x => x.Execute(method))
                .Callback(() => methodRun = true)
                .Returns(new TestResult());

            timerDecorator.Execute(method);

            Assert.True(methodRun);
        }

        [Fact]
        public void TimerDecoratorExecuteAddsDurationToResult()
        {
            MethodInfo method = ((Action)TestClass.MethodWithMoyaAttribute).Method;
            timerDecorator = new TimerDecorator(new StressTestRunner());

            var result = timerDecorator.Execute(method);

            Assert.True(result.Duration > 0);
        }

        public class TestClass
        {
            [Stress]
            public static void MethodWithMoyaAttribute()
            {
                Thread.Sleep(1);
            }
        }
    }
}

Make sure timerdecoratortest always succeeds


@using CGO.Web.Models
@model IEnumerable<SideBarSection>

            @foreach (var sideBarSection in Model)
            {

@sideBarSection.Title

                foreach (var link in sideBarSection.Links)
                {
                    @SideBarLink(link)
                }
            }

@helper SideBarLink(SideBarLink link)
{
    if (link.IsActive)
    {

@link.Title

    }
    else
    {

@link.Title

    }
}

Tidy up the display of the side bar.

Tidy up the display of the side bar.

Upgrade the classes to Bootstrap 3.


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

namespace Leeroy
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		static void Main(string[] args)
		{
			if (args.FirstOrDefault() == "/test")
			{
				Overseer overseer = new Overseer(new CancellationTokenSource().Token, "BradleyGrainger", "Configuration", "master");
				overseer.Run(null);
			}
			else
			{
				ServiceBase.Run(new ServiceBase[] { new Service() });
			}
		}
	}
}

using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;

namespace Leeroy
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		static void Main(string[] args)
		{
			if (args.FirstOrDefault() == "/test")
			{
				var tokenSource = new CancellationTokenSource();
				Overseer overseer = new Overseer(tokenSource.Token, "BradleyGrainger", "Configuration", "master");
				var task = Task.Factory.StartNew(overseer.Run, tokenSource, TaskCreationOptions.LongRunning);

				MessageBox(IntPtr.Zero, "Leeroy is running. Click OK to stop.", "Leeroy", 0);

				tokenSource.Cancel();
				try
				{
					task.Wait();
				}
				catch (AggregateException)
				{
					// TODO: verify this contains a single OperationCanceledException
				}

				// shut down
				task.Dispose();
				tokenSource.Dispose();
			}
			else
			{
				ServiceBase.Run(new ServiceBase[] { new Service() });
			}
		}

		[DllImport("user32.dll", CharSet = CharSet.Auto)]
		public static extern int MessageBox(IntPtr hWnd, String text, String caption, int options);
	}
}

Allow Leeroy to run until canceled in test mode.


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

using System;
using System.IO;
using Couchbase.Lite.DI;

namespace Couchbase.Lite.Support
{
    // NOTE: AppContext.BaseDirectory is not entirely reliable, but there is no other choice
    // It seems to usually be in the right place?

    [CouchbaseDependency]
    internal sealed class DefaultDirectoryResolver : IDefaultDirectoryResolver
    {
        #region IDefaultDirectoryResolver

        public string DefaultDirectory()
        {
            var dllDirectory = Path.GetDirectoryName(typeof(DefaultDirectoryResolver).Assembly.Location);
            return Path.Combine(dllDirectory, "CouchbaseLite");
        }

        #endregion
    }
}

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

using System;
using System.IO;
using Couchbase.Lite.DI;

namespace Couchbase.Lite.Support
{
    // NOTE: AppContext.BaseDirectory is not entirely reliable, but there is no other choice
    // It seems to usually be in the right place?

    [CouchbaseDependency]
    internal sealed class DefaultDirectoryResolver : IDefaultDirectoryResolver
    {
        #region IDefaultDirectoryResolver

        public string DefaultDirectory()
        {
            var baseDirectory = AppContext.BaseDirectory ??
                                throw new RuntimeException("BaseDirectory was null, cannot continue...");
            return Path.Combine(baseDirectory, "CouchbaseLite");
        }

        #endregion
    }
}

Revert change to .NET desktop default directory logic

It was causing DB creation in the nuget package folder
Fixes #1108


using System;
using System.IO;

using Manos;

//
//  This the default StaticContentModule that comes with all Manos apps
//  if you do not wish to serve any static content with Manos you can
//  remove its route handler from <YourApp>.cs's constructor and delete
//  this file.
//
//  All Content placed on the Content/ folder should be handled by this
//  module.
//

namespace $APPNAME {

	public class StaticContentModule : ManosModule {

		public StaticContentModule ()
		{
			Get (".*", Content);

		}

		public static void Content (IManosContext ctx)
		{
			string path = ctx.Request.LocalPath;

			if (path.StartsWith ("/"))
				path = path.Substring (1);

			if (File.Exists (path)) {
				ctx.Response.SendFile (path);
			} else
				ctx.Response.StatusCode = 404;
		}
	}
}

using System;
using System.IO;

using Manos;

//
//  This the default StaticContentModule that comes with all Manos apps
//  if you do not wish to serve any static content with Manos you can
//  remove its route handler from <YourApp>.cs's constructor and delete
//  this file.
//
//  All Content placed on the Content/ folder should be handled by this
//  module.
//

namespace $APPNAME {

	public class StaticContentModule : ManosModule {

		public StaticContentModule ()
		{
			Get (".*", Content);

		}

		public static void Content (IManosContext ctx)
		{
			string path = ctx.Request.LocalPath;

			if (path.StartsWith ("/"))
				path = path.Substring (1);

			if (File.Exists (path)) {
				ctx.Response.SendFile (path);
			} else
				ctx.Response.StatusCode = 404;

			ctx.Response.End ();
		}
	}
}

Make sure to End StaticContent.

Make sure to End StaticContent.


using Grpc.Core;
using System;

namespace MagicOnion
{
    public class ReturnStatusException : Exception
    {
        public StatusCode StatusCode { get; private set; }
        public string Detail { get; private set; }

        public ReturnStatusException(StatusCode statusCode, string detail)
        {
            this.StatusCode = statusCode;
            this.Detail = detail;
        }

        public Status ToStatus()
        {
            return new Status(StatusCode, Detail ?? "");
        }
    }
}

using Grpc.Core;
using System;

namespace MagicOnion
{
    public class ReturnStatusException : Exception
    {
        public StatusCode StatusCode { get; private set; }
        public string Detail { get; private set; }

        public ReturnStatusException(StatusCode statusCode, string detail)
            : base($"The method has returned the status code '{statusCode}'." + (string.IsNullOrWhiteSpace(detail) ? "" : $" (Detail={detail})"))
        {
            this.StatusCode = statusCode;
            this.Detail = detail;
        }

        public Status ToStatus()
        {
            return new Status(StatusCode, Detail ?? "");
        }
    }
}

Set an exception message for ReturnStatusMessage


// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "Test project classes do not need to be documented", Scope = "type", Target = "~T:Serilog.Exceptions.Test.Destructurers.ReflectionBasedDestructurerTest")]

// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "Test project classes do not need to be documented")]

Enlarge the scope of SA1600 supression to whole test project


namespace Bumblebee.Interfaces
{
    public interface ITextField : IElement, IHasText
    {
        TCustomResult EnterText<TCustomResult>(string text) where TCustomResult : IBlock;
        TCustomResult AppendText<TCustomResult>(string text) where TCustomResult : IBlock;
    }

    public interface ITextField<out TResult> : ITextField, IGenericElement<TResult> where TResult : IBlock
    {
        TResult EnterText(string text);
        TResult AppendText(string text);
    }
}

namespace Bumblebee.Interfaces
{
    public interface ITextField : IElement, IHasText
    {
        TCustomResult EnterText<TCustomResult>(string text) where TCustomResult : IBlock;
        TCustomResult AppendText<TCustomResult>(string text) where TCustomResult : IBlock;
    }

    public interface ITextField<out TResult> : ITextField, IAllowsNoOp<TResult> where TResult : IBlock
    {
        TResult EnterText(string text);
        TResult AppendText(string text);
    }
}

Allow noop on text fields

Allow noop on text fields


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

using System.ComponentModel;

namespace osu.Game.Screens.Select.Filter
{
    public enum SortMode
    {
        [Description("Artist")]
        Artist,

        [Description("Author")]
        Author,

        [Description("BPM")]
        BPM,

        [Description("Date Added")]
        DateAdded,

        [Description("Difficulty")]
        Difficulty,

        [Description("Length")]
        Length,

        [Description("Rank Achieved")]
        RankAchieved,

        [Description("Title")]
        Title,

        [Description("Source")]
        Source,
    }
}

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

using System.ComponentModel;

namespace osu.Game.Screens.Select.Filter
{
    public enum SortMode
    {
        [Description("Artist")]
        Artist,

        [Description("Author")]
        Author,

        [Description("BPM")]
        BPM,

        [Description("Date Added")]
        DateAdded,

        [Description("Difficulty")]
        Difficulty,

        [Description("Length")]
        Length,

        [Description("Rank Achieved")]
        RankAchieved,

        [Description("Source")]
        Source,

        [Description("Title")]
        Title,
    }
}

Fix enum ordering after adding source

Fix enum ordering after adding source


//-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation">
//   Copyright (c) SonarSource SA and Microsoft Corporation.  All rights reserved.
//   Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyVersion("2.2.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]
[assembly: AssemblyInformationalVersion("Version:2.2.0.0 Branch:not-set Sha1:not-set")]

[assembly: AssemblyConfiguration("")]

[assembly: AssemblyCompany("SonarSource and Microsoft")]
[assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015/2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

//-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation">
//   Copyright (c) SonarSource SA and Microsoft Corporation.  All rights reserved.
//   Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyVersion("2.2.1")]
[assembly: AssemblyFileVersion("2.2.1.0")]
[assembly: AssemblyInformationalVersion("Version:2.2.1.0 Branch:not-set Sha1:not-set")]

[assembly: AssemblyConfiguration("")]

[assembly: AssemblyCompany("SonarSource and Microsoft")]
[assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015/2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

Change version number to 2.2.1

Change version number to 2.2.1


using System.Collections;
using System.Windows.Forms;

namespace GUI.Controls
{
    internal class TreeViewFileSorter : IComparer
    {
        public int Compare(object x, object y)
        {
            var tx = x as TreeNode;
            var ty = y as TreeNode;

            var folderx = tx.ImageKey == @"_folder";
            var foldery = ty.ImageKey == @"_folder";

            if (folderx && !foldery)
            {
                return -1;
            }

            if (!folderx && foldery)
            {
                return 1;
            }

            return string.CompareOrdinal(tx.Text, ty.Text);
        }
    }
}

using System.Collections;
using System.Windows.Forms;

namespace GUI.Controls
{
    internal class TreeViewFileSorter : IComparer
    {
        public int Compare(object x, object y)
        {
            var tx = x as TreeNode;
            var ty = y as TreeNode;

            var folderx = tx.Tag is TreeViewFolder;
            var foldery = ty.Tag is TreeViewFolder;

            if (folderx && !foldery)
            {
                return -1;
            }

            if (!folderx && foldery)
            {
                return 1;
            }

            return string.CompareOrdinal(tx.Text, ty.Text);
        }
    }
}

Check folders by its tag

Check folders by its tag


using System;
using System.Net.Http;
using System.Threading.Tasks;
using Ecom.Hal.JSON;
using Newtonsoft.Json;

namespace Ecom.Hal
{
	public class HalClient
	{
		public HalClient(Uri endpoint)
		{
			Client = new HttpClient {BaseAddress = endpoint};
		}

		public T Parse<T>(string content)
		{
			return JsonConvert.DeserializeObject<T>(content, new JsonConverter[] {new HalResourceConverter()});
		}

		public Task<T> Get<T>(string path)
		{
			return Task<T>
				.Factory
				.StartNew(() =>
				          	{
				          		var body = Client.GetStringAsync(new Uri(path, UriKind.Relative)).Result;
				          		return Parse<T>(body);
				          	});

		}

		protected HttpClient Client { get; set; }
	}
}

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Ecom.Hal.JSON;
using Newtonsoft.Json;

namespace Ecom.Hal
{
	public class HalClient
	{
		public HalClient(Uri endpoint)
		{
			Client = new HttpClient {BaseAddress = endpoint};
		}

		public T Parse<T>(string content)
		{
			return JsonConvert.DeserializeObject<T>(content, new JsonConverter[] {new HalResourceConverter()});
		}

		public Task<T> Get<T>(string path)
		{
			return Task<T>
				.Factory
				.StartNew(() =>
				          	{
				          		var body = Client.GetStringAsync(new Uri(path, UriKind.Relative)).Result;
				          		return Parse<T>(body);
				          	});

		}

		public void SetCredentials(string username, string password)
		{
			Client
				.DefaultRequestHeaders
				.Authorization = new AuthenticationHeaderValue(
					"Basic",
					Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password))));
		}

		protected HttpClient Client { get; set; }
	}
}

Add support for basic auth

Add support for basic auth


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

using Caliburn.Micro;

namespace SharpGraphEditor.Models
{
    public class ZoomManager : PropertyChangedBase
    {

        public int MaxZoom { get; } = 2;

        public double CurrentZoom { get; private set; }

        public int CurrentZoomInPercents => (int)(CurrentZoom * 100);

        public ZoomManager()
        {
            CurrentZoom = 1;
        }

        public void ChangeCurrentZoom(double value)
        {
            if (value >= (1 / MaxZoom) && value <= MaxZoom)
            {
                CurrentZoom = Math.Round(value, 2);
            }
        }

        public void ChangeZoomByPercents(double percents)
        {
            CurrentZoom += percents / 100;
        }
    }
}

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

using Caliburn.Micro;

namespace SharpGraphEditor.Models
{
    public class ZoomManager : PropertyChangedBase
    {

        public double MaxZoom { get; } = 2;

        public double CurrentZoom { get; private set; }

        public int CurrentZoomInPercents => (int)(CurrentZoom * 100);

        public ZoomManager()
        {
            CurrentZoom = 1.0;
        }

        public void ChangeCurrentZoom(double value)
        {
            var newZoom = CurrentZoom + value;
            if (newZoom >= (1.0 / MaxZoom) && newZoom <= MaxZoom)
            {
                CurrentZoom = Math.Round(newZoom, 2);
            }
        }

        public void ChangeZoomByPercents(double percents)
        {
            ChangeCurrentZoom(percents / 100);
        }
    }
}

Fix bug with zoom when it didnt limit

Fix bug with zoom when it didnt limit


using BatteryCommander.Web.Services;
using FluentScheduler;
using SendGrid.Helpers.Mail;
using System;
using System.Collections.Generic;

namespace BatteryCommander.Web.Jobs
{
    public class SqliteBackupJob : IJob
    {
        private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable

        private readonly IEmailService emailSvc;

        public SqliteBackupJob(IEmailService emailSvc)
        {
            this.emailSvc = emailSvc;
        }

        public virtual void Execute()
        {
            var data = System.IO.File.ReadAllBytes("Data.db");

            var encoded = System.Convert.ToBase64String(data);

            var message = new SendGridMessage
            {
                From = new EmailAddress("Battery-Commander@redlegdev.com"),
                Subject = "Nightly Db Backup",
                Contents = new List<Content>()
                {
                    new Content
                    {
                        Type = "text/plain",
                        Value = "Please find the nightly database backup attached."
                    }
                },
                Attachments = new List<Attachment>()
                {
                    new Attachment
                    {
                        Filename = "Data.db",
                        Type = "application/octet-stream",
                        Content = encoded
                    }
                }
            };

            message.AddTo(Recipient);

            emailSvc.Send(message).Wait();
        }
    }
}

using BatteryCommander.Web.Services;
using FluentScheduler;
using SendGrid.Helpers.Mail;
using System;
using System.Collections.Generic;

namespace BatteryCommander.Web.Jobs
{
    public class SqliteBackupJob : IJob
    {
        private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable

        private readonly IEmailService emailSvc;

        public SqliteBackupJob(IEmailService emailSvc)
        {
            this.emailSvc = emailSvc;
        }

        public virtual void Execute()
        {
            var data = System.IO.File.ReadAllBytes("Data.db");

            var encoded = System.Convert.ToBase64String(data);

            var message = new SendGridMessage
            {
                From = EmailService.FROM_ADDRESS,
                Subject = "Nightly Db Backup",
                Contents = new List<Content>()
                {
                    new Content
                    {
                        Type = "text/plain",
                        Value = "Please find the nightly database backup attached."
                    }
                },
                Attachments = new List<Attachment>()
                {
                    new Attachment
                    {
                        Filename = "Data.db",
                        Type = "application/octet-stream",
                        Content = encoded
                    }
                }
            };

            message.AddTo(Recipient);

            emailSvc.Send(message).Wait();
        }
    }
}

Use common from address for backup

Use common from address for backup


using RestSharp;

namespace PivotalTrackerDotNet
{
    public abstract class AAuthenticatedService
    {
        protected readonly string m_token;
        protected RestClient RestClient;
        protected AAuthenticatedService(string token)
        {
            m_token = token;
            RestClient = new RestClient {BaseUrl = PivotalTrackerRestEndpoint.SSLENDPOINT};
        }

        protected RestRequest BuildGetRequest()
        {
            var request = new RestRequest(Method.GET);
            request.AddHeader("X-TrackerToken", m_token);
            request.RequestFormat = DataFormat.Json;
            return request;
        }

        protected RestRequest BuildPutRequest()
        {
            var request = new RestRequest(Method.PUT);
            request.AddHeader("X-TrackerToken", m_token);
            request.RequestFormat = DataFormat.Json;
            return request;
        }

        protected RestRequest BuildDeleteRequest()
        {
            var request = new RestRequest(Method.DELETE);
            request.AddHeader("X-TrackerToken", m_token);
            request.RequestFormat = DataFormat.Json;
            return request;
        }

        protected RestRequest BuildPostRequest()
        {
            var request = new RestRequest(Method.POST);
            request.AddHeader("X-TrackerToken", m_token);
            request.RequestFormat = DataFormat.Json;
            return request;
        }
    }
}

using RestSharp;

namespace PivotalTrackerDotNet
{
    using System;

    public abstract class AAuthenticatedService
    {
        protected readonly string m_token;
        protected RestClient RestClient;
        protected AAuthenticatedService(string token)
        {
            m_token = token;
            RestClient = new RestClient { BaseUrl = new Uri(PivotalTrackerRestEndpoint.SSLENDPOINT) };
        }

        protected RestRequest BuildGetRequest()
        {
            var request = new RestRequest(Method.GET);
            request.AddHeader("X-TrackerToken", m_token);
            request.RequestFormat = DataFormat.Json;
            return request;
        }

        protected RestRequest BuildPutRequest()
        {
            var request = new RestRequest(Method.PUT);
            request.AddHeader("X-TrackerToken", m_token);
            request.RequestFormat = DataFormat.Json;
            return request;
        }

        protected RestRequest BuildDeleteRequest()
        {
            var request = new RestRequest(Method.DELETE);
            request.AddHeader("X-TrackerToken", m_token);
            request.RequestFormat = DataFormat.Json;
            return request;
        }

        protected RestRequest BuildPostRequest()
        {
            var request = new RestRequest(Method.POST);
            request.AddHeader("X-TrackerToken", m_token);
            request.RequestFormat = DataFormat.Json;
            return request;
        }
    }
}

Fix RestClient BaseUrl change to Uri

Fix RestClient BaseUrl change to Uri


#load nuget:?package=Cake.Recipe&version=1.0.0

Environment.SetVariableNames();

BuildParameters.SetParameters(
    context: Context,
    buildSystem: BuildSystem,
    sourceDirectoryPath: "./src",
    title: "TfsUrlParser",
    repositoryOwner: "bbtsoftware",
    repositoryName: "TfsUrlParser",
    appVeyorAccountName: "BBTSoftwareAG",
    shouldPublishMyGet: false,
    shouldRunCodecov: false,
    shouldDeployGraphDocumentation: false);

BuildParameters.PrintParameters(Context);

ToolSettings.SetToolSettings(
    context: Context,
    dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" },
    testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* ",
    testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
    testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");

Build.RunDotNetCore();

#load nuget:?package=Cake.Recipe&version=1.0.0

Environment.SetVariableNames();

BuildParameters.SetParameters(
    context: Context,
    buildSystem: BuildSystem,
    sourceDirectoryPath: "./src",
    title: "TfsUrlParser",
    repositoryOwner: "bbtsoftware",
    repositoryName: "TfsUrlParser",
    appVeyorAccountName: "BBTSoftwareAG",
    shouldPublishMyGet: false,
    shouldRunCodecov: false,
    shouldDeployGraphDocumentation: false);

BuildParameters.PrintParameters(Context);

ToolSettings.SetToolSettings(
    context: Context,
    dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" },
    testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* -[Shouldly]*",
    testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
    testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");

Build.RunDotNetCore();

Exclude Shouldly from code coverage

Exclude Shouldly from code coverage


/*
* Programmed by Umut Celenli umut@celenli.com
*/

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

namespace MimeBank
{
    /// <summary>
    /// This is the main class to check the file mime type
    /// Header list is loaded once
    /// </summary>
    public class MimeChecker
    {
        private static List<FileHeader> list { get; set; }
        private List<FileHeader> List
        {
            get
            {
                if (list == null)
                {
                    list = HeaderData.GetList();
                }
                return list;
            }
        }
        private byte[] Buffer;

        public MimeChecker()
        {
            Buffer = new byte[256];
        }

        public FileHeader GetFileHeader(string file)
        {
            using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                fs.Read(Buffer, 0, 256);
            }
            return this.List.FirstOrDefault(mime => mime.Check(Buffer) == true);
        }
    }
}

/*
* Programmed by Umut Celenli umut@celenli.com
*/

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

namespace MimeBank
{
    /// <summary>
    /// This is the main class to check the file mime type
    /// Header list is loaded once
    /// </summary>
    public class MimeChecker
    {
        private const int maxBufferSize = 256;

        private static List<FileHeader> list { get; set; }
        private List<FileHeader> List
        {
            get
            {
                if (list == null)
                {
                    list = HeaderData.GetList();
                }
                return list;
            }
        }
        private byte[] Buffer;

        public MimeChecker()
        {
            Buffer = new byte[maxBufferSize];
        }

        public FileHeader GetFileHeader(string file)
        {
            using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                fs.Read(Buffer, 0, maxBufferSize);
            }
            return this.List.FirstOrDefault(mime => mime.Check(Buffer));
        }
    }
}

Define a const for read buffer size

Define a const for read buffer size


#if !(LESSTHAN_NET40 || NETSTANDARD1_0)
using System.Runtime.CompilerServices;
#endif

namespace System.Threading
{
    public class MonitorEx
    {
#if !(LESSTHAN_NET40 || NETSTANDARD1_0)
        [MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
#endif
        public static void Enter(object obj, ref bool lockTaken)
        {
#if LESSTHAN_NET40 || NETSTANDARD1_0

            if (obj is null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            if (lockTaken)
            {
                throw new ArgumentException("Lock taken", nameof(lockTaken));
            }

            Monitor.Enter(obj);
            Volatile.Write(ref lockTaken, true);
#else
            Monitor.Enter(obj, ref lockTaken);
#endif
        }
    }
}

#if !(LESSTHAN_NET40 || NETSTANDARD1_0)
using System.Runtime.CompilerServices;
#endif

namespace System.Threading
{
    public static class MonitorEx
    {
#if !(LESSTHAN_NET40 || NETSTANDARD1_0)
        [MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
#endif
        public static void Enter(object obj, ref bool lockTaken)
        {
#if LESSTHAN_NET40 || NETSTANDARD1_0

            if (obj is null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            if (lockTaken)
            {
                throw new ArgumentException("Lock taken", nameof(lockTaken));
            }

            Monitor.Enter(obj);
            Volatile.Write(ref lockTaken, true);
#else
            Monitor.Enter(obj, ref lockTaken);
#endif
        }
    }
}

Use static class for static methods.

Use static class for static methods.


namespace Nancy
{
    using System.Collections.Generic;
    using System.IO;

    public interface ISerializer
    {
        /// <summary>
        /// Whether the serializer can serialize the content type
        /// </summary>
        /// <param name="contentType">Content type to serialize</param>
        /// <returns>True if supported, false otherwise</returns>
        bool CanSerialize(string contentType);

        /// <summary>
        /// Gets the list of extensions that the serializer can handle.
        /// </summary>
        /// <value>An <see cref="IEnumerable{T}"/> of extensions if any are available, otherwise an empty enumerable.</value>
        IEnumerable<string> Extensions { get; }

        /// <summary>
        /// Serialize the given model with the given contentType
        /// </summary>
        /// <param name="contentType">Content type to serialize into</param>
        /// <param name="model">Model to serialize</param>
        /// <param name="outputStream">Output stream to serialize to</param>
        /// <returns>Serialized object</returns>
        void Serialize<TModel>(string contentType, TModel model, Stream outputStream);
    }
}

namespace Nancy
{
    using System.Collections.Generic;
    using System.IO;

    public interface ISerializer
    {
        /// <summary>
        /// Whether the serializer can serialize the content type
        /// </summary>
        /// <param name="contentType">Content type to serialise</param>
        /// <returns>True if supported, false otherwise</returns>
        bool CanSerialize(string contentType);

        /// <summary>
        /// Gets the list of extensions that the serializer can handle.
        /// </summary>
        /// <value>An <see cref="IEnumerable{T}"/> of extensions if any are available, otherwise an empty enumerable.</value>
        IEnumerable<string> Extensions { get; }

        /// <summary>
        /// Serialize the given model with the given contentType
        /// </summary>
        /// <param name="contentType">Content type to serialize into</param>
        /// <param name="model">Model to serialize</param>
        /// <param name="outputStream">Output stream to serialize to</param>
        /// <returns>Serialised object</returns>
        void Serialize<TModel>(string contentType, TModel model, Stream outputStream);
    }
}

Revert "Swapping Silly UK English ;)"

Revert "Swapping Silly UK English ;)"

This reverts commit 3b10acc9f764cf31b2718abf906b28ce7d200cff.


using Microsoft.EntityFrameworkCore;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork;
using System;
using System.Threading.Tasks;

namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories
{
    public class OrderRepository
        : IOrderRepository
    {
        private readonly OrderingContext _context;

        public IUnitOfWork UnitOfWork
        {
            get
            {
                return _context;
            }
        }

        public OrderRepository(OrderingContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public Order Add(Order order)
        {
            return  _context.Orders.Add(order).Entity;

        }

        public async Task<Order> GetAsync(int orderId)
        {
            return await _context.Orders.FindAsync(orderId);
        }

        public void Update(Order order)
        {
            _context.Entry(order).State = EntityState.Modified;
        }
    }
}

using Microsoft.EntityFrameworkCore;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork;
using Ordering.Domain.Exceptions;
using System;
using System.Threading.Tasks;

namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories
{
    public class OrderRepository
        : IOrderRepository
    {
        private readonly OrderingContext _context;

        public IUnitOfWork UnitOfWork
        {
            get
            {
                return _context;
            }
        }

        public OrderRepository(OrderingContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public Order Add(Order order)
        {
            return  _context.Orders.Add(order).Entity;

        }

        public async Task<Order> GetAsync(int orderId)
        {
            return await _context.Orders.FindAsync(orderId)
                ?? throw new OrderingDomainException($"Not able to get the order. Reason: no valid orderId: {orderId}");
        }

        public void Update(Order order)
        {
            _context.Entry(order).State = EntityState.Modified;
        }
    }
}

Add OrderingDomainException when the order doesn't exist with id orderId


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace XiboClient.Control
{
    class WatchDogManager
    {
        public static void Start()
        {
            // Check to see if the WatchDog EXE exists where we expect it to be
            // Uncomment to test local watchdog install.
            //string path = @"C:\Program Files (x86)\Xibo Player\watchdog\x86\XiboClientWatchdog.exe";
            string path = Path.GetDirectoryName(Application.ExecutablePath) + @"\watchdog\x86\" + Application.ProductName + "ClientWatchdog.exe";
            string args = "-p \"" + Application.ExecutablePath + "\" -l \"" + ApplicationSettings.Default.LibraryPath + "\"";

            // Start it
            if (File.Exists(path))
            {
                try
                {
                    Process process = new Process();
                    ProcessStartInfo info = new ProcessStartInfo();

                    info.CreateNoWindow = true;
                    info.WindowStyle = ProcessWindowStyle.Hidden;
                    info.FileName = "cmd.exe";
                    info.Arguments = "/c start \"watchdog\" \"" + path + "\" " + args;

                    process.StartInfo = info;
                    process.Start();
                }
                catch (Exception e)
                {
                    Trace.WriteLine(new LogMessage("WatchDogManager - Start", "Unable to start: " + e.Message), LogType.Error.ToString());
                }
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace XiboClient.Control
{
    class WatchDogManager
    {
        public static void Start()
        {
            // Check to see if the WatchDog EXE exists where we expect it to be
            // Uncomment to test local watchdog install.
            //string path = @"C:\Program Files (x86)\Xibo Player\watchdog\x86\XiboClientWatchdog.exe";
            string path = Path.GetDirectoryName(Application.ExecutablePath) + @"\watchdog\x86\" + ((Application.ProductName != "Xibo") ? Application.ProductName + "Watchdog.exe" : "XiboClientWatchdog.exe");
            string args = "-p \"" + Application.ExecutablePath + "\" -l \"" + ApplicationSettings.Default.LibraryPath + "\"";

            // Start it
            if (File.Exists(path))
            {
                try
                {
                    Process process = new Process();
                    ProcessStartInfo info = new ProcessStartInfo();

                    info.CreateNoWindow = true;
                    info.WindowStyle = ProcessWindowStyle.Hidden;
                    info.FileName = "cmd.exe";
                    info.Arguments = "/c start \"watchdog\" \"" + path + "\" " + args;

                    process.StartInfo = info;
                    process.Start();
                }
                catch (Exception e)
                {
                    Trace.WriteLine(new LogMessage("WatchDogManager - Start", "Unable to start: " + e.Message), LogType.Error.ToString());
                }
            }
        }
    }
}

Handle oddity in watchdog naming convention


using System.Linq;
using System.Windows.Forms;
using Bloom.Api;

namespace Bloom.web.controllers
{
	class KeybordingConfigApi
	{
		public void RegisterWithServer(EnhancedImageServer server)
		{
			server.RegisterEndpointHandler("keyboarding/useLongPress", (ApiRequest request) =>
			{
				//detect if some keyboarding system is active, e.g. KeyMan. If it is, don't enable LongPress
				var form = Application.OpenForms.Cast<Form>().Last();
				request.ReplyWithText(SIL.Windows.Forms.Keyboarding.KeyboardController.IsFormUsingInputProcessor(form)?"false":"true");
			});
		}
	}
}

using System;
using System.Linq;
using System.Windows.Forms;
using Bloom.Api;

namespace Bloom.web.controllers
{
	class KeybordingConfigApi
	{
		public void RegisterWithServer(EnhancedImageServer server)
		{
			server.RegisterEndpointHandler("keyboarding/useLongPress", (ApiRequest request) =>
			{
				try
				{
					//detect if some keyboarding system is active, e.g. KeyMan. If it is, don't enable LongPress
					var form = Application.OpenForms.Cast<Form>().Last();
					request.ReplyWithText(SIL.Windows.Forms.Keyboarding.KeyboardController.IsFormUsingInputProcessor(form)
						? "false"
						: "true");
				}
				catch(Exception error)
				{
					request.ReplyWithText("true"); // This is arbitrary. I don't know if it's better to assume keyman, or not.
					NonFatalProblem.Report(ModalIf.None, PassiveIf.All, "Error checking for keyman","", error);
				}
			}, handleOnUiThread:false);
		}
	}
}

Fix BL-3614 Crash while checking for keyman

I wasn't able to reproduce the crash, but I made it not require UI thread and catch any errors and report them passively.


using System;
using System.IO;
using System.Reflection;
using Newtonsoft.Json.Linq;

namespace Noobot.Core.Configuration
{
    public class ConfigReader : IConfigReader
    {
        private JObject _currentJObject;
        private readonly string _configLocation;
        private readonly object _lock = new object();
        private const string DEFAULT_LOCATION = @"configuration\config.json";
        private const string SLACKAPI_CONFIGVALUE = "slack:apiToken";

        public ConfigReader() : this(DEFAULT_LOCATION) { }
        public ConfigReader(string configurationFile)
        {
            _configLocation = configurationFile;
        }

        public bool HelpEnabled { get; set; } = true;
        public bool StatsEnabled { get; set; } = true;
        public bool AboutEnabled { get; set; } = true;

        public string SlackApiKey => GetConfigEntry<string>(SLACKAPI_CONFIGVALUE);

        public T GetConfigEntry<T>(string entryName)
        {
            return GetJObject().Value<T>(entryName);
        }

        private JObject GetJObject()
        {
            lock (_lock)
            {
                if (_currentJObject == null)
                {
                    string assemblyLocation = AssemblyLocation();
                    string fileName = Path.Combine(assemblyLocation, _configLocation);
                    string json = File.ReadAllText(fileName);
                    _currentJObject = JObject.Parse(json);
                }
            }

            return _currentJObject;
        }

        private string AssemblyLocation()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var codebase = new Uri(assembly.CodeBase);
            var path = Path.GetDirectoryName(codebase.LocalPath);
            return path;
        }
    }
}

using System;
using System.IO;
using System.Reflection;
using Newtonsoft.Json.Linq;

namespace Noobot.Core.Configuration
{
    public class ConfigReader : IConfigReader
    {
        private JObject _currentJObject;
        private readonly string _configLocation;
        private readonly object _lock = new object();
        private static readonly string DEFAULT_LOCATION = Path.Combine("configuration", "config.json");
        private const string SLACKAPI_CONFIGVALUE = "slack:apiToken";

        public ConfigReader() : this(DEFAULT_LOCATION) { }
        public ConfigReader(string configurationFile)
        {
            _configLocation = configurationFile;
        }

        public bool HelpEnabled { get; set; } = true;
        public bool StatsEnabled { get; set; } = true;
        public bool AboutEnabled { get; set; } = true;

        public string SlackApiKey => GetConfigEntry<string>(SLACKAPI_CONFIGVALUE);

        public T GetConfigEntry<T>(string entryName)
        {
            return GetJObject().Value<T>(entryName);
        }

        private JObject GetJObject()
        {
            lock (_lock)
            {
                if (_currentJObject == null)
                {
                    string assemblyLocation = AssemblyLocation();
                    string fileName = Path.Combine(assemblyLocation, _configLocation);
                    string json = File.ReadAllText(fileName);
                    _currentJObject = JObject.Parse(json);
                }
            }

            return _currentJObject;
        }

        private string AssemblyLocation()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var codebase = new Uri(assembly.CodeBase);
            var path = Path.GetDirectoryName(codebase.LocalPath);
            return path;
        }
    }
}

Allow config.json path to work on non-Windows OS

Changed the config.json path so it works on non-Windows OS where
forward slashes are used instead of backslashes.


using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Windows.Storage;
using System.Diagnostics;
using System.IO;

namespace WPCordovaClassLib.Cordova.Commands
{
    public class FileOpener2 : BaseCommand
    {

        public async void open(string options)
        {
            string[] args = JSON.JsonHelper.Deserialize<string[]>(options);

            string aliasCurrentCommandCallbackId = args[2];

            try
            {
                // Get the file.
                StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(args[0]);

                // Launch the bug query file.
                await Windows.System.Launcher.LaunchFileAsync(file);

                DispatchCommandResult(new PluginResult(PluginResult.Status.OK), aliasCurrentCommandCallbackId);
            }
            catch (FileNotFoundException)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), aliasCurrentCommandCallbackId);
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), aliasCurrentCommandCallbackId);
            }
        }
    }
}

using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Windows.Storage;
using System.Diagnostics;
using System.IO;

namespace WPCordovaClassLib.Cordova.Commands
{
    public class FileOpener2 : BaseCommand
    {

        public async void open(string options)
        {
            string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
            this.openPath(args[0].Replace("/", "\\"), args[2]);
            string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
        }

        private async void openPath(string path, string cbid)
        {
            try
            {
                StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path);
                await Windows.System.Launcher.LaunchFileAsync(file);
                DispatchCommandResult(new PluginResult(PluginResult.Status.OK), cbid);
            }
            catch (FileNotFoundException)
            {
                this.openInLocalFolder(path, cbid);
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), cbid);
            }
        }

        private async void openInLocalFolder(string path, string cbid)
        {
            try
            {
                StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(
                    Path.Combine(
                        Windows.Storage.ApplicationData.Current.LocalFolder.Path,
                        path.TrimStart('\\')
                    )
                );
                await Windows.System.Launcher.LaunchFileAsync(file);
                DispatchCommandResult(new PluginResult(PluginResult.Status.OK), cbid);
            }
            catch (FileNotFoundException)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), cbid);
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), cbid);
            }
        }
    }
}

Add support for local folder

[WP8] Add support for local folder

If file wasnt found then path is assumed to be relative path to local directory


// 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.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Users;

namespace osu.Game.Tests.Visual.Online
{
    public class TestSceneAccountCreationOverlay : OsuTestScene
    {
        private readonly Container userPanelArea;

        private IBindable<User> localUser;

        public TestSceneAccountCreationOverlay()
        {
            AccountCreationOverlay accountCreation;

            Children = new Drawable[]
            {
                accountCreation = new AccountCreationOverlay(),
                userPanelArea = new Container
                {
                    Padding = new MarginPadding(10),
                    AutoSizeAxes = Axes.Both,
                    Anchor = Anchor.TopRight,
                    Origin = Anchor.TopRight,
                },
            };

            AddStep("show", () => accountCreation.Show());
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            API.Logout();

            localUser = API.LocalUser.GetBoundCopy();
            localUser.BindValueChanged(user => { userPanelArea.Child = new UserGridPanel(user.NewValue) { Width = 200 }; }, true);

            AddStep("logout", API.Logout);
        }
    }
}

// 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Users;

namespace osu.Game.Tests.Visual.Online
{
    public class TestSceneAccountCreationOverlay : OsuTestScene
    {
        private readonly Container userPanelArea;
        private readonly AccountCreationOverlay accountCreation;

        private IBindable<User> localUser;

        public TestSceneAccountCreationOverlay()
        {
            Children = new Drawable[]
            {
                accountCreation = new AccountCreationOverlay(),
                userPanelArea = new Container
                {
                    Padding = new MarginPadding(10),
                    AutoSizeAxes = Axes.Both,
                    Anchor = Anchor.TopRight,
                    Origin = Anchor.TopRight,
                },
            };
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            API.Logout();

            localUser = API.LocalUser.GetBoundCopy();
            localUser.BindValueChanged(user => { userPanelArea.Child = new UserGridPanel(user.NewValue) { Width = 200 }; }, true);
        }

        [Test]
        public void TestOverlayVisibility()
        {
            AddStep("start hidden", () => accountCreation.Hide());
            AddStep("log out", API.Logout);

            AddStep("show manually", () => accountCreation.Show());
            AddUntilStep("overlay is visible", () => accountCreation.State.Value == Visibility.Visible);

            AddStep("log back in", () => API.Login("dummy", "password"));
            AddUntilStep("overlay is hidden", () => accountCreation.State.Value == Visibility.Hidden);
        }
    }
}

Rewrite test to cover failure case

Rewrite test to cover failure case


using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;

namespace Criteo.Profiling.Tracing.Middleware
{
    public static class TracingMiddleware
    {
        public static void UseTracing(this IApplicationBuilder app, string serviceName)
        {
            var extractor = new Middleware.ZipkinHttpTraceExtractor();
            app.Use(async (context, next) =>
            {
                Trace trace;
                var request = context.Request;
                if (!extractor.TryExtract(request.Headers, out trace))
                {
                    trace = Trace.Create();
                }
                Trace.Current = trace;
                using (new ServerTrace(serviceName, request.Method))
                {
                    trace.Record(Annotations.Tag("http.uri", request.Path));
                    await TraceHelper.TracedActionAsync(next());
                }
            });
        }
    }
}

using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;
using Microsoft.AspNetCore.Http.Extensions;

namespace Criteo.Profiling.Tracing.Middleware
{
    public static class TracingMiddleware
    {
        public static void UseTracing(this IApplicationBuilder app, string serviceName)
        {
            var extractor = new Middleware.ZipkinHttpTraceExtractor();
            app.Use(async (context, next) =>
            {
                Trace trace;
                var request = context.Request;
                if (!extractor.TryExtract(request.Headers, out trace))
                {
                    trace = Trace.Create();
                }
                Trace.Current = trace;
                using (new ServerTrace(serviceName, request.Method))
                {
                    trace.Record(Annotations.Tag("http.host", request.Host.ToString()));
                    trace.Record(Annotations.Tag("http.uri", UriHelper.GetDisplayUrl(request)));
                    trace.Record(Annotations.Tag("http.path", request.Path));
                    await TraceHelper.TracedActionAsync(next());
                }
            });
        }
    }
}

Add http.host and http.path annotations

Add http.host and http.path annotations


namespace Translatable.TranslationTest
{
    public class MainWindowTranslation : ITranslatable
    {
        private IPluralBuilder PluralBuilder { get; set; } = new DefaultPluralBuilder();

        public string Title { get; private set; } = "Main window title";

        public string SampleText { get; private set; } = "This is my content\r\nwith multiple lines";

        public string Messages { get; private set; } = "Messages";

        [Context("Some context")]
        public string Messages2 { get; private set; } = "Messages";

        private string[] NewMessagesText { get; set; } = {"You have {0} new message", "You have {0} new messages"};

        [TranslatorComment("This page is intentionally left blank")]
        public string MissingTranslation { get; set; } = "This translation might be \"missing\"";

        public EnumTranslation<TestEnum>[] TestEnumTranslation { get; private set; } = EnumTranslation<TestEnum>.CreateDefaultEnumTranslation();

        public string FormatMessageText(int messages)
        {
            var translation = PluralBuilder.GetPlural(messages, NewMessagesText);
            return string.Format(translation, messages);
        }
    }
}

namespace Translatable.TranslationTest
{
    public class MainWindowTranslation : ITranslatable
    {
        protected IPluralBuilder PluralBuilder { get; set; } = new DefaultPluralBuilder();

        public string Title { get; protected set; } = "Main window title";

        public string SampleText { get; protected set; } = "This is my content\r\nwith multiple lines";

        public string Messages { get; protected set; } = "Messages";

        [Context("Some context")]
        public string Messages2 { get; protected set; } = "Messages";

        protected string[] NewMessagesText { get; set; } = { "You have {0} new message", "You have {0} new messages" };

        [TranslatorComment("This page is intentionally left blank")]
        public string MissingTranslation { get; set; } = "This translation might be \"missing\"";

        public EnumTranslation<TestEnum>[] TestEnumTranslation { get; protected set; } = EnumTranslation<TestEnum>.CreateDefaultEnumTranslation();

        public string FormatMessageText(int messages)
        {
            var translation = PluralBuilder.GetPlural(messages, NewMessagesText);
            return string.Format(translation, messages);
        }
    }

    public class TestTranslation : MainWindowTranslation
    {
        public string Text { get; private set; } = "Test";
    }
}

Make translation work with inheritance

Make translation work with inheritance


// 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 NUnit.Framework;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.States;
using osuTK.Input;
using KeyboardState = osu.Framework.Input.States.KeyboardState;

namespace osu.Framework.Tests.Input
{
    [TestFixture]
    public class KeyCombinationTest
    {
        [Test]
        public void TestKeyCombinationDisplayTrueOrder()
        {
            var keyCombination1 = new KeyCombination(InputKey.Control, InputKey.Shift, InputKey.R);
            var keyCombination2 = new KeyCombination(InputKey.R, InputKey.Shift, InputKey.Control);

            Assert.AreEqual(keyCombination1.ReadableString(), keyCombination2.ReadableString());
        }

        [Test]
        public void TestKeyCombinationFromKeyboardStateDisplayTrueOrder()
        {
            var keyboardState = new KeyboardState();

            keyboardState.Keys.Add(Key.R);
            keyboardState.Keys.Add(Key.LShift);
            keyboardState.Keys.Add(Key.LControl);

            var keyCombination1 = KeyCombination.FromInputState(new InputState(keyboard: keyboardState));
            var keyCombination2 = new KeyCombination(InputKey.Control, InputKey.Shift, InputKey.R);

            Assert.AreEqual(keyCombination1.ReadableString(), keyCombination2.ReadableString());
        }
    }
}

// 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 NUnit.Framework;
using osu.Framework.Input.Bindings;

namespace osu.Framework.Tests.Input
{
    [TestFixture]
    public class KeyCombinationTest
    {
        private static readonly object[][] key_combination_display_test_cases =
        {
            new object[] { new KeyCombination(InputKey.Alt, InputKey.F4), "Alt-F4" },
            new object[] { new KeyCombination(InputKey.D, InputKey.Control), "Ctrl-D" },
            new object[] { new KeyCombination(InputKey.Shift, InputKey.F, InputKey.Control), "Ctrl-Shift-F" },
            new object[] { new KeyCombination(InputKey.Alt, InputKey.Control, InputKey.Super, InputKey.Shift), "Ctrl-Alt-Shift-Win" }
        };

        [TestCaseSource(nameof(key_combination_display_test_cases))]
        public void TestKeyCombinationDisplayOrder(KeyCombination keyCombination, string expectedRepresentation)
            => Assert.That(keyCombination.ReadableString(), Is.EqualTo(expectedRepresentation));
    }
}

Make tests actually test the string output


using System;
using System.Collections.Generic;
using DapperTesting.Core.Model;

namespace DapperTesting.Core.Data
{
    public class DapperPostRepository : DapperRepositoryBase, IPostRepository
    {
        public DapperPostRepository(IConnectionFactory connectionFactory, string connectionStringName) : base(connectionFactory, connectionStringName)
        {
        }

        public void Create(Post post)
        {
            throw new NotImplementedException();
        }

        public void AddDetails(int postId, PostDetails details)
        {
            throw new NotImplementedException();
        }

        public bool Delete(int postId)
        {
            throw new NotImplementedException();
        }

        public bool DeleteDetails(int detailsId)
        {
            throw new NotImplementedException();
        }

        public List<Post> GetPostsForUser(int userId)
        {
            throw new NotImplementedException();
        }

        public Post Get(int id)
        {
            throw new NotImplementedException();
        }

        public PostDetails GetDetails(int postId, int sequence)
        {
            throw new NotImplementedException();
        }

        public bool Update(Post post)
        {
            throw new NotImplementedException();
        }

        public bool UpdateDetails(PostDetails details)
        {
            throw new NotImplementedException();
        }
    }
}

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

using Dapper;

using DapperTesting.Core.Model;

namespace DapperTesting.Core.Data
{
    public class DapperPostRepository : DapperRepositoryBase, IPostRepository
    {
        public DapperPostRepository(IConnectionFactory connectionFactory, string connectionStringName) : base(connectionFactory, connectionStringName)
        {
        }

        public void Create(Post post)
        {
            throw new NotImplementedException();
        }

        public void AddDetails(int postId, PostDetails details)
        {
            throw new NotImplementedException();
        }

        public bool Delete(int postId)
        {
            throw new NotImplementedException();
        }

        public bool DeleteDetails(int detailsId)
        {
            throw new NotImplementedException();
        }

        public List<Post> GetPostsForUser(int userId)
        {
            throw new NotImplementedException();
        }

        public Post Get(int id)
        {
            const string sql = "SELECT * FROM [Posts] WHERE [Id] = @postId";

            var post = Fetch(c => c.Query<Post>(sql, new { postId = id })).SingleOrDefault();

            return post;
        }

        public PostDetails GetDetails(int postId, int sequence)
        {
            throw new NotImplementedException();
        }

        public bool Update(Post post)
        {
            throw new NotImplementedException();
        }

        public bool UpdateDetails(PostDetails details)
        {
            throw new NotImplementedException();
        }
    }
}

Add basic Get for a post

Add basic Get for a post


using System;
using NUnit.Framework;
using SevenDigital.Api.Schema;
using SevenDigital.Api.Wrapper.Exceptions;
using SevenDigital.Api.Schema.ArtistEndpoint;
using SevenDigital.Api.Schema.LockerEndpoint;

namespace SevenDigital.Api.Wrapper.Integration.Tests.Exceptions
{
	[TestFixture]
	public class ErrorConditionTests
	{
		[Test]
		public void Should_fail_with_input_parameter_exception_if_xml_error_returned()
		{
			// -- Deliberate error response
			Console.WriteLine("Trying artist/details without artistId parameter...");
			var apiXmlException = Assert.Throws<InputParameterException>(() => Api<Artist>.Create.Please());

			Assert.That(apiXmlException.ErrorCode, Is.EqualTo(ErrorCode.RequiredParameterMissing));
			Assert.That(apiXmlException.Message, Is.EqualTo("Missing parameter artistId"));
		}

		[Test]
		public void Should_fail_with_non_xml_exception_if_plaintext_error_returned_eg_unauthorised()
		{
			// -- Deliberate unauthorized response
			Console.WriteLine("Trying user/locker without any credentials...");
			var apiXmlException = Assert.Throws<OAuthException>(() => Api<Locker>.Create.Please());
			Assert.That(apiXmlException.ResponseBody, Is.EqualTo("OAuth authentication error: Resource requires access token"));
		}
	}
}

using System;
using NUnit.Framework;
using SevenDigital.Api.Schema;
using SevenDigital.Api.Wrapper.Exceptions;
using SevenDigital.Api.Schema.ArtistEndpoint;
using SevenDigital.Api.Schema.LockerEndpoint;

namespace SevenDigital.Api.Wrapper.Integration.Tests.Exceptions
{
	[TestFixture]
	public class ErrorConditionTests
	{
		[Test]
		public void Should_fail_with_input_parameter_exception_if_xml_error_returned()
		{
			// -- Deliberate error response
			Console.WriteLine("Trying artist/details without artistId parameter...");
			var apiXmlException = Assert.Throws<InputParameterException>(() => Api<Artist>.Create.Please());

			Assert.That(apiXmlException.ErrorCode, Is.EqualTo(ErrorCode.RequiredParameterMissing));
			Assert.That(apiXmlException.Message, Is.StringStarting("Missing parameter artistId"));
		}

		[Test]
		public void Should_fail_with_non_xml_exception_if_plaintext_error_returned_eg_unauthorised()
		{
			// -- Deliberate unauthorized response
			Console.WriteLine("Trying user/locker without any credentials...");
			var apiXmlException = Assert.Throws<OAuthException>(() => Api<Locker>.Create.Please());
			Assert.That(apiXmlException.ResponseBody, Is.EqualTo("OAuth authentication error: Resource requires access token"));
		}
	}
}

Make inputexception message tests more robust


using System.IO;

namespace NuGet.Extensions.Tests.TestData
{
    public class Isolation
    {
        public static DirectoryInfo GetIsolatedTestSolutionDir()
        {
            var solutionDir = new DirectoryInfo(Path.GetRandomFileName());
            CopyFilesRecursively(new DirectoryInfo(Paths.TestSolutionForAdapterFolder), solutionDir);
            return solutionDir;
        }

        public static DirectoryInfo GetIsolatedPackageSourceFromThisSolution()
        {
            var packageSource = new DirectoryInfo(Path.GetRandomFileName());
            CopyFilesRecursively(new DirectoryInfo("../packages"), packageSource);
            return packageSource;
        }

        public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
        {
            if (!target.Exists) target.Create();
            foreach (DirectoryInfo dir in source.GetDirectories())
                CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
            foreach (FileInfo file in source.GetFiles())
                file.CopyTo(Path.Combine(target.FullName, file.Name));
        }
    }
}

using System.IO;

namespace NuGet.Extensions.Tests.TestData
{
    public class Isolation
    {
        public static DirectoryInfo GetIsolatedTestSolutionDir()
        {
            var solutionDir = new DirectoryInfo(GetRandomTempDirectoryPath());
            CopyFilesRecursively(new DirectoryInfo(Paths.TestSolutionForAdapterFolder), solutionDir);
            return solutionDir;
        }

        private static string GetRandomTempDirectoryPath()
        {
            return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
        }

        public static DirectoryInfo GetIsolatedPackageSourceFromThisSolution()
        {
            var packageSource = new DirectoryInfo(GetRandomTempDirectoryPath());
            CopyFilesRecursively(new DirectoryInfo("../packages"), packageSource);
            return packageSource;
        }

        public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
        {
            if (!target.Exists) target.Create();
            foreach (DirectoryInfo dir in source.GetDirectories())
                CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
            foreach (FileInfo file in source.GetFiles())
                file.CopyTo(Path.Combine(target.FullName, file.Name));
        }
    }
}

Create temp directories in temp folder

Create temp directories in temp folder


// Compile with:
// docker run --rm -v "$PWD":/var/task lambci/lambda:build-dotnetcore2.0 dotnet publish -c Release -o pub

// Run with:
// docker run --rm -v "$PWD"/pub:/var/task lambci/lambda:dotnetcore2.0 test::test.Function::FunctionHandler "some"

using Amazon.Lambda.Core;

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace test
{
    public class Function
    {
        public string FunctionHandler(object inputEvent, ILambdaContext context)
        {
            context.Logger.Log($"inputEvent: {inputEvent}");
            return "Hello World!";
        }
    }
}

// Compile with:
// docker run --rm -v "$PWD":/var/task lambci/lambda:build-dotnetcore2.0 dotnet publish -c Release -o pub

// Run with:
// docker run --rm -v "$PWD"/pub:/var/task lambci/lambda:dotnetcore2.0 test::test.Function::FunctionHandler "some"

using System;
using System.Collections;
using Amazon.Lambda.Core;

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace test
{
    public class Function
    {
        public string FunctionHandler(object inputEvent, ILambdaContext context)
        {
            context.Logger.Log($"inputEvent: {inputEvent}");
            LambdaLogger.Log($"RemainingTime: {context.RemainingTime}");

            foreach (DictionaryEntry kv in Environment.GetEnvironmentVariables())
            {
                context.Logger.Log($"{kv.Key}={kv.Value}");
            }

            return "Hello World!";
        }
    }
}

Add RemainingTime and env vars to dotnetcore2.0 example


using System.Linq;
using GitVersion;
using GitVersionTask;
using Microsoft.Build.Framework;
using NUnit.Framework;
using Shouldly;

[TestFixture]
public class GetVersionTaskTests
{
    [Test]
    public void OutputsShouldMatchVariableProvider()
    {
        var taskProperties = typeof(GetVersion)
            .GetProperties()
            .Where(p => p.GetCustomAttributes(typeof(OutputAttribute), false).Any())
            .Select(p => p.Name);

        var variablesProperties = typeof(VersionVariables)
            .GetProperties()
            .Select(p => p.Name)
            .Except(new[] { "AvailableVariables", "Item" });

        taskProperties.ShouldBe(variablesProperties, ignoreOrder: true);
    }
}

using System.Linq;
using GitVersion;
using GitVersionTask;
using Microsoft.Build.Framework;
using NUnit.Framework;
using Shouldly;

[TestFixture]
public class GetVersionTaskTests
{
    [Test]
    public void OutputsShouldMatchVariableProvider()
    {
        var taskProperties = typeof(GetVersion)
            .GetProperties()
            .Where(p => p.GetCustomAttributes(typeof(OutputAttribute), false).Any())
            .Select(p => p.Name);

        var variablesProperties = VersionVariables.AvailableVariables;

        taskProperties.ShouldBe(variablesProperties, ignoreOrder: true);
    }
}

Use the AvailableVariables property instead of doing GetProperties() everywhere.