using AspNetCore.Security.CAS;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace CookieSample
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            // Setup based on https://github.com/aspnet/Security/tree/rel/2.0.0/samples/SocialSample
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o =>
                {
                    o.LoginPath = new PathString("/login");
                    o.Cookie = new CookieBuilder
                    {
                        Name = ".AspNet.CasSample"
                    };
                })
                .AddCAS(o =>
                {
                    o.CasServerUrlBase = Configuration["CasBaseUrl"];
                    o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                });

            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseMvcWithDefaultRoute();
        }
    }
}

using AspNetCore.Security.CAS;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace CookieSample
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            // Setup based on https://github.com/aspnet/Security/tree/rel/2.0.0/samples/SocialSample
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o =>
                {
                    o.LoginPath = new PathString("/login");
                    o.Cookie = new CookieBuilder
                    {
                        Name = ".AspNet.CasSample"
                    };
                })
                .AddCAS(o =>
                {
                    o.CasServerUrlBase = Configuration["CasBaseUrl"];   // Set in `appsettings.json` file.
                    o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                });

            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseMvcWithDefaultRoute();
        }
    }
}

Add comment to help find CAS url setting


using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using RedditSharp.Things;

namespace RedditSharp.PowerShell.Cmdlets.Posts
{
    /// <summary>
    /// <para type="description">Edit the text of a self post.  Will not work on link posts.</para>
    /// </summary>
    [Cmdlet(VerbsData.Edit,"Post")]
    [OutputType(typeof(Post))]
    public class EditPost : Cmdlet
    {
        [Parameter(Mandatory=true,Position = 0,HelpMessage = "Self post to edit")]
        public Post Target { get; set; }

        [Parameter(Mandatory = true,Position = 1,HelpMessage = "New body text/markdown.")]
        public string Body { get; set; }

        protected override void BeginProcessing()
        {
            if (Session.Reddit == null)
                ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(), "NoRedditSession",
                    ErrorCategory.InvalidOperation, Session.Reddit));
        }

        protected override void ProcessRecord()
        {
            try
            {
                Target.EditText(Body);
                Target.SelfText = Body;
                WriteObject(Target);
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "CantUpdateSelfText", ErrorCategory.InvalidOperation, Target));
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using RedditSharp.Things;

namespace RedditSharp.PowerShell.Cmdlets.Posts
{
    /// <summary>
    /// <para type="description">Edit the text of a self post.  Will not work on link posts.</para>
    /// </summary>
    [Cmdlet(VerbsData.Edit,"Post")]
    [OutputType(typeof(Post))]
    public class EditPost : Cmdlet
    {
        [Parameter(Mandatory=true,Position = 0,HelpMessage = "Self post to edit")]
        public Post InputObject { get; set; }

        [Parameter(Mandatory = true,Position = 1,HelpMessage = "New body text/markdown.")]
        public string Body { get; set; }

        protected override void BeginProcessing()
        {
            if (Session.Reddit == null)
                ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(), "NoRedditSession",
                    ErrorCategory.InvalidOperation, Session.Reddit));
        }

        protected override void ProcessRecord()
        {
            try
            {
                InputObject.EditText(Body);
                InputObject.SelfText = Body;
                WriteObject(InputObject);
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "CantUpdateSelfText", ErrorCategory.InvalidOperation, InputObject));
            }
        }
    }
}

Change to InputObject naming convention

Change to InputObject naming convention


using Bam.Core;
namespace boost
{
    abstract class GenericBoostModule :
        C.StaticLibrary
    {
        protected GenericBoostModule(
            string name)
        {
            this.Name = name;
        }

        private string Name
        {
            get;
            set;
        }

        protected C.Cxx.ObjectFileCollection BoostSource
        {
            get;
            private set;
        }

        protected override void
        Init(
            Bam.Core.Module parent)
        {
            base.Init(parent);

            this.Macros["OutputName"] = TokenizedString.CreateVerbatim(string.Format("boost_{0}-vc120-mt-1_60", this.Name));
            this.Macros["libprefix"] = TokenizedString.CreateVerbatim("lib");

            this.BoostSource = this.CreateCxxSourceContainer();
            this.CompileAgainstPublicly<BoostHeaders>(this.BoostSource);
            if (this.BuildEnvironment.Platform.Includes(EPlatform.Windows))
            {
                this.BoostSource.PrivatePatch(settings =>
                    {
                        var cxxCompiler = settings as C.ICxxOnlyCompilerSettings;
                        cxxCompiler.ExceptionHandler = C.Cxx.EExceptionHandler.Asynchronous;
                    });

                if (this.Librarian is VisualCCommon.Librarian)
                {
                    this.CompileAgainst<WindowsSDK.WindowsSDK>(this.BoostSource);
                }
            }
        }
    }
}

using Bam.Core;
namespace boost
{
    abstract class GenericBoostModule :
        C.StaticLibrary
    {
        protected GenericBoostModule(
            string name)
        {
            this.Name = name;
        }

        private string Name
        {
            get;
            set;
        }

        protected C.Cxx.ObjectFileCollection BoostSource
        {
            get;
            private set;
        }

        protected override void
        Init(
            Bam.Core.Module parent)
        {
            base.Init(parent);

            this.Macros["OutputName"] = TokenizedString.CreateVerbatim(string.Format("boost_{0}-vc120-mt-1_60", this.Name));
            this.Macros["libprefix"] = TokenizedString.CreateVerbatim("lib");

            this.BoostSource = this.CreateCxxSourceContainer();
            this.CompileAgainstPublicly<BoostHeaders>(this.BoostSource);
            if (this.BuildEnvironment.Platform.Includes(EPlatform.Windows))
            {
                this.BoostSource.PrivatePatch(settings =>
                    {
                        var cxxCompiler = settings as C.ICxxOnlyCompilerSettings;
                        cxxCompiler.ExceptionHandler = C.Cxx.EExceptionHandler.Asynchronous;

                        var vcCompiler = settings as VisualCCommon.ICommonCompilerSettings;
                        if (null != vcCompiler)
                        {
                            vcCompiler.WarningLevel = VisualCCommon.EWarningLevel.Level2; // does not compile warning-free above this level
                        }
                    });

                if (this.Librarian is VisualCCommon.Librarian)
                {
                    this.CompileAgainst<WindowsSDK.WindowsSDK>(this.BoostSource);
                }
            }
        }
    }
}

[packages,boost,1.60.0] Set VisualC warning level that a warning free compile occurs


/*
 * ******************************************************************************
 *   Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
 *   Licensed under the Apache License, Version 2.0 (the "License"). You may not use
 *   this file except in compliance with the License. A copy of the License is located at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   or in the "license" file accompanying this file.
 *   This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 *   CONDITIONS OF ANY KIND, either express or implied. See the License for the
 *   specific language governing permissions and limitations under the License.
 * ****************************************************************************
 */

using System.Reflection;

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

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

/*
 * ******************************************************************************
 *   Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
 *   Licensed under the Apache License, Version 2.0 (the "License"). You may not use
 *   this file except in compliance with the License. A copy of the License is located at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   or in the "license" file accompanying this file.
 *   This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 *   CONDITIONS OF ANY KIND, either express or implied. See the License for the
 *   specific language governing permissions and limitations under the License.
 * ****************************************************************************
 */

using System.Reflection;

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

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

Bump the version to v4.1.3

Bump the version to v4.1.3


using System;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;

namespace TestAppUWP.Core
{
    // ReSharper disable once InconsistentNaming
    public static class UIElementExtension
    {
        public static async Task<IBuffer> RenderTargetBitmapBuffer(this UIElement uiElement)
        {
            var renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(uiElement);
            return await renderTargetBitmap.GetPixelsAsync();
        }
    }
}

using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;

namespace TestAppUWP.Core
{
    // ReSharper disable once InconsistentNaming
    public static class UIElementExtension
    {
        public static async Task<IBuffer> RenderTargetBitmapBuffer(this UIElement uiElement)
        {
            var renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(uiElement);
            return await renderTargetBitmap.GetPixelsAsync();
        }

        public static async Task SaveUiElementToStream(this UIElement uiElement, IRandomAccessStream stream)
        {
            DisplayInformation displayInformation = DisplayInformation.GetForCurrentView();

            var renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(uiElement);
            IBuffer buffer = await renderTargetBitmap.GetPixelsAsync();

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
                (uint)renderTargetBitmap.PixelWidth,
                (uint)renderTargetBitmap.PixelHeight, displayInformation.LogicalDpi, displayInformation.LogicalDpi,
                buffer.ToArray());
            await encoder.FlushAsync();
        }

    }
}

Add save UIElement to stream snippet

Add save UIElement to stream snippet


using System;
using System.IO;

namespace AppHarbor
{
	public class ConsoleProgressBar
	{
		private const char ProgressBarCharacter = '\u2592';

		public static void Render(double percentage, ConsoleColor color, string message)
		{
			ConsoleColor originalColor = Console.ForegroundColor;
			Console.CursorLeft = 0;

			try
			{
				Console.CursorVisible = false;
				Console.ForegroundColor = color;

				int width = Console.WindowWidth - 1;
				int newWidth = (int)((width * percentage) / 100d);
				string progressBar = string.Empty
					.PadRight(newWidth, ProgressBarCharacter)
					.PadRight(width - newWidth, ' ');

				Console.Write(progressBar);
				message = message ?? string.Empty;

				Console.CursorTop++;

				OverwriteConsoleMessage(message);
				Console.CursorTop--;
			}
			finally
			{
				Console.ForegroundColor = originalColor;
				Console.CursorVisible = true;
			}
		}

		private static void OverwriteConsoleMessage(string message)
		{
			Console.CursorLeft = 0;
			int maxCharacterWidth = Console.WindowWidth - 1;
			if (message.Length > maxCharacterWidth)
			{
				message = message.Substring(0, maxCharacterWidth - 3) + "...";
			}
			message = message + new string(' ', maxCharacterWidth - message.Length);
			Console.Write(message);
		}
	}
}

using System;
using System.IO;

namespace AppHarbor
{
	public class ConsoleProgressBar
	{
		private const char ProgressBarCharacter = '\u2592';

		public static void Render(double percentage, ConsoleColor color, string message)
		{
			ConsoleColor originalColor = Console.ForegroundColor;
			Console.CursorLeft = 0;

			try
			{
				Console.CursorVisible = false;
				Console.ForegroundColor = color;

				int width = Console.WindowWidth - 1;
				int newWidth = (int)((width * percentage) / 100d);
				string progressBar = string.Empty
					.PadRight(newWidth, ProgressBarCharacter)
					.PadRight(width - newWidth, ' ');

				Console.Write(progressBar);
				message = message ?? string.Empty;

				Console.WriteLine();

				OverwriteConsoleMessage(message);
				Console.CursorTop--;
			}
			finally
			{
				Console.ForegroundColor = originalColor;
				Console.CursorVisible = true;
			}
		}

		private static void OverwriteConsoleMessage(string message)
		{
			Console.CursorLeft = 0;
			int maxCharacterWidth = Console.WindowWidth - 1;
			if (message.Length > maxCharacterWidth)
			{
				message = message.Substring(0, maxCharacterWidth - 3) + "...";
			}
			message = message + new string(' ', maxCharacterWidth - message.Length);
			Console.Write(message);
		}
	}
}

Use writeline instead of CursorTop++

Use writeline instead of CursorTop++

CursorTop++ is not compatible with msysgit buffer


using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using WalletWasabi.Models;

namespace WalletWasabi.Gui.ViewModels.Validation
{
	public delegate void ValidateMethod(IErrorList errors);

	public static class Validator
	{
		//public static IEnumerable<(string propertyName, ErrorDescriptors errors)> ValidateAllProperties(Dictionary<string, ValidateMethod> validationMethodCache)
		//{
		//	if(validationMethodCache is null || validationMethodCache.Count == 0)
		//	{
		//		throw new Exception("Cant call ValidateAllProperties on ViewModels with no ValidateAttributes");
		//	}

		//	var result = new List<(string propertyName, ErrorDescriptors errors)>();

		//	foreach (var propertyName in validationMethodCache.Keys)
		//	{

		//		var invokeRes = (ErrorDescriptors)validationMethodCache[propertyName].Invoke();

		//		result.Add((propertyName, invokeRes));
		//	}

		//	return result;
		//}

		//public static ErrorDescriptors ValidateProperty(ViewModelBase viewModelBase, string propertyName,
		//	Dictionary<string, MethodInfo> validationMethodCache)
		//{
		//	if (validationMethodCache is null)
		//	{
		//		return ErrorDescriptors.Empty;
		//	}

		//	ErrorDescriptors result = null;

		//	if(validationMethodCache.ContainsKey(propertyName))
		//	{
		//		var invokeRes = (ErrorDescriptors)validationMethodCache[propertyName].Invoke(viewModelBase, null);

		//		if (result is null)
		//		{
		//			result = new ErrorDescriptors();
		//		}

		//		result.AddRange(invokeRes);
		//	}

		//	return result ?? ErrorDescriptors.Empty;
		//}
	}
}

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using WalletWasabi.Models;

namespace WalletWasabi.Gui.ViewModels.Validation
{
	public delegate void ValidateMethod(IErrorList errors);
}

Remove validator methods, no longer needed.


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

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

namespace Microsoft.CodeAnalysis.CSharp.Utilities
{
    internal static class CompilationOptionsConversion
    {
        internal static LanguageVersion? GetLanguageVersion(string projectLanguageVersion)
        {
            switch (projectLanguageVersion.ToLowerInvariant())
            {
                case "iso-1":
                    return LanguageVersion.CSharp1;
                case "iso-2":
                    return LanguageVersion.CSharp2;
                case "experimental":
                    return LanguageVersion.Experimental;
                default:
                    if (!string.IsNullOrEmpty(projectLanguageVersion))
                    {
                        int version;
                        if (int.TryParse(projectLanguageVersion, out version))
                        {
                            return (LanguageVersion)version;
                        }
                    }

                    // use default;
                    return null;
            }
        }
    }
}

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

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

namespace Microsoft.CodeAnalysis.CSharp.Utilities
{
    internal static class CompilationOptionsConversion
    {
        internal static LanguageVersion? GetLanguageVersion(string projectLanguageVersion)
        {
            switch ((projectLanguageVersion ?? string.Empty).ToLowerInvariant())
            {
                case "iso-1":
                    return LanguageVersion.CSharp1;
                case "iso-2":
                    return LanguageVersion.CSharp2;
                case "experimental":
                    return LanguageVersion.Experimental;
                default:
                    if (!string.IsNullOrEmpty(projectLanguageVersion))
                    {
                        int version;
                        if (int.TryParse(projectLanguageVersion, out version))
                        {
                            return (LanguageVersion)version;
                        }
                    }

                    // use default;
                    return null;
            }
        }
    }
}

Allow null string in langversion conversion (changeset 1252651)


namespace net.opgenorth.yegvote.droid.Service
{
    using System;
    using System.IO;

    using Android.Content;

    using Environment = Android.OS.Environment;

    /// <summary>
    ///   This class will figure out where to store files.
    /// </summary>
    /// <remarks>Different versions of Android have different diretories for storage.</remarks>
    internal class ElectionServiceDownloadDirectory
    {
        private readonly Context _context;

        public ElectionServiceDownloadDirectory(Context context)
        {
            _context = context;
        }

        public void EnsureExternalStorageIsUsable()
        {
            if (Environment.MediaMountedReadOnly.Equals(Environment.ExternalStorageState))
            {
                throw new ApplicationException(String.Format("External storage {0} is mounted read-only.", _context.GetExternalFilesDir(null)));
            }
            if (!Environment.MediaMounted.Equals(Environment.ExternalStorageState))
            {
                throw new ApplicationException("External storage is not mounted.");
            }
        }

        public bool ResultsAreDownloaded
        {
            get
            {
                // TODO [TO201310041632] Maybe check to see how old the file is, > 30 minutes should return false?
                return File.Exists(GetResultsXmlFile());
            }
        }
        public string GetResultsXmlFile()
        {
            var dir = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads).AbsolutePath;
            return Path.Combine(dir, "election_results.xml");
        }
    }
}

using Android.Runtime;

namespace net.opgenorth.yegvote.droid.Service
{
    using System;
    using System.IO;

    using Android.Content;

    using Environment = Android.OS.Environment;

    /// <summary>
    ///   This class will figure out where to store files.
    /// </summary>
    /// <remarks>Different versions of Android have different diretories for storage.</remarks>
    internal class ElectionServiceDownloadDirectory
    {
        private readonly Context _context;

        public ElectionServiceDownloadDirectory(Context context)
        {
            _context = context;
        }

        public void EnsureExternalStorageIsUsable()
        {
            if (Environment.MediaMountedReadOnly.Equals(Environment.ExternalStorageState))
            {
                throw new ApplicationException(String.Format("External storage {0} is mounted read-only.", _context.GetExternalFilesDir(null)));
            }
            if (!Environment.MediaMounted.Equals(Environment.ExternalStorageState))
            {
                throw new ApplicationException("External storage is not mounted.");
            }
        }

        public bool ResultsAreDownloaded
        {
            get
            {
                // TODO [TO201310041632] Maybe check to see how old the file is, > 30 minutes should return false?
                return File.Exists(GetResultsXmlFileName());
            }
        }
        public string GetResultsXmlFileName()
        {
			var dir = _context.ExternalCacheDir.AbsolutePath;
			if (!Directory.Exists(dir))
			{
				Directory.CreateDirectory(dir);
			}
            return Path.Combine(dir, "election_results.xml");
        }
    }
}

Create the download directory if it doesn't exist.


using DavidLievrouw.Utils.ForTesting.DotNet;
using DavidLievrouw.Voter.Api.Users.Models;
using DavidLievrouw.Voter.Security;
using FakeItEasy;
using NUnit.Framework;

namespace DavidLievrouw.Voter.Api.Users.Handlers {
  [TestFixture]
  public class LogoutHandlerTests {
    LogoutHandler _sut;

    [SetUp]
    public void SetUp() {
      _sut = new LogoutHandler();
    }

    [Test]
    public void ConstructorTests() {
      Assert.That(_sut.NoDependenciesAreOptional());
    }

    [Test]
    public void DelegatesControlToAuthenticatedUserApplyer() {
      var securityContext = A.Fake<ISecurityContext>();
      var command = new LogoutRequest {
        SecurityContext = securityContext
      };

      _sut.Handle(command).Wait();

      A.CallTo(() => securityContext.SetAuthenticatedUser(null))
       .MustHaveHappened();
    }
  }
}

using DavidLievrouw.Utils.ForTesting.DotNet;
using DavidLievrouw.Voter.Api.Users.Models;
using DavidLievrouw.Voter.Security;
using FakeItEasy;
using NUnit.Framework;

namespace DavidLievrouw.Voter.Api.Users.Handlers {
  [TestFixture]
  public class LogoutHandlerTests {
    LogoutHandler _sut;

    [SetUp]
    public void SetUp() {
      _sut = new LogoutHandler();
    }

    [TestFixture]
    public class Construction : LogoutHandlerTests {
      [Test]
      public void ConstructorTests() {
        Assert.That(_sut.NoDependenciesAreOptional());
      }
    }

    [TestFixture]
    public class Handle : LogoutHandlerTests {
      [Test]
      public void DelegatesControlToAuthenticatedUserApplyer() {
        var securityContext = A.Fake<ISecurityContext>();
        var command = new LogoutRequest {
          SecurityContext = securityContext
        };

        _sut.Handle(command).Wait();

        A.CallTo(() => securityContext.SetAuthenticatedUser(null))
         .MustHaveHappened();
      }
    }
  }
}

SR: Refactor the tests in the LogoutHandler slightly.


using System;
using NSec.Cryptography;
using Xunit;

namespace NSec.Tests.Algorithms
{
    public static class Sha256Tests
    {
        public static readonly string HashOfEmpty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

        [Fact]
        public static void HashEmpty()
        {
            var a = new Sha256();

            var expected = HashOfEmpty.DecodeHex();
            var actual = a.Hash(ReadOnlySpan<byte>.Empty);

            Assert.Equal(a.DefaultHashSize, actual.Length);
            Assert.Equal(expected, actual);
        }

        [Fact]
        public static void HashEmptyWithSpan()
        {
            var a = new Sha256();

            var expected = HashOfEmpty.DecodeHex();
            var actual = new byte[expected.Length];

            a.Hash(ReadOnlySpan<byte>.Empty, actual);
            Assert.Equal(expected, actual);
        }
    }
}

using System;
using NSec.Cryptography;
using Xunit;

namespace NSec.Tests.Algorithms
{
    public static class Sha256Tests
    {
        public static readonly string HashOfEmpty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

        [Fact]
        public static void Properties()
        {
            var a = new Sha256();

            Assert.Equal(32, a.MinHashSize);
            Assert.True(a.DefaultHashSize >= a.MinHashSize);
            Assert.True(a.MaxHashSize >= a.DefaultHashSize);
            Assert.Equal(32, a.MaxHashSize);
        }

        [Fact]
        public static void HashEmpty()
        {
            var a = new Sha256();

            var expected = HashOfEmpty.DecodeHex();
            var actual = a.Hash(ReadOnlySpan<byte>.Empty);

            Assert.Equal(a.DefaultHashSize, actual.Length);
            Assert.Equal(expected, actual);
        }

        [Fact]
        public static void HashEmptyWithSize()
        {
            var a = new Sha256();

            var expected = HashOfEmpty.DecodeHex();
            var actual = a.Hash(ReadOnlySpan<byte>.Empty, a.MaxHashSize);

            Assert.Equal(a.MaxHashSize, actual.Length);
            Assert.Equal(expected, actual);
        }

        [Fact]
        public static void HashEmptyWithSpan()
        {
            var a = new Sha256();

            var expected = HashOfEmpty.DecodeHex();
            var actual = new byte[expected.Length];

            a.Hash(ReadOnlySpan<byte>.Empty, actual);
            Assert.Equal(expected, actual);
        }
    }
}

Add tests for Sha256 class

Add tests for Sha256 class


namespace Nancy.Hosting.Self
{
    /// <summary>
    /// Configuration for automatic url reservation creation
    /// </summary>
    public class UrlReservations
    {
        public UrlReservations()
        {
            this.CreateAutomatically = false;
            this.User = "Everyone";
        }

        /// <summary>
        /// Gets or sets a value indicating whether url reservations
        /// are automatically created when necessary.
        /// Defaults to false.
        /// </summary>
        public bool CreateAutomatically { get; set; }

        /// <summary>
        /// Gets or sets a value for the user to use to create the url reservations for.
        /// Defaults to the "Everyone" group.
        /// </summary>
        public string User { get; set; }
    }
}

namespace Nancy.Hosting.Self
{
    using System;
    using System.Security.Principal;

    /// <summary>
    /// Configuration for automatic url reservation creation
    /// </summary>
    public class UrlReservations
    {
        private const string EveryoneAccountName = "Everyone";

        private static readonly IdentityReference EveryoneReference =
            new SecurityIdentifier(WellKnownSidType.WorldSid, null);

        public UrlReservations()
        {
            this.CreateAutomatically = false;
            this.User = GetEveryoneAccountName();
        }

        /// <summary>
        /// Gets or sets a value indicating whether url reservations
        /// are automatically created when necessary.
        /// Defaults to false.
        /// </summary>
        public bool CreateAutomatically { get; set; }

        /// <summary>
        /// Gets or sets a value for the user to use to create the url reservations for.
        /// Defaults to the "Everyone" group.
        /// </summary>
        public string User { get; set; }

        private static string GetEveryoneAccountName()
        {
            try
            {
                var account = EveryoneReference.Translate(typeof(NTAccount)) as NTAccount;
                if (account != null)
                {
                    return account.Value;
                }

                return EveryoneAccountName;
            }
            catch (Exception)
            {
                return EveryoneAccountName;
            }
        }
    }
}

Fix for 'everyone' account in other languages


using System;
using System.Threading.Tasks;

namespace PalmDB.Serialization
{
    internal class UIntPalmValue : IPalmValue<uint>
    {
        public int Length { get; }

        public UIntPalmValue(int length)
        {
            Guard.NotNegative(length, nameof(length));

            this.Length = length;
        }

        public async Task<uint> ReadValueAsync(AsyncBinaryReader reader)
        {
            Guard.NotNull(reader, nameof(reader));

            var data = await reader.ReadAsync(this.Length);

            Array.Reverse(data);
            Array.Resize(ref data, 4);

            return BitConverter.ToUInt32(data, 0);
        }

        public async Task WriteValueAsync(AsyncBinaryWriter writer, uint value)
        {
            Guard.NotNull(writer, nameof(writer));

            var data = BitConverter.GetBytes(value);
            Array.Reverse(data);
            Array.Resize(ref data, this.Length);

            await writer.WriteAsync(data);
        }
    }
}

using System;
using System.Threading.Tasks;

namespace PalmDB.Serialization
{
    /// <summary>
    /// Represents a <see cref="uint"/> value inside a palm database.
    /// </summary>
    internal class UIntPalmValue : IPalmValue<uint>
    {
        /// <summary>
        /// Gets the length of this uint block.
        /// </summary>
        public int Length { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="UIntPalmValue"/> class.
        /// </summary>
        /// <param name="length">The length of the uint block.</param>
        public UIntPalmValue(int length)
        {
            Guard.NotNegative(length, nameof(length));

            this.Length = length;
        }

        /// <summary>
        /// Reads the <see cref="uint"/> using the specified <paramref name="reader"/>.
        /// </summary>
        /// <param name="reader">The reader.</param>
        public async Task<uint> ReadValueAsync(AsyncBinaryReader reader)
        {
            Guard.NotNull(reader, nameof(reader));

            var data = await reader.ReadAsync(this.Length);

            Array.Reverse(data);
            Array.Resize(ref data, 4);

            return BitConverter.ToUInt32(data, 0);
        }
        /// <summary>
        /// Writes the specified <paramref name="value"/> using the specified <paramref name="writer"/>.
        /// </summary>
        /// <param name="writer">The writer.</param>
        /// <param name="value">The value.</param>
        public async Task WriteValueAsync(AsyncBinaryWriter writer, uint value)
        {
            Guard.NotNull(writer, nameof(writer));

            var data = BitConverter.GetBytes(value);
            Array.Reverse(data);
            Array.Resize(ref data, this.Length);

            await writer.WriteAsync(data);
        }
    }
}

Add code documentation to the UIntPalmValue


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

using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens.Edit.Screens.Compose;
using OpenTK;

namespace osu.Game.Tests.Visual
{
    public class TestCaseBeatDivisorControl : OsuTestCase
    {
        public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(BindableBeatDivisor) };

        [BackgroundDependencyLoader]
        private void load()
        {
            Child = new BeatDivisorControl(new BindableBeatDivisor())
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Y = -200,
                Size = new Vector2(100, 110)
            };
        }
    }
}

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

using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens.Edit.Screens.Compose;
using OpenTK;

namespace osu.Game.Tests.Visual
{
    public class TestCaseBeatDivisorControl : OsuTestCase
    {
        public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(BindableBeatDivisor) };

        [BackgroundDependencyLoader]
        private void load()
        {
            Child = new BeatDivisorControl(new BindableBeatDivisor())
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Size = new Vector2(90, 90)
            };
        }
    }
}

Adjust testcase sizing to match editor

Adjust testcase sizing to match editor


using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using NullGuard;

namespace GitHub.VisualStudio.Converters
{
    /// <summary>
    /// Convert a count to visibility based on the following rule:
    /// * If count == 0, return Visibility.Visible
    /// * If count > 0, return Visibility.Collapsed
    /// </summary>
    public class CountToVisibilityConverter : IValueConverter
    {
        public object Convert([AllowNull] object value, [AllowNull] Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture)
        {
            return ((int)value == 0) ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack([AllowNull] object value, [AllowNull] Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture)
        {
            return null;
        }
    }
}

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using NullGuard;

namespace GitHub.VisualStudio.Converters
{
    /// <summary>
    /// Convert a count to visibility based on the following rule:
    /// * If count == 0, return Visibility.Visible
    /// * If count > 0, return Visibility.Collapsed
    /// </summary>
    public class CountToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture)
        {
            return ((int)value == 0) ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture)
        {
            return null;
        }
    }
}

Use AllowNull for appropriate parameters


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

using System.ComponentModel;
using System.Linq;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
using osu.Game.Screens.Play;

namespace osu.Game.Tests.Visual
{
    [Description("Player instantiated with a replay.")]
    public class TestCaseReplay : TestCasePlayer
    {
        protected override Player CreatePlayer(Ruleset ruleset)
        {
            // We create a dummy RulesetContainer just to get the replay - we don't want to use mods here
            // to simulate setting a replay rather than having the replay already set for us
            Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Concat(new[] { ruleset.GetAutoplayMod() });
            var dummyRulesetContainer = ruleset.CreateRulesetContainerWith(Beatmap.Value);

            // Reset the mods
            Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Where(m => !(m is ModAutoplay));

            return new ReplayPlayer(new Score { Replay = dummyRulesetContainer.ReplayScore.Replay });
        }
    }
}

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

using System.ComponentModel;
using System.Linq;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.Play;

namespace osu.Game.Tests.Visual
{
    [Description("Player instantiated with a replay.")]
    public class TestCaseReplay : TestCasePlayer
    {
        protected override Player CreatePlayer(Ruleset ruleset)
        {
            // We create a dummy RulesetContainer just to get the replay - we don't want to use mods here
            // to simulate setting a replay rather than having the replay already set for us
            Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Concat(new[] { ruleset.GetAutoplayMod() });
            var dummyRulesetContainer = ruleset.CreateRulesetContainerWith(Beatmap.Value);

            // Reset the mods
            Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Where(m => !(m is ModAutoplay));

            return new ReplayPlayer(dummyRulesetContainer.ReplayScore);
        }
    }
}

Create ReplayPlayer using Score from the dummy RulesetContainer


using System;
using Newtonsoft.Json;

namespace AxosoftAPI.NET.Models
{
	public class WorkLog : BaseModel
	{
		[JsonProperty("project")]
		public Project Project { get; set; }

		[JsonProperty("release")]
		public Release Release { get; set; }

		[JsonProperty("user")]
		public User User { get; set; }

		[JsonProperty("work_done")]
		public DurationUnit WorkDone { get; set; }

		[JsonProperty("item")]
		public Item Item { get; set; }

		[JsonProperty("work_log_type")]
		public WorkLogType WorklogType { get; set; }

		[JsonProperty("description")]
		public string Description { get; set; }

		[JsonProperty("date_time")]
		public DateTime? DateTime { get; set; }
	}
}

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

namespace AxosoftAPI.NET.Models
{
	public class WorkLog : BaseModel
	{
		[JsonProperty("project")]
		public Project Project { get; set; }

		[JsonProperty("release")]
		public Release Release { get; set; }

		[JsonProperty("user")]
		public User User { get; set; }

		[JsonProperty("work_done")]
		public DurationUnit WorkDone { get; set; }

		[JsonProperty("item")]
		public Item Item { get; set; }

		[JsonProperty("work_log_type")]
		public WorkLogType WorklogType { get; set; }

		[JsonProperty("description")]
		public string Description { get; set; }

		[JsonProperty("date_time")]
		public DateTime? DateTime { get; set; }

		[JsonProperty("custom_fields")]
		public IDictionary<string, object> CustomFields { get; set; }
	}
}

Add Custom Work Log field

Add Custom Work Log field


using System;

namespace DevelopmentInProgress.DipState
{
    public class LogEntry
    {
        public LogEntry(string message)
        {
            Message = message;
            Time = DateTime.Now;
        }

        public DateTime Time { get; private set; }
        public string Message { get; private set; }

        public override string ToString()
        {
            return String.Format("{0}   {1}", Time.ToString("yy-mm-dd hhmmss"), Message);
        }
    }
}

using System;

namespace DevelopmentInProgress.DipState
{
    public class LogEntry
    {
        public LogEntry(string message)
        {
            Message = message;
            Time = DateTime.Now;
        }

        public DateTime Time { get; private set; }
        public string Message { get; private set; }

        public override string ToString()
        {
            return String.Format("{0}   {1}", Time.ToString("yyyy-MM-dd HH:mm:ss"), Message);
        }
    }
}

Change time format for log entry

Change time format for log entry

Change time format to "yyyy-MM-dd HH:mm:ss"


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

namespace SGEnviro.Utilities
{
    public class NumberParseException : Exception
    {
        public NumberParseException(string message) { }
    }

    public class Parsing
    {
        public static void ParseFloatOrThrowException(string value, out float destination, string message)
        {
            if (!float.TryParse(value, out destination))
            {
                throw new Exception(message);
            }
        }
    }
}

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

namespace SGEnviro.Utilities
{
    public class NumberParseException : Exception
    {
        public NumberParseException(string message) { }
    }

    public class Parsing
    {
        public static void ParseFloatOrThrowException(string value, out float destination, string message)
        {
            if (!float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out destination))
            {
                throw new Exception(message);
            }
        }
    }
}

Use invariant culture when parsing floats.


using System;
using System.Linq;
using Pixie;
using Pixie.Markup;
using Pixie.Options;
using Pixie.Terminal;

namespace ParseOptions
{
    public static class Program
    {
        private static readonly FlagOption syntaxOnlyFlag = new FlagOption(
            OptionForm.Short("fsyntax-only"),
            OptionForm.Short("fno-syntax-only"),
            false);

        private static OptionSet parsedOptions;

        public static void Main(string[] args)
        {
            // First, acquire a terminal log. You should acquire
            // a log once and then re-use it in your application.
            var log = TerminalLog.Acquire();

            var allOptions = new Option[]
            {
                syntaxOnlyFlag
            };

            var parser = new GnuOptionSetParser(
                allOptions, syntaxOnlyFlag, syntaxOnlyFlag.PositiveForms[0]);

            parsedOptions = parser.Parse(args, log);

            foreach (var item in allOptions)
            {
                log.Log(
                    new LogEntry(
                        Severity.Info,
                        new BulletedList(
                            allOptions
                                .Select<Option, MarkupNode>(TypesetParsedOption)
                                .ToArray<MarkupNode>(),
                            true)));
            }
        }

        private static MarkupNode TypesetParsedOption(Option opt)
        {
            return new Sequence(
                new DecorationSpan(new Text(opt.Forms[0].ToString()), TextDecoration.Bold),
                new Text(": "),
                new Text(parsedOptions.GetValue<object>(opt).ToString()));
        }
    }
}

using System;
using System.Linq;
using Pixie;
using Pixie.Markup;
using Pixie.Options;
using Pixie.Terminal;
using Pixie.Transforms;

namespace ParseOptions
{
    public static class Program
    {
        private static readonly FlagOption syntaxOnlyFlag = new FlagOption(
            OptionForm.Short("fsyntax-only"),
            OptionForm.Short("fno-syntax-only"),
            false);

        private static OptionSet parsedOptions;

        public static void Main(string[] args)
        {
            // First, acquire a terminal log. You should acquire
            // a log once and then re-use it in your application.
            ILog log = TerminalLog.Acquire();

            log = new TransformLog(
                log,
                new Func<LogEntry, LogEntry>[]
                {
                    MakeDiagnostic
                });

            var allOptions = new Option[]
            {
                syntaxOnlyFlag
            };

            var parser = new GnuOptionSetParser(
                allOptions, syntaxOnlyFlag, syntaxOnlyFlag.PositiveForms[0]);

            parsedOptions = parser.Parse(args, log);

            foreach (var item in allOptions)
            {
                log.Log(
                    new LogEntry(
                        Severity.Info,
                        new BulletedList(
                            allOptions
                                .Select<Option, MarkupNode>(TypesetParsedOption)
                                .ToArray<MarkupNode>(),
                            true)));
            }
        }

        private static MarkupNode TypesetParsedOption(Option opt)
        {
            return new Sequence(
                new DecorationSpan(new Text(opt.Forms[0].ToString()), TextDecoration.Bold),
                new Text(": "),
                new Text(parsedOptions.GetValue<object>(opt).ToString()));
        }

        private static LogEntry MakeDiagnostic(LogEntry entry)
        {
            return DiagnosticExtractor.Transform(entry, new Text("program"));
        }
    }
}

Make option parsing output prettier

Make option parsing output prettier


using System;
using System.Collections.Generic;

namespace Group.Net.Groups
{
	public class PermutationGroup<T> where T : IComparable<T>
	{
		protected readonly IList<IList<int>> Generators;

		public int GeneratorCount
		{
			get { return Generators.Count; }
		}

		public PermutationGroup(IList<IList<int>> generators)
		{
			Generators = generators;
		}

		public Points<T> Apply(int index, Points<T> points)
		{
			var permutedPoints = new Points<T>(points);

			for (var i = 0; i < Generators[index].Count - 1; ++i)
				permutedPoints[Generators[index][i + 1]] = points[Generators[index][i]];

			permutedPoints[Generators[index][0]] = points[Generators[index][Generators[index].Count - 1]];

			return permutedPoints;
		}
	}
}

using System;
using System.Collections.Generic;

namespace Group.Net.Groups
{
	public class PermutationGroup<T> where T : IComparable<T>
	{
		protected readonly IList<IList<int>> Generators;

		public int GeneratorCount
		{
			get { return Generators.Count; }
		}

		public PermutationGroup(IList<IList<int>> generators)
		{
			Generators = generators;
		}

		public Points<T> Apply(int index, Points<T> points)
		{
			var permutedPoints = new Points<T>(points);

			if (permutedPoints.Count == 1)
				return permutedPoints;

			for (var i = 0; i < Generators[index].Count - 1; ++i)
				permutedPoints[Generators[index][i + 1]] = points[Generators[index][i]];

			permutedPoints[Generators[index][0]] = points[Generators[index][Generators[index].Count - 1]];

			return permutedPoints;
		}
	}
}

Fix for attempting to permute singleton Points objects.


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Globalization;
using Tgstation.Server.Api.Models;

namespace Tgstation.Server.Host.Core
{
	/// <summary>
	/// Extensions for <see cref="IApplicationBuilder"/>
	/// </summary>
	static class ApplicationBuilderExtensions
	{
		/// <summary>
		/// Return a <see cref="ConflictObjectResult"/> for <see cref="DbUpdateException"/>s
		/// </summary>
		/// <param name="applicationBuilder">The <see cref="IApplicationBuilder"/> to configure</param>
		public static void UseDbConflictHandling(this IApplicationBuilder applicationBuilder) => applicationBuilder.Use(async (context, next) =>
		{
			if (applicationBuilder == null)
				throw new ArgumentNullException(nameof(applicationBuilder));
			try
			{
				await next().ConfigureAwait(false);
			}
			catch (DbUpdateException e)
			{
				await new ConflictObjectResult(new ErrorMessage { Message = String.Format(CultureInfo.InvariantCulture, "A database conflict has occurred: {0}", (e.InnerException ?? e).Message) }).ExecuteResultAsync(new ActionContext
				{
					HttpContext = context
				}).ConfigureAwait(false);
			}
		});
	}
}

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Globalization;
using Tgstation.Server.Api.Models;

namespace Tgstation.Server.Host.Core
{
	/// <summary>
	/// Extensions for <see cref="IApplicationBuilder"/>
	/// </summary>
	static class ApplicationBuilderExtensions
	{
		/// <summary>
		/// Return a <see cref="ConflictObjectResult"/> for <see cref="DbUpdateException"/>s
		/// </summary>
		/// <param name="applicationBuilder">The <see cref="IApplicationBuilder"/> to configure</param>
		public static void UseDbConflictHandling(this IApplicationBuilder applicationBuilder)
		{
			if (applicationBuilder == null)
				throw new ArgumentNullException(nameof(applicationBuilder));
			applicationBuilder.Use(async (context, next) =>
			{
				try
				{
					await next().ConfigureAwait(false);
				}
				catch (DbUpdateException e)
				{
					await new ConflictObjectResult(new ErrorMessage { Message = String.Format(CultureInfo.InvariantCulture, "A database conflict has occurred: {0}", (e.InnerException ?? e).Message) }).ExecuteResultAsync(new ActionContext
					{
						HttpContext = context
					}).ConfigureAwait(false);
				}
			});
		}
	}
}

Check parameter before actually using it


// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

using System.Collections.Generic;
using Microsoft.Practices.Unity;

namespace EOLib
{
    public static class UnityExtensions
    {
        public static void RegisterInstance<T>(this IUnityContainer container)
        {
            container.RegisterType<T>(new ContainerControlledLifetimeManager());
        }

        public static void RegisterInstance<T, U>(this IUnityContainer container) where U : T
        {
            container.RegisterType<T, U>(new ContainerControlledLifetimeManager());
        }

        public static void RegisterVaried<T, U>(this IUnityContainer container) where U : T
        {
            RegisterEnumerableIfNeeded<T, U>(container);

            container.RegisterType<T, U>(typeof(U).Name);
        }

        public static void RegisterInstanceVaried<T, U>(this IUnityContainer container) where U : T
        {
            RegisterEnumerableIfNeeded<T, U>(container);

            container.RegisterType<T, U>(typeof(U).Name, new ContainerControlledLifetimeManager());
        }

        private static void RegisterEnumerableIfNeeded<T, U>(IUnityContainer container) where U : T
        {
            if (!container.IsRegistered(typeof(IEnumerable<T>)))
            {
                container.RegisterType<IEnumerable<T>>(
                    new ContainerControlledLifetimeManager(),
                    new InjectionFactory(c => c.ResolveAll<T>()));
            }
        }
    }
}

// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

using System.Collections.Generic;
using Microsoft.Practices.Unity;

namespace EOLib
{
    public static class UnityExtensions
    {
        public static IUnityContainer RegisterInstance<T>(this IUnityContainer container)
        {
            return container.RegisterType<T>(new ContainerControlledLifetimeManager());
        }

        public static IUnityContainer RegisterInstance<T, U>(this IUnityContainer container) where U : T
        {
            return container.RegisterType<T, U>(new ContainerControlledLifetimeManager());
        }

        public static IUnityContainer RegisterVaried<T, U>(this IUnityContainer container) where U : T
        {
            RegisterEnumerableIfNeeded<T, U>(container);

            return container.RegisterType<T, U>(typeof(U).Name);
        }

        public static IUnityContainer RegisterInstanceVaried<T, U>(this IUnityContainer container) where U : T
        {
            RegisterEnumerableIfNeeded<T, U>(container);

            return container.RegisterType<T, U>(typeof(U).Name, new ContainerControlledLifetimeManager());
        }

        private static void RegisterEnumerableIfNeeded<T, U>(IUnityContainer container) where U : T
        {
            if (!container.IsRegistered(typeof(IEnumerable<T>)))
            {
                container.RegisterType<IEnumerable<T>>(
                    new ContainerControlledLifetimeManager(),
                    new InjectionFactory(c => c.ResolveAll<T>()));
            }
        }
    }
}

Return IUnityContainer from unity extension methods


using System.Windows.Input;

namespace RegEditor
{
    public static class ComandsContextMenu
    {
        public static readonly RoutedUICommand CreateKey = new RoutedUICommand(
            "Create Key", "CreateKey", typeof(MainWindow));

        public static readonly RoutedUICommand UpdateKey = new RoutedUICommand(
            "Update Key", "UpdateKey", typeof(MainWindow));

        public static readonly RoutedUICommand DeleteKey = new RoutedUICommand(
            "Delete Key", "DeleteKey", typeof(MainWindow));
    }
}

using System.Windows.Input;

namespace RegEditor
{
    public static class ComandsContextMenu
    {
        public static readonly RoutedUICommand CreateKey = new RoutedUICommand(
            "Create Key", "CreateKey", typeof(MainWindow));

        public static readonly RoutedUICommand UpdateKey = new RoutedUICommand(
            "Update Key", "UpdateKey", typeof(MainWindow));

        public static readonly RoutedUICommand DeleteKey = new RoutedUICommand(
            "Delete Key", "DeleteKey", typeof(MainWindow));

        public static readonly RoutedUICommand DeleteKeyValue = new RoutedUICommand(
            "Delete Key Value", "DeleteKeyValue", typeof(MainWindow));

        public static readonly RoutedUICommand CreateKeyValue = new RoutedUICommand(
           "Delete Key Value", "DeleteKeyValue", typeof(MainWindow));

        public static readonly RoutedUICommand UpdateKeyValue = new RoutedUICommand(
           "Update Key Value", "UpdateKeyValue", typeof(MainWindow));

    }
}

Add puncts key value in context menu

Add puncts key value in context menu


using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using ReactiveUI;
using Splat;
using WalletWasabi.Gui.Controls.TransactionDetails.ViewModels;
using WalletWasabi.Gui.ViewModels;

namespace WalletWasabi.Gui.Controls.WalletExplorer
{
	public class TransactionInfoTabViewModel : WasabiDocumentTabViewModel
	{
		public TransactionInfoTabViewModel(TransactionDetailsViewModel transaction, UiConfig uiConfig) : base("")
		{
			Transaction = transaction;
			UiConfig = uiConfig;
			Title = $"Transaction ({transaction.TransactionId[0..10]}) Details";
		}

		public TransactionDetailsViewModel Transaction { get; }
		public UiConfig UiConfig { get; }

		public override void OnOpen(CompositeDisposable disposables)
		{
			UiConfig.WhenAnyValue(x => x.LurkingWifeMode)
				.ObserveOn(RxApp.MainThreadScheduler)
				.Subscribe(x => Transaction.RaisePropertyChanged(nameof(Transaction.TransactionId)))
				.DisposeWith(disposables);

			base.OnOpen(disposables);
		}
	}
}

using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using ReactiveUI;
using Splat;
using WalletWasabi.Gui.Controls.TransactionDetails.ViewModels;
using WalletWasabi.Gui.ViewModels;

namespace WalletWasabi.Gui.Controls.WalletExplorer
{
	public class TransactionInfoTabViewModel : WasabiDocumentTabViewModel
	{
		public TransactionInfoTabViewModel(TransactionDetailsViewModel transaction, UiConfig uiConfig) : base(title: "")
		{
			Transaction = transaction;
			UiConfig = uiConfig;
			Title = $"Transaction ({transaction.TransactionId[0..10]}) Details";
		}

		public TransactionDetailsViewModel Transaction { get; }
		public UiConfig UiConfig { get; }

		public override void OnOpen(CompositeDisposable disposables)
		{
			UiConfig.WhenAnyValue(x => x.LurkingWifeMode)
				.ObserveOn(RxApp.MainThreadScheduler)
				.Subscribe(x => Transaction.RaisePropertyChanged(nameof(Transaction.TransactionId)))
				.DisposeWith(disposables);

			base.OnOpen(disposables);
		}
	}
}

Add param name to better readability

Add param name to better readability


namespace SqlStreamStore
{
    using System;
    using System.Collections.Concurrent;
    using System.Threading.Tasks;
    using SqlStreamStore.MySql;
    using Xunit;
    using Xunit.Abstractions;

    public class MySqlStreamStoreFixturePool : IAsyncLifetime
    {
        private readonly ConcurrentQueue<MySqlStreamStoreFixture> _fixturePool
            = new ConcurrentQueue<MySqlStreamStoreFixture>();

        public async Task<MySqlStreamStoreFixture> Get(ITestOutputHelper outputHelper)
        {
            if (!_fixturePool.TryDequeue(out var fixture))
            {
                var dbUniqueName = (DateTime.UtcNow - DateTime.UnixEpoch).TotalMilliseconds;
                var databaseName = $"sss-v3-{dbUniqueName}";
                var dockerInstance = new MySqlDockerDatabaseManager(outputHelper, databaseName);
                await dockerInstance.CreateDatabase();

                fixture = new MySqlStreamStoreFixture(
                    dockerInstance,
                    databaseName,
                    onDispose:() => _fixturePool.Enqueue(fixture));

                outputHelper.WriteLine($"Using new fixture with db {databaseName}");
            }
            else
            {
                outputHelper.WriteLine($"Using pooled fixture with db {fixture.DatabaseName}");
            }

            await fixture.Prepare();

            return fixture;
        }

        public Task InitializeAsync()
        {
            return Task.CompletedTask;
        }

        public Task DisposeAsync()
        {
            return Task.CompletedTask;
        }
    }
}

namespace SqlStreamStore
{
    using System;
    using System.Collections.Concurrent;
    using System.Threading.Tasks;
    using SqlStreamStore.MySql;
    using Xunit;
    using Xunit.Abstractions;

    public class MySqlStreamStoreFixturePool : IAsyncLifetime
    {
        private readonly ConcurrentQueue<MySqlStreamStoreFixture> _fixturePool
            = new ConcurrentQueue<MySqlStreamStoreFixture>();

        public async Task<MySqlStreamStoreFixture> Get(ITestOutputHelper outputHelper)
        {
            if (!_fixturePool.TryDequeue(out var fixture))
            {
                var dbUniqueName = (DateTime.UtcNow - DateTime.UnixEpoch).TotalMilliseconds;
                var databaseName = $"sss-v3-{dbUniqueName}";
                var dockerInstance = new MySqlDockerDatabaseManager(outputHelper, databaseName); // TODO output helper here will be interleaved
                await dockerInstance.CreateDatabase();

                fixture = new MySqlStreamStoreFixture(
                    dockerInstance,
                    databaseName,
                    onDispose:() => _fixturePool.Enqueue(fixture));

                outputHelper.WriteLine($"Using new fixture with db {databaseName}");
            }
            else
            {
                outputHelper.WriteLine($"Using pooled fixture with db {fixture.DatabaseName}");
            }

            await fixture.Prepare();

            return fixture;
        }

        public Task InitializeAsync()
        {
            return Task.CompletedTask;
        }

        public Task DisposeAsync()
        {
            return Task.CompletedTask;
        }
    }
}

Add todo - this will give wrong test output.


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;

namespace osu.Game.Rulesets.Mania.Edit.Blueprints
{
    public abstract class ManiaSelectionBlueprint : OverlaySelectionBlueprint
    {
        public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject;

        [Resolved]
        private IScrollingInfo scrollingInfo { get; set; }

        protected ManiaSelectionBlueprint(DrawableHitObject drawableObject)
            : base(drawableObject)
        {
            RelativeSizeAxes = Axes.None;
        }

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

            Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero));
        }

        public override void Show()
        {
            DrawableObject.AlwaysAlive = true;
            base.Show();
        }

        public override void Hide()
        {
            DrawableObject.AlwaysAlive = false;
            base.Hide();
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;

namespace osu.Game.Rulesets.Mania.Edit.Blueprints
{
    public abstract class ManiaSelectionBlueprint : OverlaySelectionBlueprint
    {
        public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject;

        [Resolved]
        private IScrollingInfo scrollingInfo { get; set; }

        // Overriding the base because this method is called right after `Column` is changed and `DrawableObject` is not yet loaded and Parent is not set.
        public override Vector2 GetInstantDelta(Vector2 screenSpacePosition) => Parent.ToLocalSpace(screenSpacePosition) - Position;

        protected ManiaSelectionBlueprint(DrawableHitObject drawableObject)
            : base(drawableObject)
        {
            RelativeSizeAxes = Axes.None;
        }

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

            Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero));
        }

        public override void Show()
        {
            DrawableObject.AlwaysAlive = true;
            base.Show();
        }

        public override void Hide()
        {
            DrawableObject.AlwaysAlive = false;
            base.Hide();
        }
    }
}

Fix mania editor null reference

Fix mania editor null reference


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Components;
using osu.Framework.Graphics.Shapes;
using osuTK.Graphics;

namespace osu.Game.Tournament.Screens.Showcase
{
    public class ShowcaseScreen : BeatmapInfoScreen, IProvideVideo
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            AddRangeInternal(new Drawable[]
            {
                new TournamentLogo(),
                new TourneyVideo("showcase")
                {
                    Loop = true,
                    RelativeSizeAxes = Axes.Both,
                },
                new Box
                {
                    // chroma key area for stable gameplay
                    Name = "chroma",
                    Anchor = Anchor.TopCentre,
                    Origin = Anchor.TopCentre,
                    Height = 695,
                    Width = 1366,
                    Colour = new Color4(0, 255, 0, 255),
                }
            });
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Tournament.Components;
using osu.Framework.Graphics.Shapes;
using osuTK.Graphics;

namespace osu.Game.Tournament.Screens.Showcase
{
    public class ShowcaseScreen : BeatmapInfoScreen, IProvideVideo
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            AddRangeInternal(new Drawable[]
            {
                new TournamentLogo(),
                new TourneyVideo("showcase")
                {
                    Loop = true,
                    RelativeSizeAxes = Axes.Both,
                },
                new Container
                {
                    Padding = new MarginPadding { Bottom = SongBar.HEIGHT },
                    RelativeSizeAxes = Axes.Both,
                    Child = new Box
                    {
                        // chroma key area for stable gameplay
                        Name = "chroma",
                        Anchor = Anchor.TopCentre,
                        Origin = Anchor.TopCentre,
                        RelativeSizeAxes = Axes.Both,
                        Colour = new Color4(0, 255, 0, 255),
                    }
                }
            });
        }
    }
}

Use SongBar height instead of hard-coded dimensions


using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Alexa.NET.Management.AccountLinking;
using Refit;

namespace Alexa.NET.Management.Internals
{
    [Headers("Authorization: Bearer")]
    public interface IClientAccountLinkingApi
    {
        [Get("/skills/{skilIid}/accountLinkingClient")]
        Task<AccountLinkInformation> Get(string skillId);

        [Put("/skills/{skillId}/accountLinkingClient")]
        Task Update(string skillId, [Body]AccountLinkUpdate information);
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Alexa.NET.Management.AccountLinking;
using Refit;

namespace Alexa.NET.Management.Internals
{
    [Headers("Authorization: Bearer")]
    public interface IClientAccountLinkingApi
    {
        [Get("/skills/{skillId}/accountLinkingClient")]
        Task<AccountLinkInformation> Get(string skillId);

        [Put("/skills/{skillId}/accountLinkingClient")]
        Task Update(string skillId, [Body]AccountLinkUpdate information);
    }
}

Fix issue with mismatched parameter on AccountLinking Api


using System;
using ClosedXML.Excel;

namespace ClosedXML_Examples.Misc
{
    public class WorkbookProperties : IXLExample
    {
        #region Variables

        // Public

        // Private

        #endregion

        #region Properties

        // Public

        // Private

        // Override

        #endregion

        #region Events

        // Public

        // Private

        // Override

        #endregion

        #region Methods

        // Public
        public void Create(String filePath)
        {
            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("Workbook Properties");

            wb.Properties.Author = "theAuthor";
            wb.Properties.Title = "theTitle";
            wb.Properties.Subject = "theSubject";
            wb.Properties.Category = "theCategory";
            wb.Properties.Keywords = "theKeywords";
            wb.Properties.Comments = "theComments";
            wb.Properties.Status = "theStatus";
            wb.Properties.LastModifiedBy = "theLastModifiedBy";
            wb.Properties.Company = "theCompany";
            wb.Properties.Manager = "theManager";

            // Creating/Using custom properties
            wb.CustomProperties.Add("theText", "XXX");
            wb.CustomProperties.Add("theDate", new DateTime(2011, 1, 1));
            wb.CustomProperties.Add("theNumber", 123.456);
            wb.CustomProperties.Add("theBoolean", true);

            wb.SaveAs(filePath);
        }

        // Private

        // Override

        #endregion
    }
}

using System;
using ClosedXML.Excel;

namespace ClosedXML_Examples.Misc
{
    public class WorkbookProperties : IXLExample
    {
        #region Variables

        // Public

        // Private

        #endregion

        #region Properties

        // Public

        // Private

        // Override

        #endregion

        #region Events

        // Public

        // Private

        // Override

        #endregion

        #region Methods

        // Public
        public void Create(String filePath)
        {
            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("Workbook Properties");

            wb.Properties.Author = "theAuthor";
            wb.Properties.Title = "theTitle";
            wb.Properties.Subject = "theSubject";
            wb.Properties.Category = "theCategory";
            wb.Properties.Keywords = "theKeywords";
            wb.Properties.Comments = "theComments";
            wb.Properties.Status = "theStatus";
            wb.Properties.LastModifiedBy = "theLastModifiedBy";
            wb.Properties.Company = "theCompany";
            wb.Properties.Manager = "theManager";

            // Creating/Using custom properties
            wb.CustomProperties.Add("theText", "XXX");
            wb.CustomProperties.Add("theDate", new DateTime(2011, 1, 1, 17, 0, 0, DateTimeKind.Utc)); // Use UTC to make sure test can be run in any time zone
            wb.CustomProperties.Add("theNumber", 123.456);
            wb.CustomProperties.Add("theBoolean", true);

            wb.SaveAs(filePath);
        }

        // Private

        // Override

        #endregion
    }
}

Fix time zone issue in tests

Fix time zone issue in tests


using System.Reflection;

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0")]

using System.Reflection;

[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0")]

Update version to at least above published version on nuget.org


using System;

using MessageBird.Utilities;
using Newtonsoft.Json;

namespace MessageBird.Json.Converters
{
    class RFC3339DateTimeConverter : JsonConverter
    {
        private const string Format = "yyyy-MM-dd'T'HH:mm:ssK";
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is DateTime)
            {
                var dateTime = (DateTime)value;
                writer.WriteValue(dateTime.ToString(Format));
            }
            else
            {
                throw new JsonSerializationException("Expected value of type 'DateTime'.");
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Type t = (ReflectionUtils.IsNullable(objectType))
                ? Nullable.GetUnderlyingType(objectType)
                : objectType;

            if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }

            if (reader.TokenType == JsonToken.Date)
            {
                return reader.Value;
            }
            throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType));
        }

        public override bool CanConvert(Type objectType)
        {
            Type t = (ReflectionUtils.IsNullable(objectType))
               ? Nullable.GetUnderlyingType(objectType)
               : objectType;

            return t == typeof(DateTime);
        }
    }
}

using System;

using MessageBird.Utilities;
using Newtonsoft.Json;

namespace MessageBird.Json.Converters
{
    class RFC3339DateTimeConverter : JsonConverter
    {
        private const string Format = "yyyy-MM-dd'T'HH:mm:ssK";
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is DateTime)
            {
                var dateTime = (DateTime)value;
                if (dateTime.Kind == DateTimeKind.Unspecified)
                {
                    throw new JsonSerializationException("Cannot convert date time with an unspecified kind");
                }
                string convertedDateTime = dateTime.ToString(Format);
                writer.WriteValue(convertedDateTime);
            }
            else
            {
                throw new JsonSerializationException("Expected value of type 'DateTime'.");
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Type t = (ReflectionUtils.IsNullable(objectType))
                ? Nullable.GetUnderlyingType(objectType)
                : objectType;

            if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }

            if (reader.TokenType == JsonToken.Date)
            {
                return reader.Value;
            }
            throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType));
        }

        public override bool CanConvert(Type objectType)
        {
            Type t = (ReflectionUtils.IsNullable(objectType))
               ? Nullable.GetUnderlyingType(objectType)
               : objectType;

            return t == typeof(DateTime);
        }
    }
}

Raise exception when the kind of a DateTime is unspecified

To properly convert to RFC3339 format, we need to know the kind to determine the proper timezone offset.


using System;
using System.Collections.Generic;
using Engine.cgimin.texture;
using System.IO;

namespace Mugo
{
	public static class TextureLoader
	{
		private static readonly Dictionary<String, TextureHolder> textures = new Dictionary<string, TextureHolder>();

		public static TextureHolder Load(String path)
		{
			TextureHolder texture;
			if(!textures.TryGetValue(path, out texture))
			{
				var normalTexturePath = Path.ChangeExtension(path, "normals" + Path.GetExtension(path));
				var normalMapId = 0;
				if (File.Exists(normalTexturePath)) {
					normalMapId = TextureManager.LoadTexture(normalTexturePath);
				}

				texture = new TextureHolder(TextureManager.LoadTexture(path), normalMapId);
			}

			return texture;
		}
	}

	public class TextureHolder
	{
		public TextureHolder(int textureId, int normalMapId)
		{
			TextureId = textureId;
			NormalMapId = normalMapId;
		}

		public int TextureId {
			get;
			private set;
		}

		public int NormalMapId {
			get;
			private set;
		}
	}
}

using System;
using System.Collections.Generic;
using Engine.cgimin.texture;
using System.IO;

namespace Mugo
{
	public static class TextureLoader
	{
		private static readonly Dictionary<String, TextureHolder> textures = new Dictionary<string, TextureHolder>();

		public static TextureHolder Load(String path)
		{
			TextureHolder texture;
			if(!textures.TryGetValue(path, out texture))
			{
				var normalTexturePath = Path.ChangeExtension(path, "normals" + Path.GetExtension(path));
				var normalMapId = 0;
				if (File.Exists(normalTexturePath)) {
					normalMapId = TextureManager.LoadTexture(normalTexturePath);
				}

				texture = new TextureHolder(TextureManager.LoadTexture(path), normalMapId);
                textures[path] = texture;
			}

			return texture;
		}
	}

	public class TextureHolder
	{
		public TextureHolder(int textureId, int normalMapId)
		{
			TextureId = textureId;
			NormalMapId = normalMapId;
		}

		public int TextureId {
			get;
			private set;
		}

		public int NormalMapId {
			get;
			private set;
		}
	}
}

Save loaded textures in map.

Save loaded textures in map.


namespace DynamixelServo.Driver
{
   public enum ComplianceSlope
   {
      S2 = 2,
      S4 = 4,
      S8 = 8,
      S16 = 16,
      S32 = 32,
      Default = 32,
      S64 = 64,
      S128 = 128
   }
}

namespace DynamixelServo.Driver
{
   public enum ComplianceSlope
   {
      S2 = 2,
      S4 = 4,
      S8 = 8,
      S16 = 16,
      S32 = 32,
      /// <summary>
      /// Same as S32
      /// </summary>
      Default = 32,
      S64 = 64,
      S128 = 128
   }
}

Add description to default Compliance slope


using System;
using Recurly;
using Recurly.Resources;

namespace RecurlyTestRig
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new Recurly.Client("subdomain-client-lib-test", "382c053318a04154905c4d27a48f74a6");
            var site = client.GetSite("subdomain-client-lib-test");
            Console.WriteLine(site.Id);

            var account = client.GetAccount("subdomain-client-lib-test", "code-benjamin-du-monde");
            Console.WriteLine(account.CreatedAt);

            var createAccount = new AccountCreate() {
                Code = "abcsdaskdljsda",
                Username = "myuser",
                Address = new Address() {
                    City = "New Orleans",
                    Street1 = "1 Canal St.",
                    Region = "LA",
                    Country = "US",
                    PostalCode = "70115"
                }
            };

            var createdAccount = client.CreateAccount("subdomain-client-lib-test", createAccount);
            Console.WriteLine(createdAccount.CreatedAt);

            try {
                var nonexistentAccount = client.GetAccount("subdomain-client-lib-test", "idontexist");
            } catch (Recurly.ApiError err) {
                Console.WriteLine(err);
            }

        }
    }
}

using System;
using Recurly;
using Recurly.Resources;

namespace RecurlyTestRig
{
    class Program
    {
        static void Main(string[] args)
        {
          try {
            var subdomain = Environment.GetEnvironmentVariable("RECURLY_SUBDOMAIN");
            var apiKey = Environment.GetEnvironmentVariable("RECURLY_API_KEY");
            var client = new Recurly.Client(subdomain, apiKey);
            var site = client.GetSite(subdomain);
            Console.WriteLine(site.Id);

            var account = client.GetAccount(subdomain, "code-benjamin-du-monde");
            Console.WriteLine(account.CreatedAt);

            var createAccount = new CreateAccount() {
                Code = "abcsdaskdljsda",
                Username = "myuser",
                Address = new Address() {
                    City = "New Orleans",
                    Street1 = "1 Canal St.",
                    Region = "LA",
                    Country = "US",
                    PostalCode = "70115"
                }
            };

            var createdAccount = client.CreateAccount(subdomain, createAccount);
            Console.WriteLine(createdAccount.CreatedAt);

            try {
                var nonexistentAccount = client.GetAccount(subdomain, "idontexist");
            } catch (Recurly.ApiError err) {
                Console.WriteLine(err);
            }
          } catch (Recurly.ApiError err) {
                Console.WriteLine(err);
          }
        }
    }
}

Use env vars for test client

Use env vars for test client


using System.Collections.Generic;
using MongoDB.Driver;

namespace RapidCore.Mongo.Testing
{
    /// <summary>
    /// Base class for functional tests that need access to
    /// a Mongo database.
    ///
    /// It provides simple helpers that we use ourselves.
    /// </summary>
    public abstract class MongoConnectedTestBase
    {
        private MongoClient lowLevelClient;
        private IMongoDatabase db;
        private bool isConnected = false;

        protected string GetDbName()
        {
            return GetType().Name;
        }

        protected void Connect(string connectionString = "mongodb://localhost:27017")
        {
            lowLevelClient = new MongoClient(connectionString);
            lowLevelClient.DropDatabase(GetDbName());
            db = lowLevelClient.GetDatabase(GetDbName());
        }

        protected MongoClient GetClient()
        {
            if (!isConnected)
            {
                Connect();
                isConnected = true;
            }

            return lowLevelClient;
        }

        protected IMongoDatabase GetDb()
        {
            return GetClient().GetDatabase(GetDbName());
        }

        protected void EnsureEmptyCollection(string collectionName)
        {
            GetDb().DropCollection(collectionName);
        }

        protected void Insert<TDocument>(string collectionName, TDocument doc)
        {
            GetDb().GetCollection<TDocument>(collectionName).InsertOne(doc);
        }

        protected IList<TDocument> GetAll<TDocument>(string collectionName)
        {
            return GetDb().GetCollection<TDocument>(collectionName).Find(filter => true).ToList();
        }
    }
}

using System.Collections.Generic;
using MongoDB.Driver;

namespace RapidCore.Mongo.Testing
{
    /// <summary>
    /// Base class for functional tests that need access to
    /// a Mongo database.
    ///
    /// It provides simple helpers that we use ourselves.
    /// </summary>
    public abstract class MongoConnectedTestBase
    {
        private MongoClient lowLevelClient;
        private IMongoDatabase db;
        private bool isConnected = false;

        protected string ConnectionString { get; set; } = "mongodb://localhost:27017";

        protected string GetDbName()
        {
            return GetType().Name;
        }

        protected void Connect()
        {
            if (!isConnected)
            {
                lowLevelClient = new MongoClient(ConnectionString);
                lowLevelClient.DropDatabase(GetDbName());
                db = lowLevelClient.GetDatabase(GetDbName());
                isConnected = true;
            }
        }

        protected MongoClient GetClient()
        {
            Connect();
            return lowLevelClient;
        }

        protected IMongoDatabase GetDb()
        {
            return GetClient().GetDatabase(GetDbName());
        }

        protected void EnsureEmptyCollection(string collectionName)
        {
            GetDb().DropCollection(collectionName);
        }

        protected void Insert<TDocument>(string collectionName, TDocument doc)
        {
            GetDb().GetCollection<TDocument>(collectionName).InsertOne(doc);
        }

        protected IList<TDocument> GetAll<TDocument>(string collectionName)
        {
            return GetDb().GetCollection<TDocument>(collectionName).Find(filter => true).ToList();
        }
    }
}

Define a property for the connection string

This allows consumers to override the value and actually have it used.


using GitHub.Api;
using GitHub.Models;
using GitHub.Services;
using Microsoft.TeamFoundation.Controls;
using System.ComponentModel.Composition;

namespace GitHub.VisualStudio.TeamExplorer.Connect
{
    [TeamExplorerSection(GitHubConnectSection1Id, TeamExplorerPageIds.Connect, 10)]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class GitHubConnectSection1 : GitHubConnectSection
    {
        public const string GitHubConnectSection1Id = "519B47D3-F2A9-4E19-8491-8C9FA25ABE91";

        [ImportingConstructor]
        public GitHubConnectSection1(ISimpleApiClientFactory apiFactory, ITeamExplorerServiceHolder holder, IConnectionManager manager)
            : base(apiFactory, holder, manager, 1)
        {
        }
    }
}

using GitHub.Api;
using GitHub.Models;
using GitHub.Services;
using Microsoft.TeamFoundation.Controls;
using System.ComponentModel.Composition;

namespace GitHub.VisualStudio.TeamExplorer.Connect
{
    [TeamExplorerSection(GitHubConnectSection1Id, TeamExplorerPageIds.Connect, 11)]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class GitHubConnectSection1 : GitHubConnectSection
    {
        public const string GitHubConnectSection1Id = "519B47D3-F2A9-4E19-8491-8C9FA25ABE91";

        [ImportingConstructor]
        public GitHubConnectSection1(ISimpleApiClientFactory apiFactory, ITeamExplorerServiceHolder holder, IConnectionManager manager)
            : base(apiFactory, holder, manager, 1)
        {
        }
    }
}

Fix ordering of connection sections

Fix ordering of connection sections


// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using Microsoft.Azure.WebJobs.ServiceBus;

namespace Microsoft.Azure.WebJobs.Script.Description
{
    public class EventHubBindingMetadata : BindingMetadata
    {
        [AllowNameResolution]
        public string Path { get; set; }

        public override void ApplyToConfig(JobHostConfigurationBuilder configBuilder)
        {
            if (configBuilder == null)
            {
                throw new ArgumentNullException("configBuilder");
            }
            EventHubConfiguration eventHubConfig = configBuilder.EventHubConfiguration;

            string connectionString = null;
            if (!string.IsNullOrEmpty(Connection))
            {
                connectionString = Utility.GetAppSettingOrEnvironmentValue(Connection);
            }

            if (this.IsTrigger)
            {
                string eventProcessorHostName = Guid.NewGuid().ToString();

                string storageConnectionString = configBuilder.Config.StorageConnectionString;

                var eventProcessorHost = new Microsoft.ServiceBus.Messaging.EventProcessorHost(
                     eventProcessorHostName,
                     this.Path,
                     Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName,
                     connectionString,
                     storageConnectionString);

                eventHubConfig.AddEventProcessorHost(this.Path, eventProcessorHost);
            }
            else
            {
                var client = Microsoft.ServiceBus.Messaging.EventHubClient.CreateFromConnectionString(
                    connectionString, this.Path);

                eventHubConfig.AddEventHubClient(this.Path, client);
            }
        }
    }
}

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using Microsoft.Azure.WebJobs.ServiceBus;

namespace Microsoft.Azure.WebJobs.Script.Description
{
    public class EventHubBindingMetadata : BindingMetadata
    {
        [AllowNameResolution]
        public string Path { get; set; }

        // Optional Consumer group
        public string ConsumerGroup { get; set; }

        public override void ApplyToConfig(JobHostConfigurationBuilder configBuilder)
        {
            if (configBuilder == null)
            {
                throw new ArgumentNullException("configBuilder");
            }
            EventHubConfiguration eventHubConfig = configBuilder.EventHubConfiguration;

            string connectionString = null;
            if (!string.IsNullOrEmpty(Connection))
            {
                connectionString = Utility.GetAppSettingOrEnvironmentValue(Connection);
            }

            if (this.IsTrigger)
            {
                string eventProcessorHostName = Guid.NewGuid().ToString();

                string storageConnectionString = configBuilder.Config.StorageConnectionString;

                string consumerGroup = this.ConsumerGroup;
                if (consumerGroup == null)
                {
                    consumerGroup = Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName;
                }

                var eventProcessorHost = new Microsoft.ServiceBus.Messaging.EventProcessorHost(
                     eventProcessorHostName,
                     this.Path,
                     consumerGroup,
                     connectionString,
                     storageConnectionString);

                eventHubConfig.AddEventProcessorHost(this.Path, eventProcessorHost);
            }
            else
            {
                var client = Microsoft.ServiceBus.Messaging.EventHubClient.CreateFromConnectionString(
                    connectionString, this.Path);

                eventHubConfig.AddEventHubClient(this.Path, client);
            }
        }
    }
}

Support EventHub Consumer Groups in Script


using System;
using System.Windows;
using DereTore.Applications.StarlightDirector.Extensions;

namespace DereTore.Applications.StarlightDirector.UI.Controls.Pages {
    public partial class SummaryPage : IDirectorPage {

        public SummaryPage() {
            InitializeComponent();
            Table = new ObservableDictionary<string, string>();
            DataContext = this;
        }

        public ObservableDictionary<string, string> Table { get; }

        private void SummaryPage_OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) {
            var visible = (bool)e.NewValue;
            if (!visible) {
                return;
            }
            var t = Table;
            t.Clear();
            var mainWindow = this.GetMainWindow();
            var editor = mainWindow.Editor;

            Func<string, string> res = key => Application.Current.FindResource<string>(key);

            t[res(App.ResourceKeys.SummaryMusicFile)] = editor.Project.HasMusic ? editor.Project.MusicFileName : "(none)";
            t[res(App.ResourceKeys.SummaryTotalNotes)] = editor.ScoreNotes.Count.ToString();
            t[res(App.ResourceKeys.SummaryTotalBars)] = editor.ScoreBars.Count.ToString();
        }

    }
}

using System;
using System.Windows;
using DereTore.Applications.StarlightDirector.Extensions;

namespace DereTore.Applications.StarlightDirector.UI.Controls.Pages {
    public partial class SummaryPage : IDirectorPage {

        public SummaryPage() {
            InitializeComponent();
            Table = new ObservableDictionary<string, string>();
            DataContext = this;
        }

        public ObservableDictionary<string, string> Table { get; }

        private void SummaryPage_OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) {
            var visible = (bool)e.NewValue;
            if (!visible) {
                return;
            }
            var t = Table;
            t.Clear();
            var mainWindow = this.GetMainWindow();
            var editor = mainWindow.Editor;

            Func<string, string> res = key => Application.Current.FindResource<string>(key);

            t[res(App.ResourceKeys.SummaryMusicFile)] = editor.Project?.HasMusic ?? false ? editor.Project.MusicFileName : "(none)";
            t[res(App.ResourceKeys.SummaryTotalNotes)] = editor.ScoreNotes.Count.ToString();
            t[res(App.ResourceKeys.SummaryTotalBars)] = editor.ScoreBars.Count.ToString();
        }

    }
}

[director] Fix crash after discarding autosave file


using System.Reflection;

[assembly: AssemblyTitle("Autofac.Extras.Tests.DynamicProxy2")]
[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.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Arkivverket.Arkade.Core.Resources;
using Arkivverket.Arkade.Core.Testing;
using Arkivverket.Arkade.Core.Util;
using Serilog;

namespace Arkivverket.Arkade.Core.Base.Noark5
{
    public abstract class Noark5BaseTest : IArkadeTest
    {
        private static readonly ILogger Log = Serilog.Log.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
        protected readonly Stopwatch Stopwatch = new Stopwatch();

        public abstract TestId GetId();
        public abstract string GetName();
        public abstract TestType GetTestType();

        public string GetDescription()
        {
            var description = Noark5TestDescriptions.ResourceManager.GetObject(GetName()) as string;

            if (description == null)
            {
                Log.Debug($"Missing description of Noark5Test: {GetType().FullName}");
            }

            return description;
        }

        public TestRun GetTestRun()
        {
            Stopwatch.Start();
            List<TestResult> testResults = GetTestResults();
            Stopwatch.Stop();

            return new TestRun(this)
            {
                Results = testResults,
                TestDuration = Stopwatch.ElapsedMilliseconds
            };
        }

        protected abstract List<TestResult> GetTestResults();

        public int CompareTo(object obj)
        {
            var arkadeTest = (IArkadeTest) obj;

            return GetId().CompareTo(arkadeTest.GetId());
        }
    }
}

using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Arkivverket.Arkade.Core.Resources;
using Arkivverket.Arkade.Core.Testing;
using Arkivverket.Arkade.Core.Util;
using Serilog;

namespace Arkivverket.Arkade.Core.Base.Noark5
{
    public abstract class Noark5BaseTest : IArkadeTest
    {
        private static readonly ILogger Log = Serilog.Log.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
        protected readonly Stopwatch Stopwatch = new Stopwatch();

        public abstract TestId GetId();
        public abstract string GetName();
        public abstract TestType GetTestType();

        public string GetDescription()
        {
            var description = Noark5TestDescriptions.ResourceManager.GetObject(GetId().ToString()) as string;

            if (description == null)
            {
                Log.Debug($"Missing description of Noark 5 test: {GetId()}");
            }

            return description;
        }

        public TestRun GetTestRun()
        {
            Stopwatch.Start();
            List<TestResult> testResults = GetTestResults();
            Stopwatch.Stop();

            return new TestRun(this)
            {
                Results = testResults,
                TestDuration = Stopwatch.ElapsedMilliseconds
            };
        }

        protected abstract List<TestResult> GetTestResults();

        public int CompareTo(object obj)
        {
            var arkadeTest = (IArkadeTest) obj;

            return GetId().CompareTo(arkadeTest.GetId());
        }
    }
}

Use TestID for N5 test description lookup

ARKADE-273