using System;
using System.ServiceModel;

namespace MultiMiner.Remoting.Server
{
    public class RemotingServer
    {
        private bool serviceStarted = false;
        private ServiceHost myServiceHost = null;

        public void Startup()
        {
            Uri baseAddress = new Uri("net.tcp://localhost:" + Config.RemotingPort + "/RemotingService");

            NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);

            myServiceHost = new ServiceHost(typeof(RemotingService), baseAddress);
            myServiceHost.AddServiceEndpoint(typeof(IRemotingService), binding, baseAddress);

            myServiceHost.Open();

            serviceStarted = true;
        }

        public void Shutdown()
        {
            if (!serviceStarted)
                return;

            myServiceHost.Close();
            myServiceHost = null;
            serviceStarted = false;
        }
    }
}

using System;
using System.Net;
using System.ServiceModel;

namespace MultiMiner.Remoting.Server
{
    public class RemotingServer
    {
        private bool serviceStarted = false;
        private ServiceHost myServiceHost = null;

        public void Startup()
        {
            //use Dns.GetHostName() instead of localhost for compatibility with Mono+Linux
            //https://github.com/nwoolls/MultiMiner/issues/62
            Uri baseAddress = new Uri(String.Format("net.tcp://{0}:{1}/RemotingService", Dns.GetHostName(), Config.RemotingPort));

            NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);

            myServiceHost = new ServiceHost(typeof(RemotingService), baseAddress);
            myServiceHost.AddServiceEndpoint(typeof(IRemotingService), binding, baseAddress);

            myServiceHost.Open();

            serviceStarted = true;
        }

        public void Shutdown()
        {
            if (!serviceStarted)
                return;

            myServiceHost.Close();
            myServiceHost = null;
            serviceStarted = false;
        }
    }
}

Improve MultiMiner Remoting compatibility on Linux+Mono


using Autofac;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using TeaCommerce.Api.Dependency;
using TeaCommerce.Api.Infrastructure.Caching;
using umbraco.interfaces;
using Umbraco.Core.Cache;

namespace TeaCommerce.Umbraco.Application.Caching
{
    public abstract class TeaCommerceCacheRefresherBase<TInstanceType, TEntity, TId> : JsonCacheRefresherBase<TInstanceType>
        where TInstanceType : ICacheRefresher
    {
        protected ICacheService CacheService => DependencyContainer.Instance.Resolve<ICacheService>();

        public abstract string CacheKeyFormat { get; }

        public override void Refresh(string jsonPayload)
        {
            var payload = JsonConvert.DeserializeObject<TeaCommerceCacheRefresherPayload<TId>>(jsonPayload);

            // Make sure it wasn't this instance that sent the payload
            if (payload.InstanceId != Constants.InstanceId)
            {
                var cacheKey = string.Format(CacheKeyFormat, payload.StoreId, payload.Id);
                var cache = CacheService.GetCacheValue<ConcurrentDictionary<TId, TEntity>>(cacheKey);
                if (cache.ContainsKey(payload.Id))
                {
                    cache.TryRemove(payload.Id, out var removed);
                }

                base.Refresh(jsonPayload);
            }
        }

        public override void Refresh(int id)
        {
            throw new NotSupportedException();
        }

        public override void Refresh(Guid id)
        {
            throw new NotSupportedException();
        }

        public override void RefreshAll()
        {
            throw new NotSupportedException();
        }

        public override void Remove(int id)
        {
            throw new NotSupportedException();
        }
    }
}

using Autofac;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using TeaCommerce.Api.Dependency;
using TeaCommerce.Api.Infrastructure.Caching;
using umbraco.interfaces;
using Umbraco.Core.Cache;

namespace TeaCommerce.Umbraco.Application.Caching
{
    public abstract class TeaCommerceCacheRefresherBase<TInstanceType, TEntity, TId> : JsonCacheRefresherBase<TInstanceType>
        where TInstanceType : ICacheRefresher
    {
        protected ICacheService CacheService => DependencyContainer.Instance.Resolve<ICacheService>();

        public abstract string CacheKeyFormat { get; }

        public override void Refresh(string jsonPayload)
        {
            var payload = JsonConvert.DeserializeObject<TeaCommerceCacheRefresherPayload<TId>>(jsonPayload);

            // Make sure it wasn't this instance that sent the payload
            if (payload != null && payload.InstanceId != Constants.InstanceId)
            {
                var cacheKey = string.Format(CacheKeyFormat, payload.StoreId, payload.Id);
                var cache = CacheService.GetCacheValue<ConcurrentDictionary<TId, TEntity>>(cacheKey);
                if (cache != null && cache.ContainsKey(payload.Id))
                {
                    cache.TryRemove(payload.Id, out var removed);
                }

                base.Refresh(jsonPayload);
            }
        }

        public override void Refresh(int id)
        {
            throw new NotSupportedException();
        }

        public override void Refresh(Guid id)
        {
            throw new NotSupportedException();
        }

        public override void RefreshAll()
        {
            throw new NotSupportedException();
        }

        public override void Remove(int id)
        {
            throw new NotSupportedException();
        }
    }
}

Add null check to cache refresher

Add null check to cache refresher


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Tigwi.UI.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            throw new NotImplementedException("HomeController.Index");
        }

        public ActionResult About()
        {
            return View();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Tigwi.UI.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            this.ViewBag.CurrentUser = "Zak";
            return this.View();
        }

        public ActionResult About()
        {
            return View();
        }
    }
}

Create an empty Home controller.

Create an empty Home controller.

That's necessary for working on the HTML at the same time.


using System.Net;
using Criteo.Profiling.Tracing.Annotation;

namespace Criteo.Profiling.Tracing
{

    /// <summary>
    /// Factory for annotations
    /// </summary>
    public static class Annotations
    {

        public static IAnnotation ClientRecv()
        {
            return new ClientRecv();
        }

        public static IAnnotation ClientSend()
        {
            return new ClientSend();
        }

        public static IAnnotation ServerRecv()
        {
            return new ServerRecv();
        }

        public static IAnnotation ServerSend()
        {
            return new ServerSend();
        }

        public static IAnnotation Rpc(string name)
        {
            return new Rpc(name);
        }

        public static IAnnotation ServiceName(string name)
        {
            return new ServiceName(name);
        }

        public static IAnnotation LocalAddr(IPEndPoint endPoint)
        {
            return new LocalAddr(endPoint);
        }

        public static IAnnotation Binary(string key, object value)
        {
            return new BinaryAnnotation(key, value);
        }

        public static IAnnotation Event(string name)
        {
            return new Event(name);
        }

    }
}

using System.Net;
using Criteo.Profiling.Tracing.Annotation;

namespace Criteo.Profiling.Tracing
{

    /// <summary>
    /// Factory for annotations
    /// </summary>
    public static class Annotations
    {
        private static readonly IAnnotation AnnClientReceive = new ClientRecv();
        private static readonly IAnnotation AnnClientSend = new ClientSend();
        private static readonly IAnnotation AnnServerReceive = new ServerRecv();
        private static readonly IAnnotation AnnServerSend = new ServerSend();

        public static IAnnotation ClientRecv()
        {
            return AnnClientReceive;
        }

        public static IAnnotation ClientSend()
        {
            return AnnClientSend;
        }

        public static IAnnotation ServerRecv()
        {
            return AnnServerReceive;
        }

        public static IAnnotation ServerSend()
        {
            return AnnServerSend;
        }

        public static IAnnotation Rpc(string name)
        {
            return new Rpc(name);
        }

        public static IAnnotation ServiceName(string name)
        {
            return new ServiceName(name);
        }

        public static IAnnotation LocalAddr(IPEndPoint endPoint)
        {
            return new LocalAddr(endPoint);
        }

        public static IAnnotation Binary(string key, object value)
        {
            return new BinaryAnnotation(key, value);
        }

        public static IAnnotation Event(string name)
        {
            return new Event(name);
        }

    }
}

Remove unnecessary object creation of IAnnotation

Change-Id: Iac7a22031d737acb1fef3c86b0297a65e06ec002
JIRA: CSI-1181


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Web.UI;

namespace CodeTorch.Web.MasterPages
{
    public class BaseMasterPage : System.Web.UI.MasterPage
    {
        protected Label currentYear;
        protected Label currentAppVersion;
        protected Label copyrightCompanyName;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (currentYear != null)
                this.currentYear.Text = DateTime.Now.Year.ToString();

            if (currentAppVersion != null)
                this.currentAppVersion.Text = GetCurrentVersion();

            if (copyrightCompanyName != null)
                this.copyrightCompanyName.Text = CodeTorch.Core.Configuration.GetInstance().App.CopyrightCompanyName;
        }

        protected string GetCurrentVersion()
        {
            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            Version appVersion = currentAssembly.GetName().Version;
            return string.Format("{0}.{1}.{2}", appVersion.Major.ToString(), appVersion.Minor.ToString(), appVersion.Build.ToString());
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Web.UI;

namespace CodeTorch.Web.MasterPages
{
    public class BaseMasterPage : System.Web.UI.MasterPage
    {
        protected Label currentYear;
        protected Label currentAppVersion;
        protected Label copyrightCompanyName;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (currentYear != null)
                this.currentYear.Text = DateTime.Now.Year.ToString();

            if (currentAppVersion != null)
                this.currentAppVersion.Text = GetCurrentVersion();

            if (copyrightCompanyName != null)
                this.copyrightCompanyName.Text = CodeTorch.Core.Configuration.GetInstance().App.CopyrightCompanyName;

        }

        protected string GetCurrentVersion()
        {
            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            Version appVersion = currentAssembly.GetName().Version;
            return string.Format("{0}.{1}.{2}", appVersion.Major.ToString(), appVersion.Minor.ToString(), appVersion.Build.ToString());
        }

    }
}

Allow base master page to be overridden

Allow base master page to be overridden


using UnityEditor;
using UnityEditor.SceneManagement;

namespace YesAndEditor {

	// Static class packed to the brim with helpful Unity editor utilities.
	public static class YesAndEditorUtil {

		// Forcefully mark open loaded scenes dirty and save them.
		[MenuItem ("File/Force Save")]
		public static void ForceSaveOpenScenes () {
			EditorSceneManager.MarkAllScenesDirty ();
			EditorSceneManager.SaveOpenScenes ();
		}
	}
}

using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using System.Linq;

namespace YesAndEditor {

	// Static class packed to the brim with helpful Unity editor utilities.
	public static class YesAndEditorUtil {

		// Forcefully mark open loaded scenes dirty and save them.
		[MenuItem ("File/Force Save")]
		public static void ForceSaveOpenScenes () {
			EditorSceneManager.MarkAllScenesDirty ();
			EditorSceneManager.SaveOpenScenes ();
		}

		// Mark an object editor-only.
		public static void SetEditorOnly(this MonoBehaviour obj, bool editorOnly = true) {
			if (editorOnly) {
				obj.gameObject.hideFlags ^= HideFlags.NotEditable;
				obj.gameObject.hideFlags ^= HideFlags.HideAndDontSave;
			}
			else {
				obj.gameObject.hideFlags &= HideFlags.NotEditable;
				obj.gameObject.hideFlags &= HideFlags.HideAndDontSave;
			}
		}
	}
}

Add a unified method to make an editor-only object


using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace FridgeShoppingList.Views
{
    public sealed partial class Splash : UserControl
    {
        public Task SplashInProgress { get; private set; }

        public Splash(SplashScreen splashScreen)
        {
            InitializeComponent();
            Window.Current.SizeChanged += (s, e) => Resize(splashScreen);
            Resize(splashScreen);
            SplashInProgress = BeginSplashProcess();
        }

        private async Task BeginSplashProcess()
        {
            await Task.Delay(100000);
        }

        private void Resize(SplashScreen splashScreen)
        {
            TextTransform.TranslateY = splashScreen.ImageLocation.Height * .75;
        }

        private void Image_Loaded(object sender, RoutedEventArgs e)
        {
            StarfleetRotateStoryboard.Begin();
        }
    }
}

using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace FridgeShoppingList.Views
{
    public sealed partial class Splash : UserControl
    {
        public Task SplashInProgress { get; private set; }

        public Splash(SplashScreen splashScreen)
        {
            InitializeComponent();
            Window.Current.SizeChanged += (s, e) => Resize(splashScreen);
            Resize(splashScreen);
            SplashInProgress = BeginSplashProcess();
        }

        private async Task BeginSplashProcess()
        {
            //Simulate some kind of fun login text here
            await Task.Delay(10000);
        }

        private void Resize(SplashScreen splashScreen)
        {
            TextTransform.TranslateY = splashScreen.ImageLocation.Height * .75;
        }

        private void Image_Loaded(object sender, RoutedEventArgs e)
        {
            StarfleetRotateStoryboard.Begin();
        }
    }
}

Remove 100sec boot screen =D

Remove 100sec boot screen =D


// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
// This file reused from: https://code.msdn.microsoft.com/Field-Engineer-501df99d

using AutoMapper;
using FieldEngineerLite.Service.DataObjects;
using FieldEngineerLite.Service.Models;

namespace FieldEngineerLite.Service
{
    public class AutomapperConfiguration
    {
        public static void CreateMapping(IConfiguration cfg)
        {
            // Apply some name changes from the entity to the DTO
            cfg.CreateMap<Job, JobDTO>()
                .ForMember(jobDTO => jobDTO.Equipments, map => map.MapFrom(job => job.Equipments));

            // For incoming requests, ignore the relationships
            cfg.CreateMap<JobDTO, Job>()
                .ForMember(jobDTO => jobDTO.Customer, map => map.Ignore())
                .ForMember(jobDTO => jobDTO.Equipments, map => map.Ignore());

            cfg.CreateMap<Customer, CustomerDTO>();
            cfg.CreateMap<Equipment, EquipmentDTO>();
        }
    }
}

// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
// This file reused from: https://code.msdn.microsoft.com/Field-Engineer-501df99d

using AutoMapper;
using FieldEngineerLite.Service.DataObjects;
using FieldEngineerLite.Service.Models;

namespace FieldEngineerLite.Service
{
    public class AutomapperConfiguration
    {
        public static void CreateMapping(IConfiguration cfg)
        {
            // Apply some name changes from the entity to the DTO
            cfg.CreateMap<Job, JobDTO>()
                .ForMember(jobDTO => jobDTO.Equipments, map => map.MapFrom(job => job.Equipments));

            // For incoming requests, ignore the relationships
            cfg.CreateMap<JobDTO, Job>()
                .ForMember(job => job.Customer, map => map.Ignore())
                .ForMember(job => job.Equipments, map => map.Ignore());

            cfg.CreateMap<Customer, CustomerDTO>();
            cfg.CreateMap<Equipment, EquipmentDTO>();
        }
    }
}

Rename variable in Automapper config to match its type (Job instead of JobDTO)


using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Glimpse.Web;
using System;

namespace Glimpse.Host.Web.AspNet
{
    public class GlimpseMiddleware
    {
        private readonly RequestDelegate _innerNext;
        private readonly MasterRequestRuntime _runtime;
        private readonly ISettings _settings;
        private readonly IContextData<MessageContext> _contextData;

        public GlimpseMiddleware(RequestDelegate innerNext, IServiceProvider serviceProvider)
        {
            _innerNext = innerNext;
            _runtime = new MasterRequestRuntime(serviceProvider);
            _contextData = new ContextData<MessageContext>();
        }

        public async Task Invoke(Microsoft.AspNet.Http.HttpContext context)
        {
            var newContext = new HttpContext(context, _settings);

            // TODO: This is the wrong place for this, AgentRuntime isn't garenteed to execute first
            _contextData.Value = new MessageContext { Id = Guid.NewGuid(), Type = "Request" };

            await _runtime.Begin(newContext);

            var handler = (IRequestHandler)null;
            if (_runtime.TryGetHandle(newContext, out handler))
            {
                await handler.Handle(newContext);
            }
            else
            {
                await _innerNext(context);
            }

            // TODO: This doesn't work correctly :(
            await _runtime.End(newContext);
        }
    }
}

using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Glimpse.Web;
using System;

namespace Glimpse.Host.Web.AspNet
{
    public class GlimpseMiddleware
    {
        private readonly RequestDelegate _innerNext;
        private readonly MasterRequestRuntime _runtime;
        private readonly ISettings _settings;
        private readonly IContextData<MessageContext> _contextData;

        public GlimpseMiddleware(RequestDelegate innerNext, IServiceProvider serviceProvider)
        {
            _innerNext = innerNext;
            _runtime = new MasterRequestRuntime(serviceProvider);
            _contextData = new ContextData<MessageContext>();
        }

        public async Task Invoke(Microsoft.AspNet.Http.HttpContext context)
        {
            var newContext = new HttpContext(context, _settings);

            // TODO: This is the wrong place for this, AgentRuntime isn't garenteed to execute first
            _contextData.Value = new MessageContext { Id = Guid.NewGuid(), Type = "Request" };

            await _runtime.Begin(newContext);

            var handler = (IRequestHandler)null;
            if (_runtime.TryGetHandle(newContext, out handler))
            {
                await handler.Handle(newContext);
            }
            else
            {
                await _innerNext(context);
            }

            // TODO: This doesn't work correctly :( (headers)
            await _runtime.End(newContext);
        }
    }
}

Update todo message to explain what is the issue


@{
	var DiscordUser = UserHelper.GetDiscordUser(User);
}

@if(DiscordUser == null) {
	Login
} else {
	@DiscordUser
}

@{
	var DiscordUser = UserHelper.GetDiscordUser(User);
}

@if(DiscordUser == null) {
	Login
} else {
	@DiscordUser.User
}

Fix showing username when logged in.

Fix showing username when logged in.


using System;

namespace StructuredLogViewer
{
    public struct ProjectImport : IEquatable<ProjectImport>
    {
        public ProjectImport(string importedProject, int line, int column)
        {
            ProjectPath = importedProject;
            Line = line;
            Column = column;
        }

        public string ProjectPath { get; set; }

        /// <summary>
        /// 0-based
        /// </summary>
        public int Line { get; set; }
        public int Column { get; set; }

        public bool Equals(ProjectImport other)
        {
            return ProjectPath == other.ProjectPath
                && Line == other.Line
                && Column == other.Column;
        }

        public override bool Equals(object obj)
        {
            if (obj is ProjectImport other)
            {
                return Equals(other);
            }

            return false;
        }

        public override int GetHashCode()
        {
            return ProjectPath.GetHashCode() ^ Line.GetHashCode() ^ Column.GetHashCode();
        }

        public override string ToString()
        {
            return $"{ProjectPath} ({Line},{Column})";
        }
    }
}

using System;

namespace StructuredLogViewer
{
    public struct ProjectImport : IEquatable<ProjectImport>
    {
        public ProjectImport(string importedProject, int line, int column)
        {
            ProjectPath = importedProject;
            Line = line;
            Column = column;
        }

        public string ProjectPath { get; set; }

        /// <summary>
        /// 0-based
        /// </summary>
        public int Line { get; set; }
        public int Column { get; set; }

        public bool Equals(ProjectImport other)
        {
            return ProjectPath == other.ProjectPath
                && Line == other.Line
                && Column == other.Column;
        }

        public override bool Equals(object obj)
        {
            if (obj is ProjectImport other)
            {
                return Equals(other);
            }

            return false;
        }

        public override int GetHashCode()
        {
            return (ProjectPath, Line, Column).GetHashCode();
        }

        public override string ToString()
        {
            return $"{ProjectPath} ({Line},{Column})";
        }
    }
}

Fix hash code to use a tuple.

Fix hash code to use a tuple.


using slang.Compiler.Clr.Compilation.Core.Builders;
using slang.Compiler.Clr.Compilation.CSharp;
using Xunit;

namespace Clr.Tests.Compilation.CSharp
{
    public class CSharpAssemblyGeneratorTests
    {
        [Fact]
        public void Given_a_defined_module_When_compiled_Then_a_CLR_class_is_created()
        {
            // Arrange
            var subject = new CSharpAssemblyGenerator();
            var assemblyDefinition = AssemblyDefinitionBuilder
                .Create("slang")
                .AsLibrary()
                .AddModule(m => m
                    .WithName("CSharpAssemblyGeneratorTestModule")
                    .WithNamespace("slang.Clr.Tests"))
                .Build();

            // Act
            var result = subject.GenerateDynamicAssembly(assemblyDefinition);

            // Assert
            result.GetType("slang.Clr.Tests.CSharpAssemblyGeneratorTestModule", true);
        }
    }
}

using System.Reflection;
using FluentAssertions;
using slang.Compiler.Clr.Compilation.Core.Builders;
using slang.Compiler.Clr.Compilation.CSharp;
using Xunit;

namespace Clr.Tests.Compilation.CSharp
{
    public class CSharpAssemblyGeneratorTests
    {
        [Fact]
        public void Given_a_defined_module_When_compiled_Then_a_corresponding_public_class_is_created()
        {
            // Arrange
            var subject = new CSharpAssemblyGenerator();
            var assemblyDefinition = AssemblyDefinitionBuilder
                .Create("slang")
                .AsLibrary()
                .AddModule(m => m
                    .WithName("CSharpAssemblyGeneratorTestModule")
                    .WithNamespace("slang.Clr.Tests"))
                .Build();

            // Act
            var result = subject.GenerateDynamicAssembly(assemblyDefinition);

            // Assert
            var typeInfo = result.GetType("slang.Clr.Tests.CSharpAssemblyGeneratorTestModule", true).GetTypeInfo();
            typeInfo.IsPublic.Should().BeTrue();
        }
    }
}

Improve test name and assertion

Improve test name and assertion

Assert against the properties of the created class not just that there
is a class created.


// 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.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Graphics;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.Multi.Components;

namespace osu.Game.Screens.Multi.Timeshift
{
    public class TimeshiftReadyButton : ReadyButton
    {
        [Resolved(typeof(Room), nameof(Room.EndDate))]
        private Bindable<DateTimeOffset?> endDate { get; set; }

        public TimeshiftReadyButton()
        {
            Text = "Start";
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            BackgroundColour = colours.Green;
            Triangles.ColourDark = colours.Green;
            Triangles.ColourLight = colours.GreenLight;
        }

        protected override void Update()
        {
            base.Update();

            Enabled.Value = endDate.Value == null || DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(GameBeatmap.Value.Track.Length) < endDate.Value;
        }
    }
}

// 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.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Graphics;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.Multi.Components;

namespace osu.Game.Screens.Multi.Timeshift
{
    public class TimeshiftReadyButton : ReadyButton
    {
        [Resolved(typeof(Room), nameof(Room.EndDate))]
        private Bindable<DateTimeOffset> endDate { get; set; }

        public TimeshiftReadyButton()
        {
            Text = "Start";
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            BackgroundColour = colours.Green;
            Triangles.ColourDark = colours.Green;
            Triangles.ColourLight = colours.GreenLight;
        }

        protected override void Update()
        {
            base.Update();

            Enabled.Value = DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(GameBeatmap.Value.Track.Length) < endDate.Value;
        }
    }
}

Fix incorrect end date usage in timeshift ready button


using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace FineBot.Workers.DI
{
    public class WorkerInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(Classes.FromThisAssembly().Pick().WithService.DefaultInterfaces());
        }
    }
}

using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace FineBot.Workers.DI
{
    public class WorkerInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(Classes.FromThisAssembly().Pick().WithService.DefaultInterfaces().LifestyleTransient());
        }
    }
}

Fix lifestyles of job to dispose after each execution


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

namespace Jebur27.Security.Interfaces
{
    public interface ISecurityManager
    {
    }
}

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

namespace Jebur27.Security.Interfaces
{
    public interface ISecurityManager
    {
        string UserName { get; set; }
        int UserSecurityLevel { get; set; }
    }
}

Update Security Manager to include Parameters


// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.ProjectEuler.Puzzles
{
    using System;
    using System.Globalization;
    using System.Linq;
    using System.Numerics;

    /// <summary>
    /// A class representing the solution to <c>https://projecteuler.net/problem=48</c>. This class cannot be inherited.
    /// </summary>
    internal sealed class Puzzle048 : Puzzle
    {
        /// <inheritdoc />
        public override string Question => "Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + N^N.";

        /// <inheritdoc />
        protected override int MinimumArguments => 1;

        /// <inheritdoc />
        protected override int SolveCore(string[] args)
        {
            int n;

            if (!TryParseInt32(args[0], out n) || n < 2)
            {
                Console.Error.WriteLine("The specified number is invalid.");
                return -1;
            }

            BigInteger value = 0;

            foreach (int exponent in Enumerable.Range(1, n))
            {
                value += BigInteger.Pow(exponent, exponent);
            }

            string result = value.ToString(CultureInfo.InvariantCulture);
            result = result.Substring(Math.Max(0, result.Length - 10), 10);

            Answer = result;

            return 0;
        }
    }
}

// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.ProjectEuler.Puzzles
{
    using System;
    using System.Globalization;
    using System.Linq;
    using System.Numerics;

    /// <summary>
    /// A class representing the solution to <c>https://projecteuler.net/problem=48</c>. This class cannot be inherited.
    /// </summary>
    internal sealed class Puzzle048 : Puzzle
    {
        /// <inheritdoc />
        public override string Question => "Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + N^N.";

        /// <inheritdoc />
        protected override int MinimumArguments => 1;

        /// <inheritdoc />
        protected override int SolveCore(string[] args)
        {
            int n;

            if (!TryParseInt32(args[0], out n) || n < 2)
            {
                Console.Error.WriteLine("The specified number is invalid.");
                return -1;
            }

            BigInteger value = BigInteger.Zero;

            foreach (int exponent in Enumerable.Range(1, n))
            {
                value += BigInteger.Pow(exponent, exponent);
            }

            string result = value.ToString(CultureInfo.InvariantCulture);
            result = result.Substring(Math.Max(0, result.Length - 10), 10);

            Answer = result;

            return 0;
        }
    }
}

Use BigInteger.Zero instead of implicit conversion


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

using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Overlays.Settings.Sections.Audio;

namespace osu.Game.Overlays.Settings.Sections
{
    public class AudioSection : SettingsSection
    {
        public override string Header => "Audio";
        public override FontAwesome Icon => FontAwesome.fa_headphones;

        public AudioSection()
        {
            Children = new Drawable[]
            {
                new AudioDevicesSettings(),
                new VolumeSettings(),
                new OffsetSettings(),
                new MainMenuSettings(),
            };
        }
    }
}

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

using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Overlays.Settings.Sections.Audio;

namespace osu.Game.Overlays.Settings.Sections
{
    public class AudioSection : SettingsSection
    {
        public override string Header => "Audio";
        public override FontAwesome Icon => FontAwesome.fa_volume_up;

        public AudioSection()
        {
            Children = new Drawable[]
            {
                new AudioDevicesSettings(),
                new VolumeSettings(),
                new OffsetSettings(),
                new MainMenuSettings(),
            };
        }
    }
}

Change icon for audio settings

Change icon for audio settings


// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;

namespace Microsoft.CodeAnalysis.Editor.Tags
{
    [ExportImageMonikerService(Name = Name), Shared]
    internal class DefaultImageMonikerService : IImageMonikerService
    {
        public const string Name = nameof(DefaultImageMonikerService);

        public bool TryGetImageMoniker(ImmutableArray<string> tags, out ImageMoniker imageMoniker)
        {
            var glyph = tags.GetFirstGlyph();

            // We can't do the compositing of these glyphs at the editor layer.  So just map them
            // to the non-add versions.
            switch (glyph)
            {
                case Glyph.AddReference:
                    glyph = Glyph.Reference;
                    break;
            }

            imageMoniker = glyph.GetImageMoniker();
            return !imageMoniker.IsNullImage();
        }
    }
}

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;

namespace Microsoft.CodeAnalysis.Editor.Tags
{
    [ExportImageMonikerService(Name = Name)]
    internal class DefaultImageMonikerService : IImageMonikerService
    {
        public const string Name = nameof(DefaultImageMonikerService);

        public bool TryGetImageMoniker(ImmutableArray<string> tags, out ImageMoniker imageMoniker)
        {
            var glyph = tags.GetFirstGlyph();

            // We can't do the compositing of these glyphs at the editor layer.  So just map them
            // to the non-add versions.
            switch (glyph)
            {
                case Glyph.AddReference:
                    glyph = Glyph.Reference;
                    break;
            }

            imageMoniker = glyph.GetImageMoniker();
            return !imageMoniker.IsNullImage();
        }
    }
}

Fix mismatched use of MEF 1 and 2

Fix mismatched use of MEF 1 and 2


using NSpec;
using NSpec.Domain;
using NSpec.Domain.Formatters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace AdHocConsoleRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            var assemblies = new Assembly[]
            {
                typeof(SampleSpecs.DummyPublicClass).Assembly,
                typeof(ConfigSampleSpecs.DummyPublicClass).Assembly,
            };

            //types that should be considered for testing
            var types = assemblies.SelectMany(asm => asm.GetTypes()).ToArray();

            //now that we have our types, set up a finder so that NSpec
            //can determine the inheritance hierarchy
            var finder = new SpecFinder(types);

            //we've got our inheritance hierarchy,
            //now we can build our test tree using default conventions
            var builder = new ContextBuilder(finder, new DefaultConventions());

            //create the nspec runner with a
            //live formatter so we get console output
            var runner = new ContextRunner(
                           builder,
                           new ConsoleFormatter(),
                           false);

            //create our final collection of concrete tests
            var testCollection = builder.Contexts().Build();

            //run the tests and get results (to do whatever you want with)
            var results = runner.Run(testCollection);

            //console write line to pause the exe
            System.Console.ReadLine();
        }
    }
}

using NSpec;
using NSpec.Domain;
using NSpec.Domain.Formatters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace AdHocConsoleRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            var assemblies = new Assembly[]
            {
                typeof(SampleSpecs.DummyPublicClass).Assembly,
                typeof(ConfigSampleSpecs.DummyPublicClass).Assembly,
            };

            //types that should be considered for testing
            var types = assemblies.SelectMany(asm => asm.GetTypes()).ToArray();

            //now that we have our types, set up a finder so that NSpec
            //can determine the inheritance hierarchy
            var finder = new SpecFinder(types);

            //we've got our inheritance hierarchy,
            //now we can build our test tree using default conventions
            var builder = new ContextBuilder(finder, new DefaultConventions());

            //create the nspec runner with a
            //live formatter so we get console output
            var runner = new ContextRunner(
                           builder,
                           new ConsoleFormatter(),
                           false);

            //create our final collection of concrete tests
            var testCollection = builder.Contexts().Build();

            //run the tests and get results (to do whatever you want with)
            var results = runner.Run(testCollection);

            //console write line to pause the exe
            Console.WriteLine(Environment.NewLine + "Press <enter> to quit...");
            Console.ReadLine();
        }
    }
}

Add closing message to sample console runner


// Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Linq;

#if NETCORE
using System.IO;
#endif

namespace Nuke.Core
{
    public static partial class EnvironmentInfo
    {
        public static string NewLine => Environment.NewLine;
        public static string MachineName => Environment.MachineName;

        public static string WorkingDirectory
#if NETCORE
            => Directory.GetCurrentDirectory();
#else
            => Environment.CurrentDirectory;
#endif
    }
}

// Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

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

#if NETCORE
using System.IO;
#endif

namespace Nuke.Core
{
    public static partial class EnvironmentInfo
    {
        public static string NewLine => Environment.NewLine;
        public static string MachineName => Environment.MachineName;

        public static string WorkingDirectory
#if NETCORE
            => Directory.GetCurrentDirectory();
#else
            => Environment.CurrentDirectory;
#endif

        public static IReadOnlyDictionary<string, string> Variables
        {
            get
            {
                var environmentVariables = Environment.GetEnvironmentVariables();
                return Environment.GetEnvironmentVariables().Keys.Cast<string>()
                        .ToDictionary(x => x, x => (string) environmentVariables[x], StringComparer.OrdinalIgnoreCase);
            }
        }

    }
}

Add wrapper for environment variables.

Add wrapper for environment variables.


using System;
using Shapes.Class;

namespace Shapes
{
    using Interfaces;
    class Program
    {
        static void Main()
        {
            IShape circle = new Circle(4);
            Console.WriteLine(circle.CalculateArea());
            circle.CalculatePerimeter();
            IShape triangle = new Triangle(5, 8.4, 6.4, 8.5);
            triangle.CalculateArea();
            triangle.CalculatePerimeter();
            IShape rectangle = new Rectangle(8, 5);
            rectangle.CalculateArea();
            rectangle.CalculatePerimeter();
            Console.WriteLine();
        }
    }
}

using System;
using Shapes.Class;

namespace Shapes
{
    using Interfaces;
    class Program
    {
        static void Main()
        {
            IShape circle = new Circle(4);
            Console.WriteLine("circle area: " + circle.CalculateArea());
            Console.WriteLine("circle perimeter: " + circle.CalculatePerimeter());
            IShape triangle = new Triangle(5, 8.4, 6.4, 8.5);
            Console.WriteLine("triangle area: " + triangle.CalculateArea());
            Console.WriteLine("triangle perimeter: " + triangle.CalculatePerimeter());
            IShape rectangle = new Rectangle(8, 5);
            Console.WriteLine("rectangle area: " + rectangle.CalculateArea());
            Console.WriteLine("rectangle perimeter: " + rectangle.CalculatePerimeter());
            Console.WriteLine();
        }
    }
}

Add ConsoleWhriteLine on Area and Perimeter Methods


using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using FluentEmail.Core;
using FluentEmail.Core.Models;
using FluentScheduler;
using System.Collections.Generic;
using System.IO;

namespace BatteryCommander.Web.Jobs
{
    public class PERSTATReportJob : IJob
    {
        private static IList<Address> Recipients => new List<Address>(new Address[]
        {
            Matt
            // new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" }
        });

        internal static Address Matt => new Address { Name = "1LT Wagner", EmailAddress = "MattGWagner@gmail.com" };

        private readonly Database db;

        private readonly IFluentEmail emailSvc;

        public PERSTATReportJob(Database db, IFluentEmail emailSvc)
        {
            this.db = db;
            this.emailSvc = emailSvc;
        }

        public virtual void Execute()
        {
            // HACK - Configure the recipients and units that this is going to be wired up for

            var unit = UnitService.Get(db, unitId: 3).Result; // C Batt

            emailSvc
                .To(Recipients)
                .SetFrom(Matt.EmailAddress, Matt.Name)
                .Subject($"{unit.Name} | RED 1 PERSTAT")
                .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit)
                .Send();
        }
    }
}

using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using FluentEmail.Core;
using FluentEmail.Core.Models;
using FluentScheduler;
using System.Collections.Generic;
using System.IO;

namespace BatteryCommander.Web.Jobs
{
    public class PERSTATReportJob : IJob
    {
        private static IList<Address> Recipients => new List<Address>(new Address[]
        {
            Matt
            // new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" }
        });

        internal static Address Matt => new Address { Name = "1LT Wagner", EmailAddress = "MattGWagner@gmail.com" };

        private readonly Database db;

        private readonly IFluentEmail emailSvc;

        public PERSTATReportJob(Database db, IFluentEmail emailSvc)
        {
            this.db = db;
            this.emailSvc = emailSvc;
        }

        public virtual void Execute()
        {
            foreach (var unit in UnitService.List(db).GetAwaiter().GetResult())
            {
                // HACK - Configure the recipients and units that this is going to be wired up for

                emailSvc
                    .To(Recipients)
                    .SetFrom(Matt.EmailAddress, Matt.Name)
                    .Subject($"{unit.Name} | RED 1 PERSTAT")
                    .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit)
                    .Send();
            }
        }
    }
}

Tweak so it'll send for any non-ignored units


#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

namespace Kooboo
{
    /// <summary>
    ///
    /// </summary>
    public static class ApplicationInitialization
    {
        #region Fields
        private class InitializationItem
        {
            public Action InitializeMethod { get; set; }
            public int Priority { get; set; }
        }
        private static List<InitializationItem> items = new List<InitializationItem>();
        #endregion

        #region Methods
        /// <summary>
        /// Registers the initializer method.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="priority">The priority.</param>
        public static void RegisterInitializerMethod(Action method, int priority)
        {
            items.Add(new InitializationItem() { InitializeMethod = method, Priority = priority });
        }
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public static void Execute()
        {
            lock (items)
            {
                foreach (var item in items.OrderBy(it => it.Priority))
                {
                    item.InitializeMethod();
                }
                items.Clear();
            }

        }
        #endregion
    }
}

#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

namespace Kooboo
{
    /// <summary>
    ///
    /// </summary>
    [Obsolete]
    public static class ApplicationInitialization
    {
        #region Fields
        private class InitializationItem
        {
            public Action InitializeMethod { get; set; }
            public int Priority { get; set; }
        }
        private static List<InitializationItem> items = new List<InitializationItem>();
        #endregion

        #region Methods
        /// <summary>
        /// Registers the initializer method.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="priority">The priority.</param>
        public static void RegisterInitializerMethod(Action method, int priority)
        {
            items.Add(new InitializationItem() { InitializeMethod = method, Priority = priority });
        }
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public static void Execute()
        {
            lock (items)
            {
                foreach (var item in items.OrderBy(it => it.Priority))
                {
                    item.InitializeMethod();
                }
                items.Clear();
            }

        }
        #endregion
    }
}

Make as an obsolete class.

Make as an obsolete class.


@model BatteryCommander.Web.Commands.UpdateSUTARequest

@using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

        @Html.DisplayNameFor(model => model.Body.Supervisor)
        @Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors)

        @Html.DisplayNameFor(model => model.Body.StartDate)
        @Html.EditorFor(model => model.Body.StartDate)

        @Html.DisplayNameFor(model => model.Body.EndDate)
        @Html.EditorFor(model => model.Body.EndDate)

        @Html.DisplayNameFor(model => model.Body.Reasoning)
        @Html.TextAreaFor(model => model.Body.Reasoning)

        @Html.DisplayNameFor(model => model.Body.MitigationPlan)
        @Html.TextAreaFor(model => model.Body.MitigationPlan)

    <button type="submit">Save</button>
}

@model BatteryCommander.Web.Commands.UpdateSUTARequest

@using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

        @Html.DisplayNameFor(model => model.Body.Supervisor)
        @Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors)

        @Html.DisplayNameFor(model => model.Body.StartDate)
        @Html.EditorFor(model => model.Body.StartDate)

        @Html.DisplayNameFor(model => model.Body.EndDate)
        @Html.EditorFor(model => model.Body.EndDate)

        @Html.DisplayNameFor(model => model.Body.Reasoning)
        @Html.TextAreaFor(model => model.Body.Reasoning, new { cols="40", rows="5" })

        @Html.DisplayNameFor(model => model.Body.MitigationPlan)
        @Html.TextAreaFor(model => model.Body.MitigationPlan, new { cols="40", rows="5" })

    <button type="submit">Save</button>
}

Make the text areas bigger on suta edit

Make the text areas bigger on suta edit


using System;
using System.ComponentModel.DataAnnotations;
using static BatteryCommander.Web.Models.Soldier;

namespace BatteryCommander.Web.Models.Reports
{
    public class Stat
    {
        public int Assigned { get; set; }

        public int Passed { get; set; }

        public int Failed { get; set; }

        [Display(Name = "Not Tested")]
        public int NotTested { get; set; }

        [Display(Name = "Pass %"), DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)]
        public Decimal PercentPass => (Decimal)Passed / Assigned;
    }

    public class Row
    {
        public Rank Rank { get; set; }

        public int Assigned { get; set; }

        public int Incomplete => Assigned - Completed;

        public int Completed { get; set; }

        [DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)]
        public Decimal Percentage => Assigned > 0 ? (Decimal)Completed / Assigned : Decimal.Zero;
    }
}

using System;
using System.ComponentModel.DataAnnotations;
using static BatteryCommander.Web.Models.Soldier;

namespace BatteryCommander.Web.Models.Reports
{
    public class Stat
    {
        public int Assigned { get; set; }

        public int Passed { get; set; }

        public int Failed { get; set; }

        [Display(Name = "Not Tested")]
        public int NotTested { get; set; }

        [Display(Name = "Pass %"), DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)]
        public Decimal PercentPass => (Assigned > 0 ? (Decimal)Passed / Assigned : Decimal.Zero;
    }

    public class Row
    {
        public Rank Rank { get; set; }

        public int Assigned { get; set; }

        public int Incomplete => Assigned - Completed;

        public int Completed { get; set; }

        [DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)]
        public Decimal Percentage => Assigned > 0 ? (Decimal)Completed / Assigned : Decimal.Zero;
    }
}

Fix a different error on unit create

Fix a different error on unit create


using UnityEngine;

public class OnActivateRefresh : MonoBehaviour
{
    private ServerUI _serverUi;
    private void Start()
    {
        _serverUi = FindObjectOfType<ServerUI>();
    }

    private void OnEnable()
    {
        _serverUi.GetServerList();
    }
}

using UnityEngine;

public class OnActivateRefresh : MonoBehaviour
{
    private ServerUI _serverUi;
    private void Start()
    {
        _serverUi = FindObjectOfType<ServerUI>();
        _serverUi.GetServerList();
    }

    private void OnEnable()
    {
        if(_serverUi)_serverUi.GetServerList();
    }
}

Fix the server list update

Fix the server list update


using UnityEditor;

namespace BitStrap
{
	public class ScriptableObjectContextMenu
	{
		[MenuItem("CONTEXT/ScriptableObject/Select in Project View")]
		public static void SelectScriptabelObject(MenuCommand menuCommand)
		{
			EditorGUIUtility.PingObject(menuCommand.context);
		}
	}
}

using UnityEditor;
using UnityEngine;

namespace BitStrap
{
	public class ScriptableObjectContextMenu
	{
		[MenuItem("CONTEXT/ScriptableObject/Select Script", false, 10)]
		public static void SelectScriptabelObjectScript(MenuCommand menuCommand)
		{
			var serializedObject = new SerializedObject(menuCommand.context);
			var scriptProperty = serializedObject.FindProperty("m_Script");
			var scriptObject = scriptProperty.objectReferenceValue;
			Selection.activeObject = scriptObject;
		}

		[MenuItem("CONTEXT/ScriptableObject/Show in Project View")]
		public static void SelectScriptabelObject(MenuCommand menuCommand)
		{
			EditorGUIUtility.PingObject(menuCommand.context);
		}
	}
}

Add context menu to select the script of a scriptable object


using System;
using JsonApiDotNetCore.Resources;

namespace JsonApiDotNetCoreTests.IntegrationTests
{
    /// <summary>
    /// Lists the various extensibility points on <see cref="IResourceDefinition{TResource,TId}" />.
    /// </summary>
    [Flags]
    public enum ResourceDefinitionExtensibilityPoints
    {
        OnApplyIncludes = 1,
        OnApplyFilter = 1 << 1,
        OnApplySort = 1 << 2,
        OnApplyPagination = 1 << 3,
        OnApplySparseFieldSet = 1 << 4,
        OnRegisterQueryableHandlersForQueryStringParameters = 1 << 5,
        GetMeta = 1 << 6,
        OnPrepareWriteAsync = 1 << 7,
        OnSetToOneRelationshipAsync = 1 << 8,
        OnSetToManyRelationshipAsync = 1 << 9,
        OnAddToRelationshipAsync = 1 << 10,
        OnRemoveFromRelationshipAsync = 1 << 11,
        OnWritingAsync = 1 << 12,
        OnWriteSucceededAsync = 1 << 13,
        OnDeserialize = 1 << 14,
        OnSerialize = 1 << 15,

        Reading = OnApplyIncludes | OnApplyFilter | OnApplySort | OnApplyPagination | OnApplySparseFieldSet |
            OnRegisterQueryableHandlersForQueryStringParameters | GetMeta,

        Writing = OnPrepareWriteAsync | OnSetToOneRelationshipAsync | OnSetToManyRelationshipAsync | OnAddToRelationshipAsync | OnRemoveFromRelationshipAsync |
            OnWritingAsync | OnWriteSucceededAsync,

        Serialization = OnDeserialize | OnSerialize,

        All = Reading | Writing | Serialization
    }
}

using System;
using JsonApiDotNetCore.Resources;

namespace JsonApiDotNetCoreTests.IntegrationTests
{
    /// <summary>
    /// Lists the various extensibility points on <see cref="IResourceDefinition{TResource,TId}" />.
    /// </summary>
    [Flags]
    public enum ResourceDefinitionExtensibilityPoints
    {
        None = 0,
        OnApplyIncludes = 1,
        OnApplyFilter = 1 << 1,
        OnApplySort = 1 << 2,
        OnApplyPagination = 1 << 3,
        OnApplySparseFieldSet = 1 << 4,
        OnRegisterQueryableHandlersForQueryStringParameters = 1 << 5,
        GetMeta = 1 << 6,
        OnPrepareWriteAsync = 1 << 7,
        OnSetToOneRelationshipAsync = 1 << 8,
        OnSetToManyRelationshipAsync = 1 << 9,
        OnAddToRelationshipAsync = 1 << 10,
        OnRemoveFromRelationshipAsync = 1 << 11,
        OnWritingAsync = 1 << 12,
        OnWriteSucceededAsync = 1 << 13,
        OnDeserialize = 1 << 14,
        OnSerialize = 1 << 15,

        Reading = OnApplyIncludes | OnApplyFilter | OnApplySort | OnApplyPagination | OnApplySparseFieldSet |
            OnRegisterQueryableHandlersForQueryStringParameters | GetMeta,

        Writing = OnPrepareWriteAsync | OnSetToOneRelationshipAsync | OnSetToManyRelationshipAsync | OnAddToRelationshipAsync | OnRemoveFromRelationshipAsync |
            OnWritingAsync | OnWriteSucceededAsync,

        Serialization = OnDeserialize | OnSerialize,

        All = Reading | Writing | Serialization
    }
}

Add None enum member to flags

Add None enum member to flags


/*
 * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
 * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 System.Reflection;
using QuantConnect.Configuration;

namespace QuantConnect
{
    /// <summary>
    /// Provides application level constant values
    /// </summary>
    public static class Constants
    {
        private static readonly string DataFolderPath = Config.Get("data-folder", @"../../../Data/");

        /// <summary>
        /// The root directory of the data folder for this application
        /// </summary>
        public static string DataFolder
        {
            get { return DataFolderPath; }
        }

        /// <summary>
        /// The directory used for storing downloaded remote files
        /// </summary>
        public const string Cache = "./cache/data";

        /// <summary>
        /// The version of lean
        /// </summary>
        public static readonly string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
    }
}

/*
 * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
 * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 System.Reflection;
using QuantConnect.Configuration;

namespace QuantConnect
{
    /// <summary>
    /// Provides application level constant values
    /// </summary>
    public static class Constants
    {
        private static readonly string DataFolderPath = Config.Get("data-folder", Config.Get("data-directory", @"../../../Data/"));

        /// <summary>
        /// The root directory of the data folder for this application
        /// </summary>
        public static string DataFolder
        {
            get { return DataFolderPath; }
        }

        /// <summary>
        /// The directory used for storing downloaded remote files
        /// </summary>
        public const string Cache = "./cache/data";

        /// <summary>
        /// The version of lean
        /// </summary>
        public static readonly string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
    }
}

Allow 'data-folder' and 'data-directory' config options


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

namespace Bearded.Utilities.Graphs
{
    class AdjacencyListDirectedGraph<T> : IDirectedGraph<T> where T : IEquatable<T>
    {
        private readonly ImmutableList<T> elements;
        private readonly ImmutableDictionary<T, ImmutableList<T>> directSuccessors;
        private readonly ImmutableDictionary<T, ImmutableList<T>> directPredecessors;

        public IEnumerable<T> Elements => elements;
        public int Count => elements.Count;

        public AdjacencyListDirectedGraph(
            ImmutableList<T> elements,
            ImmutableDictionary<T, ImmutableList<T>> directSuccessors,
            ImmutableDictionary<T, ImmutableList<T>> directPredecessors)
        {
            this.elements = elements;
            this.directSuccessors = directSuccessors;
            this.directPredecessors = directPredecessors;
        }

        public IEnumerable<T> GetDirectSuccessorsOf(T element) => directSuccessors[element];
        public IEnumerable<T> GetDirectPredecessorsOf(T element) => directPredecessors[element];
    }
}

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

namespace Bearded.Utilities.Graphs
{
    class AdjacencyListDirectedGraph<T> : IDirectedGraph<T> where T : IEquatable<T>
    {
        private readonly ImmutableList<T> elements;
        private readonly ImmutableDictionary<T, ImmutableList<T>> directSuccessors;
        private readonly ImmutableDictionary<T, ImmutableList<T>> directPredecessors;

        public IEnumerable<T> Elements => elements;
        public int Count => elements.Count;

        public AdjacencyListDirectedGraph(
            ImmutableList<T> elements,
            ImmutableDictionary<T, ImmutableList<T>> directSuccessors,
            ImmutableDictionary<T, ImmutableList<T>> directPredecessors)
        {
            this.elements = elements;
            this.directSuccessors = directSuccessors;
            this.directPredecessors = directPredecessors;
        }

        public IEnumerable<T> GetDirectSuccessorsOf(T element) =>
            directSuccessors.ContainsKey(element)
                ? directSuccessors[element]
                : throw new ArgumentOutOfRangeException(nameof(element), "Element not found in graph.");
        public IEnumerable<T> GetDirectPredecessorsOf(T element) =>
            directPredecessors.ContainsKey(element)
                ? directPredecessors[element]
                : throw new ArgumentOutOfRangeException(nameof(element), "Element not found in graph.");
    }
}

:lipstick: Make querying successors and predeccors fail explicitly


namespace SharpArch.NHibernate.NHibernateValidator
{
    using System.ComponentModel.DataAnnotations;

    using SharpArch.Domain;
    using SharpArch.Domain.DomainModel;
    using SharpArch.Domain.PersistenceSupport;

    /// <summary>
    ///     Provides a class level validator for determining if the entity has a unique domain signature
    ///     when compared with other entries in the database.
    ///
    ///     Due to the fact that .NET does not support generic attributes, this only works for entity
    ///     types having an Id of type int.
    /// </summary>
    public class HasUniqueDomainSignatureAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            var entityToValidate = value as IEntityWithTypedId<int>;
            Check.Require(
                entityToValidate != null,
                "This validator must be used at the class level of an IDomainWithTypedId<int>. The type you provided was " + value.GetType());

            var duplicateChecker = SafeServiceLocator<IEntityDuplicateChecker>.GetService();
            return ! duplicateChecker.DoesDuplicateExistWithTypedIdOf(entityToValidate);
        }

        public override string FormatErrorMessage(string name)
        {
            return "Provided values matched an existing, duplicate entity";
        }
    }
}

namespace SharpArch.NHibernate.NHibernateValidator
{
    using System.ComponentModel.DataAnnotations;

    using SharpArch.Domain;
    using SharpArch.Domain.DomainModel;
    using SharpArch.Domain.PersistenceSupport;

    /// <summary>
    ///     Provides a class level validator for determining if the entity has a unique domain signature
    ///     when compared with other entries in the database.
    ///
    ///     Due to the fact that .NET does not support generic attributes, this only works for entity
    ///     types having an Id of type int.
    /// </summary>
    public class HasUniqueDomainSignatureAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            var entityToValidate = value as IEntityWithTypedId<int>;
            Check.Require(
                entityToValidate != null,
                "This validator must be used at the class level of an IEntityWithTypedId<int>. The type you provided was " + value.GetType());

            var duplicateChecker = SafeServiceLocator<IEntityDuplicateChecker>.GetService();
            return ! duplicateChecker.DoesDuplicateExistWithTypedIdOf(entityToValidate);
        }

        public override string FormatErrorMessage(string name)
        {
            return "Provided values matched an existing, duplicate entity";
        }
    }
}

Fix type name in exception message for HasUniqueDomainSignature


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

using osu.Framework.Bindables;
using osu.Game.Graphics;
using osuTK.Graphics;

namespace osu.Game.Beatmaps.ControlPoints
{
    public class DifficultyControlPoint : ControlPoint
    {
        public static readonly DifficultyControlPoint DEFAULT = new DifficultyControlPoint
        {
            SpeedMultiplierBindable = { Disabled = true },
        };

        /// <summary>
        /// The speed multiplier at this control point.
        /// </summary>
        public readonly BindableDouble SpeedMultiplierBindable = new BindableDouble(1)
        {
            Precision = 0.1,
            Default = 1,
            MinValue = 0.1,
            MaxValue = 10
        };

        public override Color4 GetRepresentingColour(OsuColour colours) => colours.GreenDark;

        /// <summary>
        /// The speed multiplier at this control point.
        /// </summary>
        public double SpeedMultiplier
        {
            get => SpeedMultiplierBindable.Value;
            set => SpeedMultiplierBindable.Value = value;
        }

        public override bool IsRedundant(ControlPoint existing)
            => existing is DifficultyControlPoint existingDifficulty
               && SpeedMultiplier == existingDifficulty.SpeedMultiplier;

        public override void CopyFrom(ControlPoint other)
        {
            SpeedMultiplier = ((DifficultyControlPoint)other).SpeedMultiplier;

            base.CopyFrom(other);
        }
    }
}

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

using osu.Framework.Bindables;
using osu.Game.Graphics;
using osuTK.Graphics;

namespace osu.Game.Beatmaps.ControlPoints
{
    public class DifficultyControlPoint : ControlPoint
    {
        public static readonly DifficultyControlPoint DEFAULT = new DifficultyControlPoint
        {
            SpeedMultiplierBindable = { Disabled = true },
        };

        /// <summary>
        /// The speed multiplier at this control point.
        /// </summary>
        public readonly BindableDouble SpeedMultiplierBindable = new BindableDouble(1)
        {
            Precision = 0.01,
            Default = 1,
            MinValue = 0.1,
            MaxValue = 10
        };

        public override Color4 GetRepresentingColour(OsuColour colours) => colours.GreenDark;

        /// <summary>
        /// The speed multiplier at this control point.
        /// </summary>
        public double SpeedMultiplier
        {
            get => SpeedMultiplierBindable.Value;
            set => SpeedMultiplierBindable.Value = value;
        }

        public override bool IsRedundant(ControlPoint existing)
            => existing is DifficultyControlPoint existingDifficulty
               && SpeedMultiplier == existingDifficulty.SpeedMultiplier;

        public override void CopyFrom(ControlPoint other)
        {
            SpeedMultiplier = ((DifficultyControlPoint)other).SpeedMultiplier;

            base.CopyFrom(other);
        }
    }
}

Increase the precision of speed multiplier to match osu-stable


namespace Mos6510.Instructions
{
  public enum AddressingMode
  {
    Implied,
    Immediate,
    Absolute,
    AbsoluteX,
    AbsoluteY,
    Zeropage,
    ZeropageX,
    ZeropageY,
    IndirectX,
    IndirectY
  }
}

namespace Mos6510.Instructions
{
  public enum AddressingMode
  {
    Absolute,
    AbsoluteX,
    AbsoluteY,
    Accumulator,
    Immediate,
    Implied,
    IndirectX,
    IndirectY,
    Zeropage,
    ZeropageX,
    ZeropageY,
  }
}

Add the accumulator addressing mode.

Add the accumulator addressing mode.


using System.Collections.Generic;

namespace RetailStore
{
    public class RetailStore
    {
        private readonly Screen m_Screen;
        private readonly Dictionary<string, string> m_Products;

        public RetailStore(Screen screen, Dictionary<string, string> products)
        {
            m_Screen = screen;
            m_Products = products;
        }

        public void OnBarcode(string barcode)
        {
            if (barcode == null || !m_Products.ContainsKey(barcode))
            {
                m_Screen.ShowText("Product Not Found");
                return;
            }

            var product = m_Products[barcode];

            m_Screen.ShowText(product);
        }
    }
}

using System.Collections.Generic;

namespace RetailStore
{
    public class RetailStore
    {
        private readonly Screen m_Screen;
        private readonly Dictionary<string, string> m_Products;

        public RetailStore(Screen screen, Dictionary<string, string> products)
        {
            m_Screen = screen;
            m_Products = products ?? new Dictionary<string, string>();
        }

        public void OnBarcode(string barcode)
        {
            if (barcode == null || !m_Products.ContainsKey(barcode))
            {
                m_Screen.ShowText("Product Not Found");
                return;
            }

            var product = m_Products[barcode];

            m_Screen.ShowText(product);
        }
    }
}

Fix failing when passing null

Fix failing when passing null


@model alert_roster.web.Models.Message

@{
    ViewBag.Title = "Create New Message";
}

@ViewBag.Title

@using (Html.BeginForm("New", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()

Message

        @Html.ValidationSummary(true)

            @Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Content)
                @Html.ValidationMessageFor(model => model.Content)

                <input type="submit" value="Create" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

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

@model alert_roster.web.Models.Message

@{
    ViewBag.Title = "Create New Message";
}

@ViewBag.Title

    @Html.ActionLink("Back to List", "Index")

@using (Html.BeginForm("New", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()

Message

        @Html.ValidationSummary(true)

            @Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Content)
                @Html.ValidationMessageFor(model => model.Content)

                <input type="submit" value="Create" class="btn btn-default" />

}

Move back to list link

Move back to list link


using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

namespace Northwind.Model.Mapping
{
    public class OrderDetailMap : EntityTypeConfiguration<OrderDetail>
    {
        public OrderDetailMap()
        {
            // Primary Key
            HasKey(t => new { t.OrderId, t.ProductId });

            // Properties
            Property(t => t.OrderId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

            Property(t => t.ProductId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

            // Table & Column Mappings
            ToTable("OrderDetails");
            Property(t => t.OrderId).HasColumnName("OrderID");
            Property(t => t.ProductId).HasColumnName("ProductID");
            Property(t => t.UnitPrice).HasColumnName("UnitPrice");
            Property(t => t.Quantity).HasColumnName("Quantity");
            Property(t => t.Discount).HasColumnName("Discount");

            // Relationships
            HasRequired(t => t.Order)
                .WithMany(t => t.OrderDetails)
                .HasForeignKey(d => d.OrderId);
            HasRequired(t => t.Product)
                .WithMany(t => t.OrderDetails)
                .HasForeignKey(d => d.ProductId);
        }
    }
}

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

namespace Northwind.Model.Mapping
{
    public class OrderDetailMap : EntityTypeConfiguration<OrderDetail>
    {
        public OrderDetailMap()
        {
            // Primary Key
            HasKey(t => new { t.OrderId, t.ProductId });

            // Properties
            Property(t => t.OrderId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

            Property(t => t.ProductId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

            // Table & Column Mappings
            ToTable("Order Details");
            Property(t => t.OrderId).HasColumnName("OrderID");
            Property(t => t.ProductId).HasColumnName("ProductID");
            Property(t => t.UnitPrice).HasColumnName("UnitPrice");
            Property(t => t.Quantity).HasColumnName("Quantity");
            Property(t => t.Discount).HasColumnName("Discount");

            // Relationships
            HasRequired(t => t.Order)
                .WithMany(t => t.OrderDetails)
                .HasForeignKey(d => d.OrderId);
            HasRequired(t => t.Product)
                .WithMany(t => t.OrderDetails)
                .HasForeignKey(d => d.ProductId);
        }
    }
}

Change OrderDetails table name from 'OrderDetails' to 'Order Details' in the mapping.


using Machine.Specifications;

namespace Stripe.Tests
{
    [Behaviors]
    public class account_behaviors
    {
        protected static StripeAccountSharedOptions CreateOrUpdateOptions;
        protected static StripeAccount StripeAccount;

        //It should_have_the_correct_email_address = () =>
        //    StripeAccount.Email.ShouldEqual(CreateOrUpdateOptions.Email);

        It should_have_the_correct_business_info = () =>
        {
            StripeAccount.BusinessName.ShouldEqual(CreateOrUpdateOptions.BusinessName);
            StripeAccount.BusinessPrimaryColor.ShouldEqual(CreateOrUpdateOptions.BusinessPrimaryColor);
            StripeAccount.BusinessUrl.ShouldEqual(CreateOrUpdateOptions.BusinessUrl);
        };

        It should_have_the_correct_debit_negative_balances = () =>
            StripeAccount.DebitNegativeBalances.ShouldEqual(CreateOrUpdateOptions.DebitNegativeBalances.Value);

        It should_have_the_correct_decline_charge_values = () =>
        {
            StripeAccount.DeclineChargeOn.AvsFailure.ShouldEqual(CreateOrUpdateOptions.DeclineChargeOnAvsFailure.Value);
            StripeAccount.DeclineChargeOn.CvcFailure.ShouldEqual(CreateOrUpdateOptions.DeclineChargeOnCvcFailure.Value);
        };

        It should_have_the_correct_default_currency = () =>
            StripeAccount.DefaultCurrency.ShouldEqual(CreateOrUpdateOptions.DefaultCurrency);
    }
}

using Machine.Specifications;

namespace Stripe.Tests
{
    [Behaviors]
    public class account_behaviors
    {
        protected static StripeAccountSharedOptions CreateOrUpdateOptions;
        protected static StripeAccount StripeAccount;

        //It should_have_the_correct_email_address = () =>
        //    StripeAccount.Email.ShouldEqual(CreateOrUpdateOptions.Email);

        It should_have_the_correct_business_info = () =>
        {
            StripeAccount.BusinessName.ShouldEqual(CreateOrUpdateOptions.BusinessName);
            StripeAccount.BusinessPrimaryColor.ShouldEqual(CreateOrUpdateOptions.BusinessPrimaryColor);
            StripeAccount.BusinessUrl.ShouldEqual(CreateOrUpdateOptions.BusinessUrl);
        };

        It should_have_the_correct_debit_negative_balances = () =>
            StripeAccount.DebitNegativeBalances.ShouldEqual(CreateOrUpdateOptions.DebitNegativeBalances.Value);

        It should_have_the_correct_default_currency = () =>
            StripeAccount.DefaultCurrency.ShouldEqual(CreateOrUpdateOptions.DefaultCurrency);
    }
}

Remove this test as the API is broken

Remove this test as the API is broken

The API currently behaves incorrectly and this test is not useful


using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using VotingApplication.Data.Context;
using VotingApplication.Web.Api.Migrations;

namespace VotingApplication.Web.Api
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Fix the infinite recursion of Session.OptionSet.Options[0].OptionSets[0].Options[0].[...]
            // by not populating the Option.OptionSets after already encountering Session.OptionSet
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            //Enable automatic migrations
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<VotingContext, Configuration>());
            new VotingContext().Database.Initialize(false);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using VotingApplication.Data.Context;
using VotingApplication.Web.Api.Migrations;

namespace VotingApplication.Web.Api
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Fix the infinite recursion of Session.OptionSet.Options[0].OptionSets[0].Options[0].[...]
            // by not populating the Option.OptionSets after already encountering Session.OptionSet
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            //Enable automatic migrations
            //Database.SetInitializer(new MigrateDatabaseToLatestVersion<VotingContext, Configuration>());
            //new VotingContext().Database.Initialize(false);
        }
    }
}

Revert "Revert "Force fix for new databases""

This reverts commit fa7be52fa71ab991d7911c558b05ed48f2a1cda3.


namespace RedBlueGames.ToolsExamples
{
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;

    public class PrimitiveCreatorSaveData : ScriptableObject
    {
        public List<PrimitiveCreator.Config> ConfigPresets;

        public bool HasConfigForIndex(int index)
        {
            if (this.ConfigPresets == null || this.ConfigPresets.Count == 0)
            {
                return false;
            }

            return index >= 0 && index < this.ConfigPresets.Count;
        }
    }
}

namespace RedBlueGames.ToolsExamples
{
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;

    public class PrimitiveCreatorSaveData : ScriptableObject
    {
        public List<PrimitiveCreator.Config> ConfigPresets;

        private void OnEnable()
        {
            if (this.ConfigPresets == null)
            {
                this.ConfigPresets = new List<PrimitiveCreator.Config>();
            }
        }

        public bool HasConfigForIndex(int index)
        {
            if (this.ConfigPresets == null || this.ConfigPresets.Count == 0)
            {
                return false;
            }

            return index >= 0 && index < this.ConfigPresets.Count;
        }
    }
}

Fix NPE where saveData was accessed before being initialized


using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;

namespace Umbraco.Cms.Core.PropertyEditors
{
    [DataEditor(
        Constants.PropertyEditors.Aliases.ColorPickerEyeDropper,
        "Eye Dropper Color Picker",
        "eyedropper",
        Icon = "icon-colorpicker",
        Group = Constants.PropertyEditors.Groups.Pickers)]
    public class EyeDropperColorPickerPropertyEditor : DataEditor
    {
        private readonly IIOHelper _ioHelper;

        public EyeDropperColorPickerPropertyEditor(
            IDataValueEditorFactory dataValueEditorFactory,
            IIOHelper ioHelper,
            EditorType type = EditorType.PropertyValue)
            : base(dataValueEditorFactory, type)
        {
            _ioHelper = ioHelper;
        }

        /// <inheritdoc />
        protected override IConfigurationEditor CreateConfigurationEditor() => new EyeDropperColorPickerConfigurationEditor(_ioHelper);
    }
}

using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;

namespace Umbraco.Cms.Core.PropertyEditors
{
    [DataEditor(
        Constants.PropertyEditors.Aliases.ColorPickerEyeDropper,
        EditorType.PropertyValue | EditorType.MacroParameter,
        "Eye Dropper Color Picker",
        "eyedropper",
        Icon = "icon-colorpicker",
        Group = Constants.PropertyEditors.Groups.Pickers)]
    public class EyeDropperColorPickerPropertyEditor : DataEditor
    {
        private readonly IIOHelper _ioHelper;

        public EyeDropperColorPickerPropertyEditor(
            IDataValueEditorFactory dataValueEditorFactory,
            IIOHelper ioHelper,
            EditorType type = EditorType.PropertyValue)
            : base(dataValueEditorFactory, type)
        {
            _ioHelper = ioHelper;
        }

        /// <inheritdoc />
        protected override IConfigurationEditor CreateConfigurationEditor() => new EyeDropperColorPickerConfigurationEditor(_ioHelper);
    }
}

Allow Eye Dropper to be used as macro parameter editor


using System;
using System.IO;
using System.IO.Compression;
using System.Reflection;

namespace TestUtilities
{
    public static class DatacardUtility
    {
        public static string WriteDatacard(string name)
        {
            var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            Directory.CreateDirectory(directory);
            WriteDatacard(name, directory);
            return directory;
        }

        public static void WriteDatacard(string name, string directory)
        {
            var bytes = GetDatacard(name);
            Directory.CreateDirectory(directory);

            var zipFilePath = Path.Combine(directory, "DataCard.zip");
            File.WriteAllBytes(zipFilePath, bytes);

            ZipFile.ExtractToDirectory(zipFilePath, directory);
        }

        public static byte[] GetDatacard(string name)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataCards", Path.ChangeExtension(name.Replace(" ", "_"), ".zip"));
            return File.ReadAllBytes(path);
        }
    }
}

using System;
using System.IO;
using System.IO.Compression;
using System.Reflection;

namespace TestUtilities
{
    public static class DatacardUtility
    {
        public static string WriteDatacard(string name)
        {
            var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            Directory.CreateDirectory(directory);
            WriteDatacard(name, directory);
            return directory;
        }

        public static void WriteDatacard(string name, string directory)
        {
            var bytes = GetDatacard(name);
            Directory.CreateDirectory(directory);

            var zipFilePath = Path.Combine(directory, "Datacard.zip");
            File.WriteAllBytes(zipFilePath, bytes);

            ZipFile.ExtractToDirectory(zipFilePath, directory);
        }

        public static byte[] GetDatacard(string name)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Datacards", Path.ChangeExtension(name.Replace(" ", "_"), ".zip"));
            return File.ReadAllBytes(path);
        }
    }
}

Fix test datacard path case

Fix test datacard path case


using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Security.Claims;
using System.Security.Principal;
using System.Web;

namespace Bonobo.Git.Server
{
    public static class UserExtensions
    {
        public static string GetClaim(this IPrincipal user, string claimName)
        {
            string result = null;

            ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity;
            if (claimsIdentity != null)
            {
                try
                {
                    result = claimsIdentity.FindFirst(claimName).Value;
                }
                catch
                {
                }
            }

            return result;
        }

        public static string Id(this IPrincipal user)
        {
            return user.GetClaim(ClaimTypes.Upn);
        }

        public static string Name(this IPrincipal user)
        {
            return user.GetClaim(ClaimTypes.Name);
        }

        public static string[] Roles(this IPrincipal user)
        {
            string[] result = null;

            ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity;
            if (claimsIdentity != null)
            {
                try
                {
                    result = claimsIdentity.FindAll(ClaimTypes.Role).Select(x => x.Value).ToArray();
                }
                catch
                {
                }
            }

            return result;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Security.Claims;
using System.Security.Principal;
using System.Web;

namespace Bonobo.Git.Server
{
    public static class UserExtensions
    {
        public static string GetClaim(this IPrincipal user, string claimName)
        {
            string result = null;

            try
            {
                ClaimsIdentity claimsIdentity = GetClaimsIdentity(user);
                if (claimsIdentity != null)
                {
                    result = claimsIdentity.FindFirst(claimName).Value;
                }
            }
            catch
            {
            }

            return result;
        }

        public static string Id(this IPrincipal user)
        {
            return user.GetClaim(ClaimTypes.Upn);
        }

        public static string Name(this IPrincipal user)
        {
            return user.GetClaim(ClaimTypes.Name);
        }

        public static bool IsWindowsPrincipal(this IPrincipal user)
        {
            return user.Identity is WindowsIdentity;
        }

        public static string[] Roles(this IPrincipal user)
        {
            string[] result = null;

            try
            {
                ClaimsIdentity claimsIdentity = GetClaimsIdentity(user);
                if (claimsIdentity != null)
                {
                    result = claimsIdentity.FindAll(ClaimTypes.Role).Select(x => x.Value).ToArray();
                }
            }
            catch
            {
            }

            return result;
        }

        private static ClaimsIdentity GetClaimsIdentity(this IPrincipal user)
        {
            ClaimsIdentity result = null;

            ClaimsPrincipal claimsPrincipal = user as ClaimsPrincipal;
            if (claimsPrincipal != null)
            {
                result = claimsPrincipal.Identities.FirstOrDefault(x => x is ClaimsIdentity);
            }

            return result;
        }
    }
}

Use correct claims in case UserPrincipal has more than one identity


namespace Inspiring.Mvvm.Views {
   using System.Windows;
   using System.Windows.Media;
   using Inspiring.Mvvm.Common;
   using Inspiring.Mvvm.Screens;

   public class WindowService : IWindowService {
      public static readonly Event<InitializeWindowEventArgs> InitializeWindowEvent = new Event<InitializeWindowEventArgs>();

      public virtual Window CreateWindow(Window owner, string title, bool modal) {
         Window window = new Window();

         if (title != null) {
            window.Title = title;
         }

         if (owner != null) {
            window.Owner = owner;
         }

         if (modal) {
            window.ShowInTaskbar = false;
         }

         // Needed for sharp text rendering.
         TextOptions.SetTextFormattingMode(window, TextFormattingMode.Display);
         TextOptions.SetTextRenderingMode(window, TextRenderingMode.Aliased);

         return window;
      }

      public virtual void ShowWindow(Window window, bool modal) {
         if (modal) {
            window.ShowDialog();
         } else {
            window.Show();
         }
      }
   }

   public sealed class InitializeWindowEventArgs : ScreenEventArgs {
      public InitializeWindowEventArgs(IScreenBase target, Window window)
         : base(target) {
         Window = window;
      }

      public Window Window { get; private set; }
   }
}

namespace Inspiring.Mvvm.Views {
   using System.Windows;
   using System.Windows.Media;
   using Inspiring.Mvvm.Common;
   using Inspiring.Mvvm.Screens;

   public class WindowService : IWindowService {
      public static readonly Event<InitializeWindowEventArgs> InitializeWindowEvent = new Event<InitializeWindowEventArgs>();

      public virtual Window CreateWindow(Window owner, string title, bool modal) {
         var window = new Window();

         if (title != null) {
            window.Title = title;
         }

         if (owner != null) {
            window.Owner = owner;
         }

         if (modal) {
            window.ShowInTaskbar = false;
         }

         // Needed for sharp element rendering.
         window.UseLayoutRounding = true;

         // Needed for sharp text rendering.
         TextOptions.SetTextFormattingMode(window, TextFormattingMode.Display);

         return window;
      }

      public virtual void ShowWindow(Window window, bool modal) {
         if (modal) {
            window.ShowDialog();
         } else {
            window.Show();
         }
      }
   }

   public sealed class InitializeWindowEventArgs : ScreenEventArgs {
      public InitializeWindowEventArgs(IScreenBase target, Window window)
         : base(target) {
         Window = window;
      }

      public Window Window { get; private set; }
   }
}

Optimize element and text rendering for modern Windows versions

Using "TextRenderingMode.Aliased" is not recommended any more since ClearType is enabled by default and does a good job on modern Windows versions.
Enabling "UseLayoutRounding" doesn't affect text, but helps with sharp rendering of other UI elements.


using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.Hosting;

namespace Duracellko.PlanningPoker.Web
{
    public class HttpClientSetupService : BackgroundService
    {
        private readonly HttpClient _httpClient;
        private readonly IServer _server;

        public HttpClientSetupService(HttpClient httpClient, IServer server)
        {
            _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
            _server = server ?? throw new ArgumentNullException(nameof(server));
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var serverAddresses = _server.Features.Get<IServerAddressesFeature>();
            var address = serverAddresses.Addresses.FirstOrDefault();
            if (address == null)
            {
                // Default ASP.NET Core Kestrel endpoint
                address = "http://localhost:5000";
            }
            else
            {
                address = address.Replace("*", "localhost", StringComparison.Ordinal);
                address = address.Replace("+", "localhost", StringComparison.Ordinal);
            }

            _httpClient.BaseAddress = new Uri(address);

            return Task.CompletedTask;
        }
    }
}

using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.Hosting;

namespace Duracellko.PlanningPoker.Web
{
    public class HttpClientSetupService : BackgroundService
    {
        private readonly HttpClient _httpClient;
        private readonly IServer _server;

        public HttpClientSetupService(HttpClient httpClient, IServer server)
        {
            _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
            _server = server ?? throw new ArgumentNullException(nameof(server));
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var serverAddresses = _server.Features.Get<IServerAddressesFeature>();
            var address = serverAddresses.Addresses.FirstOrDefault();
            if (address == null)
            {
                // Default ASP.NET Core Kestrel endpoint
                address = "http://localhost:5000";
            }
            else
            {
                address = address.Replace("*", "localhost", StringComparison.Ordinal);
                address = address.Replace("+", "localhost", StringComparison.Ordinal);
                address = address.Replace("[::]", "localhost", StringComparison.Ordinal);
            }

            _httpClient.BaseAddress = new Uri(address);

            return Task.CompletedTask;
        }
    }
}

Replace any API endpoint [::] for localhost when configuring HttpClient base address


using System;
using System.Web.Http;
using DataBooster.DbWebApi;

namespace MyDbWebApi
{
	public static class WebApiConfig
	{
		public static void Register(HttpConfiguration config)
		{
			config.Routes.MapHttpRoute(
				name: "DbWebApi",
				routeTemplate: "{sp}",
				defaults: new { controller = "DbWebApi" }
			);

			config.SupportCsvMediaType();
			DbWebApiOptions.DerivedParametersCacheExpireInterval = new TimeSpan(0, 15, 0);
		}
	}
}

using System;
using System.Web.Http;
using DataBooster.DbWebApi;

namespace MyDbWebApi
{
	public static class WebApiConfig
	{
		public static void Register(HttpConfiguration config)
		{
			config.Routes.MapHttpRoute(
				name: "DbWebApi",
				routeTemplate: "{sp}/{ext}",
				defaults: new { controller = "DbWebApi", ext = RouteParameter.Optional },
				constraints: new { ext = @"|json|xml|csv" }
			);

			config.SupportCsvMediaType();
			DbWebApiOptions.DerivedParametersCacheExpireInterval = new TimeSpan(0, 15, 0);
		}
	}
}

Add Uri Path Extension - constraints: new { ext = @"|json|xml|csv" }


// <auto-generated/>
using System.Reflection;

[assembly: AssemblyTitleAttribute("Elders.Cronus")]
[assembly: AssemblyDescriptionAttribute("Elders.Cronus")]
[assembly: AssemblyProductAttribute("Elders.Cronus")]
[assembly: AssemblyVersionAttribute("1.2.7")]
[assembly: AssemblyInformationalVersionAttribute("1.2.7")]
[assembly: AssemblyFileVersionAttribute("1.2.7")]
namespace System {
    internal static class AssemblyVersionInformation {
        internal const string Version = "1.2.7";
    }
}

// <auto-generated/>
using System.Reflection;

[assembly: AssemblyTitleAttribute("Elders.Cronus")]
[assembly: AssemblyDescriptionAttribute("Elders.Cronus")]
[assembly: AssemblyProductAttribute("Elders.Cronus")]
[assembly: AssemblyVersionAttribute("1.2.8")]
[assembly: AssemblyInformationalVersionAttribute("1.2.8")]
[assembly: AssemblyFileVersionAttribute("1.2.8")]
namespace System {
    internal static class AssemblyVersionInformation {
        internal const string Version = "1.2.8";
    }
}

Initialize AggregateRepository only for CommandConsumer