using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using ChessVariantsTraining.DbRepositories;

namespace ChessVariantsTraining.ViewModels
{
    public class CommentSorter
    {
        ICommentVoteRepository voteRepo;
        IUserRepository userRepo;

        public CommentSorter(ICommentVoteRepository _voteRepo, IUserRepository _userRepo)
        {
            voteRepo = _voteRepo;
            userRepo = _userRepo;
        }

        public async Task<ReadOnlyCollection<Comment>> OrderAsync(List<Models.Comment> list)
        {
            return new ReadOnlyCollection<Comment>(await OrderRecursivelyAsync(list, null, 0));
        }

        async Task<List<Comment>> OrderRecursivelyAsync(List<Models.Comment> list, int? parent, int indentLevel)
        {
            List<Comment> result = new List<Comment>();

            IEnumerable<Task<Comment>> currentTopLevel = list.Where(x => x.ParentID == parent)
                .Select(async x => new Comment(x, indentLevel, await voteRepo.GetScoreForCommentAsync(x.ID), x.Deleted, (await userRepo.FindByIdAsync(x.Author)).Username))
                .OrderByDescending(async x => (await x).Score);
            foreach (Task<Comment> commentTask in currentTopLevel)
            {
                Comment comment = await commentTask;
                result.Add(comment);
                result.AddRange(await OrderRecursivelyAsync(list, comment.ID, indentLevel + 1));
            }

            return result;
        }
    }
}

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using ChessVariantsTraining.DbRepositories;

namespace ChessVariantsTraining.ViewModels
{
    public class CommentSorter
    {
        ICommentVoteRepository voteRepo;
        IUserRepository userRepo;

        public CommentSorter(ICommentVoteRepository _voteRepo, IUserRepository _userRepo)
        {
            voteRepo = _voteRepo;
            userRepo = _userRepo;
        }

        public async Task<ReadOnlyCollection<Comment>> OrderAsync(List<Models.Comment> list)
        {
            return new ReadOnlyCollection<Comment>(await OrderRecursivelyAsync(list, null, 0));
        }

        async Task<List<Comment>> OrderRecursivelyAsync(List<Models.Comment> list, int? parent, int indentLevel)
        {
            List<Comment> result = new List<Comment>();

            IEnumerable<Task<Comment>> currentTopLevelTask = list.Where(x => x.ParentID == parent)
                .Select(async x => new Comment(x, indentLevel, await voteRepo.GetScoreForCommentAsync(x.ID), x.Deleted, (await userRepo.FindByIdAsync(x.Author)).Username));
            IEnumerable<Comment> currentTopLevel = await Task.WhenAll(currentTopLevelTask);
            currentTopLevel = currentTopLevel.OrderByDescending(x => x.Score);
            foreach (Comment comment in currentTopLevel)
            {
                result.Add(comment);
                result.AddRange(await OrderRecursivelyAsync(list, comment.ID, indentLevel + 1));
            }

            return result;
        }
    }
}

Fix OrderRecursivelyAsync bug with OrderByDescending


namespace Umbraco.Core.Models
{
    /// <summary>
    /// Represents the type of a property group.
    /// </summary>
    public enum PropertyGroupType : short
    {
        /// <summary>
        /// Display as a group (using a header).
        /// </summary>
        Group = 0,
        /// <summary>
        /// Display as an app (using a name and icon).
        /// </summary>
        App = 1,
        //Tab = 2,
        //Fieldset = 3
    }
}

namespace Umbraco.Core.Models
{
    /// <summary>
    /// Represents the type of a property group.
    /// </summary>
    public enum PropertyGroupType : short
    {
        /// <summary>
        /// Display property types in a group.
        /// </summary>
        Group = 0,
        /// <summary>
        /// Display property types in a tab.
        /// </summary>
        Tab = 1
    }
}

Update property group type enum

Update property group type enum


using UnityEngine;
using UnityEngine.Events;

public class World : Planet {

    private UnityEvent onPlanetHit = new UnityEvent();
    private Lives lives;

    private void Awake() {
        lives = GetComponent<Lives>();
    }

    private void OnCollisionEnter( Collision other ) {
        onPlanetHit.Invoke();
    }

    public void AddHitListener( UnityAction call ) {
        onPlanetHit.AddListener( call );
    }

    public void AddOutOfLivesListener( UnityAction<int> call ) {
        lives.AddOutOfLivesListener( call );
    }

    public void AddLivesChangedListener( UnityAction<int> call ) {
        lives.AddLivesChangedListener( call );
    }
}

using UnityEngine;
using UnityEngine.Events;

public class World : Planet {

    private UnityEvent onPlanetHit = new UnityEvent();
    private Lives lives;

    private void Awake() {
        lives = GetComponent<Lives>();
    }

    private void OnCollisionEnter( Collision other ) {
        if( other.transform.GetComponent<Ball>() ) {
            onPlanetHit.Invoke();
        }
    }

    public void AddHitListener( UnityAction call ) {
        onPlanetHit.AddListener( call );
    }

    public void AddOutOfLivesListener( UnityAction<int> call ) {
        lives.AddOutOfLivesListener( call );
    }

    public void AddLivesChangedListener( UnityAction<int> call ) {
        lives.AddLivesChangedListener( call );
    }
}

Check for collision with balls only.

Check for collision with balls only.


using System;
using System.Diagnostics;
using Microsoft.Languages.Editor;
using Microsoft.Languages.Editor.Controller;

namespace Microsoft.VisualStudio.R.Package.Plots {
    internal sealed class PlotWindowCommandController : ICommandTarget {
        private PlotWindowPane _pane;

        public PlotWindowCommandController(PlotWindowPane pane) {
            Debug.Assert(pane != null);
            _pane = pane;
        }

        public CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg) {
            RPlotWindowContainer container = _pane.GetIVsWindowPane() as RPlotWindowContainer;
            Debug.Assert(container != null);
            container.Menu.Execute(id);
            return CommandResult.Executed;
        }

        public void PostProcessInvoke(CommandResult result, Guid group, int id, object inputArg, ref object outputArg) {
        }

        public CommandStatus Status(Guid group, int id) {
            return CommandStatus.SupportedAndEnabled;
        }
    }
}

using System;
using System.Diagnostics;
using Microsoft.Languages.Editor;
using Microsoft.Languages.Editor.Controller;

namespace Microsoft.VisualStudio.R.Package.Plots {
    internal sealed class PlotWindowCommandController : ICommandTarget {
        private PlotWindowPane _pane;

        public PlotWindowCommandController(PlotWindowPane pane) {
            Debug.Assert(pane != null);
            _pane = pane;
        }

        public CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg) {
            RPlotWindowContainer container = _pane.GetIVsWindowPane() as RPlotWindowContainer;
            Debug.Assert(container != null);
            if (container.Menu != null) {
                container.Menu.Execute(id);
            }
            return CommandResult.Executed;
        }

        public void PostProcessInvoke(CommandResult result, Guid group, int id, object inputArg, ref object outputArg) {
        }

        public CommandStatus Status(Guid group, int id) {
            RPlotWindowContainer container = _pane.GetIVsWindowPane() as RPlotWindowContainer;
            return (container != null && container.Menu != null) ? CommandStatus.SupportedAndEnabled : CommandStatus.Supported;
        }
    }
}

Disable plot buttons until plot is available


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

using System.ComponentModel.Composition;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Xaml
{
    public static class XamlStaticTypeDefinitions
    {
        /// <summary>
        /// Definition of the XAML content type.
        /// </summary>
        [Export]
        [Name(ContentTypeNames.XamlContentType)]
        [BaseDefinition(CodeRemoteContentDefinition.CodeRemoteContentTypeName)]
        internal static readonly ContentTypeDefinition XamlContentType;

        // Associate .xaml as the Xaml content type.
        [Export]
        [FileExtension(StringConstants.XamlFileExtension)]
        [ContentType(ContentTypeNames.XamlContentType)]
        internal static readonly FileExtensionToContentTypeDefinition XamlFileExtension;
    }
}

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

using System.ComponentModel.Composition;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Xaml
{
    public static class XamlStaticTypeDefinitions
    {
        /// <summary>
        /// Definition of the XAML content type.
        /// </summary>
        [Export]
        [Name(ContentTypeNames.XamlContentType)]
        [BaseDefinition("code")]
        internal static readonly ContentTypeDefinition XamlContentType;

        // Associate .xaml as the Xaml content type.
        [Export]
        [FileExtension(StringConstants.XamlFileExtension)]
        [ContentType(ContentTypeNames.XamlContentType)]
        internal static readonly FileExtensionToContentTypeDefinition XamlFileExtension;
    }
}

Remove LSP base from Xaml content type definition to avoid regressing rps


namespace TraktApiSharp.Extensions
{
    using System;
    using System.Linq;

    public static class StringExtensions
    {
        private static readonly char[] DelimiterChars = { ' ', ',', '.', ':', ';', '\n', '\t' };

        public static string FirstToUpper(this string value)
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentException("value not valid", nameof(value));

            var trimmedValue = value.Trim();

            if (trimmedValue.Length > 1)
                return char.ToUpper(trimmedValue[0]) + trimmedValue.Substring(1).ToLower();

            return trimmedValue.ToUpper();
        }

        public static int WordCount(this string value)
        {
            if (string.IsNullOrEmpty(value))
                return 0;

            var words = value.Split(DelimiterChars);
            var filteredWords = words.Where(s => !string.IsNullOrEmpty(s));
            return filteredWords.Count();
        }

        public static bool ContainsSpace(this string value)
        {
            return value.Contains(" ");
        }
    }
}

namespace TraktApiSharp.Extensions
{
    using System;
    using System.Linq;

    /// Provides helper methods for strings.
    public static class StringExtensions
    {
        private static readonly char[] DelimiterChars = { ' ', ',', '.', ':', ';', '\n', '\t' };

        /// Converts the given string to a string, in which only the first letter is capitalized.
        /// <param name="value">The string, in which only the first letter should be capitalized.</param>
        /// <returns>A string, in which only the first letter is capitalized.</returns>
        /// <exception cref="ArgumentException">Thrown, if the given string is null or empty.</exception>
        public static string FirstToUpper(this string value)
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentException("value not valid", nameof(value));

            var trimmedValue = value.Trim();

            if (trimmedValue.Length > 1)
                return char.ToUpper(trimmedValue[0]) + trimmedValue.Substring(1).ToLower();

            return trimmedValue.ToUpper();
        }

        /// Counts the words in a string.
        /// <param name="value">The string, for which the words should be counted.</param>
        /// <returns>The number of words in the given string or zero, if the given string is null or empty.</returns>
        public static int WordCount(this string value)
        {
            if (string.IsNullOrEmpty(value))
                return 0;

            var words = value.Split(DelimiterChars);
            var filteredWords = words.Where(s => !string.IsNullOrEmpty(s));
            return filteredWords.Count();
        }

        /// Returns, whether the given string contains any spaces.
        /// <param name="value">The string, which should be checked.</param>
        /// <returns>True, if the given string contains any spaces, otherwise false.</returns>
        public static bool ContainsSpace(this string value)
        {
            return value.Contains(" ");
        }
    }
}

Add documentation for string extensions.


using Atata;
using NUnit.Framework;

namespace AtataSamples.NetCore.NUnit
{
    public class SignInTests : UITestFixture
    {
        [Test]
        public void NetCoreNUnit_SignIn()
        {
            Go.To<SignInPage>().
                Email.Set("admin@mail.com").
                Password.Set("abc123").
                SignIn.ClickAndGo().
                    Heading.Should.Equal("Users"); // Verify that we are navigated to "Users" page.
        }

        [Test]
        public void NetCoreNUnit_SignIn_WithInvalidPassword()
        {
            Go.To<SignInPage>().
                Email.Set("admin@mail.com").
                Password.Set("WRONGPASSWORD").
                SignIn.Click().
                Heading.Should.Equal("Sign In"). // Verify that we are still on "Sing In" page.
                Content.Should.Contain("Password or Email is invalid"); // Verify validation message.
        }
    }
}

using Atata;
using NUnit.Framework;

namespace AtataSamples.NetCore.NUnit
{
    public class SignInTests : UITestFixture
    {
        [Test]
        public void NetCoreNUnit_SignIn()
        {
            Go.To<SignInPage>().
                Email.Set("admin@mail.com").
                Password.Set("abc123").
                SignIn.ClickAndGo().
                    Heading.Should.Equal("Users"); // Verify that we are navigated to "Users" page.
        }

        [Test]
        public void NetCoreNUnit_SignIn_WithInvalidPassword()
        {
            Go.To<SignInPage>().
                Email.Set("admin@mail.com").
                Password.Set("WRONGPASSWORD").
                SignIn.Click().
                Heading.Should.Equal("Sign In"). // Verify that we are still on "Sign In" page.
                Content.Should.Contain("Password or Email is invalid"); // Verify validation message.
        }
    }
}

Fix typo in NetCoreNUnit_SignIn_WithInvalidPassword test comment


using System;
using NUnit.Framework;
using Entelect.Extensions;
namespace Entelect.Tests.Strings
{
    [TestFixture]
    public class StringExtensionsTests
    {
        [Test]
        public void ContainsIgnoringCase()
        {
            var doesContain = "asd".Contains("S",StringComparison.OrdinalIgnoreCase);
            Assert.True(doesContain);
        }
        [Test]
        public void ListContainsIgnoringCase()
        {
            var list = new[] {"asd", "qwe", "zxc"};
            var doesContain = list.Contains("ASD", StringComparison.OrdinalIgnoreCase);
            Assert.True(doesContain);
        }
    }
}

using System;
using NUnit.Framework;
using Entelect.Extensions;
namespace Entelect.Tests.Strings
{
    [TestFixture]
    public class StringExtensionsTests
    {
        [Test]
        public void ContainsIgnoringCase()
        {
            var doesContain = "asd".Contains("S",StringComparison.OrdinalIgnoreCase);
            Assert.True(doesContain);
        }

        [Test]
        public void ListContainsIgnoringCase()
        {
            var list = new[] {"asd", "qwe", "zxc"};
            var doesContain = list.Contains("ASD", StringComparison.OrdinalIgnoreCase);
            Assert.True(doesContain);
        }

        [Test]
        public void PascalCaseToSpacedString()
        {
            const string input = "SomePascalCasedString";
            const string expectedOutput = "Some Pascal Cased String";
            var actualOutput = input.PascalToSpacedString();
            Assert.AreEqual(expectedOutput, actualOutput);
        }

        [Test]
        public void PascalCaseToSpacedStringArray()
        {
            const string input = "SomePascalCasedString";
            var expectedOutput = new []{"Some", "Pascal", "Cased","String"};
            var actualOutput = input.PascalToSpacedStringArray();
            Assert.That(expectedOutput, Is.EquivalentTo(actualOutput));
        }
    }
}

Add tests for PascalCaseToSpacedString extensions


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

[assembly: System.Reflection.AssemblyInformationalVersion("1.2.0.f8952b97")]
[assembly: System.Reflection.AssemblyVersion("1.2.0")]
[assembly: System.Reflection.AssemblyFileVersion("1.2.0")]

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

[assembly: System.Reflection.AssemblyInformationalVersion("1.2.0.eabc2527")]
[assembly: System.Reflection.AssemblyVersion("1.2.0")]
[assembly: System.Reflection.AssemblyFileVersion("1.2.0")]

Add support for Unmarried/Never married death date


using System;
using Kudu.Contracts;
using Kudu.Core.Infrastructure;

namespace Kudu.Core.Performance
{
    public class NullProfiler : IProfiler
    {
        public static IProfiler Instance = new NullProfiler();

        private NullProfiler()
        {
        }

        public IDisposable Step(string value)
        {
            return new DisposableAction(() => { });
        }
    }
}

using System;
using Kudu.Contracts;
using Kudu.Core.Infrastructure;

namespace Kudu.Core.Performance
{
    public class NullProfiler : IProfiler
    {
        public static IProfiler Instance = new NullProfiler();

        private NullProfiler()
        {
        }

        public IDisposable Step(string value)
        {
            return DisposableAction.Noop;
        }
    }
}

Return DisposableAction.Noop for the null profiler instead of creating new objects for every step.


using Microsoft.WindowsAzure.Mobile.Service;

namespace ZUMOAPPNAMEService.DataObjects
{
    public class TodoItem : TableData
    {
        public string Text { get; set; }

        public bool Complete { get; set; }
    }
}

using Microsoft.WindowsAzure.Mobile.Service;

namespace ZUMOAPPNAMEService.DataObjects
{
    public class TodoItem : EntityData
    {
        public string Text { get; set; }

        public bool Complete { get; set; }
    }
}

Split out extensions for Entity Framework, Azure Storage, and Mongo. These are now separate projects (and NuGet packages) that all reference the Tables project (which again references the core service project). New NuGet packages are creates and references added.

As part of this we have removed the TableData type and instead moved to a type specific to each backend store. For EF it is EntityData.

Updated templates to use EntityData instead of TableData.


using System;

namespace ChatRelay
{
    class Program
    {
        private static readonly Relay relay = new Relay();

        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
            Run();
        }

        public static void Run()
        {
            relay.Stop();
            try
            {
                relay.Start();
            }
            catch (Exception ex) when (ex.GetType() == typeof(RelayConfigurationException))
            {
                Console.WriteLine($"ERROR: {ex.Message}");
                return;
            }

            while (true)
            {
                char command = Console.ReadKey(true).KeyChar;

                if (command == 'q')
                {
                    Console.WriteLine("Quitting...");
                    relay.Stop();
                    return;
                }
                if (command == 'r')
                {
                    Console.WriteLine("Restarting...");
                    relay.Stop();
                    relay.Start();
                }
            }
        }

        private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
        {
            Console.WriteLine($"EXCEPTION: {e.ExceptionObject}");
            Run();
        }
    }
}

// TODO: The adapters use a Connect() Disconnect() naming convention,
// but right now they don't support reconnecting as Disconnect() is treated as more of a Dispose.
// Should probably change the naming structure or code layout to fix this. Maybe Connect/Open and Dispose?
// Alternatively, actually support disconnecting and reconnecting though more error handling is required.

// TODO: Relay emotes.

// TODO: Bot commands.
// Request that the bot tell you who is in the room in another service (reply via DM).
// Request information on the other services, mainly URL.
// Tell you how many people are on the other services (status?).

// TODO: Test on Mono.

// TODO: Logging. Would be good to basically have two log providers, rotating file on disk and console output.
// Ex, replace Console.WriteLine calls with logging calls.

// TODO: Connection monitoring. Heartbeat? IRC has Ping/Pong.

// TODO: Really think through error handling and resiliency in terms of disconnects/reconnects.
// May have to look for an alternative to the Slack API library we're using as it doesn't handling things like this well.

Move feature ideas to GitHub issue tracker


using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using Store.Models;
using Store.Storage.Data;

namespace Store.Storage.SqlServer {
  public class Client {
    public Client(DBContext _dbContext) {
      var fac = new Factory<SqlConnection>();
      dbConnection = fac.Get(_dbContext);
    }

    protected string tryCatch(Action act) { try { act(); } catch (Exception e) { return e.Message; } return OperatonResult.Succeeded.ToString("F"); }

    internal string runSql(string sql) {
      return tryCatch(() => { var runner = new CommandRunner(dbConnection); runner.Transact(new DbCommand[] { runner.BuildCommand(sql, null) }); });
    }

    internal IEnumerable<dynamic> runSqlDynamic(string sql) {
      var runner = new CommandRunner(dbConnection); return runner.ExecuteDynamic(sql, null);
    }

    protected DbConnection dbConnection;
    protected DBContext dbContext;
    protected enum OperatonResult { Succeeded = 1, Failed = 0 };
  }
}

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using Store.Models;
using Store.Storage.Data;

namespace Store.Storage.SqlServer {
  public class Client {
    public Client(DBContext _dbContext) {
      var fac = new Factory<SqlConnection>();
      Func<DBContext, string> func = (DBContext _db) => _db.userId.Length == 0 || _db.password.Length == 0 ? string.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI;", _db.server, _db.database) : string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", _db.server, _db.database, _db.userId, _db.password);
      dbConnection = fac.Get(_dbContext, func);
    }

    protected string tryCatch(Action act) { try { act(); } catch (Exception e) { return e.Message; } return OperatonResult.Succeeded.ToString("F"); }

    public string runSql(string sql) {
      return tryCatch(() => { var runner = new CommandRunner(dbConnection); runner.Transact(new DbCommand[] { runner.BuildCommand(sql, null) }); });
    }

    public IEnumerable<dynamic> runSqlDynamic(string sql) {
      var runner = new CommandRunner(dbConnection); return runner.ExecuteDynamic(sql, null);
    }

    protected DbConnection dbConnection;
    protected DBContext dbContext;
    protected enum OperatonResult { Succeeded = 1, Failed = 0 };
  }
}

Update Store.SqlServer connection string constructor


using System;

using AppKit;
using Foundation;

namespace UselessExceptions
{
	public partial class ViewController : NSViewController
	{
		public ViewController (IntPtr handle) : base (handle)
		{
		}

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			// Do any additional setup after loading the view.
		}

		public override NSObject RepresentedObject {
			get {
				return base.RepresentedObject;
			}
			set {
				base.RepresentedObject = value;
				// Update the view, if already loaded.
			}
		}
	}
}

using System;

using AppKit;
using Foundation;

namespace UselessExceptions
{
	public partial class ViewController : NSViewController
	{
		public ViewController (IntPtr handle) : base (handle)
		{
		}

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			throw new Exception ("USELESS");

			// Do any additional setup after loading the view.
		}

		public override NSObject RepresentedObject {
			get {
				return base.RepresentedObject;
			}
			set {
				base.RepresentedObject = value;
				// Update the view, if already loaded.
			}
		}
	}
}

Add exception (only difference from default template)


/*
   Copyright 2014 Daniel Cazzulino

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0
*/

namespace OctoFlow
{
    using CLAP;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public class OutDirProvider : DefaultProvider
    {
        public override object GetDefault(VerbExecutionContext context)
        {
            var gitRoot = GitRepo.Find(".");
            if (string.IsNullOrEmpty(gitRoot))
                return new DirectoryInfo(".");

            return gitRoot;
        }

        public override string Description
        {
            get { return "git repo root or current dir"; }
        }
    }
}

/*
   Copyright 2014 Daniel Cazzulino

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0
*/

namespace OctoFlow
{
    using CLAP;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public class OutDirProvider : DefaultProvider
    {
        public override object GetDefault(VerbExecutionContext context)
        {
            var gitRoot = GitRepo.Find(".");
            if (string.IsNullOrEmpty(gitRoot))
                return new DirectoryInfo(".").FullName;

            return gitRoot;
        }

        public override string Description
        {
            get { return "git repo root or current dir"; }
        }
    }
}

Fix conversion bug in out dir provider

Fix conversion bug in out dir provider


using System;
using System.Linq;
using MilpManager.Abstraction;

namespace MilpManager.Implementation.CompositeConstraints
{
    public class SOS2Calculator : ICompositeConstraintCalculator
    {
        public IVariable Set(IMilpManager milpManager, CompositeConstraintType type, ICompositeConstraintParameters parameters,
            IVariable leftVariable, params IVariable[] rightVariable)
        {
            var zero = milpManager.FromConstant(0);
            var one = milpManager.FromConstant(1);

            var nonZeroes = new [] {leftVariable}.Concat(rightVariable).Select(v => v.Operation(OperationType.IsNotEqual, zero)).ToArray();
            var nonZeroPairs = nonZeroes.Zip(nonZeroes.Skip(1), Tuple.Create).Select(pair => pair.Item1.Operation(OperationType.Conjunction, pair.Item2)).ToArray();
            var nonZeroesCount = milpManager.Operation(OperationType.Addition, nonZeroes);
            milpManager.Set(
                ConstraintType.Equal,
                milpManager.Operation(
                    OperationType.Disjunction,
                    nonZeroesCount.Operation(OperationType.IsEqual, zero),
                    nonZeroesCount.Operation(OperationType.IsEqual, one),
                    milpManager.Operation(OperationType.Conjunction,
                        nonZeroesCount.Operation(OperationType.IsEqual, milpManager.FromConstant(2)),
                        milpManager.Operation(OperationType.Addition, nonZeroPairs).Operation(OperationType.IsEqual, one)
                    )
                ),
                one
            );

            return leftVariable;
        }
    }
}

using System;
using System.Linq;
using MilpManager.Abstraction;

namespace MilpManager.Implementation.CompositeConstraints
{
    public class SOS2Calculator : ICompositeConstraintCalculator
    {
        public IVariable Set(IMilpManager milpManager, CompositeConstraintType type, ICompositeConstraintParameters parameters,
            IVariable leftVariable, params IVariable[] rightVariable)
        {
            var zero = milpManager.FromConstant(0);
            var one = milpManager.FromConstant(1);

            var nonZeroes = new [] {leftVariable}.Concat(rightVariable).Select(v => v.Operation(OperationType.IsNotEqual, zero)).ToArray();
            var nonZeroPairs = nonZeroes.Zip(nonZeroes.Skip(1), Tuple.Create).Select(pair => pair.Item1.Operation(OperationType.Conjunction, pair.Item2)).ToArray();
            if (!nonZeroPairs.Any())
            {
                nonZeroPairs = new[] {milpManager.FromConstant(0)};
            }
            var nonZeroesCount = milpManager.Operation(OperationType.Addition, nonZeroes);
            milpManager.Set(
                ConstraintType.Equal,
                milpManager.Operation(
                    OperationType.Disjunction,
                    nonZeroesCount.Operation(OperationType.IsEqual, zero),
                    nonZeroesCount.Operation(OperationType.IsEqual, one),
                    milpManager.Operation(OperationType.Conjunction,
                        nonZeroesCount.Operation(OperationType.IsEqual, milpManager.FromConstant(2)),
                        milpManager.Operation(OperationType.Addition, nonZeroPairs).Operation(OperationType.IsEqual, one)
                    )
                ),
                one
            );

            return leftVariable;
        }
    }
}

Fix for SOS2 calculator (for one element in array).


using System;

namespace Evolve.Test.Utilities
{
    public class CassandraDockerContainer
    {
        private DockerContainer _container;

        public string Id => _container.Id;
        public string ExposedPort => "9042";
        public string HostPort => "9042";
        public string ClusterName => "evolve";
        public string DataCenter => "dc1";
        public TimeSpan DelayAfterStartup => TimeSpan.FromSeconds(45);

        public bool Start(bool fromScratch = false)
        {
            _container = new DockerContainerBuilder(new DockerContainerBuilderOptions
            {
                FromImage = "cassandra",
                Tag = "latest",
                Name = "cassandra-evolve",
                Env = new[] { $"CASSANDRA_CLUSTER_NAME={ClusterName}", $"CASSANDRA_DC={DataCenter}", "CASSANDRA_RACK=rack1" },
                ExposedPort = $"{ExposedPort}/tcp",
                HostPort = HostPort,
                DelayAfterStartup = DelayAfterStartup,
                RemovePreviousContainer = fromScratch
            }).Build();

            return _container.Start();
        }
        public void Remove() => _container.Remove();
        public bool Stop() => _container.Stop();
        public void Dispose() => _container?.Dispose();
    }
}

using System;

namespace Evolve.Test.Utilities
{
    public class CassandraDockerContainer
    {
        private DockerContainer _container;

        public string Id => _container.Id;
        public string ExposedPort => "9042";
        public string HostPort => "9042";
        public string ClusterName => "evolve";
        public string DataCenter => "dc1";
        public TimeSpan DelayAfterStartup => TimeSpan.FromMinutes(1);

        public bool Start(bool fromScratch = false)
        {
            _container = new DockerContainerBuilder(new DockerContainerBuilderOptions
            {
                FromImage = "cassandra",
                Tag = "latest",
                Name = "cassandra-evolve",
                Env = new[] { $"CASSANDRA_CLUSTER_NAME={ClusterName}", $"CASSANDRA_DC={DataCenter}", "CASSANDRA_RACK=rack1" },
                ExposedPort = $"{ExposedPort}/tcp",
                HostPort = HostPort,
                DelayAfterStartup = DelayAfterStartup,
                RemovePreviousContainer = fromScratch
            }).Build();

            return _container.Start();
        }
        public void Remove() => _container.Remove();
        public bool Stop() => _container.Stop();
        public void Dispose() => _container?.Dispose();
    }
}

Increase Cassandra delay after startup

Increase Cassandra delay after startup


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

using Borodar.ReorderableList;
using UnityEditor;

namespace Borodar.RainbowFolders.Editor.Settings
{
    [CustomEditor(typeof (RainbowFoldersSettings))]
    public class RainbowFoldersSettingsEditor : UnityEditor.Editor
    {
        private const string PROP_NAME_FOLDERS = "Folders";

        private SerializedProperty _foldersProperty;

        protected void OnEnable()
        {
            _foldersProperty = serializedObject.FindProperty(PROP_NAME_FOLDERS);
        }

        public override void OnInspectorGUI()
        {
            EditorGUILayout.HelpBox("Please set your custom folder icons by specifying:\n\n" +
                                    "- Folder Name\n" +
                                    "Icon will be applied to all folders with the same name\n\n" +
                                    "- Folder Path\n" +
                                    "Icon will be applied to a single folder. The path format: Assets/SomeFolder/YourFolder", MessageType.Info);

            serializedObject.Update();
            ReorderableListGUI.Title("Rainbow Folders");
            ReorderableListGUI.ListField(_foldersProperty);
            serializedObject.ApplyModifiedProperties();
        }

    }
}

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

using Borodar.ReorderableList;
using UnityEditor;

namespace Borodar.RainbowFolders.Editor.Settings
{
    [CustomEditor(typeof (RainbowFoldersSettings))]
    public class RainbowFoldersSettingsEditor : UnityEditor.Editor
    {
        private const string PROP_NAME_FOLDERS = "Folders";

        private SerializedProperty _foldersProperty;

        protected void OnEnable()
        {
            _foldersProperty = serializedObject.FindProperty(PROP_NAME_FOLDERS);
        }

        public override void OnInspectorGUI()
        {
            serializedObject.Update();
            ReorderableListGUI.Title("Rainbow Folders");
            ReorderableListGUI.ListField(_foldersProperty);
            serializedObject.ApplyModifiedProperties();
        }

    }
}

Remove help box from the folders settings list


namespace Xamarin.Forms.OAuth.Providers
{
    public sealed class TrelloOAuthProvider : OAuthProvider
    {
        private const string _redirectUrl = "https://trelloResponse.com";
        public TrelloOAuthProvider(string clientId, string clientSecret, params string[] scopes)
            : base(new OAuthProviderDefinition(
                "Trello",
                "https://trello.com/1/authorize",
                "https://trello.com/1/OAuthGetAccessToken",
                "https://api.trello.com/1/members/me",
                clientId,
                clientSecret,
                _redirectUrl,
                scopes)
            {
                RequiresCode = true,
            })
        { }

        internal override string GetAuthorizationUrl()
        {
            return base.GetAuthorizationUrl();
        }
    }
}

using System.Collections.Generic;

namespace Xamarin.Forms.OAuth.Providers
{
    public sealed class TrelloOAuthProvider : OAuthProvider
    {
        private const string _redirectUrl = "https://trelloResponse.com";
        public TrelloOAuthProvider(string clientId, string clientSecret, params string[] scopes)
            : base(new OAuthProviderDefinition(
                "Trello",
                "https://trello.com/1/authorize",
                "https://trello.com/1/OAuthGetAccessToken",
                "https://api.trello.com/1/members/me",
                clientId,
                clientSecret,
                _redirectUrl,
                scopes)
            {
                RequiresCode = true,
            })
        { }

        internal override string GetAuthorizationUrl()
        {
            return BuildUrl(Definition.AuthorizeUrl, new KeyValuePair<string, string>[] { });
        }
    }
}

Add Trello provider (not yet working)

Add Trello provider (not yet working)


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

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using System.IO;

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

namespace test
{
    public class Function
    {
        public string FunctionHandler(Stream stream, ILambdaContext context)
        {
            context.Logger.Log("Log Hello world");
            return "Hallo world!";
        }
    }
}

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

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

using Amazon.Lambda.Core;

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

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

Add input event to dotnetcore2.0 example function


using System;
using System.Text;
using System.Security.Cryptography;

namespace Gibe.DittoProcessors.Processors
{
	public class StringToMd5HashAttribute : TestableDittoProcessorAttribute
	{
		public override object ProcessValue()
		{
			if (Value == null) throw new NullReferenceException();

			var stringValue = Value as string;

			// byte array representation of that string
			byte[] encodedValue = new UTF8Encoding().GetBytes(stringValue);

			// need MD5 to calculate the hash
			byte[] hashValue = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedValue);

			// string representation (similar to UNIX format)
			return BitConverter.ToString(hashValue).Replace("-", string.Empty).ToLower();
		}
	}
}

using System;
using System.Text;
using System.Security.Cryptography;

namespace Gibe.DittoProcessors.Processors
{
	public class StringToMd5HashAttribute : TestableDittoProcessorAttribute
	{
		public override object ProcessValue()
		{
			if (Value == null) throw new NullReferenceException();

			var stringValue = Value as string;

			byte[] encodedValue = new UTF8Encoding().GetBytes(stringValue);

			byte[] hashValue = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedValue);

			// string representation (similar to UNIX format)
			return BitConverter.ToString(hashValue).Replace("-", string.Empty).ToLower();
		}
	}
}

Update to MD5 hash PR.

Update to MD5 hash PR.


#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

[assembly: global::Android.Runtime.ResourceDesignerAttribute("Csla.Axml.Resource", IsApplication=false)]

namespace Csla.Axml
{

	[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "12.1.0.10")]
	public partial class Resource
	{

		static Resource()
		{
			global::Android.Runtime.ResourceIdManager.UpdateIdValues();
		}

		public partial class Attribute
		{

			static Attribute()
			{
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
			}

			private Attribute()
			{
			}
		}

		public partial class String
		{

			// aapt resource value: 0x7F010000
			public static int ApplicationName = 2130771968;

			static String()
			{
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
			}

			private String()
			{
			}
		}
	}
}
#pragma warning restore 1591

#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

[assembly: global::Android.Runtime.ResourceDesignerAttribute("Csla.Axml.Resource", IsApplication=false)]

namespace Csla.Axml
{

	[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "12.1.0.11")]
	public partial class Resource
	{

		static Resource()
		{
			global::Android.Runtime.ResourceIdManager.UpdateIdValues();
		}

		public partial class Attribute
		{

			static Attribute()
			{
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
			}

			private Attribute()
			{
			}
		}

		public partial class String
		{

			// aapt resource value: 0x7F010000
			public static int ApplicationName = 2130771968;

			static String()
			{
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
			}

			private String()
			{
			}
		}
	}
}
#pragma warning restore 1591

Update for .NET 6 rc2

Update for .NET 6 rc2


/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/

using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;

namespace ShiftDrive {

    /// <summary>
    /// A simple static container, for holding game assets like textures and meshes.
    /// </summary>
    internal static class Assets {

        public static SpriteFont
            fontDefault,
            fontBold;

        public static readonly Dictionary<string, Texture2D>
            textures = new Dictionary<string, Texture2D>();

        public static Model
            mdlSkybox;

        public static Effect
            fxUnlit;

        public static SoundEffect
            sndUIConfirm,
            sndUICancel,
            sndUIAppear1,
            sndUIAppear2,
            sndUIAppear3,
            sndUIAppear4;

        public static Texture2D GetTexture(string name) {
            if (!textures.ContainsKey(name.ToLowerInvariant()))
                throw new KeyNotFoundException($"Texture '{name}' was not found.");
            return textures[name.ToLowerInvariant()];
        }

    }

}

/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/

using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;

namespace ShiftDrive {

    /// <summary>
    /// A simple static container, for holding game assets like textures and meshes.
    /// </summary>
    internal static class Assets {

        public static SpriteFont
            fontDefault,
            fontBold;

        public static readonly Dictionary<string, Texture2D>
            textures = new Dictionary<string, Texture2D>();

        public static readonly Dictionary<string, SpriteSheet>
            sprites = new Dictionary<string, SpriteSheet>();

        public static Model
            mdlSkybox;

        public static Effect
            fxUnlit;

        public static SoundEffect
            sndUIConfirm,
            sndUICancel,
            sndUIAppear1,
            sndUIAppear2,
            sndUIAppear3,
            sndUIAppear4;

        public static Texture2D GetTexture(string name) {
            if (!textures.ContainsKey(name.ToLowerInvariant()))
                throw new KeyNotFoundException($"Texture '{name}' was not found.");
            return textures[name.ToLowerInvariant()];
        }

        public static SpriteSheet GetSprite(string name) {
            if (!sprites.ContainsKey(name.ToLowerInvariant()))
                throw new KeyNotFoundException($"Sprite '{name}' was not found.");
            return sprites[name.ToLowerInvariant()];
        }

    }

}

Add container for sprite sheet prototypes


// Copyright (c) 2016 Nicolas Musset. All rights reserved.
// This file is licensed under the MIT license.
// See the LICENSE.md file in the project root for more information.

using Markdig.Syntax;

namespace Markdig.Renderers.Xaml
{
    /// <summary>
    /// A XAML renderer for a <see cref="QuoteBlock"/>.
    /// </summary>
    /// <seealso cref="Xaml.XamlObjectRenderer{T}" />
    public class QuoteBlockRenderer : XamlObjectRenderer<QuoteBlock>
    {
        protected override void Write(XamlRenderer renderer, QuoteBlock obj)
        {
            renderer.EnsureLine();

            // TODO: apply quote block styling
            renderer.Write("<Paragraph>");
            renderer.WriteChildren(obj);
            renderer.WriteLine("</Paragraph>");
        }
    }
}

// Copyright (c) 2016 Nicolas Musset. All rights reserved.
// This file is licensed under the MIT license.
// See the LICENSE.md file in the project root for more information.

using Markdig.Syntax;

namespace Markdig.Renderers.Xaml
{
    /// <summary>
    /// A XAML renderer for a <see cref="QuoteBlock"/>.
    /// </summary>
    /// <seealso cref="Xaml.XamlObjectRenderer{T}" />
    public class QuoteBlockRenderer : XamlObjectRenderer<QuoteBlock>
    {
        protected override void Write(XamlRenderer renderer, QuoteBlock obj)
        {
            renderer.EnsureLine();

            // TODO: apply quote block styling
            renderer.Write("<Section>");
            renderer.WriteChildren(obj);
            renderer.WriteLine("</Section>");
        }
    }
}

[Markdig.Xaml] Use Section instead of Paragraph for quote blocks.


namespace OpcMockTests
{
    internal class OpcMockProtocol
    {
    }
}

using System;
using System.Collections.Generic;

namespace OpcMock
{
    public class OpcMockProtocol
    {
        private List<ProtocolLine> lines;

        public OpcMockProtocol()
        {
            lines = new List<ProtocolLine>();
        }

        public List<ProtocolLine> Lines
        {
            get{ return lines; }
        }

        public void Append(ProtocolLine protocolLine)
        {
            lines.Add(protocolLine);
        }
    }
}

Introduce a Protocol class for better encapsulation


using System;
using System.Collections.Generic;
using System.Text;
using GraphQL.Types;
using Snowflake.Model.Game.LibraryExtensions;

namespace Snowflake.Support.Remoting.GraphQL.Types.Model
{
    public class GameFileExtensionGraphType : ObjectGraphType<IGameFileExtension>
    {
        public GameFileExtensionGraphType()
        {
            Name = "GameFiles";
            Description = "The files of a game";

            Field<FileRecordGraphType>("files",
                description: "The files for which have metadata and are installed, not all files.",
                resolve: context => context.Source.Files);

            Field<ListGraphType<FileGraphType>>("programFiles",
                description: "The files for which have metadata and are installed ",
                arguments: new QueryArguments(new QueryArgument<BooleanGraphType>
                    {Name = "recursive", DefaultValue = false,}),
                resolve: context => context.GetArgument("recursive", false)
                    ? context.Source.ProgramRoot.EnumerateFilesRecursive()
                    : context.Source.ProgramRoot.EnumerateFiles());
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using GraphQL.Types;
using Snowflake.Model.Game.LibraryExtensions;

namespace Snowflake.Support.Remoting.GraphQL.Types.Model
{
    public class GameFileExtensionGraphType : ObjectGraphType<IGameFileExtension>
    {
        public GameFileExtensionGraphType()
        {
            Name = "GameFiles";
            Description = "The files of a game";

            Field<ListGraphType<FileRecordGraphType>>("fileRecords",
                description: "The files for which have metadata and are installed, not all files.",
                resolve: context => context.Source.Files);

            Field<ListGraphType<FileGraphType>>("programFiles",
                description: "All files inside the program files folder for this game.",
                arguments: new QueryArguments(new QueryArgument<BooleanGraphType>
                    {Name = "recursive", DefaultValue = false,}),
                resolve: context => context.GetArgument("recursive", false)
                    ? context.Source.ProgramRoot.EnumerateFilesRecursive()
                    : context.Source.ProgramRoot.EnumerateFiles());
        }
    }
}

Fix Record Graph Type Query

Fix Record Graph Type Query


using Autofac;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using NuGet.Lucene.Web;
using NuGet.Lucene.Web.Formatters;
using Owin;

namespace Klondike.SelfHost
{
    class SelfHostStartup : Klondike.Startup
    {
        private readonly SelfHostSettings selfHostSettings;

        public SelfHostStartup(SelfHostSettings selfHostSettings)
        {
            this.selfHostSettings = selfHostSettings;
        }

        protected override string MapPath(string virtualPath)
        {
            return selfHostSettings.MapPath(virtualPath);
        }

        protected override INuGetWebApiSettings CreateSettings()
        {
            return selfHostSettings;
        }

        protected override NuGetHtmlMicrodataFormatter CreateMicrodataFormatter()
        {
            return new NuGetHtmlMicrodataFormatter();
        }

        protected override void Start(IAppBuilder app, IContainer container)
        {
            var fileServerOptions = new FileServerOptions
            {
                FileSystem = new PhysicalFileSystem(selfHostSettings.BaseDirectory),
                EnableDefaultFiles = true,
            };
            fileServerOptions.DefaultFilesOptions.DefaultFileNames = new[] {"index.html"};
            app.UseFileServer(fileServerOptions);

            base.Start(app, container);
        }
    }
}

using Autofac;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using NuGet.Lucene.Web;
using NuGet.Lucene.Web.Formatters;
using Owin;

namespace Klondike.SelfHost
{
    class SelfHostStartup : Klondike.Startup
    {
        private readonly SelfHostSettings selfHostSettings;

        public SelfHostStartup(SelfHostSettings selfHostSettings)
        {
            this.selfHostSettings = selfHostSettings;
        }

        protected override string MapPath(string virtualPath)
        {
            return selfHostSettings.MapPath(virtualPath);
        }

        protected override INuGetWebApiSettings CreateSettings()
        {
            return selfHostSettings;
        }

        protected override NuGetHtmlMicrodataFormatter CreateMicrodataFormatter()
        {
            return new NuGetHtmlMicrodataFormatter();
        }

        protected override void Start(IAppBuilder app, IContainer container)
        {
            base.Start(app, container);

            var fileServerOptions = new FileServerOptions
            {
                FileSystem = new PhysicalFileSystem(selfHostSettings.BaseDirectory),
                EnableDefaultFiles = true,
            };
            fileServerOptions.DefaultFilesOptions.DefaultFileNames = new[] {"index.html"};
            app.UseFileServer(fileServerOptions);
        }
    }
}

Change order of OWIN handlers so static file handler does not preempt NuGet client redirect handler.


using System;

namespace Konsola.Parser
{
	/// <summary>
	/// Configures the options when parsing args and binding them to a context.
	/// </summary>
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	public class ContextOptionsAttribute : Attribute
	{
		/// <summary>
		/// Gets or sets the program's description.
		/// </summary>
		public string Description { get; set; }

		/// <summary>
		/// Gets or sets a value indicating whether to invoke the special methods after parsing.
		/// </summary>
		public bool InvokeMethods { get; set; }
	}
}

using System;

namespace Konsola.Parser
{
	/// <summary>
	/// Configures the options when parsing args and binding them to a context.
	/// </summary>
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	public class ContextOptionsAttribute : Attribute
	{
		/// <summary>
		/// Gets or sets the program's description.
		/// </summary>
		public string Description { get; set; }

		/// <summary>
		/// Gets or sets a value indicating whether to handle empty program invocations as help.
		/// </summary>
		public bool HandleEmptyInvocationAsHelp { get; set; }

		/// <summary>
		/// Gets or sets a value indicating whether to invoke the special methods after parsing.
		/// </summary>
		public bool InvokeMethods { get; set; }
	}
}

Add an option to enable handling of help on empty invocations


using System;
using System.Collections.Generic;
using System.Windows.Data;

namespace NuGet.Dialog.PackageManagerUI
{

    public class StringCollectionsToStringConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (targetType == typeof(string))
            {

                string stringValue = value as string;
                if (stringValue != null)
                {
                    return stringValue;
                }
                else
                {
                    IEnumerable<string> parts = (IEnumerable<string>)value;
                    return String.Join(", ", parts);
                }
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Windows.Data;

namespace NuGet.Dialog.PackageManagerUI
{
    public class StringCollectionsToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (targetType == typeof(string))
            {
                string stringValue = value as string;
                if (stringValue != null)
                {
                    return stringValue;
                }
                else if (value == null)
                {
                    return String.Empty;
                }
                {
                    IEnumerable<string> parts = (IEnumerable<string>)value;
                    return String.Join(", ", parts);
                }
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

Add a safety check for when Authors is null, which shouldn't happen in the first place. Work items: 1727, 1728

--HG--
branch : 1.6


using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace Dangl.WebDocumentation.Models
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions options) : base(options) { }

        public DbSet<DocumentationProject> DocumentationProjects { get; set; }

        public DbSet<UserProjectAccess> UserProjects { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            // Make the Name unique so it can be used as a single identifier for a project ( -> Urls may contain the project name instead of the Guid)
            builder.Entity<DocumentationProject>()
                .HasIndex(Entity => Entity.Name)
                .IsUnique();

            // Make the ApiKey unique so it can be used as a single identifier for a project
            builder.Entity<DocumentationProject>()
                .HasIndex(Entity => Entity.ApiKey)
                .IsUnique();

            // Composite key for UserProject Access
            builder.Entity<UserProjectAccess>()
                .HasKey(Entity => new {Entity.ProjectId, Entity.UserId});

            builder.Entity<UserProjectAccess>()
                .HasOne(Entity => Entity.Project)
                .WithMany(Project => Project.UserAccess)
                .OnDelete(DeleteBehavior.Cascade);
        }
    }
}

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

namespace Dangl.WebDocumentation.Models
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions options) : base(options) { }

        public DbSet<DocumentationProject> DocumentationProjects { get; set; }

        public DbSet<UserProjectAccess> UserProjects { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            foreach (var entity in builder.Model.GetEntityTypes())
            {
                entity.Relational().TableName = entity.DisplayName();
            }

            base.OnModelCreating(builder);

            // Make the Name unique so it can be used as a single identifier for a project ( -> Urls may contain the project name instead of the Guid)
            builder.Entity<DocumentationProject>()
                .HasIndex(Entity => Entity.Name)
                .IsUnique();

            // Make the ApiKey unique so it can be used as a single identifier for a project
            builder.Entity<DocumentationProject>()
                .HasIndex(Entity => Entity.ApiKey)
                .IsUnique();

            // Composite key for UserProject Access
            builder.Entity<UserProjectAccess>()
                .HasKey(Entity => new {Entity.ProjectId, Entity.UserId});

            builder.Entity<UserProjectAccess>()
                .HasOne(Entity => Entity.Project)
                .WithMany(Project => Project.UserAccess)
                .OnDelete(DeleteBehavior.Cascade);
        }
    }
}

Change ModelBuilder to use old EntityFrameworkCore RC1 naming conventions


using System.Web.Http;
using Newtonsoft.Json;

namespace WebApiTestApplication.Controllers
{
    public class MegaClass : AnotherClass
    {
        public int Something { get; set; }
    }

    public class Chain1<T1, T2>
    {
        public T1 Value11 { get; set; }
        public T2 Value12 { get; set; }
    }

    public class Chain2<TValue> : Chain1<TValue, int>
    {
        public TValue Value2 { get; set; }
    }

    public class Chain3 : Chain2<MegaClass>
    {
        public object Value3 { get; set; }
    }

    [RoutePrefix("api/thingy")]
    public class ThingyController : ApiController
    {
        [HttpGet]
        [Route("")]
        public string GetAll()
        {
            return $"values";
        }

        [HttpGet]
        [Route("{id}")]
        public string Get(int? id, string x, [FromUri]MegaClass c)
        {
            var valueJson = JsonConvert.SerializeObject(c);
            return $"value {id} {x} {valueJson}";
        }

        [HttpGet]
        [Route("")]
        public string Getty(string x, int y)
        {
            return $"value {x} {y}";
        }

        [HttpPost]
        [Route("")]
        public string Post(MegaClass value)
        {
            var valueJson = JsonConvert.SerializeObject(value);
            return $"thanks for the {valueJson} in the ace!";
        }
    }
}

using System.Web.Http;
using Newtonsoft.Json;

namespace WebApiTestApplication.Controllers
{
    public class MegaClass : AnotherClass
    {
        public int Something { get; set; }
    }

    public class Chain1<T>
    {
        public T Value { get; set; }
    }

    public class Chain1<T1, T2>
    {
        public T1 Value11 { get; set; }
        public T2 Value12 { get; set; }
    }

    public class Chain2<TValue> : Chain1<TValue, int>
    {
        public TValue Value2 { get; set; }
    }

    public class Chain3 : Chain2<MegaClass>
    {
        public object Value3 { get; set; }
    }

    [RoutePrefix("api/thingy")]
    public class ThingyController : ApiController
    {
        [HttpGet]
        [Route("")]
        public string GetAll()
        {
            return $"values";
        }

        [HttpGet]
        [Route("{id}")]
        public string Get(int? id, string x, [FromUri]MegaClass c)
        {
            var valueJson = JsonConvert.SerializeObject(c);
            return $"value {id} {x} {valueJson}";
        }

        [HttpGet]
        [Route("")]
        public string Getty(string x, int y)
        {
            return $"value {x} {y}";
        }

        [HttpPost]
        [Route("")]
        public string Post(MegaClass value)
        {
            var valueJson = JsonConvert.SerializeObject(value);
            return $"thanks for the {valueJson} in the ace!";
        }
    }
}

Add test for generic name collision on frontend


// -----------------------------------------------------------------------
// <copyright file="GeometryImpl.cs" company="Steven Kirk">
// Copyright 2014 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------

namespace Perspex.Direct2D1.Media
{
    using Perspex.Platform;
    using SharpDX.Direct2D1;
    using Splat;

    public abstract class GeometryImpl : IGeometryImpl
    {
        private TransformedGeometry transformed;

        public abstract Rect Bounds
        {
            get;
        }

        public abstract Geometry DefiningGeometry
        {
            get;
        }

        public Geometry Geometry
        {
            get { return this.transformed ?? this.DefiningGeometry; }
        }

        public Matrix Transform
        {
            get
            {
                return this.transformed != null ?
                    this.transformed.Transform.ToPerspex() :
                    Matrix.Identity;
            }

            set
            {
                if (value != this.Transform)
                {
                    if (this.transformed != null)
                    {
                        this.transformed.Dispose();
                    }

                    if (!value.IsIdentity)
                    {
                        Factory factory = Locator.Current.GetService<Factory>();
                        this.transformed = new TransformedGeometry(
                            factory,
                            this.DefiningGeometry,
                            value.ToDirect2D());
                    }
                }
            }
        }

        public abstract Rect GetRenderBounds(double strokeThickness);
    }
}

// -----------------------------------------------------------------------
// <copyright file="GeometryImpl.cs" company="Steven Kirk">
// Copyright 2014 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------

namespace Perspex.Direct2D1.Media
{
    using Perspex.Platform;
    using SharpDX.Direct2D1;
    using Splat;

    public abstract class GeometryImpl : IGeometryImpl
    {
        private TransformedGeometry transformed;

        public abstract Rect Bounds
        {
            get;
        }

        public abstract Geometry DefiningGeometry
        {
            get;
        }

        public Geometry Geometry
        {
            get { return this.transformed ?? this.DefiningGeometry; }
        }

        public Matrix Transform
        {
            get
            {
                return this.transformed != null ?
                    this.transformed.Transform.ToPerspex() :
                    Matrix.Identity;
            }

            set
            {
                if (value != this.Transform)
                {
                    if (this.transformed != null)
                    {
                        this.transformed.Dispose();
                        this.transformed = null;
                    }

                    if (!value.IsIdentity)
                    {
                        Factory factory = Locator.Current.GetService<Factory>();
                        this.transformed = new TransformedGeometry(
                            factory,
                            this.DefiningGeometry,
                            value.ToDirect2D());
                    }
                }
            }
        }

        public abstract Rect GetRenderBounds(double strokeThickness);
    }
}

Fix potential reference after dispose.

Fix potential reference after dispose.


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

namespace WindowsAzure.Table.Extensions
{
    internal static class TypeExtentions
    {
        private static readonly HashSet<Type> _supportedEntityPropertyTypes = new HashSet<Type>
        {
            typeof(long),
            typeof(int),
            typeof(Guid),
            typeof(double),
            typeof(string),
            typeof(bool),
            typeof(DateTime),
            typeof(DateTimeOffset),
            typeof(byte[]),
        };

        public static bool IsSupportedEntityPropertyType(this Type type)
        {
            if (type.GetTypeInfo().IsEnum)
            {
                return _supportedEntityPropertyTypes.Contains(type);
            }

            return _supportedEntityPropertyTypes.Contains(type)
                || _supportedEntityPropertyTypes.Contains(Nullable.GetUnderlyingType(type));
        }
    }
}

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

namespace WindowsAzure.Table.Extensions
{
    internal static class TypeExtentions
    {
        private static readonly HashSet<Type> _supportedEntityPropertyTypes = new HashSet<Type>
        {
            typeof(long),
            typeof(int),
            typeof(Guid),
            typeof(double),
            typeof(string),
            typeof(bool),
            typeof(DateTime),
            typeof(DateTimeOffset),
            typeof(byte[]),
        };

        public static bool IsSupportedEntityPropertyType(this Type type)
        {
            if (type.GetTypeInfo().IsEnum)
            {
                return _supportedEntityPropertyTypes.Contains(Enum.GetUnderlyingType(type));
            }

            return _supportedEntityPropertyTypes.Contains(type)
                || _supportedEntityPropertyTypes.Contains(Nullable.GetUnderlyingType(type));
        }
    }
}

Fix supported enum check in type extentions.


using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Metadata.Utils;
using JetBrains.ReSharper.Psi.ExtensionsAPI.ExternalAnnotations;
using JetBrains.TestFramework.Utils;
using JetBrains.Util;

namespace JetBrains.ReSharper.Plugins.Unity.Tests
{
    [ShellComponent]
    public class AnnotationsLoader : IExternalAnnotationsFileProvider
    {
        private readonly OneToSetMap<string, FileSystemPath> myAnnotations;

        public AnnotationsLoader()
        {
            myAnnotations = new OneToSetMap<string, FileSystemPath>(StringComparer.OrdinalIgnoreCase);
            var testDataPathBase = TestUtil.GetTestDataPathBase(GetType().Assembly);
            var annotationsPath = testDataPathBase.Parent.Parent / "src" / "resharper-unity" / "annotations";
            Assertion.Assert(annotationsPath.ExistsDirectory, $"Cannot find annotations: {annotationsPath}");
            var annotationFiles = annotationsPath.GetChildFiles();
            foreach (var annotationFile in annotationFiles)
            {
                myAnnotations.Add(annotationFile.NameWithoutExtension, annotationFile);
            }
        }

        public IEnumerable<FileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, FileSystemPath assemblyLocation = null)
        {
            if (assemblyName == null)
                return myAnnotations.Values;
            return myAnnotations[assemblyName.Name];
        }
    }
}

using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Metadata.Utils;
using JetBrains.ReSharper.Psi.ExtensionsAPI.ExternalAnnotations;
using JetBrains.TestFramework.Utils;
using JetBrains.Util;

namespace JetBrains.ReSharper.Plugins.Unity.Tests
{
    [ShellComponent]
    public class AnnotationsLoader : IExternalAnnotationsFileProvider
    {
        private readonly OneToSetMap<string, FileSystemPath> myAnnotations;

        public AnnotationsLoader()
        {
            myAnnotations = new OneToSetMap<string, FileSystemPath>(StringComparer.OrdinalIgnoreCase);
            var testDataPathBase = TestUtil.GetTestDataPathBase(GetType().Assembly);
            var annotationsPath = testDataPathBase.Parent.Parent / "src" / "annotations";
            Assertion.Assert(annotationsPath.ExistsDirectory, $"Cannot find annotations: {annotationsPath}");
            var annotationFiles = annotationsPath.GetChildFiles();
            foreach (var annotationFile in annotationFiles)
            {
                myAnnotations.Add(annotationFile.NameWithoutExtension, annotationFile);
            }
        }

        public IEnumerable<FileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, FileSystemPath assemblyLocation = null)
        {
            if (assemblyName == null)
                return myAnnotations.Values;
            return myAnnotations[assemblyName.Name];
        }
    }
}

Fix annotations loader for tests

Fix annotations loader for tests


using System.Collections.Generic;
using System.Linq;
using Thinktecture.IdentityServer.Core;
using Thinktecture.IdentityServer.Core.Models;

namespace Thinktecture.IdentityServer.Host.Config
{
    public class Scopes
    {
        public static IEnumerable<Scope> Get()
        {
            return new[]
                {
                    Scope.OpenId,
                    Scope.Profile,
                    Scope.Email,
                    Scope.OfflineAccess,

                    new Scope
                    {
                        Name = "roles",
                        DisplayName = "Roles",
                        Type = ScopeType.Identity,
                        Claims = new[]
                        {
                            new ScopeClaim("role")
                        }
                    },

                    new Scope
                    {
                        Name = "read",
                        DisplayName = "Read data",
                        Type = ScopeType.Resource,
                        Emphasize = false,
                    },
                    new Scope
                    {
                        Name = "write",
                        DisplayName = "Write data",
                        Type = ScopeType.Resource,
                        Emphasize = true,
                    },
                    new Scope
                    {
                        Name = "idmgr",
                        DisplayName = "IdentityManager",
                        Type = ScopeType.Resource,
                        Emphasize = true,
                        Claims = new List<ScopeClaim>
                        {
                            new ScopeClaim("name"),
                            new ScopeClaim("role")
                        }
                    }
                };
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using Thinktecture.IdentityServer.Core;
using Thinktecture.IdentityServer.Core.Models;

namespace Thinktecture.IdentityServer.Host.Config
{
    public class Scopes
    {
        public static IEnumerable<Scope> Get()
        {
            return new[]
                {
                    Scope.OpenId,
                    Scope.Profile,
                    Scope.Email,
                    Scope.OfflineAccess,

                    new Scope
                    {
                        Name = "roles",
                        DisplayName = "Roles",
                        Description = "Your organizational roles",
                        Type = ScopeType.Identity,
                        Claims = new[]
                        {
                            new ScopeClaim("role")
                        }
                    },

                    new Scope
                    {
                        Name = "read",
                        DisplayName = "Read data",
                        Type = ScopeType.Resource,
                        Emphasize = false,
                    },
                    new Scope
                    {
                        Name = "write",
                        DisplayName = "Write data",
                        Type = ScopeType.Resource,
                        Emphasize = true,
                    },
                    new Scope
                    {
                        Name = "idmgr",
                        DisplayName = "IdentityManager",
                        Type = ScopeType.Resource,
                        Emphasize = true,
                        Claims = new List<ScopeClaim>
                        {
                            new ScopeClaim("name"),
                            new ScopeClaim("role")
                        }
                    }
                };
        }
    }
}

Add description for roles scope

Add description for roles scope


public class BuildVersion
{
    public GitVersion GitVersion { get; private set; }
    public string Version { get; private set; }
    public string Milestone { get; private set; }
    public string SemVersion { get; private set; }
    public string GemVersion { get; private set; }
    public string VsixVersion { get; private set; }

    public static BuildVersion Calculate(ICakeContext context, BuildParameters parameters, GitVersion gitVersion)
    {
        var version = gitVersion.MajorMinorPatch;
        var semVersion = gitVersion.LegacySemVer;
        var vsixVersion = gitVersion.MajorMinorPatch;

        if (!string.IsNullOrWhiteSpace(gitVersion.BuildMetaData)) {
            semVersion += "." + gitVersion.BuildMetaData;
            vsixVersion += "." + DateTime.UtcNow.ToString("yyMMddHH");
        }

        return new BuildVersion
        {
            GitVersion = gitVersion,
            Milestone  = version,
            Version    = version,
            SemVersion = semVersion,
            GemVersion = semVersion.Replace("-", "."),
            VsixVersion = vsixVersion,
        };
    }
}

public class BuildVersion
{
    public GitVersion GitVersion { get; private set; }
    public string Version { get; private set; }
    public string Milestone { get; private set; }
    public string SemVersion { get; private set; }
    public string GemVersion { get; private set; }
    public string VsixVersion { get; private set; }

    public static BuildVersion Calculate(ICakeContext context, BuildParameters parameters, GitVersion gitVersion)
    {
        var version = gitVersion.MajorMinorPatch;
        var semVersion = gitVersion.LegacySemVer;
        var vsixVersion = gitVersion.MajorMinorPatch;

        if (!string.IsNullOrWhiteSpace(gitVersion.BuildMetaData)) {
            semVersion += "-" + gitVersion.BuildMetaData;
            vsixVersion += "." + DateTime.UtcNow.ToString("yyMMddHH");
        }

        return new BuildVersion
        {
            GitVersion = gitVersion,
            Milestone  = version,
            Version    = version,
            SemVersion = semVersion,
            GemVersion = semVersion.Replace("-", "."),
            VsixVersion = vsixVersion,
        };
    }
}

Revert "Use dot instead of dash to separate build metadata"

This reverts commit 9567abb6ce15b29cc59ab36c0172d31aa9c661fe.


using System.Linq;
using System.Threading.Tasks;
using Bugsnag.Payload;
using Xunit;

namespace Bugsnag.Tests.Payload
{
  public class ExceptionTests
  {
    [Fact]
    public void CorrectNumberOfExceptions()
    {
      var exception = new System.Exception("oh noes!");

      var exceptions = new Exceptions(exception, 5);

      Assert.Single(exceptions);
    }

    [Fact]
    public void IncludeInnerExceptions()
    {
      var innerException = new System.Exception();
      var exception = new System.Exception("oh noes!", innerException);

      var exceptions = new Exceptions(exception, 5);

      Assert.Equal(2, exceptions.Count());
    }

    [Fact]
    public void HandleAggregateExceptions()
    {
      Exceptions exceptions = null;
      var exceptionsToThrow = new[] { new System.Exception(), new System.DllNotFoundException() };
      var tasks = exceptionsToThrow.Select(e => Task.Run(() => { throw e; })).ToArray();

      try
      {
        Task.WaitAll(tasks);
      }
      catch (System.Exception exception)
      {
        exceptions = new Exceptions(exception, 0);
      }

      var results = exceptions.ToArray();

      Assert.Contains(results, exception => exception.ErrorClass == "System.DllNotFoundException");
      Assert.Contains(results, exception => exception.ErrorClass == "System.Exception");
      Assert.Contains(results, exception => exception.ErrorClass == "System.AggregateException");
    }
  }
}

using System.Linq;
using System.Threading.Tasks;
using Bugsnag.Payload;
using Xunit;

namespace Bugsnag.Tests.Payload
{
  public class ExceptionTests
  {
    [Fact]
    public void CorrectNumberOfExceptions()
    {
      var exception = new System.Exception("oh noes!");

      var exceptions = new Exceptions(exception, 5);

      Assert.Single(exceptions);
    }

    [Fact]
    public void IncludeInnerExceptions()
    {
      var innerException = new System.Exception();
      var exception = new System.Exception("oh noes!", innerException);

      var exceptions = new Exceptions(exception, 5);

      Assert.Equal(2, exceptions.Count());
    }

    public class AggregateExceptions
    {
      Exception[] exceptions;

      public AggregateExceptions()
      {
        Exceptions exceptions = null;
        var exceptionsToThrow = new[] { new System.Exception(), new System.DllNotFoundException() };
        var tasks = exceptionsToThrow.Select(e => Task.Run(() => { throw e; })).ToArray();

        try
        {
          Task.WaitAll(tasks);
        }
        catch (System.Exception exception)
        {
          exceptions = new Exceptions(exception, 0);
        }

        this.exceptions = exceptions.ToArray();
      }

      [Fact]
      public void ContainsDllNotFoundException()
      {
        Assert.Contains(exceptions, exception => exception.ErrorClass == "System.DllNotFoundException");
      }

      [Fact]
      public void ContainsException()
      {
        Assert.Contains(exceptions, exception => exception.ErrorClass == "System.Exception");
      }

      [Fact]
      public void AggregateExceptionIsLast()
      {
        var lastException = exceptions.Last();
        Assert.Equal("System.AggregateException", lastException.ErrorClass);
      }
    }
  }
}

Add test that aggregate exception is last


namespace AngleSharp.Css.ValueConverters
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using AngleSharp.Dom.Css;
    using AngleSharp.Parser.Css;

    sealed class FunctionValueConverter<T> : IValueConverter<T>
    {
        readonly String _name;
        readonly IValueConverter<T> _arguments;

        public FunctionValueConverter(String name, IValueConverter<T> arguments)
        {
            _name = name;
            _arguments = arguments;
        }

        public Boolean TryConvert(IEnumerable<CssToken> value, Action<T> setResult)
        {
            var args = ExtractArguments(value);
            return args != null && _arguments.TryConvert(args, setResult);
        }

        public Boolean Validate(IEnumerable<CssToken> value)
        {
            var args = ExtractArguments(value);
            return args != null && _arguments.Validate(args);
        }

        List<CssToken> ExtractArguments(IEnumerable<CssToken> value)
        {
            var iter = value.GetEnumerator();

            if (iter.MoveNext() && IsFunction(iter.Current))
            {
                var tokens = new List<CssToken>();

                while (iter.MoveNext())
                {
                    tokens.Add(iter.Current);
                }

                if (tokens.Count > 0 && tokens[tokens.Count - 1].Type == CssTokenType.RoundBracketClose)
                {
                    return tokens;
                }
            }

            return null;
        }

        Boolean IsFunction(CssToken value)
        {
            return value.Type == CssTokenType.Function && value.Data.Equals(_name, StringComparison.OrdinalIgnoreCase);
        }
    }
}

namespace AngleSharp.Css.ValueConverters
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using AngleSharp.Dom.Css;
    using AngleSharp.Parser.Css;

    sealed class FunctionValueConverter<T> : IValueConverter<T>
    {
        readonly String _name;
        readonly IValueConverter<T> _arguments;

        public FunctionValueConverter(String name, IValueConverter<T> arguments)
        {
            _name = name;
            _arguments = arguments;
        }

        public Boolean TryConvert(IEnumerable<CssToken> value, Action<T> setResult)
        {
            var args = ExtractArguments(value);
            return args != null && _arguments.TryConvert(args, setResult);
        }

        public Boolean Validate(IEnumerable<CssToken> value)
        {
            var args = ExtractArguments(value);
            return args != null && _arguments.Validate(args);
        }

        List<CssToken> ExtractArguments(IEnumerable<CssToken> value)
        {
            var iter = value.GetEnumerator();

            if (iter.MoveNext() && IsFunction(iter.Current))
            {
                var tokens = new List<CssToken>();

                while (iter.MoveNext())
                {
                    tokens.Add(iter.Current);
                }

                if (tokens.Count > 0 && tokens[tokens.Count - 1].Type == CssTokenType.RoundBracketClose)
                {
                    tokens.RemoveAt(tokens.Count - 1);
                    return tokens;
                }
            }

            return null;
        }

        Boolean IsFunction(CssToken value)
        {
            return value.Type == CssTokenType.Function && value.Data.Equals(_name, StringComparison.OrdinalIgnoreCase);
        }
    }
}

Remove closing bracket from arguments

Remove closing bracket from arguments


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DokanNet.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DokanNet.Tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// 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("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: CLSCompliant(true)]

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DokanNet.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DokanNet.Tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// 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("0.8.0.0")]
[assembly: AssemblyFileVersion("0.8.0.0")]
[assembly: CLSCompliant(true)]

Adjust version number to match DokanNet

Adjust version number to match DokanNet


// 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.Linq;
using osu.Framework.Audio.Track;
using osu.Game.Rulesets.Objects.Types;

namespace osu.Game.Beatmaps
{
    public partial class WorkingBeatmap
    {
        private class VirtualBeatmapTrack : TrackVirtual
        {
            private readonly IBeatmap beatmap;

            public VirtualBeatmapTrack(IBeatmap beatmap)
            {
                this.beatmap = beatmap;
            }

            protected override void UpdateState()
            {
                updateVirtualLength();
                base.UpdateState();
            }

            private void updateVirtualLength()
            {
                var lastObject = beatmap.HitObjects.LastOrDefault();

                switch (lastObject)
                {
                    case null:
                        Length = 1000;
                        break;
                    case IHasEndTime endTime:
                        Length = endTime.EndTime + 1000;
                        break;
                    default:
                        Length = lastObject.StartTime + 1000;
                        break;
                }
            }
        }
    }
}

// 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.Linq;
using osu.Framework.Audio.Track;
using osu.Game.Rulesets.Objects.Types;

namespace osu.Game.Beatmaps
{
    public partial class WorkingBeatmap
    {
        /// <summary>
        /// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>.
        /// </summary>
        private class VirtualBeatmapTrack : TrackVirtual
        {
            private readonly IBeatmap beatmap;

            public VirtualBeatmapTrack(IBeatmap beatmap)
            {
                this.beatmap = beatmap;
                updateVirtualLength();
            }

            protected override void UpdateState()
            {
                updateVirtualLength();
                base.UpdateState();
            }

            private void updateVirtualLength()
            {
                var lastObject = beatmap.HitObjects.LastOrDefault();

                switch (lastObject)
                {
                    case null:
                        Length = 1000;
                        break;
                    case IHasEndTime endTime:
                        Length = endTime.EndTime + 1000;
                        break;
                    default:
                        Length = lastObject.StartTime + 1000;
                        break;
                }
            }
        }
    }
}

Update the length once during construction


using System.Collections.Generic;

namespace RockLib.Encryption.Symmetric
{
    /// <summary>
    /// Defines an xml-serializable object that contains the information needed to configure an
    /// instance of <see cref="SymmetricCrypto"/>.
    /// </summary>
    public class CryptoConfiguration
    {
        /// <summary>
        /// Gets the collection of credentials that will be available for encryption or
        /// decryption operations.
        /// </summary>
        public List<ICredential> Credentials { get; set; } = new List<ICredential>();
    }
}

using System.Collections.Generic;

namespace RockLib.Encryption.Symmetric
{
    /// <summary>
    /// Defines an xml-serializable object that contains the information needed to configure an
    /// instance of <see cref="SymmetricCrypto"/>.
    /// </summary>
    public class CryptoConfiguration
    {
        /// <summary>
        /// Gets the collection of credentials that will be available for encryption or
        /// decryption operations.
        /// </summary>
        public List<Credential> Credentials { get; set; } = new List<Credential>();
    }
}

Revert CrytoConfiguration to using Credential implementation


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

using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Drawables;
using osu.Framework.Graphics.Sprites;
using OpenTK;
using OpenTK.Graphics;

namespace osu.Framework.VisualTests
{
    class VisualTestGame : Game
    {
        public override void Load()
        {
            base.Load();
            Host.Size = new Vector2(1366, 768);

            SampleGame test = new SampleGame();

            DrawVisualiser drawVis;

            Add(test);
            Add(drawVis = new DrawVisualiser(test));

            Add(new CursorContainer());
        }

        class SampleGame : LargeContainer
        {
            SpriteText text;
            int num = 0;

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

                Box box;

                Add(box = new Box()
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Size = new Vector2(150, 150),
                    Colour = Color4.Tomato
                });

                Add(text = new SpriteText());

                box.RotateTo(360 * 10, 60000);
            }

            protected override void Update()
            {
                text.Text = (num++).ToString();
                base.Update();
            }
        }
    }
}

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

using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Drawables;
using osu.Framework.Graphics.Sprites;
using OpenTK;
using OpenTK.Graphics;

namespace osu.Framework.VisualTests
{
    class VisualTestGame : Game
    {
        public override void Load()
        {
            base.Load();
            Host.Size = new Vector2(1366, 768);

            SampleGame test = new SampleGame();

            DrawVisualiser drawVis;

            Add(test);
            Add(drawVis = new DrawVisualiser(test));

            Add(new CursorContainer());
        }

        class SampleGame : LargeContainer
        {
            SpriteText text;
            int num = 0;

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

                Box box;

                Add(box = new Box()
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Size = new Vector2(150, 150),
                    Colour = Color4.Tomato
                });

                Add(text = new SpriteText()
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                });

                box.RotateTo(360 * 10, 60000);
            }

            protected override void Update()
            {
                base.Update();
                text.Text = $@"frame count: {num++}";
            }
        }
    }
}

Add frame counter to give DrawVis a bit more activity.


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

using System;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mods;

namespace osu.Game.Rulesets.Mania.Mods
{
    public abstract class ManiaKeyMod : Mod, IApplicableToBeatmapConverter
    {
        public override string Acronym => Name;
        public abstract int KeyCount { get; }
        public override ModType Type => ModType.Conversion;
        public override double ScoreMultiplier => 1; // TODO: Implement the mania key mod score multiplier
        public override bool Ranked => true;

        public void ApplyToBeatmapConverter(IBeatmapConverter beatmapConverter)
        {
            var mbc = (ManiaBeatmapConverter)beatmapConverter;

            // Although this can work, for now let's not allow keymods for mania-specific beatmaps
            if (mbc.IsForCurrentRuleset)
                return;

            mbc.TargetColumns = KeyCount;
        }

        public override Type[] IncompatibleMods => new[]
        {
            typeof(ManiaModKey1),
            typeof(ManiaModKey2),
            typeof(ManiaModKey3),
            typeof(ManiaModKey4),
            typeof(ManiaModKey5),
            typeof(ManiaModKey6),
            typeof(ManiaModKey7),
            typeof(ManiaModKey8),
            typeof(ManiaModKey9),
        }.Except(new[] { GetType() }).ToArray();
    }
}

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

using System;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mods;

namespace osu.Game.Rulesets.Mania.Mods
{
    public abstract class ManiaKeyMod : Mod, IApplicableToBeatmapConverter
    {
        public override string Acronym => Name;
        public abstract int KeyCount { get; }
        public override ModType Type => ModType.Conversion;
        public override double ScoreMultiplier => 1; // TODO: Implement the mania key mod score multiplier
        public override bool Ranked => true;

        public void ApplyToBeatmapConverter(IBeatmapConverter beatmapConverter)
        {
            var mbc = (ManiaBeatmapConverter)beatmapConverter;

            // Although this can work, for now let's not allow keymods for mania-specific beatmaps
            if (mbc.IsForCurrentRuleset)
                return;

            mbc.TargetColumns = KeyCount;
        }

        public override Type[] IncompatibleMods => new[]
        {
            typeof(ManiaModKey1),
            typeof(ManiaModKey2),
            typeof(ManiaModKey3),
            typeof(ManiaModKey4),
            typeof(ManiaModKey5),
            typeof(ManiaModKey6),
            typeof(ManiaModKey7),
            typeof(ManiaModKey8),
            typeof(ManiaModKey9),
            typeof(ManiaModKey10),
        }.Except(new[] { GetType() }).ToArray();
    }
}

Add 10K mod to incompatibility list

Add 10K mod to incompatibility list