#if !NO_UNITY
using System;
using UnityEngine;
using UnityEngine.Events;

namespace FullSerializer {
    partial class fsConverterRegistrar {
        // Disable the converter for the time being. Unity's JsonUtility API cannot be called from
        // within a C# ISerializationCallbackReceiver callback.

        // public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter;
    }
}

namespace FullSerializer.Internal.Converters {
    // The standard FS reflection converter has started causing Unity to crash when processing
    // UnityEvent. We can send the serialization through JsonUtility which appears to work correctly
    // instead.
    //
    // We have to support legacy serialization formats so importing works as expected.
    public class UnityEvent_Converter : fsConverter {
        public override bool CanProcess(Type type) {
            return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false;
        }

        public override bool RequestCycleSupport(Type storageType) {
            return false;
        }

        public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
            Type objectType = (Type)instance;

            fsResult result = fsResult.Success;
            instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType);
            return result;
        }

        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
            fsResult result = fsResult.Success;
            serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance));
            return result;
        }
    }
}
#endif

#if !NO_UNITY && UNITY_5_3_OR_NEWER
using System;
using UnityEngine;
using UnityEngine.Events;

namespace FullSerializer {
    partial class fsConverterRegistrar {
        // Disable the converter for the time being. Unity's JsonUtility API cannot be called from
        // within a C# ISerializationCallbackReceiver callback.

        // public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter;
    }
}

namespace FullSerializer.Internal.Converters {
    // The standard FS reflection converter has started causing Unity to crash when processing
    // UnityEvent. We can send the serialization through JsonUtility which appears to work correctly
    // instead.
    //
    // We have to support legacy serialization formats so importing works as expected.
    public class UnityEvent_Converter : fsConverter {
        public override bool CanProcess(Type type) {
            return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false;
        }

        public override bool RequestCycleSupport(Type storageType) {
            return false;
        }

        public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
            Type objectType = (Type)instance;

            fsResult result = fsResult.Success;
            instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType);
            return result;
        }

        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
            fsResult result = fsResult.Success;
            serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance));
            return result;
        }
    }
}
#endif

Fix compilation on Unity < 5.3.

Fix compilation on Unity < 5.3.

Fixes issue #108.


using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;

namespace Line.Messaging
{
    internal static class HttpResponseMessageExtensions
    {
        /// <summary>
        /// Validate the response status.
        /// </summary>
        /// <param name="response">HttpResponseMessage</param>
        /// <returns>HttpResponseMessage</returns>
        internal static async Task<HttpResponseMessage> EnsureSuccessStatusCodeAsync(this HttpResponseMessage response)
        {
            if (response.IsSuccessStatusCode)
            {
                return response;
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                var errorMessage = JsonConvert.DeserializeObject<ErrorResponseMessage>(content, new CamelCaseJsonSerializerSettings());
                throw new LineResponseException(errorMessage.Message) { StatusCode = response.StatusCode, ResponseMessage = errorMessage };
            }
        }
    }
}

using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;

namespace Line.Messaging
{
    internal static class HttpResponseMessageExtensions
    {
        /// <summary>
        /// Validate the response status.
        /// </summary>
        /// <param name="response">HttpResponseMessage</param>
        /// <returns>HttpResponseMessage</returns>
        internal static async Task<HttpResponseMessage> EnsureSuccessStatusCodeAsync(this HttpResponseMessage response)
        {
            if (response.IsSuccessStatusCode)
            {
                return response;
            }
            else
            {
                ErrorResponseMessage errorMessage;
                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    errorMessage = JsonConvert.DeserializeObject<ErrorResponseMessage>(content, new CamelCaseJsonSerializerSettings());
                }
                catch
                {
                    errorMessage = new ErrorResponseMessage() { Message = content, Details = new ErrorResponseMessage.ErrorDetails[0] };
                }
                throw new LineResponseException(errorMessage.Message) { StatusCode = response.StatusCode, ResponseMessage = errorMessage };

            }
        }
    }
}

Add processing when error response JSON failed parsing


//*********************************************************//
//    Copyright (c) Microsoft. All rights reserved.
//
//    Apache 2.0 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.Threading.Tasks;
using Microsoft.NodejsTools.Npm;
using Microsoft.NodejsTools.Npm.SPI;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace NpmTests {
    [TestClass]
    public class NpmExecuteCommandTests {
        // https://nodejstools.codeplex.com/workitem/1575
        [TestMethod, Priority(0), Timeout(180000)]
        public async Task TestNpmCommandProcessExitSucceeds() {
            var npmPath = NpmHelpers.GetPathToNpm();
            var redirector = new NpmCommand.NpmCommandRedirector(new NpmBinCommand(null, false));

            for (int j = 0; j < 200; j++) {
                await NpmHelpers.ExecuteNpmCommandAsync(
                    redirector,
                    npmPath,
                    null,
                    new[] {"config", "get", "registry"},
                    null);
            }
        }
    }
}

//*********************************************************//
//    Copyright (c) Microsoft. All rights reserved.
//
//    Apache 2.0 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.Threading.Tasks;
using Microsoft.NodejsTools.Npm;
using Microsoft.NodejsTools.Npm.SPI;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace NpmTests {
    [TestClass]
    public class NpmExecuteCommandTests {
        // https://nodejstools.codeplex.com/workitem/1575
        [Ignore]
        [TestMethod, Priority(0), Timeout(180000)]
        public async Task TestNpmCommandProcessExitSucceeds() {
            var npmPath = NpmHelpers.GetPathToNpm();
            var redirector = new NpmCommand.NpmCommandRedirector(new NpmBinCommand(null, false));

            for (int j = 0; j < 200; j++) {
                await NpmHelpers.ExecuteNpmCommandAsync(
                    redirector,
                    npmPath,
                    null,
                    new[] {"config", "get", "registry"},
                    null);
            }
        }
    }
}

Disable locally failiny npm command test


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

using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using OpenTK;
using osu.Framework.Graphics.Sprites;

namespace osu.Framework.Graphics.Cursor
{
    public class CursorContainer : Container
    {
        protected Drawable ActiveCursor;

        public CursorContainer()
        {
            Depth = float.MaxValue;
            RelativeSizeAxes = Axes.Both;
        }

        public override void Load(BaseGame game)
        {
            base.Load(game);

            Add(ActiveCursor = CreateCursor());
        }

        protected virtual Drawable CreateCursor() => new Cursor();

        public override bool Contains(Vector2 screenSpacePos) => true;

        protected override bool OnMouseMove(InputState state)
        {
            ActiveCursor.Position = state.Mouse.Position;
            return base.OnMouseMove(state);
        }

        class Cursor : CircularContainer
        {
            public Cursor()
            {
                Children = new[]
                {
                    new Box
                    {
                        Size = new Vector2(6, 6),
                        Origin = Anchor.Centre,
                        Anchor = Anchor.Centre,
                    }
                };
            }
        }
    }
}

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

using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using OpenTK;
using osu.Framework.Graphics.Sprites;
using OpenTK.Graphics;

namespace osu.Framework.Graphics.Cursor
{
    public class CursorContainer : Container
    {
        protected Drawable ActiveCursor;

        public CursorContainer()
        {
            Depth = float.MaxValue;
            RelativeSizeAxes = Axes.Both;
        }

        public override void Load(BaseGame game)
        {
            base.Load(game);

            Add(ActiveCursor = CreateCursor());
        }

        protected virtual Drawable CreateCursor() => new Cursor();

        public override bool Contains(Vector2 screenSpacePos) => true;

        protected override bool OnMouseMove(InputState state)
        {
            ActiveCursor.Position = state.Mouse.Position;
            return base.OnMouseMove(state);
        }

        class Cursor : CircularContainer
        {
            public Cursor()
            {
                BorderThickness = 2;
                BorderColour = new Color4(247, 99, 164, 255);

                Masking = true;
                GlowColour = new Color4(247, 99, 164, 6);
                GlowRadius = 50;

                Children = new[]
                {
                    new Box
                    {
                        Size = new Vector2(8, 8),
                        Origin = Anchor.Centre,
                        Anchor = Anchor.Centre,
                    }
                };
            }
        }
    }
}

Add a subtle glow to the cursor.

Add a subtle glow to the cursor.


using System.Web.Mvc;
using Cake.Web.Core.Content;

namespace Cake.Web.Controllers
{
    public class DownloadController : Controller
    {
        private readonly PackagesConfigContent _content;

        public DownloadController(PackagesConfigContent content)
        {
            _content = content;
        }

        public ActionResult Windows()
        {
            return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/build.ps1");
        }

        public ActionResult PowerShell()
        {
            return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/build.ps1");
        }

        public ActionResult Linux()
        {
            return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/build.sh");
        }

        // ReSharper disable once InconsistentNaming
        public ActionResult OSX()
        {
            return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/build.sh");
        }

        public ActionResult Bash()
        {
            return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/build.sh");
        }

        public ActionResult Configuration()
        {
            return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/cake.config");
        }

        public ActionResult Packages()
        {
            var result = File(_content.Data, "text/xml", "packages.config");
            Response.Charset = "utf-8";
            return result;
        }
    }
}

using System.Web.Mvc;
using Cake.Web.Core.Content;

namespace Cake.Web.Controllers
{
    public class DownloadController : Controller
    {
        private readonly PackagesConfigContent _content;

        public DownloadController(PackagesConfigContent content)
        {
            _content = content;
        }

        public ActionResult Windows()
        {
            return Download("https://raw.githubusercontent.com/cake-build/resources/master/build.ps1");
        }

        public ActionResult PowerShell()
        {
            return Download("https://raw.githubusercontent.com/cake-build/resources/master/build.ps1");
        }

        public ActionResult Linux()
        {
            return Download("https://raw.githubusercontent.com/cake-build/resources/master/build.sh");
        }

        // ReSharper disable once InconsistentNaming
        public ActionResult OSX()
        {
            return Download("https://raw.githubusercontent.com/cake-build/resources/master/build.sh");
        }

        public ActionResult Bash()
        {
            return Download("https://raw.githubusercontent.com/cake-build/resources/master/build.sh");
        }

        public ActionResult Configuration()
        {
            return Download("https://raw.githubusercontent.com/cake-build/resources/master/cake.config");
        }

        public ActionResult Packages()
        {
            var result = File(_content.Data, "text/xml", "packages.config");
            Response.Charset = "utf-8";
            return result;
        }

        private ActionResult Download(string url)
        {
            using (var client = new System.Net.WebClient())
            {
                return File(
                    client.DownloadData(url),
                    "text/plain; charset=utf-8"
                    );
            }
        }
    }
}

Change from Redirect to Proxy downloads

Change from Redirect to Proxy downloads


/// <summary>
/// Used by the ModuleInit. All code inside the Initialize method is ran as soon as the assembly is loaded.
/// </summary>
public static class ModuleInitializer
{
    /// <summary>
    /// Initializes the module.
    /// </summary>
    public static void Initialize()
    {

    }
}

using System.Reactive.Concurrency;
using ReactiveUI;

/// <summary>
/// Used by the ModuleInit. All code inside the Initialize method is ran as soon as the assembly is loaded.
/// </summary>
public static class ModuleInitializer
{
    /// <summary>
    /// Initializes the module.
    /// </summary>
    public static void Initialize()
    {
        RxApp.MainThreadScheduler = new WaitForDispatcherScheduler(() => DispatcherScheduler.Current);
    }
}

Make sure the MainThreadScheduler is set properly

Fixes an issue when running SaveAllTheTime with ReSharper where
ReactiveUI detects it is running in a test runner, this causes the
MainThreadScheduler to not run subscribe delegates on the dispatcher in
some cases where required


using System;
using Exceptionless.Core.Extensions;
using Exceptionless.Core.Utility;
using Foundatio.ServiceProvider;
using SimpleInjector;

namespace Exceptionless.Core.Jobs {
    public class JobBootstrapper : BootstrappedServiceProviderBase {
        public override IServiceProvider Bootstrap() {
            var container = new Container();
            container.Options.AllowOverridingRegistrations = true;
            container.Options.PropertySelectionBehavior = new InjectAttributePropertySelectionBehavior();

            container.RegisterPackage<Bootstrapper>();

            return container;
        }
    }
}

using System;
using System.Reflection;
using Exceptionless.Core.Extensions;
using Exceptionless.Core.Utility;
using Foundatio.ServiceProvider;
using NLog.Fluent;
using SimpleInjector;

namespace Exceptionless.Core.Jobs {
    public class JobBootstrapper : BootstrappedServiceProviderBase {
        public override IServiceProvider Bootstrap() {
            var container = new Container();
            container.Options.AllowOverridingRegistrations = true;
            container.Options.PropertySelectionBehavior = new InjectAttributePropertySelectionBehavior();

            container.RegisterPackage<Bootstrapper>();

            Assembly insulationAssembly = null;
            try {
                insulationAssembly = Assembly.Load("Exceptionless.Insulation");
            } catch (Exception ex) {
                Log.Error().Message("Unable to load the insulation asssembly.").Exception(ex).Write();
            }

            if (insulationAssembly != null)
                container.RegisterPackages(new[] { insulationAssembly });

            return container;
        }
    }
}

Add insulation bootstrapper to jobs.

Add insulation bootstrapper to jobs.


using System;
using System.Threading;
using System.Threading.Tasks;
using Docker.DotNet;
using Docker.DotNet.Models;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Metrics;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace SharpLab.Container.Manager.Azure {
    public class ContainerCountMetricReporter : BackgroundService {
        private static readonly MetricIdentifier ContainerCountMetric = new("Custom Metrics", "Container Count");

        private readonly DockerClient _dockerClient;
        private readonly TelemetryClient _telemetryClient;
        private readonly ILogger<ContainerCountMetricReporter> _logger;

        public ContainerCountMetricReporter(
            DockerClient dockerClient,
            TelemetryClient telemetryClient,
            ILogger<ContainerCountMetricReporter> logger
        ) {
            _dockerClient = dockerClient;
            _telemetryClient = telemetryClient;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
            while (!stoppingToken.IsCancellationRequested) {
                try {
                    var containers = await _dockerClient.Containers.ListContainersAsync(new ContainersListParameters { All = true });

                    _telemetryClient.GetMetric(ContainerCountMetric).TrackValue(containers.Count);
                }
                catch (Exception ex) {
                    _logger.LogError(ex, "Failed to report container count");
                    await Task.Delay(TimeSpan.FromMinutes(4), stoppingToken);
                }
                await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Docker.DotNet;
using Docker.DotNet.Models;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Metrics;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace SharpLab.Container.Manager.Azure {
    public class ContainerCountMetricReporter : BackgroundService {
        private static readonly MetricIdentifier ContainerCountMetric = new("Custom Metrics", "Container Count");

        private static readonly ContainersListParameters RunningOnlyListParameters = new() {
            Filters = new Dictionary<string, IDictionary<string, bool>> {
                { "status", new Dictionary<string, bool> { { "running", true } } }
            }
        };

        private readonly DockerClient _dockerClient;
        private readonly TelemetryClient _telemetryClient;
        private readonly ILogger<ContainerCountMetricReporter> _logger;

        public ContainerCountMetricReporter(
            DockerClient dockerClient,
            TelemetryClient telemetryClient,
            ILogger<ContainerCountMetricReporter> logger
        ) {
            _dockerClient = dockerClient;
            _telemetryClient = telemetryClient;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
            while (!stoppingToken.IsCancellationRequested) {
                try {
                    var containers = await _dockerClient.Containers.ListContainersAsync(RunningOnlyListParameters);

                    _telemetryClient.GetMetric(ContainerCountMetric).TrackValue(containers.Count);
                }
                catch (Exception ex) {
                    _logger.LogError(ex, "Failed to report container count");
                    await Task.Delay(TimeSpan.FromMinutes(4), stoppingToken);
                }
                await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
            }
        }
    }
}

Update Container Host to only count running containers


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Chrome Developer Tools")]
[assembly: AssemblyDescription("Contains the classes and utilities used to interact with the Chrome Developer Tools")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MasterDevs")]
[assembly: AssemblyProduct("MasterDevs.ChromeWebTools")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e7da0b93-c53b-4b4e-a873-88490c1e61cc")]

[assembly: AssemblyVersion("1.0.1")]
[assembly: AssemblyFileVersion("1.0.1")]

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Chrome Developer Tools")]
[assembly: AssemblyDescription("Contains the classes and utilities used to interact with the Chrome Developer Tools")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MasterDevs")]
[assembly: AssemblyProduct("MasterDevs.ChromeWebTools")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e7da0b93-c53b-4b4e-a873-88490c1e61cc")]

[assembly: AssemblyVersion("1.0.1")]
[assembly: AssemblyFileVersion("1.0.1")]

Mark the assembly as CLS Compliant

Mark the assembly as CLS Compliant


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

using System;
using osu.Game.Database;

#nullable enable

namespace osu.Game.Rulesets
{
    /// <summary>
    /// A representation of a ruleset's metadata.
    /// </summary>
    public interface IRulesetInfo : IHasOnlineID
    {
        /// <summary>
        /// The user-exposed name of this ruleset.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// An acronym defined by the ruleset that can be used as a permanent identifier.
        /// </summary>
        string ShortName { get; }

        /// <summary>
        /// A string representation of this ruleset, to be used with reflection to instantiate the ruleset represented by this metadata.
        /// </summary>
        string InstantiationInfo { get; }

        public Ruleset? CreateInstance()
        {
            var type = Type.GetType(InstantiationInfo);

            if (type == null)
                return null;

            var ruleset = Activator.CreateInstance(type) as Ruleset;

            // overwrite the pre-populated RulesetInfo with a potentially database attached copy.
            // ruleset.RulesetInfo = this;

            return ruleset;
        }
    }
}

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

using System;
using osu.Game.Database;

#nullable enable

namespace osu.Game.Rulesets
{
    /// <summary>
    /// A representation of a ruleset's metadata.
    /// </summary>
    public interface IRulesetInfo : IHasOnlineID
    {
        /// <summary>
        /// The user-exposed name of this ruleset.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// An acronym defined by the ruleset that can be used as a permanent identifier.
        /// </summary>
        string ShortName { get; }

        /// <summary>
        /// A string representation of this ruleset, to be used with reflection to instantiate the ruleset represented by this metadata.
        /// </summary>
        string InstantiationInfo { get; }

        public Ruleset? CreateInstance()
        {
            var type = Type.GetType(InstantiationInfo);

            if (type == null)
                return null;

            var ruleset = Activator.CreateInstance(type) as Ruleset;

            // overwrite the pre-populated RulesetInfo with a potentially database attached copy.
            // TODO: figure if we still want/need this after switching to realm.
            // ruleset.RulesetInfo = this;

            return ruleset;
        }
    }
}

Add TODO reminder about ruleset reference transfer quirk


using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup(typeof(SignInCheckIn.Startup))]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
namespace SignInCheckIn
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888

            // Branch the pipeline here for requests that start with "/signalr"
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // versions of IE) require JSONP to work cross domain
                    // EnableJSONP = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });
        }
    }
}

using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup(typeof(SignInCheckIn.Startup))]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
namespace SignInCheckIn
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            // Branch the pipeline here for requests that start with /signalr
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);

                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the /signalr
                // path.
                map.RunSignalR();
            });
        }
    }
}

Clean up the signalr mapping

Clean up the signalr mapping


// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Reflection;
using Microsoft.Framework.DependencyInjection;

namespace Microsoft.AspNet.Builder
{
    public static class UseMiddlewareExtensions
    {
        public static IApplicationBuilder UseMiddleware<T>(this IApplicationBuilder builder, params object[] args)
        {
            return builder.UseMiddleware(typeof(T), args);
        }

        public static IApplicationBuilder UseMiddleware(this IApplicationBuilder builder, Type middleware, params object[] args)
        {
            return builder.Use(next =>
            {
                var typeActivator = builder.ApplicationServices.GetService<ITypeActivator>();
                var instance = typeActivator.CreateInstance(builder.ApplicationServices, middleware, new[] { next }.Concat(args).ToArray());
                var methodinfo = middleware.GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public);
                return (RequestDelegate)methodinfo.CreateDelegate(typeof(RequestDelegate), instance);
            });
        }
    }
}

// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Reflection;
using Microsoft.Framework.DependencyInjection;

namespace Microsoft.AspNet.Builder
{
    public static class UseMiddlewareExtensions
    {
        public static IApplicationBuilder UseMiddleware<T>(this IApplicationBuilder builder, params object[] args)
        {
            return builder.UseMiddleware(typeof(T), args);
        }

        public static IApplicationBuilder UseMiddleware(this IApplicationBuilder builder, Type middleware, params object[] args)
        {
            return builder.Use(next =>
            {
                var typeActivator = builder.ApplicationServices.GetRequiredService<ITypeActivator>();
                var instance = typeActivator.CreateInstance(builder.ApplicationServices, middleware, new[] { next }.Concat(args).ToArray());
                var methodinfo = middleware.GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public);
                return (RequestDelegate)methodinfo.CreateDelegate(typeof(RequestDelegate), instance);
            });
        }
    }
}

Change GetService calls to GetRequiredService

GetRequiredService throws for missing services like GetService used to.


using System;
using System.Collections.Generic;
using System.IO;
using AppHarbor.Commands;
using Xunit;

namespace AppHarbor.Tests.Commands
{
	public class HelpCommandTest
	{
		private static Type FooCommandType = typeof(FooCommand);
		private static Type FooBarCommandType = typeof(FooBarCommand);
		private static Type BazQuxCommandType = typeof(BazQuxCommand);

		[CommandHelp("Lorem Ipsum motherfucker", "[bar]")]
		class FooCommand { }

		[CommandHelp("Lorem Ipsum motherfucker", "[bar]")]
		class FooBarCommand { }

		[CommandHelp("Ipsum lol", "[Quz]", "quux")]
		class BazQuxCommand { }

		[Fact]
		public void ShouldOutputHelpInformation()
		{
			var types = new List<Type> { FooCommandType, BazQuxCommandType, FooBarCommandType };
			var writer = new StringWriter();
			var helpCommand = new HelpCommand(types, writer);

			helpCommand.Execute(new string[0]);

			Assert.Equal("Usage: appharbor COMMAND [command-options]\r\n\r\nAvailable commands:\r\n\r\n  bar foo [bar]               #  Lorem Ipsum motherfucker\r\n  foo [bar]                   #  Lorem Ipsum motherfucker\r\n  qux baz [quz]               #  Ipsum lol (\"quux\")\r\n", writer.ToString());
		}
	}
}

using System;
using System.Collections.Generic;
using System.IO;
using AppHarbor.Commands;
using Xunit;

namespace AppHarbor.Tests.Commands
{
	public class HelpCommandTest
	{
		private static Type FooCommandType = typeof(FooCommand);
		private static Type FooBarCommandType = typeof(FooBarCommand);
		private static Type BazQuxCommandType = typeof(BazQuxCommand);

		[CommandHelp("Lorem Ipsum motherfucker", "[bar]")]
		class FooCommand { }

		[CommandHelp("Lorem Ipsum motherfucker", "[bar]")]
		class FooBarCommand { }

		[CommandHelp("Ipsum lol", "[Quz]", "quux")]
		class BazQuxCommand { }

		[Fact]
		public void ShouldOutputHelpInformation()
		{
			var types = new List<Type> { FooCommandType, BazQuxCommandType, FooBarCommandType };
			var writer = new StringWriter();
			var helpCommand = new HelpCommand(types, writer);

			helpCommand.Execute(new string[0]);
			Assert.Equal("Usage: appharbor COMMAND [command-options]\r\n\r\nAvailable commands:\r\n\r\n  bar foo [bar]               #  Lorem Ipsum motherfucker\r\n  foo [bar]                   #  Lorem Ipsum motherfucker\r\n  qux baz [quz]               #  Ipsum lol (\"quux\")\r\n\r\nCommon options:\r\n  -h, --help                 Show command help\r\n",
				writer.ToString());
		}
	}
}

Include common options in test

Include common options in test


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

namespace Mindscape.Raygun4Net.Parsers
{
  public class RaygunRequestDataJsonParser : IRaygunRequestDataParser
  {
    public IDictionary ToDictionary(string data)
    {
      try
      {
        return SimpleJson.DeserializeObject<Dictionary<string, string>>(data) as IDictionary;
      }
      catch
      {
        return null;
      }
    }
  }
}

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

namespace Mindscape.Raygun4Net.Parsers
{
  public class RaygunRequestDataJsonParser : IRaygunRequestDataParser
  {
    public IDictionary ToDictionary(string data)
    {
      try
      {
        return SimpleJson.DeserializeObject<Dictionary<string, object>>(data) as IDictionary;
      }
      catch
      {
        return null;
      }
    }
  }
}

Allow the json parser to deserialize non string values.


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

namespace Couchbase.Linq.QueryGeneration
{
    /// <summary>
    /// Helpers for N1QL query generation
    /// </summary>
    public static class N1QlHelpers
    {

        /// <summary>
        ///     Escapes a N1QL identifier using tick (`) characters
        /// </summary>
        /// <param name="identifier">The identifier to format</param>
        /// <returns>An escaped identifier</returns>
        public static string EscapeIdentifier(string identifier)
        {
            if (identifier == null)
            {
                throw new ArgumentNullException("identifier");
            }

            if (identifier.IndexOf('`') >= 0)
            {
                // This should not occur, and is primarily in place to prevent N1QL injection attacks
                // So it isn't performance critical to perform this replace in the StringBuilder

                identifier = identifier.Replace("`", "``");
            }

            var sb = new StringBuilder(identifier.Length + 2);

            sb.Append('`');
            sb.Append(identifier);
            sb.Append('`');

            return sb.ToString();
        }

    }
}

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

namespace Couchbase.Linq.QueryGeneration
{
    /// <summary>
    /// Helpers for N1QL query generation
    /// </summary>
    public static class N1QlHelpers
    {

        /// <summary>
        ///     Escapes a N1QL identifier using tick (`) characters
        /// </summary>
        /// <param name="identifier">The identifier to format</param>
        /// <returns>An escaped identifier</returns>
        public static string EscapeIdentifier(string identifier)
        {
            if (identifier == null)
            {
                throw new ArgumentNullException("identifier");
            }

            if (identifier.IndexOf('`') >= 0)
            {
                // This should not occur, and is primarily in place to prevent N1QL injection attacks
                // So it isn't performance critical to perform this replace in a StringBuilder with the concatenation

                identifier = identifier.Replace("`", "``");
            }

            return string.Concat("`", identifier, "`");
        }

    }
}

Improve N1QL identifier escaping performance

Modifications
-------------
Changed N1QlHelpers.EscapeIdentifier to using string.Concat instead of a
StringBuilder to wrap identifiers in tick marks.  When repeating the call
to EscapeIdentifier 10,000,000 times, it was approximately 50% slower to
use a StringBuilder for this function.  string.Concat, using strings and
not characters for the ticks, was the fastest alternative found.


using System.Web;
using System.Web.Optimization;

namespace TwitterWebApplication
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));

            bundles.Add(new StyleBundle("~/Structure/css").Include(
                      "~/Content/Structure/*.css"));

            bundles.Add(new StyleBundle("~/Presentation/css").Include(
                      "~/Content/Presentation/*.css"));

            bundles.Add(new StyleBundle("~/MediaQueries/css").Include(
                      "~/Content/MediaQueries/*.css"));
        }
    }
}

using System.Web;
using System.Web.Optimization;

namespace TwitterWebApplication
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-1.10.2.min.js",
                        "~/Scripts/jquery-1.10.2.intellisense.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));

            bundles.Add(new StyleBundle("~/Structure/css").Include(
                      "~/Content/Structure/*.css"));

            bundles.Add(new StyleBundle("~/Presentation/css").Include(
                      "~/Content/Presentation/*.css"));

            bundles.Add(new StyleBundle("~/MediaQueries/css").Include(
                      "~/Content/MediaQueries/*.css"));
        }
    }
}

Change import of jquery files.

Change import of jquery files.


using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Modules.JsonNet
{
    /// <summary>
    /// IFormatter implementation based on Newtonsoft.Json serialization.
    /// Requires the Serializable attribute and optionally the  ISerializable interface.
    /// Reads/writes fields, including inherited and compiler generated.
    /// Reconstructs an identical object graph on deserialization.
    /// </summary>
    public class JsonNetFormatter : IFormatter
    {
        private readonly JsonSerializer _serializer;

        public SerializationBinder Binder{ get; set; }
        public StreamingContext Context { get; set; }
        public ISurrogateSelector SurrogateSelector { get; set; }

        public JsonNetFormatter()
        {
            var settings = new JsonSerializerSettings()
            {
                ContractResolver = new DefaultContractResolver
                {
                    IgnoreSerializableAttribute = false,
                    SerializeCompilerGeneratedMembers = true
                },
                PreserveReferencesHandling = PreserveReferencesHandling.All,
                TypeNameHandling = TypeNameHandling.All,
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple

            };
            _serializer = JsonSerializer.Create(settings);
        }

        public object Deserialize(Stream serializationStream)
        {
            var reader = new JsonTextReader(new StreamReader(serializationStream));
            return _serializer.Deserialize(reader);
        }

        public void Serialize(Stream serializationStream, object graph)
        {
            var writer = new JsonTextWriter(new StreamWriter(serializationStream));
            _serializer.Serialize(writer, graph);
            writer.Flush();
        }
    }
}

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Modules.JsonNet
{
    /// <summary>
    /// IFormatter implementation based on Newtonsoft.Json serialization.
    /// Requires the Serializable attribute and optionally the  ISerializable interface.
    /// Reads/writes fields, including inherited and compiler generated.
    /// Reconstructs an identical object graph on deserialization.
    /// </summary>
    public class JsonNetFormatter : IFormatter
    {
        private readonly JsonSerializer _serializer;

        public SerializationBinder Binder{ get; set; }
        public StreamingContext Context { get; set; }
        public ISurrogateSelector SurrogateSelector { get; set; }

        public JsonNetFormatter()
        {
            var settings = new JsonSerializerSettings()
            {
                ContractResolver = new DefaultContractResolver
                {
                    IgnoreSerializableAttribute = false,
                    SerializeCompilerGeneratedMembers = true
                },
                PreserveReferencesHandling = PreserveReferencesHandling.All,
                TypeNameHandling = TypeNameHandling.All,
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                MissingMemberHandling = MissingMemberHandling.Ignore
            };
            _serializer = JsonSerializer.Create(settings);
        }

        public object Deserialize(Stream serializationStream)
        {
            var reader = new JsonTextReader(new StreamReader(serializationStream));
            return _serializer.Deserialize(reader);
        }

        public void Serialize(Stream serializationStream, object graph)
        {
            var writer = new JsonTextWriter(new StreamWriter(serializationStream));
            _serializer.Serialize(writer, graph);
            writer.Flush();
        }
    }
}

Allow missing members without throwing exceptions

BinaryFormatter does not always throw exceptions when a class member does not exist from the serialized data, but Newtonsoft.Json does.  This allows using JSON config files that are version-independent.  This may be better as a configurable option somehow, rather than explicitly always enabled.


// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;

namespace Commands.Network.Test.ScenarioTests
{
    public class TestDnsAvailabilityTest
    {
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestDnsAvailability()
        {
            NetworkResourcesController.NewInstance.RunPsTest("Test-DnsAvailability");
        }
    }
}

// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;

namespace Commands.Network.Test.ScenarioTests
{
    public class TestDnsAvailabilityTest
    {
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestDnsAvailability()
        {
           //  NetworkResourcesController.NewInstance.RunPsTest("Test-DnsAvailability");
        }
    }
}

Disable test to temp pass build

Disable test to temp pass build


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TweetDeck Client for Windows")]
[assembly: AssemblyDescription("TweetDeck Client for Windows")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct(Program.BrandName)]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7f09373d-8beb-416f-a48d-45d8aaeb8caf")]

[assembly: NeutralResourcesLanguage("en")]

[assembly: CLSCompliant(true)]

#if DEBUG
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("TweetTest.System")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("TweetTest.Unit")]
#endif

Remove directives to expose assembly internals to now removed test projects


@{
    ViewBag.Title = "Contact";
}

@ViewBag.Title.

@ViewBag.Message

<address>
    One Microsoft Way

    Redmond, WA 98052-6399

    P:
    425.555.0100
</address>

<address>
    Support:   Support@example.com

    Marketing: Marketing@example.com
    Travis: travis.elkins@zirmed.com
</address>

@{
    ViewBag.Title = "Contact";
}

@ViewBag.Title.

@ViewBag.Message

<address>
    One Microsoft Way

    Redmond, WA 98052-6399

    P:
    425.555.0100
</address>

<address>
    Support:   Support@example.com

    Marketing: Marketing@example.com
    Travis: travis.elkins@zirmed.com
    Travis2: travis.elkins@zirmed.com
</address>

Add Travis2 to contact page.

Add Travis2 to contact page.


using System;
using FFImageLoading.Drawables;

namespace FFImageLoading.Cache
{
    public class LRUCache : Android.Util.LruCache
    {
        public LRUCache(int maxSize) : base(maxSize)
        {
        }

        public event EventHandler<EntryRemovedEventArgs<Java.Lang.Object>> OnEntryRemoved;

        protected override int SizeOf(Java.Lang.Object key, Java.Lang.Object value)
        {
            var drawable = value as ISelfDisposingBitmapDrawable;

            if (drawable != null)
                return drawable.SizeInBytes;

            return 0;
        }

        protected override void EntryRemoved(bool evicted, Java.Lang.Object key, Java.Lang.Object oldValue, Java.Lang.Object newValue)
        {
            base.EntryRemoved(evicted, key, oldValue, newValue);
            OnEntryRemoved?.Invoke(this, new EntryRemovedEventArgs<Java.Lang.Object>(key.ToString(), oldValue, evicted));
        }
    }

    public class EntryRemovedEventArgs<TValue> : EventArgs
    {
        public EntryRemovedEventArgs(string key, TValue value, bool evicted)
        {
            Key = key;
            Value = value;
            Evicted = evicted;
        }

        public bool Evicted;
        public string Key;
        public TValue Value;
    }

    public class EntryAddedEventArgs<TValue> : EventArgs
    {
        public EntryAddedEventArgs(string key, TValue value)
        {
            Key = key;
            Value = value;
        }

        public string Key;
        public TValue Value;
    }
}

using System;
using FFImageLoading.Drawables;

namespace FFImageLoading.Cache
{
    public class LRUCache : Android.Util.LruCache
    {
        public LRUCache(int maxSize) : base(maxSize)
        {
        }

        public event EventHandler<EntryRemovedEventArgs<Java.Lang.Object>> OnEntryRemoved;

        protected override int SizeOf(Java.Lang.Object key, Java.Lang.Object value)
        {
            var drawable = value as ISelfDisposingBitmapDrawable;

            if (drawable != null && drawable.Handle.ToInt32() != 0)
                return drawable.SizeInBytes;

            return 0;
        }

        protected override void EntryRemoved(bool evicted, Java.Lang.Object key, Java.Lang.Object oldValue, Java.Lang.Object newValue)
        {
            base.EntryRemoved(evicted, key, oldValue, newValue);
            OnEntryRemoved?.Invoke(this, new EntryRemovedEventArgs<Java.Lang.Object>(key.ToString(), oldValue, evicted));
        }
    }

    public class EntryRemovedEventArgs<TValue> : EventArgs
    {
        public EntryRemovedEventArgs(string key, TValue value, bool evicted)
        {
            Key = key;
            Value = value;
            Evicted = evicted;
        }

        public bool Evicted;
        public string Key;
        public TValue Value;
    }

    public class EntryAddedEventArgs<TValue> : EventArgs
    {
        public EntryAddedEventArgs(string key, TValue value)
        {
            Key = key;
            Value = value;
        }

        public string Key;
        public TValue Value;
    }
}

Fix Cannot access a disposed object crash in LruCache.SizeOf method


using UnityEngine;
using System.Collections;

public class Menus : MonoBehaviour {
    public enum MenuState
    {
        Starting = 0,
        Playing = 1,
        GameOver = 2
    }

    public GameLoopManager gameLoopManager;
    public SpriteRenderer titleSprite;
    public SpriteRenderer gameOverSprite;
    public MenuState menuState = MenuState.Starting;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
        titleSprite.enabled = false;
        gameOverSprite.enabled = false;
	    switch(menuState)
        {
            case MenuState.Starting:
                titleSprite.enabled = true;
                if (Input.GetButton("Confirm"))
                {
                    gameLoopManager.StartGame();
                    menuState = MenuState.Playing;
                }
                else
                {
                    if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.Alpha1)) gameLoopManager.InitializeGame(1);
                    if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.Alpha2)) gameLoopManager.InitializeGame(2);
                    if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.Alpha3)) gameLoopManager.InitializeGame(3);
                    if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.Alpha4)) gameLoopManager.InitializeGame(4);
                }
                break;
            case MenuState.GameOver:
                gameOverSprite.enabled = true;
                break;
        }
	}
}

using UnityEngine;
using System.Collections;

public class Menus : MonoBehaviour {
    public enum MenuState
    {
        Starting = 0,
        Playing = 1,
        GameOver = 2
    }

    public GameLoopManager gameLoopManager;
    public SpriteRenderer titleSprite;
    public SpriteRenderer gameOverSprite;
    public MenuState menuState = MenuState.Starting;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
        titleSprite.enabled = false;
        gameOverSprite.enabled = false;
	    switch(menuState)
        {
            case MenuState.Starting:
                titleSprite.enabled = true;
                if (Input.GetButton("Confirm"))
                {
                    gameLoopManager.StartGame();
                    menuState = MenuState.Playing;
                }
                else
                {
                    if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.Alpha1)) gameLoopManager.InitializeGame(1);
                    if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.Alpha2)) gameLoopManager.InitializeGame(2);
                    if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.Alpha3)) gameLoopManager.InitializeGame(3);
                    if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.Alpha4)) gameLoopManager.InitializeGame(4);
                }
                break;
            case MenuState.GameOver:
                gameOverSprite.enabled = true;
                break;
        }
	}
}

Change player count with both left shift or right shift + num key


using System;
using MonoTouch.ObjCRuntime;

[assembly: LinkWith ("libTTTAttributedLabel.a", LinkTarget.Simulator | LinkTarget.ArmV7, ForceLoad = true)]

using System;
using MonoTouch.ObjCRuntime;

[assembly: LinkWith ("libTTTAttributedLabel.a", LinkTarget.Simulator | LinkTarget.ArmV7 | LinkTarget.ArmV7s, Frameworks = "CoreGraphics CoreText QuartzCore", ForceLoad = true)]

Update with LinkTarget.ArmV7s and frameworks.


using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows;

namespace Mahapps.Metro.Tests
{
    /// <summary>
    /// This class is the ultimate hack to work around that we can't
    /// create more than one application in the same AppDomain
    ///
    /// It is once initialized at the start and never properly cleaned up,
    /// this means the AppDomain will throw an exception when xUnit unloads it.
    /// </summary>
    public class TestHost
    {
        private TestApp app;
        private readonly Thread appThread;
        private readonly AutoResetEvent gate = new AutoResetEvent(false);

        private static TestHost testHost;

        public static void Initialize()
        {
            if (testHost == null)
            {
                testHost = new TestHost();
            }
        }

        private TestHost()
        {
            appThread = new Thread(StartDispatcher);
            appThread.SetApartmentState(ApartmentState.STA);
            appThread.Start();

            gate.WaitOne();
        }

        private void StartDispatcher()
        {
            app = new TestApp { ShutdownMode = ShutdownMode.OnExplicitShutdown };
            app.Startup += (sender, args) => gate.Set();
            app.Run();
        }

        /// <summary>
        /// Await this method in every test that should run on the UI thread.
        /// </summary>
        public static SwitchContextToUiThreadAwaiter SwitchToAppThread()
        {
            return new SwitchContextToUiThreadAwaiter(testHost.app.Dispatcher);
        }
    }
}

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows;

namespace Mahapps.Metro.Tests
{
    /// <summary>
    /// This class is the ultimate hack to work around that we can't
    /// create more than one application in the same AppDomain
    ///
    /// It is initialized once at startup and is never properly cleaned up,
    /// this means the AppDomain will throw an exception when xUnit unloads it.
    ///
    /// Your test runner will inevitably hate you and hang endlessly.
    ///
    /// Better than no unit tests.
    /// </summary>
    public class TestHost
    {
        private TestApp app;
        private readonly Thread appThread;
        private readonly AutoResetEvent gate = new AutoResetEvent(false);

        private static TestHost testHost;

        public static void Initialize()
        {
            if (testHost == null)
            {
                testHost = new TestHost();
            }
        }

        private TestHost()
        {
            appThread = new Thread(StartDispatcher);
            appThread.SetApartmentState(ApartmentState.STA);
            appThread.Start();

            gate.WaitOne();
        }

        private void StartDispatcher()
        {
            app = new TestApp { ShutdownMode = ShutdownMode.OnExplicitShutdown };
            app.Startup += (sender, args) => gate.Set();
            app.Run();
        }

        /// <summary>
        /// Await this method in every test that should run on the UI thread.
        /// </summary>
        public static SwitchContextToUiThreadAwaiter SwitchToAppThread()
        {
            return new SwitchContextToUiThreadAwaiter(testHost.app.Dispatcher);
        }
    }
}

Clarify that your unit test runner will never speak with you again


using System.Threading.Tasks;
using System.Web.Mvc;
using SFA.DAS.Authorization.Mvc.Attributes;
using SFA.DAS.EmployerFinance.Web.Orchestrators;

namespace SFA.DAS.EmployerFinance.Web.Controllers
{
    [DasAuthorize("EmployerFeature.TransfersMatching")]
    [RoutePrefix("accounts/{HashedAccountId}")]
    public class TransfersController : Controller
    {
        private readonly TransfersOrchestrator _transfersOrchestrator;

        public TransfersController(TransfersOrchestrator transfersOrchestrator)
        {
            _transfersOrchestrator = transfersOrchestrator;
        }

        [HttpGet]
        [Route("transfers")]
        public async Task<ActionResult> Index(string hashedAccountId)
        {
            var viewModel = await _transfersOrchestrator.GetIndexViewModel(hashedAccountId);

            return View(viewModel);
        }

        [HttpGet]
        [Route("transfers/financial-breakdown")]
        public ActionResult FinancialBreakdown(string hashedAccountId)
        {
            return View();
        }
    }
}

using System.Threading.Tasks;
using System.Web.Mvc;
using SFA.DAS.Authorization.Mvc.Attributes;
using SFA.DAS.EmployerFinance.Web.Orchestrators;

namespace SFA.DAS.EmployerFinance.Web.Controllers
{
    [RoutePrefix("accounts/{HashedAccountId}")]
    public class TransfersController : Controller
    {
        private readonly TransfersOrchestrator _transfersOrchestrator;

        public TransfersController(TransfersOrchestrator transfersOrchestrator)
        {
            _transfersOrchestrator = transfersOrchestrator;
        }

        [HttpGet]
        [Route("transfers")]
        public async Task<ActionResult> Index(string hashedAccountId)
        {
            var viewModel = await _transfersOrchestrator.GetIndexViewModel(hashedAccountId);

            return View(viewModel);
        }

        [DasAuthorize("EmployerFeature.FinanceDetails")]
        [HttpGet]
        [Route("transfers/financial-breakdown")]
        public ActionResult FinancialBreakdown(string hashedAccountId)
        {
            return View();
        }
    }
}

Remove TransfersMatching flag and use the new one at action level


using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;

namespace SocialSample
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel(options =>
                {
                    if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT")))
                    {
                        // ANCM is not hosting the process
                        options.Listen(IPAddress.Loopback, 5000, listenOptions =>
                        {
                            // Configure SSL
                            var serverCertificate = LoadCertificate();
                            listenOptions.UseHttps(serverCertificate);
                        });
                    }
                })
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }

        private static X509Certificate2 LoadCertificate()
        {
            var socialSampleAssembly = typeof(Startup).GetTypeInfo().Assembly;
            var embeddedFileProvider = new EmbeddedFileProvider(socialSampleAssembly, "SocialSample");
            var certificateFileInfo = embeddedFileProvider.GetFileInfo("compiler/resources/cert.pfx");
            using (var certificateStream = certificateFileInfo.CreateReadStream())
            {
                byte[] certificatePayload;
                using (var memoryStream = new MemoryStream())
                {
                    certificateStream.CopyTo(memoryStream);
                    certificatePayload = memoryStream.ToArray();
                }

                return new X509Certificate2(certificatePayload, "testPassword");
            }
        }
    }
}

using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;

namespace SocialSample
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel(options =>
                {
                    if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT")))
                    {
                        // ANCM is not hosting the process
                        options.Listen(IPAddress.Loopback, 44318, listenOptions =>
                        {
                            // Configure SSL
                            var serverCertificate = LoadCertificate();
                            listenOptions.UseHttps(serverCertificate);
                        });
                    }
                })
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }

        private static X509Certificate2 LoadCertificate()
        {
            var socialSampleAssembly = typeof(Startup).GetTypeInfo().Assembly;
            var embeddedFileProvider = new EmbeddedFileProvider(socialSampleAssembly, "SocialSample");
            var certificateFileInfo = embeddedFileProvider.GetFileInfo("compiler/resources/cert.pfx");
            using (var certificateStream = certificateFileInfo.CreateReadStream())
            {
                byte[] certificatePayload;
                using (var memoryStream = new MemoryStream())
                {
                    certificateStream.CopyTo(memoryStream);
                    certificatePayload = memoryStream.ToArray();
                }

                return new X509Certificate2(certificatePayload, "testPassword");
            }
        }
    }
}

Fix the social sample port.

Fix the social sample port.


using System;
using System.IO;

namespace Hangman {
  public class Hangman {
    public static void Main(string[] args) {
      var game = new Game("HANG THE MAN");

      string titleText = File.ReadAllText("title.txt");

      object[] titleCell = {titleText, Cell.CentreAlign};
      object[] titleRow = {titleCell};

      while (true) {
        string shownWord = game.ShownWord();

        object[] wordCell = {shownWord, Cell.CentreAlign};
        object[] wordRow = {wordCell};

        object[] lettersCell = {"Incorrect letters:\n A B I U", Cell.LeftAlign};
        object[] livesCell   = {"Lives remaining:\n 11/15",     Cell.RightAlign};
        object[] statsRow = {lettersCell, livesCell};

        object[] statusCell = {"Press any letter to guess!", Cell.CentreAlign};
        object[] statusRow = {statusCell};

        object[] tableConfig = {
          titleRow,
          wordRow,
          statsRow,
          statusRow
        };

        // var table = new Table(                 // Broken
        //   Math.Min(81, Console.WindowWidth),
        //   2,
        //   rows
        // );

        var table = TableFactory.Build(tableConfig);

        // var tableOutput = table.Draw();

        // Console.WriteLine(tableOutput);

        Console.WriteLine("Still Alive");

        char key = Console.ReadKey(true).KeyChar;
        bool wasCorrect = game.GuessLetter(Char.ToUpper(key));
        Console.Clear();
      }
    }
  }
}

using System;
using System.IO;

namespace Hangman {
  public class Hangman {
    public static void Main(string[] args) {
      var game = new Game("HANG THE MAN");

      string titleText = File.ReadAllText("title.txt");

      object[] titleCell = {titleText, Cell.CentreAlign};
      object[] titleRow = {titleCell};

      while (true) {
        string shownWord = game.ShownWord();

        object[] wordCell = {shownWord, Cell.CentreAlign};
        object[] wordRow = {wordCell};

        object[] lettersCell = {"Incorrect letters:\n A B I U", Cell.LeftAlign};
        object[] livesCell   = {"Lives remaining:\n 11/15",     Cell.RightAlign};
        object[] statsRow = {lettersCell, livesCell};

        object[] statusCell = {"Press any letter to guess!", Cell.CentreAlign};
        object[] statusRow = {statusCell};

        object[] tableConfig = {
          titleRow,
          wordRow,
          statsRow,
          statusRow
        };

        var table = TableFactory.Build(tableConfig);
        var tableOutput = table.Draw();
        Console.WriteLine(tableOutput);

        Console.WriteLine("Still Alive");

        char key = Console.ReadKey(true).KeyChar;
        bool wasCorrect = game.GuessLetter(Char.ToUpper(key));
        Console.Clear();
      }
    }
  }
}

Call Draw on the output of Build

Call Draw on the output of Build


using System;
using System.Windows.Forms;
using VigilantCupcake.OperatingSystemUtilities;

namespace VigilantCupcake {

    internal static class Program {

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main() {
            if (!SingleInstance.Start()) {
                SingleInstance.ShowFirstInstance();
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (Properties.Settings.Default.UpgradeRequired) {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.UpgradeRequired = false;
                Properties.Settings.Default.Save();
            }

            try {
                MainForm mainForm = new MainForm();
                Application.Run(mainForm);
            } catch (Exception e) {
                MessageBox.Show(e.Message);
            }

            SingleInstance.Stop();
        }
    }
}

using System;
using System.Windows.Forms;
using VigilantCupcake.OperatingSystemUtilities;

namespace VigilantCupcake {

    internal static class Program {

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main() {

            if (Properties.Settings.Default.UpgradeRequired) {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.UpgradeRequired = false;
                Properties.Settings.Default.Save();
            }

            if (!SingleInstance.Start()) {
                SingleInstance.ShowFirstInstance();
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            try {
                MainForm mainForm = new MainForm();
                Application.Run(mainForm);
            } catch (Exception e) {
                MessageBox.Show(e.Message);
            }

            SingleInstance.Stop();
        }
    }
}

Move settings update to first line

Move settings update to first line


using Albatross.Expression;
using System;

namespace RollGen.Domain
{
    public class RandomDice : Dice
    {
        private readonly Random random;

        public RandomDice(Random random)
        {
            this.random = random;
        }

        public override PartialRoll Roll(int quantity = 1)
        {
            return new RandomPartialRoll(quantity, random);
        }

        public override object Compute(string rolled)
        {
            var unrolledDieRolls = rollRegex.Matches(rolled);

            if (unrolledDieRolls.Count > 0)
            {
                var message = string.Format("Cannot compute unrolled die roll {0}", unrolledDieRolls[0]);
                throw new ArgumentException(message);
            }

            return Parser.GetParser().Compile(rolled).EvalValue(null);
        }
    }
}

using Albatross.Expression;
using System;

namespace RollGen.Domain
{
    public class RandomDice : Dice
    {
        private readonly Random random;

        public RandomDice(Random random)
        {
            this.random = random;
        }

        public override PartialRoll Roll(int quantity = 1)
        {
            return new RandomPartialRoll(quantity, random);
        }

        public override object Compute(string rolled)
        {
            if (rollRegex.IsMatch(rolled))
            {
                var match = rollRegex.Match(rolled);
                var message = string.Format("Cannot compute unrolled die roll {0}", match.Value);
                throw new ArgumentException(message);
            }

            return Parser.GetParser().Compile(rolled).EvalValue(null);
        }
    }
}

Check regex for only 1 match

Check regex for only 1 match


using SRPCommon.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using System.Diagnostics.CodeAnalysis;

namespace SRPCommon.Scene
{
	public class MeshInstancePrimitive : Primitive
	{
		public override PrimitiveType Type => PrimitiveType.MeshInstance;

		public SceneMesh Mesh { get; private set; }

		public override bool IsValid => Mesh != null;

		[JsonProperty("mesh")]
		[SuppressMessage("Language", "CSE0002:Use getter-only auto properties", Justification = "Needed for serialisation")]
		private string MeshName { get; set; }

		internal override void PostLoad(Scene scene)
		{
			base.PostLoad(scene);

			if (MeshName != null)
			{
				// Look up mesh in the scene's collection.
				SceneMesh mesh;
				if (scene.Meshes.TryGetValue(MeshName, out mesh))
				{
					Mesh = mesh;
				}
				else
				{
					OutputLogger.Instance.LogLine(LogCategory.Log, "Mesh not found: " + MeshName);
				}
			}
		}
	}
}

using SRPCommon.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using System.Diagnostics.CodeAnalysis;

namespace SRPCommon.Scene
{
	public class MeshInstancePrimitive : Primitive
	{
		public override PrimitiveType Type => PrimitiveType.MeshInstance;

		public SceneMesh Mesh { get; private set; }

		public override bool IsValid => Mesh != null && Mesh.IsValid;

		[JsonProperty("mesh")]
		[SuppressMessage("Language", "CSE0002:Use getter-only auto properties", Justification = "Needed for serialisation")]
		private string MeshName { get; set; }

		internal override void PostLoad(Scene scene)
		{
			base.PostLoad(scene);

			if (MeshName != null)
			{
				// Look up mesh in the scene's collection.
				SceneMesh mesh;
				if (scene.Meshes.TryGetValue(MeshName, out mesh))
				{
					Mesh = mesh;
				}
				else
				{
					OutputLogger.Instance.LogLine(LogCategory.Log, "Mesh not found: " + MeshName);
				}
			}
		}
	}
}

Fix exception with invalid mesh

Fix exception with invalid mesh


using System;

namespace CertiPay.Common.WorkQueue
{
    public class CompletedWorkItem<T>
    {
        public T WorkItem { get; set; }

        public String Server { get; set; }

        public DateTime CompletedAt { get; set; }

        // TODO Version?

        public CompletedWorkItem()
        {
            this.Server = System.Environment.MachineName;
            this.CompletedAt = DateTime.UtcNow;
        }
    }
}

using System;

namespace CertiPay.Common.WorkQueue
{
    public class CompletedWorkItem<T>
    {
        public T WorkItem { get; set; }

        public String Server { get; set; }

        public DateTime CompletedAt { get; set; }

        public String Version { get; set; }

        public EnvUtil.Environment Environment { get; set; }

        public CompletedWorkItem()
        {
            this.Server = System.Environment.MachineName;
            this.CompletedAt = DateTime.UtcNow;
            this.Version = Utilities.Version;
            this.Environment = EnvUtil.Current;
        }
    }
}

Add version and environment to completed/failed work item


@using CkanDotNet.Web.Models.Helpers
@using System.Configuration

<!--v Denvergov:1of3(head) v-->
	<!--[if lt IE 9]>
	<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
	<link rel="Stylesheet" type="text/css" href="http://dgqa.denvergov.org/dgskin1/Scripts/Denvergov.style.skin.css" />
    <link rel="shortcut icon" href="@Url.Content("~/Content/Theme/" + SettingsHelper.GetCatalogTheme() + "/favicon.ico")"/>
	<script type="text/javascript" src="@Url.Content(ConfigurationManager.AppSettings["Catalog.SkinLocation"] + "/dgskin1/Scripts/Denvergov.skin.js")"></script>
<!--^ Denvergov:1of3(head) ^-->

<link rel="Stylesheet" type="text/css" href="@Url.Content(ConfigurationManager.AppSettings["Catalog.SkinLocation"] + "/Portals/_default/Skins/DenverGov/skin.css")" />

<link href="@Url.Content("~/Content/Theme/" + SettingsHelper.GetCatalogTheme() + "/Styles.css")" rel="stylesheet" type="text/css" />

@using CkanDotNet.Web.Models.Helpers
@using System.Configuration

<!--v Denvergov:1of3(head) v-->
	<!--[if lt IE 9]>
	<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
	<link rel="Stylesheet" type="text/css" href="@Url.Content(ConfigurationManager.AppSettings["Catalog.SkinLocation"] + "/dgskin1/Scripts/Denvergov.style.skin.css")" />
    <link rel="shortcut icon" href="@Url.Content("~/Content/Theme/" + SettingsHelper.GetCatalogTheme() + "/favicon.ico")"/>
	<script type="text/javascript" src="@Url.Content(ConfigurationManager.AppSettings["Catalog.SkinLocation"] + "/dgskin1/Scripts/Denvergov.skin.js")"></script>
<!--^ Denvergov:1of3(head) ^-->

<link rel="Stylesheet" type="text/css" href="@Url.Content(ConfigurationManager.AppSettings["Catalog.SkinLocation"] + "/Portals/_default/Skins/DenverGov/skin.css")" />

<link href="@Url.Content("~/Content/Theme/" + SettingsHelper.GetCatalogTheme() + "/Styles.css")" rel="stylesheet" type="text/css" />

Fix Denver theme to point CSS to configured skin location


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using UsageSampleMvc.AspNetCore.Models;

namespace UsageSampleMvc.AspNetCore.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using UsageSampleMvc.AspNetCore.Models;

namespace UsageSampleMvc.AspNetCore.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [Authorize]
        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        [Authorize]
        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Add Authorize attributes to verify sample


using System.Net;
using System.Net.Http;
using System.Web.Http.ExceptionHandling;
using FluentValidation;
using NLog;
using SFA.DAS.Commitments.Application.Exceptions;

namespace SFA.DAS.Commitments.Api
{
    public class CustomExceptionHandler : ExceptionHandler
    {
        private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

        public override void Handle(ExceptionHandlerContext context)
        {
            if (context.Exception is ValidationException)
            {
                var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                var message = ((ValidationException)context.Exception).Message;
                response.Content = new StringContent(message);
                context.Result = new CustomErrorResult(context.Request, response);

                Logger.Warn(context.Exception, "Validation error");

                return;
            }

            if (context.Exception is UnauthorizedException)
            {
                var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                var message = ((UnauthorizedException)context.Exception).Message;
                response.Content = new StringContent(message);
                context.Result = new CustomErrorResult(context.Request, response);

                Logger.Warn(context.Exception, "Authorisation error");

                return;
            }

            base.Handle(context);
        }
    }
}

using System.Net;
using System.Net.Http;
using System.Web.Http.ExceptionHandling;
using FluentValidation;
using NLog;
using SFA.DAS.Commitments.Application.Exceptions;

namespace SFA.DAS.Commitments.Api
{
    public class CustomExceptionHandler : ExceptionHandler
    {
        private static readonly ILogger _logger = LogManager.GetCurrentClassLogger();

        public override void Handle(ExceptionHandlerContext context)
        {
            if (context.Exception is ValidationException)
            {
                var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                var message = ((ValidationException)context.Exception).Message;
                response.Content = new StringContent(message);
                context.Result = new CustomErrorResult(context.Request, response);

                _logger.Warn(context.Exception, "Validation error");

                return;
            }

            if (context.Exception is UnauthorizedException)
            {
                var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                var message = ((UnauthorizedException)context.Exception).Message;
                response.Content = new StringContent(message);
                context.Result = new CustomErrorResult(context.Request, response);

                _logger.Warn(context.Exception, "Authorisation error");

                return;
            }

            _logger.Error(context.Exception, "Unhandled exception");

            base.Handle(context);
        }
    }
}

Put unhandled exception logging in to custom handler class.


@model Vaskelista.Models.Household

@{
    ViewBag.Title = "Create";
}

Velkommen til vaskelista

Her kan du velge hva vaskelisten din skal hete:

@Request.Url.ToString()

                        @foreach (string randomUrl in ViewBag.RandomUrls)
                        {

                                @using (Html.BeginForm("Create", "Household", FormMethod.Post))
                                {
                                    @Html.AntiForgeryToken()
                                    @Html.HiddenFor(model => model.Token, new { Value = randomUrl })
                                    <input type="submit" value="@randomUrl" class="btn btn-default" />
                                }

                        }

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Adjust column width on url part on the create household page


namespace NRules.Fluent.Dsl
{
    /// <summary>
    /// Root of the query method chain.
    /// </summary>
    public interface IQuery
    {
        /// <summary>
        /// Internal query builder.
        /// This method is intended for framework use only.
        /// </summary>
        IQueryBuilder Builder { get; }
    }

    /// <summary>
    /// Intermediate query chain element.
    /// </summary>
    /// <typeparam name="TSource">Type of the element the query operates on.</typeparam>
    public interface IQuery<out TSource>
    {
        /// <summary>
        /// Internal query builder.
        /// This method is intended for framework use only.
        /// </summary>
        IQueryBuilder Builder { get; }
    }
}

using System.ComponentModel;

namespace NRules.Fluent.Dsl
{
    /// <summary>
    /// Root of the query method chain.
    /// </summary>
    public interface IQuery
    {
        /// <summary>
        /// Internal query builder.
        /// This method is intended for framework use only.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        IQueryBuilder Builder { get; }
    }

    /// <summary>
    /// Intermediate query chain element.
    /// </summary>
    /// <typeparam name="TSource">Type of the element the query operates on.</typeparam>
    public interface IQuery<out TSource>
    {
        /// <summary>
        /// Internal query builder.
        /// This method is intended for framework use only.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        IQueryBuilder Builder { get; }
    }
}

Mark internal query builder non-browsable


using System;
using Flood.GUI.Controls;
using Flood.GUI.Renderers;
using Flood.GUI.Skins;

namespace Flood.Editor.Client.Gui
{
    public abstract class GuiWindow : IDisposable
    {
        /// <summary>
        /// Native GUI window.
        /// </summary>
        public Window NativeWindow  { get; set; }

        /// <summary>
        /// Renderer of the GUI.
        /// </summary>
        public Renderer Renderer { get; private set; }

        /// <summary>
        /// Skin of the GUI.
        /// </summary>
        public Skin Skin { get; private set; }

        public Canvas Canvas { get; private set; }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposing) return;

            Canvas.Dispose();
            Skin.Dispose();
            Renderer.Dispose();
        }

        public void Init(Renderer renderer, string textureName, Flood.GUI.Font defaultFont)
        {
            Renderer = renderer;

            var resMan = FloodEngine.GetEngine().ResourceManager;
            var options = new ResourceLoadOptions {Name = textureName, AsynchronousLoad = false};
            var imageHandle = resMan.LoadResource<Image>(options);

            Skin = new TexturedSkin(renderer, imageHandle, defaultFont);
            Canvas = new Canvas(Skin);

            Init();
        }

        protected abstract void Init();

        public void Render()
        {
            Canvas.RenderCanvas();
        }
    }
}

using System;
using Flood.GUI.Controls;
using Flood.GUI.Renderers;
using Flood.GUI.Skins;

namespace Flood.Editor.Client.Gui
{
    public abstract class GuiWindow : IDisposable
    {
        /// <summary>
        /// Native GUI window.
        /// </summary>
        public Window NativeWindow  { get; set; }

        /// <summary>
        /// Renderer of the GUI.
        /// </summary>
        public Renderer Renderer { get; private set; }

        /// <summary>
        /// Skin of the GUI.
        /// </summary>
        public Skin Skin { get; private set; }

        public Canvas Canvas { get; private set; }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposing) return;

            Canvas.Dispose();
            Skin.Dispose();
            Renderer.Dispose();
        }

        public void Init(Renderer renderer, string textureName, Flood.GUI.Font defaultFont)
        {
            Renderer = renderer;

            var resMan = FloodEngine.GetEngine().ResourceManager;
            var options = new ResourceLoadOptions {Name = textureName, AsynchronousLoad = false};
            var imageHandle = resMan.LoadResource<Image>(options);
            if (imageHandle.Id == 0)
                return;

            Skin = new TexturedSkin(renderer, imageHandle, defaultFont);
            Canvas = new Canvas(Skin);

            Init();
        }

        protected abstract void Init();

        public void Render()
        {
            Canvas.RenderCanvas();
        }
    }
}

Check for a valid image handle when loading resources in the editor.


namespace FlatBuffers
{
    public static class FieldTypeMetaData
    {
        public const string Index = "id";
        public const string Required = "required";
    }
}

Build fix? (not sure why travis doesn't see this file)


using System;
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.Classes;

namespace DesktopWidgets.Actions
{
    public abstract class ActionBase
    {
        [DisplayName("Delay")]
        public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0);

        [DisplayName("Show Errors")]
        public bool ShowErrors { get; set; } = false;

        public void Execute()
        {
            DelayedAction.RunAction((int) Delay.TotalMilliseconds, () =>
            {
                try
                {
                    ExecuteAction();
                }
                catch (Exception ex)
                {
                    if (ShowErrors)
                        Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}",
                            image: MessageBoxImage.Error);
                }
            });
        }

        public virtual void ExecuteAction()
        {
        }
    }
}

using System;
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.Classes;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace DesktopWidgets.Actions
{
    public abstract class ActionBase
    {
        [PropertyOrder(0)]
        [DisplayName("Delay")]
        public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0);

        [PropertyOrder(1)]
        [DisplayName("Show Errors")]
        public bool ShowErrors { get; set; } = false;

        public void Execute()
        {
            DelayedAction.RunAction((int) Delay.TotalMilliseconds, () =>
            {
                try
                {
                    ExecuteAction();
                }
                catch (Exception ex)
                {
                    if (ShowErrors)
                        Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}",
                            image: MessageBoxImage.Error);
                }
            });
        }

        public virtual void ExecuteAction()
        {
        }
    }
}

Add base action property ordering

Add base action property ordering


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

namespace SharpDX.Direct2D1
{
    public partial class SvgDocument
    {
        /// <summary>
        /// Finds an svg element by id
        /// </summary>
        /// <param name="id">Id to lookup for</param>
        /// <returns>SvgElement</returns>
        public SvgElement FindElementById(string id)
        {
            SharpDX.Result __result__;
            SvgElement svgElement;
            __result__ = TryFindElementById_(id, out svgElement);

            __result__.CheckError();
            return svgElement;
        }

        /// <summary>
        /// Try to find an element by id
        /// </summary>
        /// <param name="id">id to search for</param>
        /// <param name="svgElement">When this method completes, contains the relevant element (if applicable)</param>
        /// <returns>true if element has been found, false otherwise</returns>
        public bool TryFindElementById(string id, out SvgElement svgElement)
        {
            SharpDX.Result __result__;
            __result__ = TryFindElementById_(id, out svgElement);

            return __result__.Code >= 0;
        }
    }
}

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

namespace SharpDX.Direct2D1
{
    public partial class SvgDocument
    {
        /// <summary>
        /// Finds an svg element by id
        /// </summary>
        /// <param name="id">Id to lookup for</param>
        /// <returns>SvgElement if found, null otherwise</returns>
        public SvgElement FindElementById(string id)
        {
            SharpDX.Result __result__;
            SvgElement svgElement;
            __result__ = TryFindElementById_(id, out svgElement);

            __result__.CheckError();
            return svgElement;
        }
    }
}

Remove some methods to try get element, as if an element is not found, Direct2D only returns a zero pointer with a S_Ok hresult


namespace ChessDotNet
{
    public abstract class ChessPiece
    {
        public abstract Player Owner
        {
            get;
            set;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj))
                return true;
            if (obj == null || GetType() != obj.GetType())
                return false;
            ChessPiece piece1 = this;
            ChessPiece piece2 = (ChessPiece)obj;
            return piece1.Owner == piece2.Owner;
        }

        public override int GetHashCode()
        {
            return new { Piece = GetFenCharacter(), Owner }.GetHashCode();
        }

        public static bool operator ==(ChessPiece piece1, ChessPiece piece2)
        {
            if (ReferenceEquals(piece1, piece2))
                return true;
            if ((object)piece1 == null || (object)piece2 == null)
                return false;
            return piece1.Equals(piece2);
        }

        public static bool operator !=(ChessPiece piece1, ChessPiece piece2)
        {
            if (ReferenceEquals(piece1, piece2))
                return false;
            if ((object)piece1 == null || (object)piece2 == null)
                return true;
            return !piece1.Equals(piece2);
        }

        public abstract string GetFenCharacter();
        public abstract bool IsValidDestination(Position from, Position to);
    }
}

namespace ChessDotNet
{
    public abstract class ChessPiece
    {
        public abstract Player Owner
        {
            get;
            set;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj))
                return true;
            if (obj == null || GetType() != obj.GetType())
                return false;
            ChessPiece piece1 = this;
            ChessPiece piece2 = (ChessPiece)obj;
            return piece1.Owner == piece2.Owner;
        }

        public override int GetHashCode()
        {
            return new { Piece = GetFenCharacter(), Owner }.GetHashCode();
        }

        public static bool operator ==(ChessPiece piece1, ChessPiece piece2)
        {
            if (ReferenceEquals(piece1, piece2))
                return true;
            if ((object)piece1 == null || (object)piece2 == null)
                return false;
            return piece1.Equals(piece2);
        }

        public static bool operator !=(ChessPiece piece1, ChessPiece piece2)
        {
            if (ReferenceEquals(piece1, piece2))
                return false;
            if ((object)piece1 == null || (object)piece2 == null)
                return true;
            return !piece1.Equals(piece2);
        }

        public abstract string GetFenCharacter();
        public abstract bool IsValidDestination(Position from, Position to, ChessGame game);
    }
}

Add ChessGame parameter to IsValidDestination