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

namespace Fungus
{
	[EventHandlerInfo("",
	                  "Flowchart Enabled",
	                  "The block will execute when the Flowchart game object is enabled.")]
	[AddComponentMenu("")]
	public class FlowchartEnabled : EventHandler
	{
		protected virtual void OnEnable()
		{
			ExecuteBlock();
		}
	}
}

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

namespace Fungus
{
	[EventHandlerInfo("",
	                  "Flowchart Enabled",
	                  "The block will execute when the Flowchart game object is enabled.")]
	[AddComponentMenu("")]
	public class FlowchartEnabled : EventHandler
	{
		protected virtual void OnEnable()
		{
			// Blocks use coroutines to schedule command execution, but Unity's coroutines are
			// sometimes unreliable when enabling / disabling objects.
			// To workaround this we execute the block on the next frame.
			Invoke("DoEvent", 0);
		}

		protected virtual void DoEvent()
		{
			ExecuteBlock();
		}
	}
}

Fix for Flowchart Enabled event handler coroutine issue


using Klawr.ClrHost.Interfaces;
using Klawr.UnrealEngine;

namespace $RootNamespace$
{
    public class $ScriptName$ : UKlawrScriptComponent
    {
        public $ScriptName$(long instanceID, UObjectHandle nativeComponent)
            : base(instanceID, nativeComponent)
        {
        }
    }
}

using Klawr.ClrHost.Interfaces;
using Klawr.ClrHost.Managed.SafeHandles;
using Klawr.UnrealEngine;

namespace $RootNamespace$
{
    public class $ScriptName$ : UKlawrScriptComponent
    {
        public $ScriptName$(long instanceID, UObjectHandle nativeComponent)
            : base(instanceID, nativeComponent)
        {
        }
    }
}

Add missing namespace to Klawr script component template

This fixes an issue where adding a new script in UnrealEd broke
building of the GameScripts assembly.


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

namespace CsProjArrange
{
    /// <summary>
    /// Compares a list of attributes in order by value.
    /// </summary>
    public class AttributeKeyComparer : IComparer<IEnumerable<XAttribute>>
    {
        public AttributeKeyComparer(IEnumerable<string> sortAttributes)
        {
            SortAttributes = sortAttributes;
        }

        public IEnumerable<string> SortAttributes
        {
            get;
            set;
        }

        public int Compare(IEnumerable<XAttribute> x, IEnumerable<XAttribute> y)
        {
            if (x == null)
            {
                if (y == null)
                {
                    return 0;
                }
                return 1;
            }
            if (y == null)
            {
                return -1;
            }
            foreach (var attribute in SortAttributes)
            {
                string xValue = null;
                string yValue = null;
                var xAttribute = x.FirstOrDefault(a => a.Name.LocalName == attribute);
                var yAttribute = y.FirstOrDefault(a => a.Name.LocalName == attribute);
                if (xAttribute != null)
                {
                    xValue = xAttribute.Value;
                }
                if (yAttribute != null)
                {
                    yValue = yAttribute.Value;
                }
                int result = string.Compare(xValue ?? string.Empty, yValue ?? string.Empty);
                if (result != 0)
                {
                    return result;
                }
            }

            return 0;
        }
    }
}

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

namespace CsProjArrange
{
    /// <summary>
    /// Compares a list of attributes in order by value.
    /// </summary>
    public class AttributeKeyComparer : IComparer<IEnumerable<XAttribute>>
    {
        public AttributeKeyComparer(IEnumerable<string> sortAttributes)
        {
            SortAttributes = sortAttributes;
        }

        public IEnumerable<string> SortAttributes
        {
            get;
            set;
        }

        public int Compare(IEnumerable<XAttribute> x, IEnumerable<XAttribute> y)
        {
            if (x == null)
            {
                if (y == null)
                {
                    return 0;
                }
                return 1;
            }
            if (y == null)
            {
                return -1;
            }
            foreach (var attribute in SortAttributes)
            {
                string xValue = null;
                string yValue = null;
                var xAttribute = x.FirstOrDefault(a => a.Name.LocalName == attribute);
                var yAttribute = y.FirstOrDefault(a => a.Name.LocalName == attribute);
                if (xAttribute != null)
                {
                    xValue = xAttribute.Value;
                }
                if (yAttribute != null)
                {
                    yValue = yAttribute.Value;
                }
                int result = string.Compare(xValue ?? string.Empty, yValue ?? string.Empty, StringComparison.InvariantCulture);
                if (result != 0)
                {
                    return result;
                }
            }

            return 0;
        }
    }
}

Use invariant culture for string comparisons


using WalletWasabi.Fluent.ViewModels.NavBar;
using WalletWasabi.Helpers;

namespace WalletWasabi.Fluent.ViewModels.Wallets.Actions
{
	public abstract partial class WalletActionViewModel : NavBarItemViewModel
	{
		[AutoNotify] private bool _isEnabled;

		protected WalletActionViewModel(WalletViewModelBase wallet)
		{
			Wallet = Guard.NotNull(nameof(wallet), wallet);
		}

		public WalletViewModelBase Wallet { get; }

		public override string ToString() => Title;
	}
}

using System.Reactive;
using System.Reactive.Linq;
using ReactiveUI;
using WalletWasabi.Fluent.ViewModels.NavBar;
using WalletWasabi.Helpers;
using WalletWasabi.Wallets;

namespace WalletWasabi.Fluent.ViewModels.Wallets.Actions
{
	public abstract partial class WalletActionViewModel : NavBarItemViewModel
	{
		[AutoNotify] private bool _isEnabled;

		protected WalletActionViewModel(WalletViewModelBase wallet)
		{
			Wallet = Guard.NotNull(nameof(wallet), wallet);

			wallet.WhenAnyValue(x => x.WalletState).Select(x => IsEnabled = (x == WalletState.Started));
		}

		public WalletViewModelBase Wallet { get; }

		public override string ToString() => Title;
	}
}

Set IsEnabled wallet action property depending on wallet state


using System.Globalization;
using System.Text;

namespace SCPI.Acquire
{
    public class ACQUIRE_SRATE : ICommand
    {
        public string Description => "Query the current sample rate. The default unit is Sa/s.";

        public float SampleRate { get; private set; }

        public string Command(params string[] parameters) => ":ACQuire:SRATe?";

        public string HelpMessage()
        {
            var syntax = nameof(ACQUIRE_SRATE) + "\n";
            var example = "Example: " + nameof(ACQUIRE_SRATE);

            return $"{syntax}\n{example}";
        }

        public bool Parse(byte[] data)
        {
            if (data == null)
            {
                return false;
            }

            if (float.TryParse(Encoding.ASCII.GetString(data), NumberStyles.Any,
                               CultureInfo.InvariantCulture, out float sampleRate))
            {
                SampleRate = sampleRate;

                return true;
            }

            return false;
        }
    }
}

using SCPI.Extensions;
using System.Text;

namespace SCPI.Acquire
{
    public class ACQUIRE_SRATE : ICommand
    {
        public string Description => "Query the current sample rate. The default unit is Sa/s.";

        public float SampleRate { get; private set; }

        public string Command(params string[] parameters) => ":ACQuire:SRATe?";

        public string HelpMessage()
        {
            var syntax = nameof(ACQUIRE_SRATE) + "\n";
            var example = "Example: " + nameof(ACQUIRE_SRATE);

            return $"{syntax}\n{example}";
        }

        public bool Parse(byte[] data)
        {
            if (data == null)
            {
                return false;
            }

            if (Encoding.ASCII.GetString(data).ScientificNotationStringToFloat(out float sampleRate))
            {
                SampleRate = sampleRate;

                return true;
            }

            return false;
        }
    }
}

Use extension method for string to float conversion


using ICities;
using CitiesHarmony.API;

namespace UOCRevisited
{
    /// <summary>
    /// The base mod class for instantiation by the game.
    /// </summary>
    public class UOCRMod : IUserMod
    {
        // Public mod name and description.
        public string Name => ModName + " " + Version;
        public string Description => "Place as many roads with outside connections as you want";

        // Internal and private name and version components.
        internal static string ModName => "Unlimited Outside Connections Revisited";
        internal static string Version => BaseVersion + " " + Beta;
        internal static string Beta => "BETA 1";
        private static string BaseVersion => "1.0";

        /// <summary>
        /// Called by the game when the mod is enabled.
        /// </summary>
        public void OnEnabled()
        {
            // Apply Harmony patches via Cities Harmony.
            // Called here instead of OnCreated to allow the auto-downloader to do its work prior to launch.
            HarmonyHelper.DoOnHarmonyReady(() => Patcher.PatchAll());
        }

        /// <summary>
        /// Called by the game when the mod is disabled.
        /// </summary>
        public void OnDisabled()
        {
            // Unapply Harmony patches via Cities Harmony.
            if (HarmonyHelper.IsHarmonyInstalled)
            {
                Patcher.UnpatchAll();
            }
        }
    }
}

using ICities;
using CitiesHarmony.API;

namespace UOCRevisited
{
    /// <summary>
    /// The base mod class for instantiation by the game.
    /// </summary>
    public class UOCRMod : IUserMod
    {
        // Public mod name and description.
        public string Name => ModName + " " + Version;
        public string Description => "Place as many roads with outside connections as you want";

        // Internal and private name and version components.
        internal static string ModName => "Unlimited Outside Connections Revisited";
        internal static string Version => BaseVersion + " " + Beta;
        internal static string Beta => "BETA 2";
        private static string BaseVersion => "1.0";

        /// <summary>
        /// Called by the game when the mod is enabled.
        /// </summary>
        public void OnEnabled()
        {
            // Apply Harmony patches via Cities Harmony.
            // Called here instead of OnCreated to allow the auto-downloader to do its work prior to launch.
            HarmonyHelper.DoOnHarmonyReady(() => Patcher.PatchAll());
        }

        /// <summary>
        /// Called by the game when the mod is disabled.
        /// </summary>
        public void OnDisabled()
        {
            // Unapply Harmony patches via Cities Harmony.
            if (HarmonyHelper.IsHarmonyInstalled)
            {
                Patcher.UnpatchAll();
            }
        }
    }
}

Prepare for 1.0 BETA 2.

Prepare for 1.0 BETA 2.


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OpenStardriveServer.Domain.Database;
using OpenStardriveServer.HostedServices;

namespace OpenStardriveServer;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        DependencyInjectionConfig.ConfigureServices(services);
        services.AddSingleton(x => new SqliteDatabase
        {
            ConnectionString = $"Data Source=openstardrive-server.sqlite"
        });

        services.AddControllers();

        services.AddHostedService<ServerInitializationService>();
        services.AddHostedService<CommandProcessingService>();
        services.AddHostedService<ChronometerService>();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
    }
}

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OpenStardriveServer.Domain.Database;
using OpenStardriveServer.HostedServices;

namespace OpenStardriveServer;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        DependencyInjectionConfig.ConfigureServices(services);
        services.AddSingleton(x => new SqliteDatabase
        {
            ConnectionString = $"Data Source=openstardrive-server.sqlite"
        });

        services.AddControllers();

        services.AddHostedService<ServerInitializationService>();
        services.AddHostedService<CommandProcessingService>();
        services.AddHostedService<ChronometerService>();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();
        app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().Build());
        app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
    }
}

Add CORS for local testing

Add CORS for local testing


namespace Raygun.Messages.Tests
{
    using NUnit.Framework;

    using Shouldly;

    [TestFixture]
    public class RaygunClientMessageTests
    {
        [Test]
        public void Should_return_name_from_the_AssemblyTitleAttribute()
        {
            // Given
            var sut = SutFactory();

            // When / Then
            sut.Name.ShouldBe("Raygun.Owin");
        }

        [Test]
        public void Should_return_version_from_the_AssemblyVersionAttribute()
        {
            // Given
            var sut = SutFactory();

            // When / Then
            sut.Version.ShouldBe("0.1.0.0");
        }

        [Test]
        public void Should_return_client_url_for_the_github_repository()
        {
            // Given
            var sut = SutFactory();

            // When / Then
            sut.ClientUrl.ShouldBe("https://github.com/xt0rted/Raygun.Owin");
        }

        private static RaygunClientMessage SutFactory()
        {
            return new RaygunClientMessage();
        }
    }
}

namespace Raygun.Messages.Tests
{
    using NUnit.Framework;

    using Shouldly;

    [TestFixture]
    public class RaygunClientMessageTests
    {
        [Test]
        public void Should_return_name_from_the_AssemblyTitleAttribute()
        {
            // Given
            var sut = SutFactory();

            // When / Then
            sut.Name.ShouldBe("Raygun.Owin");
        }

        [Test]
        public void Should_return_version_from_the_AssemblyVersionAttribute()
        {
            // Given
            var sut = SutFactory();
            var expected = typeof (RaygunClient).Assembly.GetName().Version.ToString();

            // When / Then
            sut.Version.ShouldBe(expected);
        }

        [Test]
        public void Should_return_client_url_for_the_github_repository()
        {
            // Given
            var sut = SutFactory();

            // When / Then
            sut.ClientUrl.ShouldBe("https://github.com/xt0rted/Raygun.Owin");
        }

        private static RaygunClientMessage SutFactory()
        {
            return new RaygunClientMessage();
        }
    }
}

Load the expected version from the assembly


namespace Prometheus.HttpExporter.AspNetCore.InFlight
{
    public class HttpInFlightOptions : HttpExporterOptionsBase
    {
        public Gauge Gauge { get; set; } =
            Metrics.CreateGauge(DefaultName, DefaultHelp);

        private const string DefaultName = "aspnet_http_inflight";
        private const string DefaultHelp = "Total number of requests currently being processed.";
    }
}

namespace Prometheus.HttpExporter.AspNetCore.InFlight
{
    public class HttpInFlightOptions : HttpExporterOptionsBase
    {
        public Gauge Gauge { get; set; } =
            Metrics.CreateGauge(DefaultName, DefaultHelp);

        private const string DefaultName = "http_executing_requests";
        private const string DefaultHelp = "The number of requests currently being processed.";
    }
}

Change http inflight requests default name to match Prometheus guidelines


using Newtonsoft.Json;
using SourceSchemaParser.JsonConverters;
using System;
using System.Collections.Generic;

namespace SourceSchemaParser.Dota2
{
    public class DotaSchemaItem : SchemaItem
    {
        public DotaSchemaItemTool Tool { get; set; }

        [JsonProperty("tournament_url")]
        public string TournamentUrl { get; set; }

        [JsonProperty("image_banner")]
        public string ImageBannerPath { get; set; }

        [JsonProperty("item_rarity")]
        public string ItemRarity { get; set; }

        [JsonProperty("item_slot")]
        public string ItemSlot { get; set; }

        [JsonProperty("price_info")]
        public DotaSchemaItemPriceInfo PriceInfo { get; set; }

        [JsonConverter(typeof(DotaSchemaUsedByHeroesJsonConverter))]
        [JsonProperty("used_by_heroes")]
        public IList<string> UsedByHeroes { get; set; }
    }

    public class DotaSchemaItemPriceInfo
    {
        [JsonProperty("bucket")]
        public string Bucket { get; set; }
        [JsonProperty("class")]
        public string Class { get; set; }
        [JsonProperty("category_tags")]
        public string CategoryTags { get; set; }
        [JsonProperty("date")]
        public DateTime? Date { get; set; }
        [JsonConverter(typeof(DotaSchemaItemPriceJsonConverter))]
        [JsonProperty("price")]
        public decimal? Price { get; set; }
        [JsonConverter(typeof(StringToBoolJsonConverter))]
        [JsonProperty("is_pack_item")]
        public bool? IsPackItem { get; set; }
    }
}

using Newtonsoft.Json;
using SourceSchemaParser.JsonConverters;
using System;
using System.Collections.Generic;

namespace SourceSchemaParser.Dota2
{
    public class DotaSchemaItem : SchemaItem
    {
        public DotaSchemaItemTool Tool { get; set; }

        [JsonProperty("tournament_url")]
        public string TournamentUrl { get; set; }

        [JsonProperty("image_banner")]
        public string ImageBannerPath { get; set; }

        [JsonProperty("item_rarity")]
        public string ItemRarity { get; set; }

        [JsonProperty("item_quality")]
        public string ItemQuality { get; set; }

        [JsonProperty("item_slot")]
        public string ItemSlot { get; set; }

        [JsonProperty("price_info")]
        public DotaSchemaItemPriceInfo PriceInfo { get; set; }

        [JsonConverter(typeof(DotaSchemaUsedByHeroesJsonConverter))]
        [JsonProperty("used_by_heroes")]
        public IList<string> UsedByHeroes { get; set; }
    }

    public class DotaSchemaItemPriceInfo
    {
        [JsonProperty("bucket")]
        public string Bucket { get; set; }
        [JsonProperty("class")]
        public string Class { get; set; }
        [JsonProperty("category_tags")]
        public string CategoryTags { get; set; }
        [JsonProperty("date")]
        public DateTime? Date { get; set; }
        [JsonConverter(typeof(DotaSchemaItemPriceJsonConverter))]
        [JsonProperty("price")]
        public decimal? Price { get; set; }
        [JsonConverter(typeof(StringToBoolJsonConverter))]
        [JsonProperty("is_pack_item")]
        public bool? IsPackItem { get; set; }
    }
}

Add item quality to schema items.

Add item quality to schema items.


using System;
using System.Data;
using System.Threading.Tasks;
using Dapper.FastCrud;
using Dapper.FastCrud.Configuration.StatementOptions.Builders;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Helpers;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
    public abstract partial class Repository<TSession, TEntity, TPk>
        where TEntity : class, IEntity<TPk>
        where TSession : ISession
    {
        public TEntity Get(TPk key, ISession session = null)
        {
            return GetAsync(key, session).Result;
        }

        public async Task<TEntity> GetAsync(TPk key, ISession session = null)
        {
            var entity = CreateInstanceHelper.Resolve<TEntity>();
            entity.Id = key;
            if (session != null)
            {
                return await session.GetAsync(entity);
            }
            using (var uow = Factory.CreateSession<TSession>())
            {
                return await uow.GetAsync(entity);
            }
        }
        protected async Task<TEntity> GetAsync(IDbConnection connection, TEntity keys, Action<ISelectSqlSqlStatementOptionsBuilder<TEntity>> statement)
        {
            if (connection != null)
            {
                return await connection.GetAsync(keys, statement);
            }
            using (var uow = Factory.CreateSession<TSession>())
            {
                return await uow.GetAsync(keys, statement);
            }
        }
    }
}

using System;
using System.Data;
using System.Threading.Tasks;
using Dapper.FastCrud;
using Dapper.FastCrud.Configuration.StatementOptions.Builders;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Helpers;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
    public abstract partial class Repository<TSession, TEntity, TPk>
        where TEntity : class, IEntity<TPk>
        where TSession : ISession
    {
        public TEntity GetKey(TPk key, ISession session = null)
        {
            return GetKeyAsync(key, session).Result;
        }

        public async Task<TEntity> GetKeyAsync(TPk key, ISession session = null)
        {
            var entity = CreateInstanceHelper.Resolve<TEntity>();
            entity.Id = key;
            return await GetAsync(entity, session);
        }

        public TEntity Get(TEntity entity, ISession session = null)
        {
            return GetAsync(entity, session).Result;
        }

        public async Task<TEntity> GetAsync(TEntity entity, ISession session = null)
        {
            if (session != null)
            {
                return await session.GetAsync(entity);
            }
            using (var uow = Factory.CreateSession<TSession>())
            {
                return await uow.GetAsync(entity);
            }
        }
    }
}

Add an entity get. and change old get to get key


// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;
using MICore;

namespace AndroidDebugLauncher
{
    internal static class TargetArchitectureExtensions
    {
        public static string ToNDKArchitectureName(this TargetArchitecture arch)
        {
            switch (arch)
            {
                case TargetArchitecture.X86:
                    return "x86";

                case TargetArchitecture.X64:
                    return "x64";

                case TargetArchitecture.ARM:
                    return "arm";

                case TargetArchitecture.ARM64:
                    return "arm64";

                default:
                    Debug.Fail("Should be impossible");
                    throw new InvalidOperationException();
            }
        }
    }
}

// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;
using MICore;

namespace AndroidDebugLauncher
{
    internal static class TargetArchitectureExtensions
    {
        public static string ToNDKArchitectureName(this TargetArchitecture arch)
        {
            switch (arch)
            {
                case TargetArchitecture.X86:
                    return "x86";

                case TargetArchitecture.X64:
                    return "x86_64";

                case TargetArchitecture.ARM:
                    return "arm";

                case TargetArchitecture.ARM64:
                    return "arm64";

                default:
                    Debug.Fail("Should be impossible");
                    throw new InvalidOperationException();
            }
        }
    }
}

Use correct extension for Android x64 folder


using Bartender.Tests.Context;
using Moq;
using Xunit;

namespace Bartender.Tests
{
    public class CancellableAsyncQueryDispatcherTests : DispatcherTests
    {
        [Fact]
        public async void ShouldHandleQueryOnce_WhenCallDispatchAsyncMethod()
        {
            await CancellableAsyncQueryDispatcher.DispatchAsync<Query, ReadModel>(Query, CancellationToken);
            MockedCancellableAsyncQueryHandler.Verify(x => x.HandleAsync(It.IsAny<Query>(), CancellationToken), Times.Once);
        }
    }
}

using Bartender.Tests.Context;
using Moq;
using Shouldly;
using Xunit;

namespace Bartender.Tests
{
    public class CancellableAsyncQueryDispatcherTests : DispatcherTests
    {
        [Fact]
        public async void ShouldHandleQueryOnce_WhenCallDispatchAsyncMethod()
        {
            await CancellableAsyncQueryDispatcher.DispatchAsync<Query, ReadModel>(Query, CancellationToken);
            MockedCancellableAsyncQueryHandler.Verify(x => x.HandleAsync(It.IsAny<Query>(), CancellationToken), Times.Once);
        }

        [Fact]
        public async void ShouldReturnReadModel_WhenCallDispatchAsyncMethod()
        {
            var readModel = await CancellableAsyncQueryDispatcher.DispatchAsync<Query, ReadModel>(Query, CancellationToken);
            readModel.ShouldBeSameAs(ReadModel);
        }

        [Fact]
        public void ShouldThrowException_WhenNoAsyncQueryHandler()
        {
            MockedDependencyContainer
                .Setup(method => method.GetAllInstances<ICancellableAsyncQueryHandler<Query, ReadModel>>())
                .Returns(() => new ICancellableAsyncQueryHandler<Query, ReadModel>[0]);

            Should
                .Throw<DispatcherException>(async () => await CancellableAsyncQueryDispatcher.DispatchAsync<Query, ReadModel>(Query, CancellationToken))
                .Message
                .ShouldBe(NoHandlerExceptionMessageExpected);
        }

        [Fact]
        public void ShouldThrowException_WhenMultipleAsyncQueryHandler()
        {
            MockedDependencyContainer
                .Setup(method => method.GetAllInstances<ICancellableAsyncQueryHandler<Query, ReadModel>>())
                .Returns(() => new [] { MockedCancellableAsyncQueryHandler.Object, MockedCancellableAsyncQueryHandler.Object });

            Should
                .Throw<DispatcherException>(async () => await CancellableAsyncQueryDispatcher.DispatchAsync<Query, ReadModel>(Query, CancellationToken))
                .Message
                .ShouldBe(MultipleHandlerExceptionMessageExpected);
        }
    }
}

Add test cover for cancellable async query handling


using System;
using System.Collections.Generic;

namespace Seq.Api.Model.Diagnostics
{
    public class ServerMetricsEntity : Entity
    {
        public ServerMetricsEntity()
        {
            RunningTasks = new List<RunningTaskPart>();
        }

        public double EventStoreDaysRecorded { get; set; }
        public double EventStoreDaysCached { get; set; }
        public int EventStoreEventsCached { get; set; }
        public DateTime? EventStoreFirstSegmentDateUtc { get; set; }
        public DateTime? EventStoreLastSegmentDateUtc { get; set; }
        public long EventStoreDiskRemainingBytes { get; set; }

        public int EndpointArrivalsPerMinute { get; set; }
        public int EndpointInfluxPerMinute { get; set; }
        public long EndpointIngestedBytesPerMinute { get; set; }
        public int EndpointInvalidPayloadsPerMinute { get; set; }
        public int EndpointUnauthorizedPayloadsPerMinute { get; set; }

        public TimeSpan ProcessUptime { get; set; }
        public long ProcessWorkingSetBytes { get; set; }
        public int ProcessThreads { get; set; }
        public int ProcessThreadPoolUserThreadsAvailable { get; set; }
        public int ProcessThreadPoolIocpThreadsAvailable { get; set; }

        public double SystemMemoryUtilization { get; set; }

        public List<RunningTaskPart> RunningTasks { get; set; }

        public int QueriesPerMinute { get; set; }
        public int QueryCacheTimeSliceHitsPerMinute { get; set; }
        public int QueryCacheInvalidationsPerMinute { get; set; }

        public int DocumentStoreActiveSessions { get; set; }
        public int DocumentStoreActiveTransactions { get; set; }
    }
}

using System;
using System.Collections.Generic;

namespace Seq.Api.Model.Diagnostics
{
    public class ServerMetricsEntity : Entity
    {
        public ServerMetricsEntity()
        {
            RunningTasks = new List<RunningTaskPart>();
        }

        public double EventStoreDaysRecorded { get; set; }
        public double EventStoreDaysCached { get; set; }
        public int EventStoreEventsCached { get; set; }
        public DateTime? EventStoreFirstSegmentDateUtc { get; set; }
        public DateTime? EventStoreLastSegmentDateUtc { get; set; }
        public long EventStoreDiskRemainingBytes { get; set; }

        public int EndpointArrivalsPerMinute { get; set; }
        public int EndpointInfluxPerMinute { get; set; }
        public long EndpointIngestedBytesPerMinute { get; set; }
        public int EndpointInvalidPayloadsPerMinute { get; set; }
        public int EndpointUnauthorizedPayloadsPerMinute { get; set; }

        public TimeSpan ProcessUptime { get; set; }
        public long ProcessWorkingSetBytes { get; set; }
        public int ProcessThreads { get; set; }
        public int ProcessThreadPoolUserThreadsAvailable { get; set; }
        public int ProcessThreadPoolIocpThreadsAvailable { get; set; }

        public double SystemMemoryUtilization { get; set; }

        public List<RunningTaskPart> RunningTasks { get; set; }

        public int QueriesPerMinute { get; set; }
        public int QueryCacheTimeSliceHitsPerMinute { get; set; }
        public int QueryCacheInvalidationsPerMinute { get; set; }

        public int DocumentStoreActiveSessions { get; set; }
    }
}

Remove active transactions metric no longer supplied by Seq 4


using Xunit;

namespace Dcc.Test
{
    public class DccMiddlewareTests
    {
        [Fact]
        public void SanityTest()
        {
            Assert.True(true);
        }
    }
}

using FluentAssertions;

using Xunit;

namespace Dcc.Test
{
    public class DccMiddlewareTests
    {
        [Fact]
        public void SanityTest()
        {
            true.Should().BeTrue();
        }
    }
}

Make use of FluentAssertions in sanity unit test.


using System;
using Tralus.Framework.BusinessModel.Entities;

namespace Tralus.Framework.Migration.Migrations
{
    using System.Data.Entity.Migrations;

    public sealed class Configuration :  TralusDbMigrationConfiguration<Data.FrameworkDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(Tralus.Framework.Data.FrameworkDbContext context)
        {
            base.Seed(context);
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

            //var administratorRole = new Role(true)
            //{

            //    Name = "Administrators",
            //    IsAdministrative = true,
            //    CanEditModel = true,
            //};

            context.Set<Role>().AddOrUpdate(new Role(true)
            {
                Id = new Guid("F011D97A-CDA4-46F4-BE33-B48C4CAB9A3E"),
                Name = "Administrators",
                IsAdministrative = true,
                CanEditModel = true,
            });
        }
    }
}

using System;
using Tralus.Framework.BusinessModel.Entities;

namespace Tralus.Framework.Migration.Migrations
{
    using System.Data.Entity.Migrations;

    public sealed class Configuration :  TralusDbMigrationConfiguration<Data.FrameworkDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(Tralus.Framework.Data.FrameworkDbContext context)
        {
            base.Seed(context);
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

            //var administratorRole = new Role(true)
            //{

            //    Name = "Administrators",
            //    IsAdministrative = true,
            //    CanEditModel = true,
            //};

            context.Set<Role>().AddOrUpdate(new Role(true)
            {
                Id = new Guid("F011D97A-CDA4-46F4-BE33-B48C4CAB9A3E"),
                Name = "Administrators",
                IsAdministrative = false,
                CanEditModel = true,
            });
        }
    }
}

Correct Administrators Role (set IsAdministrator to false)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CompetitionPlatform.Data.ProjectCategory;

namespace CompetitionPlatform.Data.ProjectCategory
{
    public class ProjectCategoriesRepository : IProjectCategoriesRepository
    {
        public List<string> GetCategories()
        {
            return new List<string>
            {
                "Finance",
                "Technology",
                "Bitcoin",
                "Mobile",
                "Payments"
            };
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CompetitionPlatform.Data.ProjectCategory;

namespace CompetitionPlatform.Data.ProjectCategory
{
    public class ProjectCategoriesRepository : IProjectCategoriesRepository
    {
        public List<string> GetCategories()
        {
            return new List<string>
            {
                "Finance",
                "Technology",
                "Bitcoin",
                "Mobile",
                "Payments",
                "Communications and media"
            };
        }
    }
}

Add new category - "Communications and media".


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

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

    public class SA1008CSharp7UnitTests : SA1008UnitTests
    {
    }
}

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

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

    using static StyleCop.Analyzers.SpacingRules.SA1008OpeningParenthesisMustBeSpacedCorrectly;

    public class SA1008CSharp7UnitTests : SA1008UnitTests
    {
        /// <summary>
        /// Verifies that spacing for <c>ref</c> expressions is handled properly.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
        [Fact]
        public async Task TestRefExpressionAsync()
        {
            var testCode = @"namespace TestNamespace
{
    using System.Threading.Tasks;

    public class TestClass
    {
        public void TestMethod()
        {
            int test = 1;
            ref int t = ref( test);
        }
    }
}
";

            var fixedCode = @"namespace TestNamespace
{
    using System.Threading.Tasks;

    public class TestClass
    {
        public void TestMethod()
        {
            int test = 1;
            ref int t = ref (test);
        }
    }
}
";

            DiagnosticResult[] expectedDiagnostics =
            {
                this.CSharpDiagnostic(DescriptorPreceded).WithLocation(10, 28),
                this.CSharpDiagnostic(DescriptorNotFollowed).WithLocation(10, 28),
            };

            await this.VerifyCSharpDiagnosticAsync(testCode, expectedDiagnostics, CancellationToken.None).ConfigureAwait(false);
            await this.VerifyCSharpDiagnosticAsync(fixedCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
            await this.VerifyCSharpFixAsync(testCode, fixedCode, numberOfFixAllIterations: 2).ConfigureAwait(false);
        }
    }
}

Add SA1008 tests for ref expressions

Add SA1008 tests for ref expressions


namespace Fixie.Assertions
{
    using System;
    using System.Collections;

    class EnumerableEqualityComparer
    {
        public bool EnumerableEqual(IEnumerable x, IEnumerable y)
        {
            var enumeratorX = x.GetEnumerator();
            var enumeratorY = y.GetEnumerator();

            while (true)
            {
                bool hasNextX = enumeratorX.MoveNext();
                bool hasNextY = enumeratorY.MoveNext();

                if (!hasNextX || !hasNextY)
                    return hasNextX == hasNextY;

                if (enumeratorX.Current != null || enumeratorY.Current != null)
                {
                    if (enumeratorX.Current != null && enumeratorY.Current == null)
                        return false;

                    if (enumeratorX.Current == null)
                        return false;

                    var xType = enumeratorX.Current.GetType();
                    var yType = enumeratorY.Current.GetType();

                    if (xType.IsAssignableFrom(yType))
                    {
                        if (!Equals(enumeratorX.Current, enumeratorY.Current, xType))
                            return false;
                    }
                    else if (yType.IsAssignableFrom(xType))
                    {
                        if (!Equals(enumeratorY.Current, enumeratorX.Current, yType))
                            return false;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
        }

        static bool Equals(object a, object b, Type baseType)
        {
            var assertComparerType = typeof(AssertEqualityComparer);
            var equal = assertComparerType.GetMethod("Equal");
            var specificEqual = equal.MakeGenericMethod(baseType);
            return (bool)specificEqual.Invoke(null, new[] { a, b });
        }
    }
}

namespace Fixie.Assertions
{
    using System;
    using System.Collections;

    class EnumerableEqualityComparer
    {
        public bool EnumerableEqual(IEnumerable x, IEnumerable y)
        {
            var enumeratorX = x.GetEnumerator();
            var enumeratorY = y.GetEnumerator();

            while (true)
            {
                bool hasNextX = enumeratorX.MoveNext();
                bool hasNextY = enumeratorY.MoveNext();

                if (!hasNextX || !hasNextY)
                    return hasNextX == hasNextY;

                if (enumeratorX.Current != null || enumeratorY.Current != null)
                {
                    if (enumeratorX.Current != null && enumeratorY.Current == null)
                        return false;

                    if (enumeratorX.Current == null)
                        return false;

                    var xType = enumeratorX.Current.GetType();
                    var yType = enumeratorY.Current.GetType();

                    if (xType.IsAssignableFrom(yType))
                    {
                        if (!ItemsEqual(enumeratorX.Current, enumeratorY.Current, xType))
                            return false;
                    }
                    else if (yType.IsAssignableFrom(xType))
                    {
                        if (!ItemsEqual(enumeratorY.Current, enumeratorX.Current, yType))
                            return false;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
        }

        static bool ItemsEqual(object a, object b, Type baseType)
        {
            var assertComparerType = typeof(AssertEqualityComparer);
            var equal = assertComparerType.GetMethod("Equal");
            var specificEqual = equal.MakeGenericMethod(baseType);
            return (bool)specificEqual.Invoke(null, new[] { a, b });
        }
    }
}

Rename Enumerable.Equals(object, object, Type) to ItemsEqual, for clarity of purpose.


using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using DbAndRepository;
using DbAndRepository.IRepositories;
using DbAndRepository.Repostirories;

namespace TechSupportService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "TechSupportService1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select TechSupportService1.svc or TechSupportService1.svc.cs at the Solution Explorer and start debugging.
    public class TechSupportService1 : ITechSupportService1
    {
        private ILoginDataRepository Auth;

        public TechSupportService1()
        {
           TechSupportDatabaseEntities1 d=new TechSupportDatabaseEntities1();
           Auth=new LoginDataRepository(d);
        }
        public LoginResult Login(string username, string password)
        {
            string name = "";
            bool a= Auth.Authenticate(username, password,out name);
            return new LoginResult() {Role = "",Valid = a};
        }

    }
}

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using DbAndRepository;
using DbAndRepository.IRepositories;
using DbAndRepository.Repostirories;

namespace TechSupportService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "TechSupportService1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select TechSupportService1.svc or TechSupportService1.svc.cs at the Solution Explorer and start debugging.
    public class TechSupportService1 : ITechSupportService1
    {
        private ILoginDataRepository Auth;

        public TechSupportService1()
        {
           TechSupportDatabaseEntities d = new TechSupportDatabaseEntities();
           Auth = new LoginDataRepository(d);
        }
        public LoginResult Login(string username, string password)
        {
            string name = string.Empty,
                   role = string.Empty;
            bool a= Auth.Authenticate(username, password,out name, out role);
            return new LoginResult()
            {
                Role = role,
                Valid = a
            };
        }

    }
}

Update TecSupportService1 with the new parameter list.


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

namespace Entitas.Unity {

    public class ScriptingDefineSymbols {

        public Dictionary<BuildTargetGroup, string> buildTargetToDefSymbol { get { return _buildTargetToDefSymbol; } }

        readonly Dictionary<BuildTargetGroup, string> _buildTargetToDefSymbol;

        public ScriptingDefineSymbols() {
            _buildTargetToDefSymbol = Enum.GetValues(typeof(BuildTargetGroup))
                .Cast<BuildTargetGroup>()
                .Where(buildTargetGroup => buildTargetGroup != BuildTargetGroup.Unknown)
                .Distinct()
                    .ToDictionary(
                    buildTargetGroup => buildTargetGroup,
                    buildTargetGroup => PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup)
                );
        }

        public void AddDefineSymbol(string defineSymbol) {
            foreach(var kv in _buildTargetToDefSymbol) {
                PlayerSettings.SetScriptingDefineSymbolsForGroup(
                    kv.Key, kv.Value.Replace(defineSymbol, string.Empty) + "," + defineSymbol
                );
            }
        }

        public void RemoveDefineSymbol(string defineSymbol) {
            foreach(var kv in _buildTargetToDefSymbol) {
                PlayerSettings.SetScriptingDefineSymbolsForGroup(
                    kv.Key, kv.Value.Replace(defineSymbol, string.Empty)
                );
            }
        }
    }
}

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

namespace Entitas.Unity {

    public class ScriptingDefineSymbols {

        public Dictionary<BuildTargetGroup, string> buildTargetToDefSymbol { get { return _buildTargetToDefSymbol; } }

        readonly Dictionary<BuildTargetGroup, string> _buildTargetToDefSymbol;

        public ScriptingDefineSymbols() {
            _buildTargetToDefSymbol = Enum.GetValues(typeof(BuildTargetGroup))
                .Cast<BuildTargetGroup>()
                .Where(buildTargetGroup => buildTargetGroup != BuildTargetGroup.Unknown)
                .Where(buildTargetGroup => !isBuildTargetObsolete(buildTargetGroup))
                .Distinct()
                    .ToDictionary(
                    buildTargetGroup => buildTargetGroup,
                    buildTargetGroup => PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup)
                );
        }

        public void AddDefineSymbol(string defineSymbol) {
            foreach(var kv in _buildTargetToDefSymbol) {
                PlayerSettings.SetScriptingDefineSymbolsForGroup(
                    kv.Key, kv.Value.Replace(defineSymbol, string.Empty) + "," + defineSymbol
                );
            }
        }

        public void RemoveDefineSymbol(string defineSymbol) {
            foreach(var kv in _buildTargetToDefSymbol) {
                PlayerSettings.SetScriptingDefineSymbolsForGroup(
                    kv.Key, kv.Value.Replace(defineSymbol, string.Empty)
                );
            }
        }

        bool isBuildTargetObsolete(BuildTargetGroup value) {
            var fieldInfo = value.GetType().GetField(value.ToString());
            var attributes = (ObsoleteAttribute[])fieldInfo.GetCustomAttributes(typeof(ObsoleteAttribute), false);
            return (attributes != null && attributes.Length > 0);
        }
    }
}

Fix error when turning visual debugging on/off in Unity 5.4 or newer


namespace ForecastPCL.Test
{
    using System;
    using System.Configuration;
    using System.Threading.Tasks;

    using DarkSkyApi;

    using NUnit.Framework;

    [TestFixture]
    public class LanguageTests
    {
        // These coordinates came from the Forecast API documentation,
        // and should return forecasts with all blocks.
        private const double AlcatrazLatitude = 37.8267;
        private const double AlcatrazLongitude = -122.423;

        /// <summary>
        /// API key to be used for testing. This should be specified in the
        /// test project's app.config file.
        /// </summary>
        private string apiKey;

        /// <summary>
        /// Sets up all tests by retrieving the API key from app.config.
        /// </summary>
        [TestFixtureSetUp]
        public void SetUp()
        {
            apiKey = ConfigurationManager.AppSettings["ApiKey"];
        }

        [Test]
        public void AllLanguagesHaveValues()
        {
            foreach (Language language in Enum.GetValues(typeof(Language)))
            {
                Assert.That(() => language.ToValue(), Throws.Nothing);
            }
        }

        [Test]
        public async Task UnicodeLanguageIsSupported()
        {
            var client = new ForecastApi(apiKey);
            var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese);
            Assert.That(result, Is.Not.Null);
        }
    }
}

namespace ForecastPCL.Test
{
    using System;
    using System.Configuration;
    using System.Threading.Tasks;

    using DarkSkyApi;

    using NUnit.Framework;

    [TestFixture]
    public class LanguageTests
    {
        // These coordinates came from the Forecast API documentation,
        // and should return forecasts with all blocks.
        private const double AlcatrazLatitude = 37.8267;
        private const double AlcatrazLongitude = -122.423;

        /// <summary>
        /// API key to be used for testing. This should be specified in the
        /// test project's app.config file.
        /// </summary>
        private string apiKey;

        /// <summary>
        /// Sets up all tests by retrieving the API key from app.config.
        /// </summary>
        [OneTimeSetUp]
        public void SetUp()
        {
            apiKey = ConfigurationManager.AppSettings["ApiKey"];
        }

        [Test]
        public void AllLanguagesHaveValues()
        {
            foreach (Language language in Enum.GetValues(typeof(Language)))
            {
                Assert.That(() => language.ToValue(), Throws.Nothing);
            }
        }

        [Test]
        public async Task UnicodeLanguageIsSupported()
        {
            var client = new ForecastApi(apiKey);
            var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese);
            Assert.That(result, Is.Not.Null);
        }
    }
}

Use OneTimeSetUp instead of TestFixtureSetUp.


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Diagnostics.Tracing;
using System.Reflection;
using Xunit;

namespace System.Net.NameResolution.Tests
{
    public static class LoggingTest
    {
        [Fact]
        public static void EventSource_ExistsWithCorrectId()
        {
            Type esType = typeof(Dns).GetTypeInfo().Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
            Assert.NotNull(esType);

            Assert.Equal("Microsoft-System-Net-NameResolution", EventSource.GetName(esType));
            Assert.Equal(Guid.Parse("5f302add-3825-520e-8fa0-627b206e2e7e"), EventSource.GetGuid(esType));

            Assert.NotEmpty(EventSource.GenerateManifest(esType, esType.GetTypeInfo().Assembly.Location));
        }
    }
}

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Diagnostics.Tracing;
using System.Reflection;
using Xunit;

namespace System.Net.NameResolution.Tests
{
    public static class LoggingTest
    {
        [Fact]
        public static void EventSource_ExistsWithCorrectId()
        {
            Type esType = typeof(Dns).GetTypeInfo().Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
            Assert.NotNull(esType);

            Assert.Equal("Microsoft-System-Net-NameResolution", EventSource.GetName(esType));
            Assert.Equal(Guid.Parse("5f302add-3825-520e-8fa0-627b206e2e7e"), EventSource.GetGuid(esType));

            Assert.NotEmpty(EventSource.GenerateManifest(esType, "assemblyPathToIncludeInManifest"));
        }
    }
}

Fix build for versions without Assembly.Location


namespace SFA.DAS.EmployerAccounts.Web.Authorization
{
    public static class AuthorizationConstants
    {
        public const string Tier2User = "Tier2User";
        public const string TeamViewRoute = "accounts/{hashedaccountid}/teams/view";
        public const string TeamRoute = "accounts/{hashedaccountid}/teams";
        public const string TeamInvite = "accounts/{hashedaccountid}/teams/invite";
        public const string TeamInviteComplete = "accounts/{hashedaccountid}/teams/invite/next";
        public const string TeamMemberRemove = "accounts/{hashedaccountid}/teams/remove";
        public const string TeamReview = "accounts/{hashedaccountid}/teams/{email}/review";
        public const string TeamMemberRoleChange = "accounts/{hashedaccountid}/teams/{email}/role/change";
        public const string TeamMemberInviteResend = "accounts/{hashedaccountid}/teams/resend";
        public const string TeamMemberInviteCancel = "accounts/{hashedaccountid}/teams/{invitationId}/cancel";
    }
}

namespace SFA.DAS.EmployerAccounts.Web.Authorization
{
    public static class AuthorizationConstants
    {
        public const string Tier2User = "Tier2User";
        public const string TeamViewRoute = "accounts/{hashedaccountid}/teams/view";
        public const string TeamRoute = "accounts/{hashedaccountid}/teams";
        public const string TeamInvite = "accounts/{hashedaccountid}/teams/invite";
        public const string TeamInviteComplete = "accounts/{hashedaccountid}/teams/invite/next";
        public const string TeamMemberRemove = "accounts/{hashedaccountid}/teams/{email}/remove";
        public const string TeamReview = "accounts/{hashedaccountid}/teams/{email}/review";
        public const string TeamMemberRoleChange = "accounts/{hashedaccountid}/teams/{email}/role/change";
        public const string TeamMemberInviteResend = "accounts/{hashedaccountid}/teams/resend";
        public const string TeamMemberInviteCancel = "accounts/{hashedaccountid}/teams/{invitationId}/cancel";
    }
}

Update remove route to correct value

Update remove route to correct value


using Serilog.Core;
using Serilog.Events;

namespace Umbraco.Core.Logging.SerilogExtensions
{
    /// <summary>
    /// This is used to create a new property in Logs called 'Log4NetLevel'
    /// So that we can map Serilog levels to Log4Net levels - so log files stay consistent
    /// </summary>
    public class Log4NetLevelMapperEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var log4NetLevel = string.Empty;

            switch (logEvent.Level)
            {
                case LogEventLevel.Debug:
                    log4NetLevel = "DEBUG";
                    break;

                case LogEventLevel.Error:
                    log4NetLevel = "ERROR";
                    break;

                case LogEventLevel.Fatal:
                    log4NetLevel = "FATAL";
                    break;

                case LogEventLevel.Information:
                    log4NetLevel = "INFO";
                    break;

                case LogEventLevel.Verbose:
                    log4NetLevel = "ALL";
                    break;

                case LogEventLevel.Warning:
                    log4NetLevel = "WARN";
                    break;
            }

            //Pad string so that all log levels are 5 chars long (needed to keep the txt log file lined up nicely)
            log4NetLevel = log4NetLevel.PadRight(5);

            logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Log4NetLevel", log4NetLevel));
        }
    }
}

using Serilog.Core;
using Serilog.Events;

namespace Umbraco.Core.Logging.SerilogExtensions
{
    /// <summary>
    /// This is used to create a new property in Logs called 'Log4NetLevel'
    /// So that we can map Serilog levels to Log4Net levels - so log files stay consistent
    /// </summary>
    internal class Log4NetLevelMapperEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var log4NetLevel = string.Empty;

            switch (logEvent.Level)
            {
                case LogEventLevel.Debug:
                    log4NetLevel = "DEBUG";
                    break;

                case LogEventLevel.Error:
                    log4NetLevel = "ERROR";
                    break;

                case LogEventLevel.Fatal:
                    log4NetLevel = "FATAL";
                    break;

                case LogEventLevel.Information:
                    log4NetLevel = "INFO";
                    break;

                case LogEventLevel.Verbose:
                    log4NetLevel = "ALL";
                    break;

                case LogEventLevel.Warning:
                    log4NetLevel = "WARN";
                    break;
            }

            //Pad string so that all log levels are 5 chars long (needed to keep the txt log file lined up nicely)
            log4NetLevel = log4NetLevel.PadRight(5);

            logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Log4NetLevel", log4NetLevel));
        }
    }
}

Make Log4NetLevel enricher internal - no need for it to be public


using System.Text;
using Microsoft.AspNetCore.Mvc;
using RabbitMQ.Client;

namespace Rabbit.Controllers
{
    public class RabbitController : Controller
    {
        ConnectionFactory _rabbitConnection;

        public RabbitController([FromServices] ConnectionFactory rabbitConnection)
        {
            _rabbitConnection = rabbitConnection;
        }

        public IActionResult Receive()
        {
            using (var connection = _rabbitConnection.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                CreateQueue(channel);
                var data = channel.BasicGet("rabbit-test", true);
                if (data != null) {
                    ViewData["message"] = Encoding.UTF8.GetString(data.Body);
                }
            }

            return View();
        }

        public IActionResult Send(string message)
        {
            if (message != null && message != "") {
                using (var connection = _rabbitConnection.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    CreateQueue(channel);
                    var body = Encoding.UTF8.GetBytes(message);
                    channel.BasicPublish(exchange: "",
                                         routingKey: "rabbit-test",
                                         basicProperties: null,
                                         body: body);
                }
            }
            return View();
        }

        protected void CreateQueue(IModel channel)
        {
            channel.QueueDeclare(queue: "rabbit-test",
                             durable: false,
                             exclusive: false,
                             autoDelete: false,
                             arguments: null);
        }
    }
}

using System.Text;
using Microsoft.AspNetCore.Mvc;
using RabbitMQ.Client;

#if SSL
using System.Security.Authentication;
using System.Net.Security;
#endif

namespace Rabbit.Controllers
{
    public class RabbitController : Controller
    {
        ConnectionFactory _rabbitConnection;

        public RabbitController([FromServices] ConnectionFactory rabbitConnection)
        {
            _rabbitConnection = rabbitConnection;
#if SSL
            SslOption opt = new SslOption();
            opt.Version = SslProtocols.Tls12;
            opt.Enabled = true;
            // Only needed if want to disable certificate validations
            //opt.AcceptablePolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors |
            //    SslPolicyErrors.RemoteCertificateNameMismatch | SslPolicyErrors.RemoteCertificateNotAvailable;
            _rabbitConnection.Ssl = opt;
#endif
        }

        public IActionResult Receive()
        {
            using (var connection = _rabbitConnection.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                CreateQueue(channel);
                var data = channel.BasicGet("rabbit-test", true);
                if (data != null) {
                    ViewData["message"] = Encoding.UTF8.GetString(data.Body);
                }
            }

            return View();
        }

        public IActionResult Send(string message)
        {
            if (message != null && message != "") {
                using (var connection = _rabbitConnection.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    CreateQueue(channel);
                    var body = Encoding.UTF8.GetBytes(message);
                    channel.BasicPublish(exchange: "",
                                         routingKey: "rabbit-test",
                                         basicProperties: null,
                                         body: body);
                }
            }
            return View();
        }

        protected void CreateQueue(IModel channel)
        {
            channel.QueueDeclare(queue: "rabbit-test",
                             durable: false,
                             exclusive: false,
                             autoDelete: false,
                             arguments: null);
        }
    }
}

Add SSL option to Rabbit sample

Add SSL option to Rabbit sample


using Ets.Mobile.ViewModel.Contracts.Settings;
using System;
using System.Reactive.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using ReactiveUI;
using System.Reactive.Concurrency;

namespace Ets.Mobile.Content.Settings
{
    public sealed partial class Options : UserControl
    {
        public Options()
        {
            InitializeComponent();
            this.Events().DataContextChanged.Subscribe(args =>
            {
                var options = args.NewValue as IOptionsViewModel;
                if (options != null)
                {
                    options.HandleScheduleBackgroundService.IsExecuting.Subscribe(isExecuting =>
                    {
                        ShowSchedule.IsEnabled = !isExecuting;
                        LoadingShowScheduleChanged.Visibility = isExecuting ? Visibility.Visible : Visibility.Collapsed;
                    });
                }
            });
        }
    }
}

using Ets.Mobile.ViewModel.Contracts.Settings;
using System;
using System.Reactive.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Ets.Mobile.Content.Settings
{
    public sealed partial class Options : UserControl
    {
        public Options()
        {
            InitializeComponent();
            this.Events().DataContextChanged.Subscribe(args =>
            {
                var options = args.NewValue as IOptionsViewModel;
                if (options != null)
                {
                    options.HandleScheduleBackgroundService.IsExecuting.Subscribe(isExecuting =>
                    {
                        ShowSchedule.IsEnabled = !isExecuting;
                        LoadingShowScheduleChanged.Visibility = isExecuting ? Visibility.Visible : Visibility.Collapsed;
                    });
                }
            });
        }
    }
}

Use ReactiveUI Events for Data Context Changed


<!DOCTYPE html>
<html>
<head>
    <title>Zaaikalender | @ViewBag.Title</title>

	<link rel="stylesheet" href="/Content/Stylesheets/responsive-square-elements.css">

	<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="/Scripts/flowtype.js"></script>
    <script src="/Scripts/font-settings.js"></script>

</head>
<body>
	<div class="container">
		@RenderBody()
	</div>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
    <title>Zaaikalender | @ViewBag.Title</title>

	<link rel="stylesheet" href="/Content/Stylesheets/responsive-square-elements.css">

    <!--[if lte IE 8]>
        <script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/4.0.3/es5-shim.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv-printshiv.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
	<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="/Scripts/flowtype.js"></script>
    <script src="/Scripts/font-settings.js"></script>
    <script src="/Scripts/month-click-listeners.js"></script>

</head>
<body>
	<div class="container">
		@RenderBody()
	</div>
</body>
</html>

Add scripts that make HTML5, CSS and JavaScript work in Internet Explorer 8 and lower


using System.Xml;

namespace Palaso.Xml
{
	public static class XmlDomExtensions
	{
		public static XmlDocument StripXHtmlNameSpace(this XmlDocument node)
		{
			XmlDocument x = new XmlDocument();
			x.LoadXml(node.OuterXml.Replace("xmlns", "xmlnsNeutered"));
			return x;
		}

		public static void AddStyleSheet(this XmlDocument dom, string cssFilePath)
		{
			var head = dom.SelectSingleNodeHonoringDefaultNS("//head");
			AddSheet(dom, head, cssFilePath);
		}

		private static void AddSheet(this XmlDocument dom, XmlNode head, string cssFilePath)
		{
			var link = dom.CreateElement("link", "http://www.w3.org/1999/xhtml");
			link.SetAttribute("rel", "stylesheet");
			link.SetAttribute("href", "file://" + cssFilePath);
			link.SetAttribute("type", "text/css");
			head.AppendChild(link);
		}
	}
}

using System;
using System.IO;
using System.Xml;

namespace Palaso.Xml
{
	public static class XmlDomExtensions
	{
		public static XmlDocument StripXHtmlNameSpace(this XmlDocument node)
		{
			XmlDocument x = new XmlDocument();
			x.LoadXml(node.OuterXml.Replace("xmlns", "xmlnsNeutered"));
			return x;
		}

		public static void AddStyleSheet(this XmlDocument dom, string cssFilePath)
		{
			var head = dom.SelectSingleNodeHonoringDefaultNS("//head");
			AddSheet(dom, head, cssFilePath);
		}

		private static void AddSheet(this XmlDocument dom, XmlNode head, string cssFilePath)
		{
			var link = dom.CreateElement("link", "http://www.w3.org/1999/xhtml");
			link.SetAttribute("rel", "stylesheet");

			if(cssFilePath.Contains(Path.PathSeparator.ToString())) // review: not sure about relative vs. complete paths
			{
				link.SetAttribute("href", "file://" + cssFilePath);
			}
			else //at least with gecko/firefox, something like "file://foo.css" is never found, so just give it raw
			{
				link.SetAttribute("href",cssFilePath);
			}
			link.SetAttribute("type", "text/css");
			head.AppendChild(link);
		}
	}
}

Tweak Stylesheet Link writing in XMlDomExtenstions


using static System.Console;
using CIV.Ccs;
using CIV.Interfaces;

namespace CIV
{
    class Program
    {
        static void Main(string[] args)
        {
  			var text = System.IO.File.ReadAllText(args[0]);

			var processes = CcsFacade.ParseAll(text);
            var trace = CcsFacade.RandomTrace(processes["Prison"], 450);
            foreach (var action in trace)
            {
                WriteLine(action);
            }
        }
    }
}

using static System.Console;
using System.Linq;
using CIV.Ccs;
using CIV.Hml;

namespace CIV
{
    class Program
    {
        static void Main(string[] args)
        {
  			var text = System.IO.File.ReadAllText(args[0]);

			var processes = CcsFacade.ParseAll(text);
            var hmlText = "[[ack]][[ack]][[ack]](<<ack>>tt and [[freeAll]]ff)";
            var prova = HmlFacade.ParseAll(hmlText);
            WriteLine(prova.Check(processes["Prison"]));
        }
    }
}

Remove RandomTrace stuff from main

Remove RandomTrace stuff from main


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CommandLine;
using Meraki;

namespace Meraki.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Parser.Default.ParseArguments<LabOptions, DumpOptions>(args)
                    .WithParsed<LabOptions>(clo => new CiscoLearningLab().Run(clo.ApiKey).Wait())
                    .WithParsed<DumpOptions>(clo => new Dump().Run(clo.ApiKey).Wait())
                    .WithNotParsed(errors => System.Console.Error.WriteLine("InvalidArgs"));
            }
            catch (Exception ex)
            {
                System.Console.Error.WriteLine(ex);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CommandLine;
using Meraki;

namespace Meraki.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Parser.Default.ParseArguments<LabOptions, DumpOptions>(args)
                    .WithParsed<LabOptions>(clo => new CiscoLearningLab().Run(clo.ApiKey).Wait())
                    .WithParsed<DumpOptions>(clo => new Dump().Run(clo.ApiKey).Wait());
            }
            catch (Exception ex)
            {
                System.Console.Error.WriteLine(ex);
            }
        }
    }
}

Fix command line error display

Fix command line error display


using System.Dynamic;

namespace KenticoInspector.Core.Models
{
    public class ReportResults
    {
        public ReportResults()
        {
            Data = new ExpandoObject();
        }

        public dynamic Data { get; set; }
        public string Status { get; set; }
        public string Summary { get; set; }
        public string Type { get; set; }
    }
}

using System.Dynamic;

namespace KenticoInspector.Core.Models
{
    public class ReportResults
    {
        public ReportResults()
        {
            Data = new ExpandoObject();
        }

        public dynamic Data { get; set; }
        public string Heading { get; set; }
        public string Status { get; set; }
        public string Summary { get; set; }
        public string Type { get; set; }
    }
}

Add heading to report result class

Add heading to report result class


using System.Collections.Generic;

namespace Arkivverket.Arkade.Core.Util.FileFormatIdentification;

public interface IFileFormatInfoFilesGenerator
{
    void Generate(IEnumerable<IFileFormatInfo> fileFormatInfoSet, string relativePathRoot, string resultFileFullPath);
}

using System.Collections.Generic;

namespace Arkivverket.Arkade.Core.Util.FileFormatIdentification
{
    public interface IFileFormatInfoFilesGenerator
    {
        void Generate(IEnumerable<IFileFormatInfo> fileFormatInfoSet, string relativePathRoot,
            string resultFileFullPath);
    }
}

Add namespace brackets - because of teamcity

ARKADE-631


using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PathViewer
{
    public partial class FormPathViewer : Form
    {
        public FormPathViewer()
        {
            InitializeComponent();
            LoadPaths();
        }

        private void LoadPaths()
        {
            // Get the PATH from the registery
            string regKey = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\";
            string regValue = (string)Registry.LocalMachine.OpenSubKey(regKey).GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);

            // Split the string
            var paths = regValue.Split(';');

            // Display them
            foreach(var i in paths)
            {
                lvPaths.Items.Add(i);
            }
        }
    }
}

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PathViewer
{
    public partial class FormPathViewer : Form
    {
        public FormPathViewer()
        {
            InitializeComponent();
            LoadPaths();
        }

        private void LoadPaths()
        {
            // Get the PATH from the registery
            string regKey = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\";
            string regValue = (string)Registry.LocalMachine.OpenSubKey(regKey).GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);

            // Split the string
            var paths = regValue.Split(';');

            // Display them
            foreach(var i in paths)
            {
                lvPaths.Items.Add(i);
            }
        }

        // Have the column width match the listview width
        private void lvPaths_Resize(object sender, EventArgs e)
        {
            lvPaths.Columns[0].Width = lvPaths.Width;
        }
    }
}

Set the column width to resize when the listview resizes


using System.Reflection;

[assembly: AssemblyTitle("Autofac.Extras.Tests.Moq")]
[assembly: AssemblyDescription("")]

Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.


using System.Drawing;
using System.Windows.Forms;

using BrightIdeasSoftware;

namespace SteamGames
{
	internal sealed class GameRenderer : AbstractRenderer
	{
		private readonly StringFormat sf;

		public GameRenderer()
		{
			sf = new StringFormat(StringFormat.GenericTypographic);
			sf.Alignment = StringAlignment.Center;
			sf.Trimming = StringTrimming.EllipsisWord;
		}

		public override bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, object rowObject)
		{
			if (e.Item.ListView.SelectedItems.Contains(e.Item))
			{
				g.FillRectangle(Brushes.RoyalBlue, itemBounds);
			}
			else
			{
				g.FillRectangle(Brushes.Black, itemBounds);
			}

			var game = (Game) rowObject;
			if (game.Logo != null)
			{
				g.DrawImage(game.Logo, new Rectangle(itemBounds.Location, new Size(184, 69)));
			}

			g.DrawString(game.Name, e.Item.Font, Brushes.White, new RectangleF(itemBounds.X, itemBounds.Y + 69, 184, 30), sf);
			return true;
		}
	}
}

using System.Drawing;
using System.Windows.Forms;

using BrightIdeasSoftware;

namespace SteamGames
{
	internal sealed class GameRenderer : AbstractRenderer
	{
		private readonly StringFormat sf;
		private Brush SelectionBrush = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));

		public GameRenderer()
		{
			sf = new StringFormat(StringFormat.GenericTypographic);
			sf.Alignment = StringAlignment.Center;
			sf.Trimming = StringTrimming.EllipsisWord;
		}

		public override bool RenderItem(DrawListViewItemEventArgs e, Graphics g, Rectangle itemBounds, object rowObject)
		{
			if (e.Item.ListView.SelectedItems.Contains(e.Item))
			{
				g.FillRectangle(SelectionBrush, itemBounds);
			}
			else
			{
				g.FillRectangle(Brushes.Black, itemBounds);
			}

			var game = (Game) rowObject;
			if (game.Logo != null)
			{
				g.DrawImage(game.Logo, new Rectangle(itemBounds.Location, new Size(184, 69)));
			}

			g.DrawString(game.Name, e.Item.Font, Brushes.White, new RectangleF(itemBounds.X, itemBounds.Y + 69, 184, 30), sf);
			return true;
		}
	}
}

Use system highlight color in game list selection


using System;
using System.Collections.Generic;
using Assent.Reporters.DiffPrograms;

namespace Assent.Reporters
{
    public class DiffReporter : IReporter
    {
#if NET45
        internal static readonly bool IsWindows = Environment.OSVersion.Platform == PlatformID.Win32NT;
#else
        internal static readonly bool IsWindows = System.Runtime.InteropServices.RuntimeInformation
            .IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);
#endif

        static DiffReporter()
        {
            DefaultDiffPrograms = IsWindows
                ? new IDiffProgram[]
                {
                    new BeyondCompareDiffProgram(),
                    new KDiff3DiffProgram(),
                    new XdiffDiffProgram(),
                    new P4MergeDiffProgram(),
                    new VsCodeDiffProgram()
                }
                : new IDiffProgram[]
                {
                    new VsCodeDiffProgram()
                };

        }

        public static readonly IReadOnlyList<IDiffProgram> DefaultDiffPrograms;

        private readonly IReadOnlyList<IDiffProgram> _diffPrograms;

        public DiffReporter() : this(DefaultDiffPrograms)
        {
        }

        public DiffReporter(IReadOnlyList<IDiffProgram> diffPrograms)
        {
            _diffPrograms = diffPrograms;
        }

        public void Report(string receivedFile, string approvedFile)
        {
            foreach (var program in _diffPrograms)
                if (program.Launch(receivedFile, approvedFile))
                    return;

            throw new Exception("Could not find a diff program to use");
        }
    }
}

using System;
using System.Collections.Generic;
using Assent.Reporters.DiffPrograms;

namespace Assent.Reporters
{
    public class DiffReporter : IReporter
    {
#if NET45
        internal static readonly bool IsWindows = Environment.OSVersion.Platform == PlatformID.Win32NT;
#else
        internal static readonly bool IsWindows = System.Runtime.InteropServices.RuntimeInformation
            .IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);
#endif

        static DiffReporter()
        {
            DefaultDiffPrograms = IsWindows
                ? new IDiffProgram[]
                {
                    new BeyondCompareDiffProgram(),
                    new KDiff3DiffProgram(),
                    new XdiffDiffProgram(),
                    new P4MergeDiffProgram(),
                    new VsCodeDiffProgram()
                }
                : new IDiffProgram[]
                {
                    new BeyondCompareDiffProgram(),
                    new VsCodeDiffProgram()
                };

        }

        public static readonly IReadOnlyList<IDiffProgram> DefaultDiffPrograms;

        private readonly IReadOnlyList<IDiffProgram> _diffPrograms;

        public DiffReporter() : this(DefaultDiffPrograms)
        {
        }

        public DiffReporter(IReadOnlyList<IDiffProgram> diffPrograms)
        {
            _diffPrograms = diffPrograms;
        }

        public void Report(string receivedFile, string approvedFile)
        {
            foreach (var program in _diffPrograms)
                if (program.Launch(receivedFile, approvedFile))
                    return;

            throw new Exception("Could not find a diff program to use");
        }
    }
}

Support Beyond Compare on linux

Support Beyond Compare on linux


// 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.

#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;

namespace osu.Game.Online.RealtimeMultiplayer
{
    [Serializable]
    public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
    {
        public int? BeatmapID { get; set; }

        public int? RulesetID { get; set; }

        public string Name { get; set; } = "Unnamed room";

        [NotNull]
        public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();

        public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && Name.Equals(other.Name, StringComparison.Ordinal);

        public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
    }
}

// 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.

#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;

namespace osu.Game.Online.RealtimeMultiplayer
{
    [Serializable]
    public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
    {
        public int BeatmapID { get; set; }

        public int? RulesetID { get; set; }

        public string Name { get; set; } = "Unnamed room";

        [NotNull]
        public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();

        public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && Name.Equals(other.Name, StringComparison.Ordinal);

        public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
    }
}

Make room setting's BeatmapID non-nullable


namespace TraktApiSharp.Objects.Get.Users.Lists
{
    using Newtonsoft.Json;
    using System.Globalization;

    /// <summary>
    /// A collection of ids for various web services for a Trakt list.
    /// </summary>
    public class TraktListIds
    {
        /// <summary>
        /// The Trakt numeric id for the list.
        /// </summary>
        [JsonProperty(PropertyName = "trakt")]
        public int Trakt { get; set; }

        /// <summary>
        /// The Trakt slug for the list.
        /// </summary>
        [JsonProperty(PropertyName = "slug")]
        public string Slug { get; set; }

        /// <summary>
        /// Tests, if at least one id has been set.
        /// </summary>
        [JsonIgnore]
        public bool HasAnyId => Trakt > 0 || !string.IsNullOrEmpty(Slug);

        /// <summary>
        /// Get the most reliable id from those that have been set for the list.
        /// </summary>
        /// <returns>The id as a string.</returns>
        public string GetBestId()
        {
            if (Trakt > 0)
                return Trakt.ToString(CultureInfo.InvariantCulture);

            if (!string.IsNullOrEmpty(Slug))
                return Slug;

            return string.Empty;
        }
    }
}

namespace TraktApiSharp.Objects.Get.Users.Lists
{
    using Newtonsoft.Json;

    /// A collection of ids for various web services, including the Trakt id, for a Trakt list.
    public class TraktListIds
    {
        /// Gets or sets the Trakt numeric id.
        [JsonProperty(PropertyName = "trakt")]
        public int Trakt { get; set; }

        /// Gets or sets the Trakt slug.
        [JsonProperty(PropertyName = "slug")]
        public string Slug { get; set; }

        /// Returns, whether any id has been set.
        [JsonIgnore]
        public bool HasAnyId => Trakt > 0 || !string.IsNullOrEmpty(Slug);

        /// Gets the most reliable id from those that have been set.
        /// <returns>The id as a string or an empty string, if no id is set.</returns>
        public string GetBestId()
        {
            if (Trakt > 0)
                return Trakt.ToString();

            if (!string.IsNullOrEmpty(Slug))
                return Slug;

            return string.Empty;
        }
    }
}

Update existing documentation for list ids.


// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Internals.Mapping
{
    using System;
    using Reflection;

    public class NullableValueObjectMapper<T, TValue> :
        IObjectMapper<T>
        where TValue : struct
    {
        readonly ReadWriteProperty<T> _property;

        public NullableValueObjectMapper(ReadWriteProperty<T> property)
        {
            _property = property;
        }

        public void ApplyTo(T obj, IObjectValueProvider valueProvider)
        {
            object value;
            if (valueProvider.TryGetValue(_property.Property.Name, out value))
            {
                TValue? nullableValue = value as TValue?;
                if (!nullableValue.HasValue)
                    nullableValue = (TValue)Convert.ChangeType(value, typeof(TValue));

                _property.Set(obj, nullableValue);
            }
        }
    }
}

// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Internals.Mapping
{
    using System;
    using System.ComponentModel;
    using Reflection;

    public class NullableValueObjectMapper<T, TValue> :
        IObjectMapper<T>
        where TValue : struct
    {
        readonly ReadWriteProperty<T> _property;

        public NullableValueObjectMapper(ReadWriteProperty<T> property)
        {
            _property = property;
        }

        public void ApplyTo(T obj, IObjectValueProvider valueProvider)
        {
            object value;
            if (valueProvider.TryGetValue(_property.Property.Name, out value))
            {
                TValue? nullableValue = null;
                if (value != null)
                {
                    var converter = TypeDescriptor.GetConverter(typeof(TValue));
                    nullableValue = converter.CanConvertFrom(value.GetType())
                        ? (TValue)converter.ConvertFrom(value)
                        : default(TValue?);
                }

                _property.Set(obj, nullableValue);
            }
        }
    }
}

Use a type converter to try and convert values

Former-commit-id: 9abec8ae101be7d50e3c33ca999a128a7d4cad98


using MailKit.Net.Smtp;
using MimeKit;
using MimeKit.Text;
using System;
using System.Collections.Generic;

namespace SecretSanta.Utilities
{
    public static class EmailMessage
    {
        public static void Send(MailboxAddress from, IEnumerable<MailboxAddress> to, string subject, string body)
        {
            using (var smtp = new SmtpClient())
            {
                var message = new MimeMessage();
                message.From.Add(from);
                message.To.AddRange(to);
                message.Subject = subject;
                message.Body = new TextPart(TextFormat.Html) { Text = body.Replace(Environment.NewLine, "<br />") };

                smtp.Connect(AppSettings.SmtpHost, AppSettings.SmtpPort, true);
                smtp.Authenticate(AppSettings.SmtpUser, AppSettings.SmtpPass);
                smtp.Send(message);
                smtp.Disconnect(true);
            }
        }
    }
}

using MailKit.Net.Smtp;
using MimeKit;
using MimeKit.Text;
using System;
using System.Collections.Generic;

namespace SecretSanta.Utilities
{
    public static class EmailMessage
    {
        public static void Send(MailboxAddress from, IEnumerable<MailboxAddress> to, string subject, string body)
        {
            using (var smtp = new SmtpClient())
            {
                var message = new MimeMessage();
                message.From.Add(from);
                message.To.AddRange(to);
                message.Subject = subject;
                message.Body = new TextPart(TextFormat.Html) { Text = body.Replace(Environment.NewLine, "<br />") };

                smtp.Connect(AppSettings.SmtpHost, AppSettings.SmtpPort, false);
                smtp.Authenticate(AppSettings.SmtpUser, AppSettings.SmtpPass);
                smtp.Send(message);
                smtp.Disconnect(true);
            }
        }
    }
}

Disable SSL for sending e-mails

Disable SSL for sending e-mails


using Content.Shared.GameObjects.Components.Movement;
using Robust.Client.Player;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;

#nullable enable

namespace Content.Client.GameObjects.Components.Movement
{
    [RegisterComponent]
    [ComponentReference(typeof(IMoverComponent))]
    public class PlayerInputMoverComponent : SharedPlayerInputMoverComponent, IMoverComponent
    {
        public override GridCoordinates LastPosition { get; set; }
        public override float StepSoundDistance { get; set; }

        public override void HandleComponentState(ComponentState? curState, ComponentState? nextState)
        {
            if (IoCManager.Resolve<IPlayerManager>().LocalPlayer!.ControlledEntity == Owner)
            {
                base.HandleComponentState(curState, nextState);
            }
        }
    }
}

using Content.Shared.GameObjects.Components.Movement;
using Robust.Shared.GameObjects;
using Robust.Shared.Map;

#nullable enable

namespace Content.Client.GameObjects.Components.Movement
{
    [RegisterComponent]
    [ComponentReference(typeof(IMoverComponent))]
    public class PlayerInputMoverComponent : SharedPlayerInputMoverComponent, IMoverComponent
    {
        public override GridCoordinates LastPosition { get; set; }
        public override float StepSoundDistance { get; set; }
    }
}

Remove bad component state hack from client mover component.


using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Dangl.WebDocumentation.ViewModels.Admin
{
    public class CreateProjectViewModel
    {
        [Display(Name ="Name")]
        public string ProjectName { get; set; }

        [Display(Name ="Public access")]
        public bool IsPublic { get; set; }

        [Display(Name ="Path to index")]
        public string PathToIndexPage { get; set; }

        [Display(Name ="Users with access")]
        public IEnumerable<string> AvailableUsers { get; set; }
        public IEnumerable<string> UsersWithAccess { get; set; }
    }
}

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Dangl.WebDocumentation.ViewModels.Admin
{
    public class CreateProjectViewModel
    {
        [Display(Name ="Name")]
        [Required]
        public string ProjectName { get; set; }

        [Display(Name ="Public access")]
        public bool IsPublic { get; set; }

        [Display(Name ="Path to index")]
        [Required]
        public string PathToIndexPage { get; set; }

        [Display(Name ="Users with access")]
        public IEnumerable<string> AvailableUsers { get; set; }
        public IEnumerable<string> UsersWithAccess { get; set; }
    }
}

Mark required properties in ViewModel

Mark required properties in ViewModel


using System;

namespace DAQ.Environment
{
    public class PHBonesawFileSystem : DAQ.Environment.FileSystem
    {
        public PHBonesawFileSystem()
        {
            Paths.Add("MOTMasterDataPath", "C:\\Users\\cafmot\\Box\\CaF MOT\\MOTData\\MOTMasterData\\");
            Paths.Add("scriptListPath", "C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts");
            Paths.Add("daqDLLPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\bin\\CaF\\daq.dll");
            Paths.Add("MOTMasterExePath", "C:\\ControlPrograms\\EDMSuite\\MOTMaster\\bin\\CaF\\");
            Paths.Add("ExternalFilesPath", "C:\\Users\\cafmot\\Documents\\Temp Camera Images\\");
            Paths.Add("HardwareClassPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\MoleculeMOTHardware.cs");

            DataSearchPaths.Add(Paths["scanMasterDataPath"]);

            SortDataByDate = false;
        }
    }
}

using System;

namespace DAQ.Environment
{
    public class PHBonesawFileSystem : DAQ.Environment.FileSystem
    {
        public PHBonesawFileSystem()
        {
            Paths.Add("MOTMasterDataPath", "C:\\Users\\cafmot\\Box Sync\\CaF MOT\\MOTData\\MOTMasterData\\");
            Paths.Add("scriptListPath", "C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts");
            Paths.Add("daqDLLPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\bin\\CaF\\daq.dll");
            Paths.Add("MOTMasterExePath", "C:\\ControlPrograms\\EDMSuite\\MOTMaster\\bin\\CaF\\");
            Paths.Add("ExternalFilesPath", "C:\\Users\\cafmot\\Documents\\Temp Camera Images\\");
            Paths.Add("HardwareClassPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\MoleculeMOTHardware.cs");

            DataSearchPaths.Add(Paths["scanMasterDataPath"]);

            SortDataByDate = false;
        }
    }
}

Change CaF file system paths

Change CaF file system paths

- We've moved back to using Box sync (instead of Box drive) on lab
computer so file paths have changed


#load ../amazon.csx

pvc.Task("push", () => {
	pvc.Source("src/**/*.*")
	   .Pipe(new PvcCloudFront(
		accessKey: keys.accessKey,
		secretKey: keys.secretKey,
		bucketName: "pvcbuild-com",
		distributionId: "E13RNZ6AJTCYUR"
	   ));
});

#load ../amazon.csx

pvc.Task("push", () => {
	pvc.Source("src/**/*.*")
	   .Pipe((streams) => {
		// strip src folder from paths
		var currentDirectory = Directory.GetCurrentDirectory();
		var resultStreams = new List<PvcStream>();
		foreach (var stream in streams) {
			var fullPath = Path.GetFullPath(stream.StreamName);
			var relPath = fullPath.Substring(currentDirectory.Length + "src/".Length + 1);

			resultStreams.Add(new PvcStream(() => stream).As(relPath, stream.OriginalSourcePath));
		}

		return resultStreams;
	   })
	   .Pipe(new PvcCloudFront(
		accessKey: keys.accessKey,
		secretKey: keys.secretKey,
		bucketName: "pvcbuild.com",
		distributionId: "E13RNZ6AJTCYUR"
	   ));
});

Remove src folder from paths before pushing


namespace NLogging
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public abstract class Handler : IHandler
    {
        private IFormatter formatter;
        private LogLevel logLevel;

        protected Handler()
        {
            this.formatter = new Formatter();
            this.logLevel = LogLevel.NOTSET;
        }

        abstract public void push(Record record);
        abstract public void flush();
        public void SetFormatter(IFormatter formatter)
        {
            this.formatter = formatter;
        }

        public void SetLogLevel(LogLevel level)
        {
            this.logLevel = level;
        }

    }
}

namespace NLogging
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public abstract class Handler : IHandler
    {
        private IFormatter formatter;

        protected Handler()
        {
            this.formatter = new Formatter();
        }

        abstract public void push(Record record);
        abstract public void flush();

        public void SetFormatter(IFormatter formatter)
        {
            this.formatter = formatter;
        }

    }
}

Remove set log level from base handler class.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
using GladNet;

namespace Booma.Proxy
{
	[SceneTypeCreate(GameSceneType.Pioneer2)]
	public sealed class Default6DCommandHandler : Command6DHandler<UnknownSubCommand6DCommand>
	{
		private int recievedCount = 0;

		/// <inheritdoc />
		public Default6DCommandHandler(ILog logger)
			: base(logger)
		{
		}

		/// <inheritdoc />
		protected override async Task HandleSubMessage(IPeerMessageContext<PSOBBGamePacketPayloadClient> context, UnknownSubCommand6DCommand command)
		{
			if(Logger.IsInfoEnabled)
				Logger.Info($"Recieved Unknown: {command}");

			//TODO: We kinda just count how many we've recieved.
			if(recievedCount == 4)
			{
				if(Logger.IsInfoEnabled)
					Logger.Info($"About to send: {nameof(BlockFinishedGameBurstingRequestPayload)}");

				//If we've recieved 4 so far this is the 5th one
				//meaning we are done and can probably send
				//the UnFreeze packet to everyone.
				await context.PayloadSendService.SendMessage(new BlockFinishedGameBurstingRequestPayload());
			}

			recievedCount++;
		}
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
using GladNet;

namespace Booma.Proxy
{
	[SceneTypeCreate(GameSceneType.Pioneer2)]
	public sealed class Default6DCommandHandler : Command6DHandler<UnknownSubCommand6DCommand>
	{
		private int recievedCount = 0;

		/// <inheritdoc />
		public Default6DCommandHandler(ILog logger)
			: base(logger)
		{
		}

		/// <inheritdoc />
		protected override async Task HandleSubMessage(IPeerMessageContext<PSOBBGamePacketPayloadClient> context, UnknownSubCommand6DCommand command)
		{
			if(Logger.IsInfoEnabled)
				Logger.Info($"Recieved Unknown: {command}");

			//TODO: Only 3/4 of these are static. The 0x70 is player specific and we should expect N of them where N is the player number.
			//TODO: We kinda just count how many we've recieved.
			if(recievedCount == 3)
			{
				if(Logger.IsInfoEnabled)
					Logger.Info($"About to send: {nameof(BlockFinishedGameBurstingRequestPayload)}");

				//If we've recieved 4 so far this is the 5th one
				//meaning we are done and can probably send
				//the UnFreeze packet to everyone.
				await context.PayloadSendService.SendMessage(new BlockFinishedGameBurstingRequestPayload());
			}

			recievedCount++;
		}
	}
}

Fix fault in temp impl of 6D handling

Fix fault in temp impl of 6D handling