using MyDocs.Common.Contract.Service;
using MyDocs.Common.Model.View;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Pickers;

namespace MyDocs.WindowsStore.Service
{
    public class FileOpenPickerService : IFileOpenPickerService
    {
        public async Task<IEnumerable<StorageFile>> PickSubDocuments()
        {
            var filePicker = new FileOpenPicker();
            filePicker.FileTypeFilter.Add("*");
            filePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            filePicker.ViewMode = PickerViewMode.List;

            var files = await filePicker.PickMultipleFilesAsync();
            var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(document.Id.ToString(), CreationCollisionOption.OpenIfExists);
            var tasks = files.Select(file => file.CopyAsync(folder, file.Name, NameCollisionOption.GenerateUniqueName).AsTask());
            return await Task.WhenAll(tasks);
        }

        public async Task<StorageFile> PickImportFile()
        {
            var filePicker = new FileOpenPicker();
            filePicker.FileTypeFilter.Add(".zip");
            return await filePicker.PickSingleFileAsync();
        }
    }
}

using MyDocs.Common.Contract.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Pickers;

namespace MyDocs.WindowsStore.Service
{
    public class FileOpenPickerService : IFileOpenPickerService
    {
        public async Task<IEnumerable<StorageFile>> PickSubDocuments()
        {
            var filePicker = new FileOpenPicker();
            filePicker.FileTypeFilter.Add("*");
            filePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            filePicker.ViewMode = PickerViewMode.List;

            var files = await filePicker.PickMultipleFilesAsync();
            var folder = ApplicationData.Current.TemporaryFolder;
            var tasks = files.Select(file =>
            {
                var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.Name);
                return file.CopyAsync(folder, fileName).AsTask();
            });
            return await Task.WhenAll(tasks);
        }

        public async Task<StorageFile> PickImportFile()
        {
            var filePicker = new FileOpenPicker();
            filePicker.FileTypeFilter.Add(".zip");
            return await filePicker.PickSingleFileAsync();
        }
    }
}

Copy file to temp folder as long as document is not saved


using System;
using System.Linq;

namespace Elasticsearch.Net.Aws
{
    /// <summary>
    /// Encapsulates
    /// </summary>
    public class AwsSettings
    {
        /// <summary>
        /// Gets or sets the region. e.g. us-east-1. Required.
        /// </summary>
        public string Region { get; set; }

        /// <summary>
        /// Gets or sets the AWS access key. Required.
        /// </summary>
        public string AccessKey { get; set; }

        /// <summary>
        /// Gets or sets the AWS secret key. e.g. wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY
        ///  Required.
        /// </summary>
        public string SecretKey { get; set; }

        /// <summary>
        /// Gets or sets the security token
        ///  Required.
        /// </summary>
        public string Token { get; set; }

    }
}

using System;
using System.Linq;

namespace Elasticsearch.Net.Aws
{
    /// <summary>
    /// Encapsulates
    /// </summary>
    public class AwsSettings
    {
        /// <summary>
        /// Gets or sets the region. e.g. us-east-1. Required.
        /// </summary>
        public string Region { get; set; }

        /// <summary>
        /// Gets or sets the AWS access key. Required.
        /// </summary>
        public string AccessKey { get; set; }

        /// <summary>
        /// Gets or sets the AWS secret key. e.g. wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY
        ///  Required.
        /// </summary>
        public string SecretKey { get; set; }

        /// <summary>
        /// Gets or sets the security token.
        /// </summary>
        public string Token { get; set; }
    }
}

Edit comment. Token is not required.

Edit comment. Token is not required.


using System;
using System.Reactive;
using ReactiveUI;
using GitHub.Models;

namespace GitHub.InlineReviews.ViewModels
{
    public class TooltipCommentViewModel : ICommentViewModel
    {
        internal TooltipCommentViewModel(IAccount user, string body, DateTimeOffset updatedAt)
        {
            User = user;
            Body = body;
            UpdatedAt = updatedAt;
        }

        public ReactiveCommand<object> BeginEdit { get; }

        public string Body { get; set; }

        public ReactiveCommand<object> CancelEdit { get; }

        public ReactiveCommand<Unit> CommitEdit { get; }

        public CommentEditState EditState { get; }

        public string ErrorMessage { get; }

        public int Id { get; }

        public DateTimeOffset UpdatedAt { get; }

        public IAccount User { get; }
    }

}

using System;
using System.Reactive;
using ReactiveUI;
using GitHub.Models;

namespace GitHub.InlineReviews.ViewModels
{
    public class TooltipCommentViewModel : ICommentViewModel
    {
        internal TooltipCommentViewModel(IAccount user, string body, DateTimeOffset updatedAt)
        {
            User = user;
            Body = body;
            UpdatedAt = updatedAt;
        }

        public ReactiveCommand<object> BeginEdit { get; }

        public string Body { get; set; }

        public ReactiveCommand<object> CancelEdit { get; }

        public ReactiveCommand<Unit> CommitEdit { get; }

        public CommentEditState EditState { get; }

        public string ErrorMessage { get; }

        public int Id { get; }

        public bool IsReadOnly { get; set; }

        public DateTimeOffset UpdatedAt { get; }

        public IAccount User { get; }
    }

}

Fix build by adding IsReadOnly implementation


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

using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace System.Net.Utilities.Tests
{
    internal static class TestSettings
    {
        public static readonly string LocalHost = "localhost";
        public const int PingTimeout = 200;

        public const string PayloadAsString = "'Post hoc ergo propter hoc'. 'After it, therefore because of it'. It means one thing follows the other, therefore it was caused by the other. But it's not always true. In fact it's hardly ever true.";
        public static readonly byte[] PayloadAsBytes = Encoding.UTF8.GetBytes(TestSettings.PayloadAsString);

        public static Task<IPAddress> GetLocalIPAddress()
        {
            return ResolveHost(LocalHost);
        }

        private static async Task<IPAddress> ResolveHost(string host)
        {
            IPHostEntry hostEntry = await Dns.GetHostEntryAsync(host);
            IPAddress ret = null;

            foreach (IPAddress address in hostEntry.AddressList)
            {
                if (address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    ret = address;
                }
            }

            // If there's no IPv6 addresses, just take the first (IPv4) address.
            if (ret == null)
            {
                ret = hostEntry.AddressList[0];
            }

            if (ret != null)
            {
                return ret;
            }

            throw new InvalidOperationException("Unable to discover any addresses for host " + host);
        }
    }
}

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

using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace System.Net.Utilities.Tests
{
    internal static class TestSettings
    {
        public static readonly string LocalHost = "localhost";
        public const int PingTimeout = 1000;

        public const string PayloadAsString = "'Post hoc ergo propter hoc'. 'After it, therefore because of it'. It means one thing follows the other, therefore it was caused by the other. But it's not always true. In fact it's hardly ever true.";
        public static readonly byte[] PayloadAsBytes = Encoding.UTF8.GetBytes(TestSettings.PayloadAsString);

        public static Task<IPAddress> GetLocalIPAddress()
        {
            return ResolveHost(LocalHost);
        }

        private static async Task<IPAddress> ResolveHost(string host)
        {
            IPHostEntry hostEntry = await Dns.GetHostEntryAsync(host);
            IPAddress ret = null;

            foreach (IPAddress address in hostEntry.AddressList)
            {
                if (address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    ret = address;
                }
            }

            // If there's no IPv6 addresses, just take the first (IPv4) address.
            if (ret == null)
            {
                ret = hostEntry.AddressList[0];
            }

            if (ret != null)
            {
                return ret;
            }

            throw new InvalidOperationException("Unable to discover any addresses for host " + host);
        }
    }
}

Raise Ping timeout for tests slightly

Raise Ping timeout for tests slightly

The Linux implementation is timing out more than expected in these tests, because the default timeout value for them is very low, actually the minimum timeout for the ping utility. The ping utility code path is being taken in the CI runs because of the lack of permissions. Interestingly, the OSX tests are not timing out on these requests.


// 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.Collections.Generic;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Platform;
using osuTK;

namespace osu.Framework.Input
{
    public class UserInputManager : PassThroughInputManager
    {
        protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers;

        protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true;

        public UserInputManager()
        {
            IsAlive = true;
            UseParentInput = false;
        }

        public override void HandleInputStateChange(InputStateChangeEvent inputStateChange)
        {
            switch (inputStateChange)
            {
                case MousePositionChangeEvent mousePositionChange:
                    var mouse = mousePositionChange.State.Mouse;
                    // confine cursor
                    if (Host.Window != null && Host.Window.CursorState.HasFlag(CursorState.Confined))
                        mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height));
                    break;

                case MouseScrollChangeEvent _:
                    if (Host.Window != null && !Host.Window.CursorInWindow)
                        return;
                    break;
            }

            base.HandleInputStateChange(inputStateChange);
        }
    }
}

// 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.Collections.Generic;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Platform;
using osuTK;

namespace osu.Framework.Input
{
    public class UserInputManager : PassThroughInputManager
    {
        protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers;

        protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true;

        protected internal UserInputManager()
        {
            // IsAlive is being forced to true here as UserInputManager is at the very top of the Draw Hierarchy, which means it never becomes alive normally.
            IsAlive = true;
            UseParentInput = false;
        }

        public override void HandleInputStateChange(InputStateChangeEvent inputStateChange)
        {
            switch (inputStateChange)
            {
                case MousePositionChangeEvent mousePositionChange:
                    var mouse = mousePositionChange.State.Mouse;
                    // confine cursor
                    if (Host.Window != null && Host.Window.CursorState.HasFlag(CursorState.Confined))
                        mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height));
                    break;

                case MouseScrollChangeEvent _:
                    if (Host.Window != null && !Host.Window.CursorInWindow)
                        return;
                    break;
            }

            base.HandleInputStateChange(inputStateChange);
        }
    }
}

Add comment and make constructor protected internal


using System;

namespace AsmResolver.PE.Debug
{
    /// <summary>
    /// Provides an implementation of a debug data entry that was stored in a PE file.
    /// </summary>
    public class SerializedDebugDataEntry : DebugDataEntry
    {
        private readonly IDebugDataReader _dataReader;
        private readonly DebugDataType _type;
        private readonly uint _sizeOfData;
        private readonly uint _addressOfRawData;
        private readonly uint _pointerToRawData;

        /// <summary>
        /// Reads a single debug data entry from an input stream.
        /// </summary>
        /// <param name="reader">The input stream.</param>
        /// <param name="dataReader">The object responsible for reading the contents.</param>
        public SerializedDebugDataEntry(IBinaryStreamReader reader, IDebugDataReader dataReader)
        {
            if (reader == null)
                throw new ArgumentNullException(nameof(reader));
            _dataReader = dataReader ?? throw new ArgumentNullException(nameof(dataReader));

            Characteristics = reader.ReadUInt32();
            TimeDateStamp = reader.ReadUInt32();
            MajorVersion = reader.ReadUInt16();
            MinorVersion = reader.ReadUInt16();
            _type = (DebugDataType) reader.ReadUInt32();
            _sizeOfData = reader.ReadUInt32();
            _addressOfRawData = reader.ReadUInt32();
            _pointerToRawData = reader.ReadUInt32();
        }

        /// <inheritdoc />
        protected override IDebugDataSegment GetContents() =>
            _dataReader.ReadDebugData(_type, _addressOfRawData, _sizeOfData);
    }
}

using System;

namespace AsmResolver.PE.Debug
{
    /// <summary>
    /// Provides an implementation of a debug data entry that was stored in a PE file.
    /// </summary>
    public class SerializedDebugDataEntry : DebugDataEntry
    {
        private readonly IDebugDataReader _dataReader;
        private readonly DebugDataType _type;
        private readonly uint _sizeOfData;
        private readonly uint _addressOfRawData;
        private readonly uint _pointerToRawData;

        /// <summary>
        /// Reads a single debug data entry from an input stream.
        /// </summary>
        /// <param name="reader">The input stream.</param>
        /// <param name="dataReader">The object responsible for reading the contents.</param>
        public SerializedDebugDataEntry(IBinaryStreamReader reader, IDebugDataReader dataReader)
        {
            if (reader == null)
                throw new ArgumentNullException(nameof(reader));
            _dataReader = dataReader ?? throw new ArgumentNullException(nameof(dataReader));
            FileOffset = reader.FileOffset;
            Rva = reader.Rva;

            Characteristics = reader.ReadUInt32();
            TimeDateStamp = reader.ReadUInt32();
            MajorVersion = reader.ReadUInt16();
            MinorVersion = reader.ReadUInt16();
            _type = (DebugDataType) reader.ReadUInt32();
            _sizeOfData = reader.ReadUInt32();
            _addressOfRawData = reader.ReadUInt32();
            _pointerToRawData = reader.ReadUInt32();
        }

        /// <inheritdoc />
        protected override IDebugDataSegment GetContents() =>
            _dataReader.ReadDebugData(_type, _addressOfRawData, _sizeOfData);
    }
}

Add missing file offset registration.

Add missing file offset registration.


using System.Reflection;
using System.Runtime.CompilerServices;
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("SqlServerHelpers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SqlServerHelpers")]
[assembly: AssemblyCopyright("Copyright ©  2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5595bad6-6335-4e57-b4ac-bb5b9e77fbaa")]

// 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")]

using System.Reflection;
using System.Runtime.CompilerServices;
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("SqlServerHelpers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SqlServerHelpers")]
[assembly: AssemblyCopyright("Copyright © Josh Keegan 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5595bad6-6335-4e57-b4ac-bb5b9e77fbaa")]

// 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.*")]

Use default build & revision numbers

Use default build & revision numbers


using System;
using System.Reflection;

// TODO: Automate this
[assembly: AssemblyInformationalVersion ("1.1.0")]

namespace Tomboy {
	public class Defines {
		public const string VERSION = "1.1.0";
		public static readonly string DATADIR = System.IO.Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location);
		public static readonly string GNOME_LOCALE_DIR = System.IO.Path.Combine (DATADIR, "locale");
		public const string GNOME_HELP_DIR = "@datadir@/gnome/help/tomboy";
		public const string PKGLIBDIR = "@pkglibdir@";
		public static readonly string SYS_ADDINS_DIR = DATADIR;
		public const string TOMBOY_WEBSITE = "http://www.gnome.org/projects/tomboy/";
	}
}

using System;
using System.Reflection;

// TODO: Automate this
[assembly: AssemblyInformationalVersion ("1.1.0")]
[assembly: AssemblyProduct("Tomboy")]
[assembly: AssemblyTitle("Tomboy Notes")]

namespace Tomboy {
	public class Defines {
		public const string VERSION = "1.1.0";
		public static readonly string DATADIR = System.IO.Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location);
		public static readonly string GNOME_LOCALE_DIR = System.IO.Path.Combine (DATADIR, "locale");
		public const string GNOME_HELP_DIR = "@datadir@/gnome/help/tomboy";
		public const string PKGLIBDIR = "@pkglibdir@";
		public static readonly string SYS_ADDINS_DIR = DATADIR;
		public const string TOMBOY_WEBSITE = "http://www.gnome.org/projects/tomboy/";
	}
}

Add the product name and the assembly title custom attributes

https://bugzilla.gnome.org/show_bug.cgi?id=585297


using System.Collections.Generic;
using NSpec;

namespace SampleSpecs.Bug
{
    class grandparents_run_first : nspec
    {
        List<int> ints = null;

        void describe_NSpec()                                       //describe RSpec do
        {
            before = () => ints = new List<int>();                    //  before(:each) { @array = Array.new }

            context["something that works in rspec but not nspec"] = () =>    //  context "something that works in rspec but not nspec" do
            {
                before = () => ints.Add(1);

                describe["sibling context"] = () =>                           //    context "sibling context" do
                {
                    before = () => ints.Add(1);                       //      before(:each) { @array << "sibling 1" }

                    specify = () => ints.Count.should_be(1);                //        it { @array.count.should == 1 }
                };                                                         //    end

                describe["another sibling context"] = () =>                   //    context "another sibling context" do
                {
                    before = () => ints.Add(1);                       //      before(:each) { @array << "sibling 2" }

                    specify = () => ints.Count.should_be(1);                //      it { @array.count.should == 1 }
                };                                                         //    end
            };                                                             //  end
        }                                                                  //end
    }
}

Align side-by-side comments in SampleSpecs.Bug test


using System.Xml;
using FluentNHibernate;
using FluentNHibernate.Mapping;

namespace FluentNHibernate.QuickStart.Domain.Mapping
{
    public class CatMap : ClassMap<Cat>, IMapGenerator
    {
        public CatMap()
        {
            //set up our generator as UUID.HEX
            Id(x => x.Id)
                .GeneratedBy
                .UuidHex("B");

            //non-nullable string with a length of 16
            Map(x => x.Name)
                .WithLengthOf(16)
                .CanNotBeNull();

            //simple properties
            Map(x => x.Sex);
            Map(x => x.Weight);
        }

        #region IMapGenerator Members

        public XmlDocument Generate()
        {
            return CreateMapping(new MappingVisitor());
        }

        #endregion
    }
}

using System.Xml;
using FluentNHibernate;
using FluentNHibernate.Mapping;

namespace FluentNHibernate.QuickStart.Domain.Mapping
{
    public class CatMap : ClassMap<Cat>, IMapGenerator
    {
        public CatMap()
        {
            //set up our generator as UUID.HEX
            Id(x => x.Id)
                .GeneratedBy
                .UuidHex("B");

            //non-nullable string with a length of 16
            Map(x => x.Name)
                .WithLengthOf(16)
                .Not.Nullable();

            //simple properties
            Map(x => x.Sex);
            Map(x => x.Weight);
        }

        #region IMapGenerator Members

        public XmlDocument Generate()
        {
            return CreateMapping(new MappingVisitor());
        }

        #endregion
    }
}

Fix for a compile error in the QuickStart.

git-svn-id: a161142445158cf41e00e2afdd70bb78aded5464@286 48f0ce17-cc52-0410-af8c-857c09b6549b


using System.IO;
using System;

namespace Bari.Core.Generic
{
    public class LocalFileSystemDirectoryWatcher: IFileSystemDirectoryWatcher
	{
        private readonly FileSystemWatcher watcher;
        private readonly string path;

        public event EventHandler<FileSystemChangedEventArgs> Changed;

        public LocalFileSystemDirectoryWatcher(string path)
        {
            this.path = path;

            watcher = new FileSystemWatcher(path)
            {
                IncludeSubdirectories = true,
                NotifyFilter = NotifyFilters.FileName
            };
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;
            watcher.Deleted += OnChanged;
            watcher.Renamed += OnChanged;
            watcher.EnableRaisingEvents = true;
        }

        public void Stop()
        {
            watcher.Dispose();
        }

        public void Dispose()
        {
            Stop();
        }

        private void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (Changed != null)
            {
                Changed(this, new FileSystemChangedEventArgs(e.FullPath.Substring(path.Length).TrimStart(Path.DirectorySeparatorChar)));
            }
        }
	}

}

using System.IO;
using System;

namespace Bari.Core.Generic
{
    public class LocalFileSystemDirectoryWatcher: IFileSystemDirectoryWatcher
	{
        private readonly FileSystemWatcher watcher;
        private readonly string path;

        public event EventHandler<FileSystemChangedEventArgs> Changed;

        public LocalFileSystemDirectoryWatcher(string path)
        {
            this.path = path;

            watcher = new FileSystemWatcher(path);
            watcher.IncludeSubdirectories = true;
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;
            watcher.Deleted += OnChanged;
            watcher.Renamed += OnChanged;
            watcher.EnableRaisingEvents = true;
        }

        public void Stop()
        {
            watcher.Dispose();
        }

        public void Dispose()
        {
            Stop();
        }

        private void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (Changed != null)
            {
                Changed(this, new FileSystemChangedEventArgs(e.FullPath.Substring(path.Length).TrimStart(Path.DirectorySeparatorChar)));
            }
        }
	}

}

Revert "Fix of previous commit"

Revert "Fix of previous commit"

This reverts commit 0577394e161a7ee52f543ba1a948331f1d080e80.


using System.Linq;
using FluentAssertions;
using Xunit;

namespace Okanshi.Test
{
    public class CounterTest
    {
        private readonly Counter counter;

        public CounterTest()
        {
            counter = new Counter(MonitorConfig.Build("Test"));
        }

        [Fact]
        public void Initial_peak_is_zero()
        {
            var value = counter.GetValues();

            value.First().Value.Should().Be(0);
        }

        [Theory]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(110)]
        public void Incrementing_value_updates_peak(int amount)
        {
            counter.Increment(amount);

            counter.GetValues().First().Value.Should().Be(amount);
        }

        [Theory]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(110)]
        public void Get_and_reset_returns_the_peak(int amount)
        {
            counter.Increment(amount);

            counter.GetValuesAndReset().First().Value.Should().Be(amount);
        }

        [Fact]
        public void Peak_is_reset_after_get_and_reset()
        {
            counter.Increment();

            counter.GetValuesAndReset();

            var value = counter.GetValues();
            value.First().Value.Should().Be(0);
        }

        [Fact]
        public void Value_is_called_value()
        {
            counter.GetValues().Single().Name.Should().Be("value");
        }
    }
}

using System.Linq;
using FluentAssertions;
using Xunit;

namespace Okanshi.Test
{
    public class CounterTest
    {
        private readonly Counter counter;

        public CounterTest()
        {
            counter = new Counter(MonitorConfig.Build("Test"));
        }

        [Fact]
        public void Initial_peak_is_zero()
        {
            var value = counter.GetValues();

            value.First().Value.Should().Be(0);
        }

        [Theory]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(110)]
        public void Incrementing_value_updates_peak(int amount)
        {
            counter.Increment(amount);

            counter.GetValues().First().Value.Should().Be(amount);
        }

        [Theory]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(110)]
        public void Get_and_reset_returns_the_peak(int amount)
        {
            counter.Increment(amount);

            counter.GetValuesAndReset().First().Value.Should().Be(amount);
        }

        [Fact]
        public void Peak_is_reset_after_get_and_reset()
        {
            counter.Increment();

            counter.GetValuesAndReset();

            var value = counter.GetValues();
            value.First().Value.Should().Be(0);
        }

        [Fact]
        public void Value_is_called_value()
        {
            counter.GetValues().Single().Name.Should().Be("value");
        }

        [Fact]
        public void Increment_with_negative_values_works()
        {
            counter.Increment(-1);

            counter.GetValues().Single().Value.Should().Be(-1);
        }
    }
}

Add test for incrementing with negative number

It is now possible to increment with negative numbers, but no tests for
this existed

Signed-off-by: Kim Christensen <aa8e4f65ee1f7dee724d3c54a33e387cc279d580@gmail.com>


using System.IO;
using System.Security.Cryptography;
using Mono.Security;
using Mono.Security.Cryptography;

namespace Xpdm.PurpleOnion
{
	class Program
	{
		private static void Main()
		{
			long count = 0;
			while (true)
			{
				RSA pki = RSA.Create();
				ASN1 asn = RSAExtensions.ToAsn1Key(pki);
				byte[] hash = SHA1CryptoServiceProvider.Create().ComputeHash(asn.GetBytes());
				string onion = ConvertExtensions.FromBytesToBase32String(hash).Substring(0,16).ToLowerInvariant();
				if (onion.Contains("tor") || onion.Contains("mirror"))
				{
					System.Console.WriteLine("Found: " + onion);
					Directory.CreateDirectory(onion);
					File.WriteAllText(Path.Combine(onion, "pki.xml"), pki.ToXmlString(true));
					File.WriteAllText(Path.Combine(onion, "private_key"), System.Convert.ToBase64String(PKCS8.PrivateKeyInfo.Encode(pki)));
					File.WriteAllText(Path.Combine(onion, "hostname"), onion + ".onion");
				}

				System.Console.WriteLine(onion + " " + ++count);
			}
		}
	}
}

using System;
using System.IO;
using System.Security.Cryptography;
using Mono.Security;
using Mono.Security.Cryptography;

namespace Xpdm.PurpleOnion
{
	class Program
	{
		private static void Main()
		{
			long count = 0;
			while (true)
			{
				RSA pki = RSA.Create();
				ASN1 asn = RSAExtensions.ToAsn1Key(pki);
				byte[] hash = SHA1CryptoServiceProvider.Create().ComputeHash(asn.GetBytes());
				string onion = ConvertExtensions.FromBytesToBase32String(hash).Substring(0,16).ToLowerInvariant();
				if (onion.Contains("tor") || onion.Contains("mirror"))
				{
					Console.WriteLine("Found: " + onion);
					Directory.CreateDirectory(onion);
					File.WriteAllText(Path.Combine(onion, "pki.xml"), pki.ToXmlString(true));
					File.WriteAllText(Path.Combine(onion, "private_key"), System.Convert.ToBase64String(PKCS8.PrivateKeyInfo.Encode(pki)));
					File.WriteAllText(Path.Combine(onion, "hostname"), onion + ".onion");
				}

				Console.WriteLine(onion + " " + ++count);
			}
		}
	}
}

Add a namespace reference for System

Add a namespace reference for System


// 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.Linq;
using NUnit.Framework;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics.Containers;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Screens.Play.HUD;
using osu.Game.Skinning;
using osu.Game.Tests.Visual;
using osuTK;

namespace osu.Game.Rulesets.Catch.Tests
{
    [TestFixture]
    public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene
    {
        protected override Ruleset CreatePlayerRuleset() => new CatchRuleset();

        [Test]
        public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin)
        {
            if (withModifiedSkin)
            {
                AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f));
                AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget));
                AddStep("exit player", () => Player.Exit());
                CreateTest(null);
            }

            AddAssert("legacy HUD combo counter hidden", () =>
            {
                return Player.ChildrenOfType<LegacyComboCounter>().All(c => c.ChildrenOfType<Container>().Single().Alpha == 0f);
            });
        }
    }
}

// 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.Linq;
using NUnit.Framework;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics.Containers;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Screens.Play.HUD;
using osu.Game.Skinning;
using osu.Game.Tests.Visual;
using osuTK;

namespace osu.Game.Rulesets.Catch.Tests
{
    [TestFixture]
    public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene
    {
        protected override Ruleset CreatePlayerRuleset() => new CatchRuleset();

        [Test]
        [Ignore("HUD components broken, remove when fixed.")]
        public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin)
        {
            if (withModifiedSkin)
            {
                AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f));
                AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget));
                AddStep("exit player", () => Player.Exit());
                CreateTest(null);
            }

            AddAssert("legacy HUD combo counter hidden", () =>
            {
                return Player.ChildrenOfType<LegacyComboCounter>().All(c => !c.ChildrenOfType<Container>().Single().IsPresent);
            });
        }
    }
}

Revert "Remove ignore attribute from now fixed test scene"

This reverts commit 4e12a2734ccf28dae236d6c78385e79d69bf32d7.


using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;
using StackExchange.Opserver.Data.Dashboard;
using StackExchange.Opserver.Helpers;
using StackExchange.Opserver.Models;
using StackExchange.Opserver.Views.Dashboard;

namespace StackExchange.Opserver.Controllers
{
    public partial class DashboardController : StatusController
    {
        protected override ISecurableSection SettingsSection
        {
            get { return Current.Settings.Dashboard; }
        }

        protected override string TopTab
        {
            get { return TopTabs.BuiltIn.Dashboard; }
        }

        [Route("dashboard")]
        public ActionResult Dashboard(string filter)
        {
            var vd = new DashboardModel
                {
                    Nodes = DashboardData.Current.AllNodes.Where(n => !Current.Settings.Dashboard.ExcludePatternRegex.IsMatch(n.Name)).ToList(),
                    ErrorMessages = DashboardData.Current.GetExceptions(),
                    Filter = filter
                };
            return View(Current.IsAjaxRequest ? "Dashboard.Table" : "Dashboard", vd);
        }

        [Route("dashboard/node")]
        public ActionResult SingleNode([DefaultValue(CurrentStatusTypes.Stats)]CurrentStatusTypes view, string node = null)
        {
            var vd = new NodeModel
            {
                CurrentNode = DashboardData.Current.GetNode(node),
                CurrentStatusType = view
            };

            return View("Node",vd);
        }
    }
}

using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;
using StackExchange.Opserver.Data.Dashboard;
using StackExchange.Opserver.Helpers;
using StackExchange.Opserver.Models;
using StackExchange.Opserver.Views.Dashboard;

namespace StackExchange.Opserver.Controllers
{
    public partial class DashboardController : StatusController
    {
        protected override ISecurableSection SettingsSection
        {
            get { return Current.Settings.Dashboard; }
        }

        protected override string TopTab
        {
            get { return TopTabs.BuiltIn.Dashboard; }
        }

        [Route("dashboard")]
        public ActionResult Dashboard(string filter)
        {
            var nodes = DashboardData.Current.AllNodes;
            if(Current.Settings.Dashboard.ExcludePatternRegex!=null)
            {
                nodes = nodes.Where(n => !Current.Settings.Dashboard.ExcludePatternRegex.IsMatch(n.Name)).ToList();
            }
            var vd = new DashboardModel
                {
                    Nodes = nodes,
                    ErrorMessages = DashboardData.Current.GetExceptions(),
                    Filter = filter
                };
            return View(Current.IsAjaxRequest ? "Dashboard.Table" : "Dashboard", vd);
        }

        [Route("dashboard/node")]
        public ActionResult SingleNode([DefaultValue(CurrentStatusTypes.Stats)]CurrentStatusTypes view, string node = null)
        {
            var vd = new NodeModel
            {
                CurrentNode = DashboardData.Current.GetNode(node),
                CurrentStatusType = view
            };

            return View("Node",vd);
        }
    }
}

Allow Dashboard.ExcludePatternRegex to be null


using System.Data.SqlClient;
using System.Management.Automation;

namespace PSql
{
    [Cmdlet(VerbsCommunications.Disconnect, "Sql")]
    public class DisconnectSqlCommand : Cmdlet
    {
        // -Connection
        [Alias("c", "cn")]
        [Parameter(Position = 0, ValueFromPipeline = true, ValueFromRemainingArguments = true)]
        public SqlConnection[] Connection { get; set; }

        protected override void ProcessRecord()
        {
            foreach (var connection in Connection)
            {
                if (connection == null)
                    continue;

                ConnectionInfo.Get(connection).IsDisconnecting = true;
                connection.Dispose();
            }
        }
    }
}

using System.Data.SqlClient;
using System.Management.Automation;

namespace PSql
{
    [Cmdlet(VerbsCommunications.Disconnect, "Sql")]
    public class DisconnectSqlCommand : Cmdlet
    {
        // -Connection
        [Alias("c", "cn")]
        [Parameter(Position = 0, ValueFromPipeline = true, ValueFromRemainingArguments = true)]
        public SqlConnection[] Connection { get; set; }

        protected override void ProcessRecord()
        {
            var connections = Connection;
            if (connections == null)
                return;

            foreach (var connection in connections)
            {
                if (connection == null)
                    continue;

                ConnectionInfo.Get(connection).IsDisconnecting = true;
                connection.Dispose();
            }
        }
    }
}

Fix NRE if null array.

Fix NRE if null array.


using System;
using Microsoft.AspNetCore.Hosting;
using TwentyTwenty.Mvc;
using TwentyTwenty.Mvc.ErrorHandling;
using TwentyTwenty.Mvc.HealthCheck;
using TwentyTwenty.Mvc.ReadOnlyMode;

namespace Microsoft.AspNetCore.Builder
{
    public static class ErrorHandling
    {
        public static void UseErrorHandling(this IApplicationBuilder app, ICodeMap codeMap)
            => app.UseErrorHandling(codeMap.MapErrorCode);

        public static void UseErrorHandling(this IApplicationBuilder app, Func<int, int> codeMap = null)
        {
            app.UseMiddleware<ErrorHandlerMiddleware>(codeMap);
        }

        public static void UseHealthCheck(this IApplicationBuilder app)
            => app.UseHealthCheck("/status/health-check");

        public static void UseHealthCheck(this IApplicationBuilder app, string path)
        {
            app.Map(path, builder =>
            {
                builder.UseMiddleware<HealthCheckMiddleware>();
            });
        }

        public static void UseReadOnlyMode(this IApplicationBuilder app)
        {
            app.UseMiddleware<ReadOnlyModeMiddleware>();
        }
    }
}

using System;
using Microsoft.AspNetCore.Hosting;
using TwentyTwenty.Mvc;
using TwentyTwenty.Mvc.ErrorHandling;
using TwentyTwenty.Mvc.HealthCheck;
using TwentyTwenty.Mvc.ReadOnlyMode;
using TwentyTwenty.Mvc.Version;

namespace Microsoft.AspNetCore.Builder
{
    public static class ErrorHandling
    {
        public static void UseErrorHandling(this IApplicationBuilder app, ICodeMap codeMap)
            => app.UseErrorHandling(codeMap.MapErrorCode);

        public static void UseErrorHandling(this IApplicationBuilder app, Func<int, int> codeMap = null)
        {
            app.UseMiddleware<ErrorHandlerMiddleware>(codeMap);
        }

        public static void UseHealthCheck(this IApplicationBuilder app)
            => app.UseHealthCheck("/status/health-check");

        public static void UseHealthCheck(this IApplicationBuilder app, string path)
        {
            app.Map(path, builder =>
            {
                builder.UseMiddleware<HealthCheckMiddleware>();
            });
        }

        public static void UseReadOnlyMode(this IApplicationBuilder app)
        {
            app.UseMiddleware<ReadOnlyModeMiddleware>();
        }

        public static void UseVersionHeader(this IApplicationBuilder app, string headerName = "api-version")
        {
            app.UseMiddleware<VersionHeaderMiddleware>(headerName);
        }
    }
}

Add extension method for using version header middleware.


using System.Runtime.CompilerServices;
using System.Reflection;

[assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Management")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Utility")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Security")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Linux.Host")]
[assembly:InternalsVisibleTo("PowerShell.Linux.Test")]
[assembly:InternalsVisibleTo("powershell")]
[assembly:AssemblyFileVersionAttribute("1.0.0.0")]
[assembly:AssemblyVersion("1.0.0.0")]

namespace System.Management.Automation
{
	internal class NTVerpVars
	{
		internal const int PRODUCTMAJORVERSION = 10;
		internal const int PRODUCTMINORVERSION = 0;
		internal const int PRODUCTBUILD        = 10032;
		internal const int PRODUCTBUILD_QFE    = 0;
		internal const int PACKAGEBUILD_QFE    = 814;
	}
}

using System.Runtime.CompilerServices;
using System.Reflection;

[assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Management")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Utility")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Security")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Linux.Host")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Linux.UnitTests")]
[assembly:InternalsVisibleTo("powershell")]
[assembly:AssemblyFileVersionAttribute("1.0.0.0")]
[assembly:AssemblyVersion("1.0.0.0")]

namespace System.Management.Automation
{
	internal class NTVerpVars
	{
		internal const int PRODUCTMAJORVERSION = 10;
		internal const int PRODUCTMINORVERSION = 0;
		internal const int PRODUCTBUILD        = 10032;
		internal const int PRODUCTBUILD_QFE    = 0;
		internal const int PACKAGEBUILD_QFE    = 814;
	}
}

Change SMA assembly info for DNX xUnit runner


using System;

namespace Stranne.VasttrafikNET.Extensions
{
    internal static class DateTimeOffsetExtension
    {
        private const string TimeZoneName = "W. Europe Standard Time";

        public static TimeSpan GetVasttrafikTimeOffset(this DateTimeOffset dateTimeOffset)
        {
            return TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName).GetUtcOffset(dateTimeOffset);
        }

        public static DateTimeOffset AddVasttrafikTimeSpan(this DateTimeOffset dateTimeOffset)
        {
            var timeOffset = dateTimeOffset.GetVasttrafikTimeOffset();
            return new DateTimeOffset(dateTimeOffset.DateTime, timeOffset);
        }

        public static DateTimeOffset ConvertToVasttrafikTimeZone(this DateTimeOffset dateTimeOffset)
        {
            return TimeZoneInfo.ConvertTime(dateTimeOffset, TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName));
        }
    }
}

using System;
using System.Runtime.InteropServices;

namespace Stranne.VasttrafikNET.Extensions
{
    internal static class DateTimeOffsetExtension
    {
        public static TimeSpan GetVasttrafikTimeOffset(this DateTimeOffset dateTimeOffset)
        {
            return TimeZoneInfo.FindSystemTimeZoneById(GetTimeZoneName()).GetUtcOffset(dateTimeOffset);
        }

        public static DateTimeOffset AddVasttrafikTimeSpan(this DateTimeOffset dateTimeOffset)
        {
            var timeOffset = dateTimeOffset.GetVasttrafikTimeOffset();
            return new DateTimeOffset(dateTimeOffset.DateTime, timeOffset);
        }

        public static DateTimeOffset ConvertToVasttrafikTimeZone(this DateTimeOffset dateTimeOffset)
        {
            return TimeZoneInfo.ConvertTime(dateTimeOffset, TimeZoneInfo.FindSystemTimeZoneById(GetTimeZoneName()));
        }

        private static string GetTimeZoneName() {
            var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            return isWindows
                ? "W. Europe Standard Time"
                : "Europe/Stockholm";
        }
    }
}

Fix time zone name on non windows platforms


using System;
using Android.Content;
using Android.Telephony;
using Uri = Android.Net.Uri;

namespace Plugin.Messaging
{
    internal class PhoneCallTask : IPhoneCallTask
    {
        public PhoneCallTask()
        {
        }

        #region IPhoneCallTask Members

        public bool CanMakePhoneCall
        {
            get { return true; }
        }

        public void MakePhoneCall(string number, string name = null)
        {
            if (string.IsNullOrWhiteSpace(number))
                throw new ArgumentException("number");

            if (CanMakePhoneCall)
            {
                var phoneNumber = PhoneNumberUtils.FormatNumber(number);

                Uri telUri = Uri.Parse("tel:" + phoneNumber);
                var dialIntent = new Intent(Intent.ActionDial, telUri);

                dialIntent.StartNewActivity();
            }
        }

        #endregion
    }
}

using System;
using Android.Content;
using Android.Telephony;
using Uri = Android.Net.Uri;

namespace Plugin.Messaging
{
    internal class PhoneCallTask : IPhoneCallTask
    {
        public PhoneCallTask()
        {
        }

        #region IPhoneCallTask Members

        public bool CanMakePhoneCall
        {
            get
            {
                var packageManager = Android.App.Application.Context.PackageManager;
                var dialIntent = new Intent(Intent.ActionDial);

                return null != dialIntent.ResolveActivity(packageManager);
            }
        }

        public void MakePhoneCall(string number, string name = null)
        {
            if (string.IsNullOrWhiteSpace(number))
                throw new ArgumentException("number");

            if (CanMakePhoneCall)
            {
                var phoneNumber = PhoneNumberUtils.FormatNumber(number);

                Uri telUri = Uri.Parse("tel:" + phoneNumber);
                var dialIntent = new Intent(Intent.ActionDial, telUri);

                dialIntent.StartNewActivity();
            }
        }

        #endregion
    }
}

Check if a phone call is possible on Andriod


using CK.AspNet.Auth;
using CK.Auth;
using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.AspNetCore.Http
{
    /// <summary>
    /// Exposes <see cref="WebFrontAuthenticate"/> extension method on <see cref="HttpContext"/>.
    /// </summary>
    static public class CKAspNetAuthHttpContextExtensions
    {
        /// <summary>
        /// Obtains the current <see cref="IAuthenticationInfo"/>, either because it is already
        /// in <see cref="HttpContext.Items"/> or by extracting authentication from request.
        /// It is never null, but can be <see cref="IAuthenticationInfoType.None"/>.
        /// </summary>
        /// <param name="this">This context.</param>
        /// <returns>Never null, can be <see cref="IAuthenticationInfoType.None"/>.</returns>
        static public IAuthenticationInfo WebFrontAuthenticate( this HttpContext @this )
        {
            IAuthenticationInfo authInfo = null;
            object o;
            if( @this.Items.TryGetValue( typeof( IAuthenticationInfo ), out o ) )
            {
                authInfo = (IAuthenticationInfo)o;
            }
            else
            {
                WebFrontAuthService s = (WebFrontAuthService)@this.RequestServices.GetService( typeof( WebFrontAuthService ) );
                if( s == null ) throw new InvalidOperationException( "Missing WebFrontAuthService registration in Services." );
                authInfo = s.ReadAndCacheAuthenticationHeader( @this ).Info;
            }
            return authInfo;
        }
    }
}

using CK.AspNet.Auth;
using CK.Auth;
using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.AspNetCore.Http
{
    /// <summary>
    /// Exposes <see cref="WebFrontAuthenticate"/> extension method on <see cref="HttpContext"/>.
    /// </summary>
    static public class CKAspNetAuthHttpContextExtensions
    {
        /// <summary>
        /// Obtains the current <see cref="IAuthenticationInfo"/>, either because it is already
        /// in <see cref="HttpContext.Items"/> or by extracting authentication from request.
        /// It is never null, but can be <see cref="IAuthenticationInfoType.None"/>.
        /// </summary>
        /// <param name="this">This context.</param>
        /// <returns>Never null, can be <see cref="IAuthenticationInfoType.None"/>.</returns>
        static public IAuthenticationInfo WebFrontAuthenticate( this HttpContext @this )
        {
            IAuthenticationInfo authInfo = null;
            object o;
            if( @this.Items.TryGetValue( typeof( FrontAuthenticationInfo ), out o ) )
            {
                authInfo = ((FrontAuthenticationInfo)o).Info;
            }
            else
            {
                WebFrontAuthService s = (WebFrontAuthService)@this.RequestServices.GetService( typeof( WebFrontAuthService ) );
                if( s == null ) throw new InvalidOperationException( "Missing WebFrontAuthService registration in Services." );
                authInfo = s.ReadAndCacheAuthenticationHeader( @this ).Info;
            }
            return authInfo;
        }
    }
}

Fix bad key in Context.Items.

Fix bad key in Context.Items.


using System.ComponentModel.DataAnnotations;

namespace BoozeHoundCloud.Models.Core
{
  public class Account
  {
    //-------------------------------------------------------------------------

    public const int NameMaxLength = 64;

    //-------------------------------------------------------------------------

    public int Id { get; set; }

    [MaxLength(NameMaxLength)]
    public string Name { get; set; }

    public AccountType AccountType { get; set; }

    public int AccountTypeId { get; set; }

    public decimal Balance { get; set; }

    //-------------------------------------------------------------------------
  }
}

using System.ComponentModel.DataAnnotations;

namespace BoozeHoundCloud.Models.Core
{
  public class Account
  {
    //-------------------------------------------------------------------------

    public const int NameMaxLength = 64;

    //-------------------------------------------------------------------------

    public int Id { get; set; }

    [MaxLength(NameMaxLength)]
    public string Name { get; set; }

    // Virtual so entity framework can lazy load.
    public virtual AccountType AccountType { get; set; }

    public int AccountTypeId { get; set; }

    public decimal Balance { get; set; }

    //-------------------------------------------------------------------------
  }
}

Fix for entity not loading from db.

Fix for entity not loading from db.


using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using JabbR.Infrastructure;
using JabbR.Services;

namespace JabbR.Middleware
{
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public class AuthorizationHandler
    {
        private readonly AppFunc _next;
        private readonly IAuthenticationTokenService _authenticationTokenService;

        public AuthorizationHandler(AppFunc next, IAuthenticationTokenService authenticationTokenService)
        {
            _next = next;
            _authenticationTokenService = authenticationTokenService;
        }

        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new Gate.Request(env);

            string userToken;
            string userId;
            if (request.Cookies.TryGetValue(Constants.UserTokenCookie, out userToken) &&
                _authenticationTokenService.TryGetUserId(userToken, out userId))
            {
                // Add the JabbR user id claim
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, userId));
                var identity = new ClaimsIdentity(claims, Constants.JabbRAuthType);

                var principal = (ClaimsPrincipal)env["server.User"];

                if (principal == null)
                {
                    principal = new ClaimsPrincipal(identity);
                }
                else
                {
                    // Add the jabbr identity to the current claims principal
                    principal.AddIdentity(identity);
                }

                env["server.User"] = principal;
            }

            return _next(env);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using JabbR.Infrastructure;
using JabbR.Services;

namespace JabbR.Middleware
{
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public class AuthorizationHandler
    {
        private readonly AppFunc _next;
        private readonly IAuthenticationTokenService _authenticationTokenService;

        public AuthorizationHandler(AppFunc next, IAuthenticationTokenService authenticationTokenService)
        {
            _next = next;
            _authenticationTokenService = authenticationTokenService;
        }

        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new Gate.Request(env);

            string userToken;
            string userId;
            if (request.Cookies.TryGetValue(Constants.UserTokenCookie, out userToken) &&
                _authenticationTokenService.TryGetUserId(userToken, out userId))
            {
                // Add the JabbR user id claim
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, userId));
                var identity = new ClaimsIdentity(claims, Constants.JabbRAuthType);
                env["server.User"] = new ClaimsPrincipal(identity);
            }

            return _next(env);
        }
    }
}

Create a new claims principal everytime if jabbr authenticated.


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

public class FistForceApply : MonoBehaviour {
	public static float forceAmount = 10000000f;
	public forceField forceField;
	public GameObject movingParentObj;
	public Vector3 oldPosition;

	void Start(){
		oldPosition = (movingParentObj.transform.position);
	}
	void FixedUpdate(){
		//Debug.Log ("VELO - "+GetComponent<Rigidbody>().velocity.magnitude);
		if((movingParentObj.transform.position - oldPosition).magnitude/Time.fixedDeltaTime >1f){
			forceField.turnOnForceField((movingParentObj.transform.position - oldPosition).normalized);
		}
		oldPosition = (movingParentObj.transform.position);
	}
	void OnCollisionEnter(Collision col)
	{
		if (col.gameObject.tag == "Fish") {
			Debug.Log ("COLLIDED - "+col.gameObject.name);
			col.rigidbody.AddForce (gameObject.GetComponent<Rigidbody>().velocity.normalized * Time.deltaTime * forceAmount);
		}
	}
}

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

public class FistForceApply : MonoBehaviour {
	public static float forceAmount = 10000000f;

	void OnCollisionEnter(Collision col)
	{
		if (col.gameObject.tag == "Fish") {
			Debug.Log ("COLLIDED - "+col.gameObject.name);
			col.rigidbody.AddForce (gameObject.GetComponent<Rigidbody>().velocity.normalized * Time.deltaTime * forceAmount);
		}
	}
}

Remove forcefield from fist movement

Remove forcefield from fist movement

PT


using BearLib;
using Roguelike.Entities;
using Roguelike.World;
using System.Collections.Generic;

namespace Roguelike.Render
{
    public abstract class Renderer : IRenderer
    {
        public const int MapLayer = 0;
        public const int EntityLayer = 5;

        public abstract void RenderEntities(IEnumerable<Entity> entities, Camera camera);

        public void RenderMap(Map map, Camera camera)
        {
            Terminal.Layer(MapLayer);

            for (int x = camera.Left; x < camera.Right; x++)
            {
                for (int y = camera.Top; y < camera.Bottom; y++)
                {
                    RenderTile(map, x, y, camera);
                }
            }
        }

        protected abstract void RenderTile(Map map, int x, int y, Camera camera);
    }
}

using BearLib;
using Roguelike.Entities;
using Roguelike.World;
using System.Collections.Generic;

namespace Roguelike.Render
{
    public abstract class Renderer : IRenderer
    {
        public const int MapLayer = 0;
        public const int EntityLayer = 10;

        public abstract void RenderEntities(IEnumerable<Entity> entities, Camera camera);

        public void RenderMap(Map map, Camera camera)
        {
            Terminal.Layer(MapLayer);

            for (int x = camera.Left; x < camera.Right; x++)
            {
                for (int y = camera.Top; y < camera.Bottom; y++)
                {
                    RenderTile(map, x, y, camera);
                }
            }
        }

        protected abstract void RenderTile(Map map, int x, int y, Camera camera);
    }
}

Adjust default entity rendering layer.

Adjust default entity rendering layer.


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

using System;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// Extension methods for adding directory browser services.
    /// </summary>
    public static class DirectoryBrowserServiceExtensions
    {
        /// <summary>
        /// Adds directory browser middleware services.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
        public static void AddDirectoryBrowser(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddWebEncoders();
        }
    }
}

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

using System;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// Extension methods for adding directory browser services.
    /// </summary>
    public static class DirectoryBrowserServiceExtensions
    {
        /// <summary>
        /// Adds directory browser middleware services.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
        /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
        public static IServiceCollection AddDirectoryBrowser(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddWebEncoders();

            return services;
        }
    }
}

Return IServiceCollection from AddDirectoryBrowser extension methods


using System;

namespace SharpDX
{
    /// <summary>
    /// Base class for a <see cref="IDisposable"/> class.
    /// </summary>
    public abstract class DisposeBase : IDisposable
    {
        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="DisposeBase"/> is reclaimed by garbage collection.
        /// </summary>
        ~DisposeBase()
        {
            // Finalizer calls Dispose(false)
            Dispose(false);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected abstract void Dispose(bool disposing);
    }
}

using System;

namespace SharpDX
{
    /// <summary>
    /// Base class for a <see cref="IDisposable"/> class.
    /// </summary>
    public abstract class DisposeBase : IDisposable
    {
        protected bool IsDisposed;

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="DisposeBase"/> is reclaimed by garbage collection.
        /// </summary>
        ~DisposeBase()
        {
            // Finalizer calls Dispose(false)
            Dispose(false);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            // TODO Should we throw an exception if this method is called more than once?
            if (!IsDisposed)
            {
                Dispose(true);
                GC.SuppressFinalize(this);
                IsDisposed = true;
            }
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected abstract void Dispose(bool disposing);
    }
}

[Core] Add IsDisposed safeguard to Dispose method


@using System.Globalization
@using Microsoft.Extensions.Configuration
@using MartinCostello.LondonTravel.Site
@using MartinCostello.LondonTravel.Site.Extensions
@using MartinCostello.LondonTravel.Site.Models
@using MartinCostello.LondonTravel.Site.Options
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@addTagHelper "*, LondonTravel.Site"
@inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet

@using System.Globalization
@using Microsoft.Extensions.Configuration
@using MartinCostello.LondonTravel.Site
@using MartinCostello.LondonTravel.Site.Extensions
@using MartinCostello.LondonTravel.Site.Identity
@using MartinCostello.LondonTravel.Site.Models
@using MartinCostello.LondonTravel.Site.Options
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@addTagHelper "*, LondonTravel.Site"
@inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet

Add Identity namespace to view imports

Add Identity namespace to view imports

Add the Identity namespace to the view imports.


using System;
using System.ComponentModel.Composition.Hosting;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MuffinFramework.Tests
{
    [TestClass]
    public class MuffinClientTests
    {
        [TestMethod]
        public void DoubleStartTest()
        {
            // arrange
            InvalidOperationException expectedException = null;
            var client = new MuffinClient(new AggregateCatalog());
            client.Start();

            // act
            try
            {
                // try to start the client a second time...
                client.Start();
            }
            catch (InvalidOperationException ex)
            {
                expectedException = ex;
            }

            // assert
            Assert.IsNotNull(expectedException);
        }
    }
}

using System;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MuffinFramework.Tests
{
    [TestClass]
    public class MuffinClientTests
    {
        [TestMethod]
        public void DoubleStartTest()
        {
            // arrange
            InvalidOperationException expectedException = null;
            var client = new MuffinClient(new AggregateCatalog());
            client.Start();

            // act
            try
            {
                // try to start the client a second time...
                client.Start();
            }
            catch (InvalidOperationException ex)
            {
                expectedException = ex;
            }

            // assert
            Assert.IsNotNull(expectedException);
        }

        [TestMethod]
        public void Constructor1Test()
        {
            // arrange

            // act
            var client = new MuffinClient();

            // assert
            Assert.IsNotNull(client.MuffinLoader);
            Assert.IsNotNull(client.ServiceLoader);
            Assert.IsNotNull(client.PlatformLoader);

            Assert.IsNotNull(client.AggregateCatalog);
            Assert.AreEqual(1, client.AggregateCatalog.Catalogs.Count);
        }

        [TestMethod]
        public void Constructor2Test()
        {
            // arrange
            var catalog = new AggregateCatalog();

            // act
            var client = new MuffinClient(catalog);

            // assert
            Assert.IsNotNull(client.MuffinLoader);
            Assert.IsNotNull(client.ServiceLoader);
            Assert.IsNotNull(client.PlatformLoader);
            Assert.AreSame(catalog, client.AggregateCatalog);
        }

        [TestMethod]
        public void Constructor3Test()
        {
            // arrange
            var catalog1 = new TypeCatalog();
            var catalog2 = new TypeCatalog();

            // act
            var client = new MuffinClient(catalog1, catalog2);

            // assert
            Assert.IsNotNull(client.MuffinLoader);
            Assert.IsNotNull(client.ServiceLoader);
            Assert.IsNotNull(client.PlatformLoader);

            Assert.IsNotNull(client.AggregateCatalog);
            Assert.AreEqual(2, client.AggregateCatalog.Catalogs.Count);
        }

        [TestMethod]
        public void Constructor4Test()
        {
            // arrange

            // act
            var client = new MuffinClient(new ComposablePartCatalog[] {});

            // assert
            Assert.IsNotNull(client.MuffinLoader);
            Assert.IsNotNull(client.ServiceLoader);
            Assert.IsNotNull(client.PlatformLoader);

            Assert.IsNotNull(client.AggregateCatalog);
            Assert.AreEqual(0, client.AggregateCatalog.Catalogs.Count);
        }
    }
}

Add tests for constructors of MuffinClient


using System.Collections.Generic;

namespace NFleet.Data
{
    public class VehicleDataSet : IResponseData, IVersioned
    {
        public static string MIMEType = "application/vnd.jyu.nfleet.vehicleset";
        public static string MIMEVersion = "2.0";

        int IVersioned.VersionNumber { get; set; }
        public List<VehicleData> Items { get; set; }
        public List<Link> Meta { get; set; }

        public VehicleDataSet()
        {
            Items = new List<VehicleData>();
            Meta = new List<Link>();
        }
    }
}

using System.Collections.Generic;

namespace NFleet.Data
{
    public class VehicleDataSet : IResponseData, IVersioned
    {
        public static string MIMEType = "application/vnd.jyu.nfleet.vehicleset";
        public static string MIMEVersion = "2.2";

        int IVersioned.VersionNumber { get; set; }
        public List<VehicleData> Items { get; set; }
        public List<Link> Meta { get; set; }

        public VehicleDataSet()
        {
            Items = new List<VehicleData>();
            Meta = new List<Link>();
        }
    }
}

Update vehicle data set mime type version to 2.2


#region

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;
using Owin;
using Saturn72.Core;
using Saturn72.Core.Configuration;
using Saturn72.Core.Extensibility;
using Saturn72.Extensions;

#endregion

namespace Saturn72.Module.Owin
{
    public class OwinModule : IModule
    {
        private string _baseUri;
        private CancellationTokenSource _tokenSource;

        public void Load()
        {
            _baseUri = ConfigManager.GetConfigMap<OwinConfigMap>().Config.ServerUri;
        }

        public void Start()
        {
            Guard.HasValue(_baseUri);
            Trace.WriteLine("Starting web Server. Feel free to browse to {0}...".AsFormat(_baseUri));
            _tokenSource = new CancellationTokenSource();

            Task.Run(() => StartWebServer(), _tokenSource.Token);
        }

        public void Stop()
        {
            _tokenSource.Cancel();
        }

        private void StartWebServer()
        {
            Action<IAppBuilder> startupAction =
                appBuilder => new Startup().Configure(appBuilder);

            using (WebApp.Start(_baseUri, startupAction))
            {
                Trace.WriteLine("web server started. uri: " + _baseUri);

                //TODO: remove busy wait from here . replace with HttpServer
                while (true)
                {
                    //Console.ReadLine();
                }
            }
            Console.WriteLine("web server stoped");
        }
    }
}

#region

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;
using Owin;
using Saturn72.Core;
using Saturn72.Core.Configuration;
using Saturn72.Core.Extensibility;
using Saturn72.Extensions;

#endregion

namespace Saturn72.Module.Owin
{
    public class OwinModule : IModule
    {
        private string _baseUri;
        private CancellationTokenSource _tokenSource;

        public void Load()
        {
            _baseUri = ConfigManager.GetConfigMap<OwinConfigMap>().Config.ServerUri;
        }

        public void Start()
        {
            Guard.HasValue(_baseUri);
            PublishUrlMessage();
            _tokenSource = new CancellationTokenSource();

            Task.Run(() => StartWebServer(), _tokenSource.Token);
        }

        private void PublishUrlMessage()
        {
            var tmpColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Cyan;
            Trace.WriteLine("Starting web Server. Feel free to browse to {0}...".AsFormat(_baseUri));
            Console.ForegroundColor = tmpColor;
        }

        public void Stop()
        {
            _tokenSource.Cancel();
        }

        private void StartWebServer()
        {
            Action<IAppBuilder> startupAction =
                appBuilder => new Startup().Configure(appBuilder);

            using (WebApp.Start(_baseUri, startupAction))
            {
                Trace.WriteLine("web server started. uri: " + _baseUri);

                //TODO: remove busy wait from here . replace with HttpServer
                while (true)
                {
                    //Console.ReadLine();
                }
            }
            Console.WriteLine("web server stoped");
        }
    }
}

Add cinsole coloring for server URL

Add cinsole coloring for server URL


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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace Nether.Web.IntegrationTests
{
    public class SwaggerTests
    {
        [Fact]
        public async Task GET_Swagger_returns_200_OK()
        {
            var client = new HttpClient();

            var response = await client.GetAsync("http://localhost:5000/api/swagger/v0.1/swagger.json");

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
    }
}

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace Nether.Web.IntegrationTests
{
    public class SwaggerTests
    {
        [Fact]
        public async Task GET_Swagger_returns_200_OK()
        {
            var client = new HttpClient();

            var response = await client.GetAsync($"{WebTestBase.BaseUrl}/api/swagger/v0.1/swagger.json");

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
    }
}

Use configured base url for swagger test


// 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Screens.OnlinePlay.Multiplayer.Match;

namespace osu.Game.Tests.Visual.Multiplayer
{
    public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene
    {
        [SetUp]
        public new void Setup() => Schedule(() =>
        {
            Child = new Container
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                RelativeSizeAxes = Axes.X,
                Height = 50,
                Child = new MultiplayerMatchFooter()
            };
        });
    }
}

// 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Game.Screens.OnlinePlay.Multiplayer.Match;

namespace osu.Game.Tests.Visual.Multiplayer
{
    public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene
    {
        [SetUp]
        public new void Setup() => Schedule(() =>
        {
            Child = new PopoverContainer
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                RelativeSizeAxes = Axes.X,
                Height = 50,
                Child = new MultiplayerMatchFooter()
            };
        });
    }
}

Fix `MultiplayerMatchFooter` test crash due to missing `PopoverContainer`

Clicking the countdown button would crash. I did consider removing the
test altogether but maybe it'll be useful in the future?


using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Documents;
using System.Windows.Media.Media3D;
using Common.Logging;
using NCmdLiner.SolutionCreator.Library.Common;

namespace NCmdLiner.SolutionCreator.Library.Services
{
    public class FolderResolver : IFolderResolver
    {
        private readonly ITextResolver _textResolver;
        private readonly IFileResolver _fileResolver;
        private readonly ILog _logger;

        public FolderResolver(ITextResolver textResolver, IFileResolver fileResolver, ILog logger)
        {
            _textResolver = textResolver;
            _fileResolver = fileResolver;
            _logger = logger;
        }

        public void Resolve(string sourceFolder, string targetFolder)
        {
            if (!Directory.Exists(sourceFolder)) throw new DirectoryNotFoundException("Source folder not found: " + sourceFolder);

            var sourceDirectory = new DirectoryInfo(sourceFolder);

            var sourceDirectories = sourceDirectory.GetDirectories("*", SearchOption.AllDirectories).ToList();
            var sourceFiles = sourceDirectory.GetFiles("*", SearchOption.AllDirectories).ToList();
            foreach (var sourceSubDirectory in sourceDirectories)
            {
                var targetSubDirectory = new DirectoryInfo(_textResolver.Resolve(sourceSubDirectory.FullName.Replace(sourceFolder, targetFolder)));
                Directory.CreateDirectory(targetSubDirectory.FullName);
            }

            foreach (var sourceFile in sourceFiles)
            {
                var targetFile = new FileInfo(_textResolver.Resolve(sourceFile.FullName.Replace(sourceFolder, targetFolder)));
                _fileResolver.Resolve(sourceFile.FullName, targetFile.FullName);
            }
        }
    }
}

using System.IO;
using System.Linq;
using Common.Logging;

namespace NCmdLiner.SolutionCreator.Library.Services
{
    public class FolderResolver : IFolderResolver
    {
        private readonly ITextResolver _textResolver;
        private readonly IFileResolver _fileResolver;
        private readonly ILog _logger;

        public FolderResolver(ITextResolver textResolver, IFileResolver fileResolver, ILog logger)
        {
            _textResolver = textResolver;
            _fileResolver = fileResolver;
            _logger = logger;
        }

        public void Resolve(string sourceFolder, string targetFolder)
        {
            if (!Directory.Exists(sourceFolder)) throw new DirectoryNotFoundException("Source folder not found: " + sourceFolder);

            var sourceDirectory = new DirectoryInfo(sourceFolder);

            var sourceDirectories = sourceDirectory.GetDirectories("*", SearchOption.AllDirectories).ToList();
            var sourceFiles = sourceDirectory.GetFiles("*", SearchOption.AllDirectories).ToList();
            foreach (var sourceSubDirectory in sourceDirectories)
            {
                var targetSubDirectory = new DirectoryInfo(_textResolver.Resolve(sourceSubDirectory.FullName.Replace(sourceFolder, targetFolder)));
                Directory.CreateDirectory(targetSubDirectory.FullName);
            }

            foreach (var sourceFile in sourceFiles)
            {
                if (sourceFile.Name == ".git" || sourceFile.Name == ".gitignore") continue;

                var targetFile = new FileInfo(_textResolver.Resolve(sourceFile.FullName.Replace(sourceFolder, targetFolder)));
                _fileResolver.Resolve(sourceFile.FullName, targetFile.FullName);
            }
        }
    }
}

Exclude git specific files from beeing resolved.


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

namespace DeploymentCockpit.Data
{
    public class UnitOfWorkFactory : IUnitOfWorkFactory
    {
        public IUnitOfWork Create()
        {
            return new UnitOfWork(new DeploymentCockpitEntities());
        }
    }
}

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

namespace DeploymentCockpit.Data
{
    public class UnitOfWorkFactory : IUnitOfWorkFactory
    {
        public IUnitOfWork Create()
        {
            var ctx = new DeploymentCockpitEntities();
            ctx.Configuration.LazyLoadingEnabled = false;
            return new UnitOfWork(ctx);
        }
    }
}

Disable Entity Framework Lazy Loading

Disable Entity Framework Lazy Loading


using System;
using Memoria.Prime.Ini;

namespace Memoria
{
    public sealed partial class Configuration
    {
        private sealed class GraphicsSection : IniSection
        {
            public readonly IniValue<Int32> BattleFPS;
            public readonly IniValue<Int32> MovieFPS;
            public readonly IniValue<Int32> BattleSwirlFrames;
            public readonly IniValue<Boolean> WidescreenSupport;
            public readonly IniValue<Int32> TileSize;
            public readonly IniValue<Int32> SkipIntros;
            public readonly IniValue<Int32> GarnetHair;

            public GraphicsSection() : base(nameof(GraphicsSection), false)
            {
                BattleFPS = BindInt32(nameof(BattleFPS), 15);
                MovieFPS = BindInt32(nameof(MovieFPS), 15);
                BattleSwirlFrames = BindInt32(nameof(BattleSwirlFrames), 115);
                WidescreenSupport = BindBoolean(nameof(WidescreenSupport), true);
                TileSize = BindInt32(nameof(TileSize), 64);
                SkipIntros = BindInt32(nameof(SkipIntros), 0);
                GarnetHair = BindInt32(nameof(GarnetHair), 0);
            }
        }
    }
}

using System;
using Memoria.Prime.Ini;

namespace Memoria
{
    public sealed partial class Configuration
    {
        private sealed class GraphicsSection : IniSection
        {
            public readonly IniValue<Int32> BattleFPS;
            public readonly IniValue<Int32> MovieFPS;
            public readonly IniValue<Int32> BattleSwirlFrames;
            public readonly IniValue<Boolean> WidescreenSupport;
            public readonly IniValue<Int32> TileSize;
            public readonly IniValue<Int32> SkipIntros;
            public readonly IniValue<Int32> GarnetHair;

            public GraphicsSection() : base(nameof(GraphicsSection), false)
            {
                BattleFPS = BindInt32(nameof(BattleFPS), 15);
                MovieFPS = BindInt32(nameof(MovieFPS), 15);
                BattleSwirlFrames = BindInt32(nameof(BattleSwirlFrames), 115);
                WidescreenSupport = BindBoolean(nameof(WidescreenSupport), true);
                TileSize = BindInt32(nameof(TileSize), 32);
                SkipIntros = BindInt32(nameof(SkipIntros), 0);
                GarnetHair = BindInt32(nameof(GarnetHair), 0);
            }
        }
    }
}

Set default tile size to 32. Change it via config.

Default tile size is 32. If you need to change it do that via Memoria.ini


using Digirati.IIIF.Model.JsonLD;
using Digirati.IIIF.Serialisation;
using Newtonsoft.Json;

namespace Digirati.IIIF.Model.Types.ImageApi
{
    // Also known as an "info.json"
    public class ImageService : JSONLDBase, IImageService, IHasService
    {
        // Allow additional context
        //public override dynamic Context
        //{
        //    get { return "http://iiif.io/api/image/2/context.json"; }
        //}

        [JsonProperty(Order = 4, PropertyName = "protocol")]
        public string Protocol
        {
            get { return "http://iiif.io/api/image"; }
        }

        [JsonProperty(Order = 35, PropertyName = "height")]
        public int? Height { get; set; }

        [JsonProperty(Order = 36, PropertyName = "width")]
        public int? Width { get; set; }

        [JsonProperty(Order = 37, PropertyName = "sizes")]
        public Size[] Sizes { get; set; }

        [JsonProperty(Order = 38, PropertyName = "tiles")]
        public TileSource[] Tiles { get; set; }

        // IProfile or IProfile[]
        [JsonProperty(Order = 39, PropertyName = "profile")]
        [JsonConverter(typeof(ProfileSerialiser))]
        public dynamic Profile { get; set; }

        // Service or Service[] - not currently an interface
        [JsonProperty(Order = 99, PropertyName = "service")]
        [JsonConverter(typeof(ServiceSerialiser))]
        public dynamic Service { get; set; }
    }
}

using Digirati.IIIF.Model.JsonLD;
using Digirati.IIIF.Serialisation;
using Newtonsoft.Json;

namespace Digirati.IIIF.Model.Types.ImageApi
{
    // Also known as an "info.json"
    public class ImageService : JSONLDBase, IImageService, IHasService
    {
        // Allow additional context
        //public override dynamic Context
        //{
        //    get { return "http://iiif.io/api/image/2/context.json"; }
        //}

        [JsonProperty(Order = 4, PropertyName = "protocol")]
        public string Protocol
        {
            get { return "http://iiif.io/api/image"; }
        }

        [JsonProperty(Order = 35, PropertyName = "height")]
        public int Height { get; set; }

        [JsonProperty(Order = 36, PropertyName = "width")]
        public int Width { get; set; }

        [JsonProperty(Order = 37, PropertyName = "sizes")]
        public Size[] Sizes { get; set; }

        [JsonProperty(Order = 38, PropertyName = "tiles")]
        public TileSource[] Tiles { get; set; }

        // IProfile or IProfile[]
        [JsonProperty(Order = 39, PropertyName = "profile")]
        [JsonConverter(typeof(ProfileSerialiser))]
        public dynamic Profile { get; set; }

        // Service or Service[] - not currently an interface
        [JsonProperty(Order = 99, PropertyName = "service")]
        [JsonConverter(typeof(ServiceSerialiser))]
        public dynamic Service { get; set; }
    }
}

Revert "Height and width should be optional according to the spec."

This reverts commit e19253c1157f95920ec6f7ff2ad49bc4aca1bac1.


using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;

namespace HotChocolatey.Administrative
{
    public class AdministrativeCommanderProvider
    {
        private Process administrativeProcess;

        public AdministrativeCommander Create(Action<string> outputLineCallback)
        {
            StartAdmin();
            return new AdministrativeCommander(outputLineCallback);
        }

        public void Close()
        {
            if (!(administrativeProcess?.HasExited ?? true))
            {
                new AdministrativeCommander(a => { }).Die();
            }
        }

        private void StartAdmin()
        {
            if (administrativeProcess?.HasExited ?? true)
            {
                administrativeProcess = new Process
                {
                    StartInfo =
                    {
                        FileName = GetFileName(),
                        Verb = "runas",
                        CreateNoWindow = true,
                        UseShellExecute = true,
                        WindowStyle = ProcessWindowStyle.Hidden
                    }
                };
                administrativeProcess.Start();

                Thread.Sleep(100);
            }
        }

        private static string GetFileName()
        {
            return Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "HotChocolateyAdministrator.exe");
        }
    }
}

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;

namespace HotChocolatey.Administrative
{
    public class AdministrativeCommanderProvider
    {
        private Process administrativeProcess;

        public AdministrativeCommander Create(Action<string> outputLineCallback)
        {
            StartAdmin();
            return new AdministrativeCommander(outputLineCallback);
        }

        public void Close()
        {
            if (!(administrativeProcess?.HasExited ?? true))
            {
                new AdministrativeCommander(a => { }).Die();
            }
        }

        private void StartAdmin()
        {
            if (administrativeProcess?.HasExited ?? true)
            {
                administrativeProcess = new Process
                {
                    StartInfo =
                    {
                        FileName = GetFileName(),
                        Verb = "runas",
                        CreateNoWindow = true,
                        UseShellExecute = true,
                        WindowStyle = ProcessWindowStyle.Hidden
                    }
                };
                administrativeProcess.Start();

                Thread.Sleep(100);
            }
        }

        private static string GetFileName()
        {
            return Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "HotChocolatey.Administrator.exe");
        }
    }
}

Fix crash when starting administrative by typo in filename


Add AssemblyFileVersion attribute to assembly


using System;
using System.Reactive.Disposables;
using SolidWorks.Interop.sldworks;

namespace SolidworksAddinFramework
{
    public static class ModelViewManagerExtensions
    {
        public static IDisposable CreateSectionView(this IModelViewManager modelViewManager, Action<SectionViewData> config)
        {
            var data = modelViewManager.CreateSectionViewData();
            config(data);
            if (!modelViewManager.CreateSectionView(data))
            {
                throw new Exception("Error while creating section view.");
            }
            // TODO `modelViewManager.RemoveSectionView` returns `false` and doesn't remove the section view
            // when `SectionViewData::GraphicsOnlySection` is `true`
            return Disposable.Create(() => modelViewManager.RemoveSectionView());
        }
    }
}

using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using SolidWorks.Interop.sldworks;

namespace SolidworksAddinFramework
{
    public static class ModelViewManagerExtensions
    {
        private static readonly ISubject<SectionViewData> _CreateSectionViewObservable = new Subject<SectionViewData>();

        public static IObservable<SectionViewData> CreateSectionViewObservable => _CreateSectionViewObservable.AsObservable();

        public static IDisposable CreateSectionView(this IModelViewManager modelViewManager, Action<SectionViewData> config)
        {
            var data = modelViewManager.CreateSectionViewData();
            config(data);
            _CreateSectionViewObservable.OnNext(data);
            if (!modelViewManager.CreateSectionView(data))
            {
                throw new Exception("Error while creating section view.");
            }
            // TODO `modelViewManager.RemoveSectionView` returns `false` and doesn't remove the section view
            // when `SectionViewData::GraphicsOnlySection` is `true`
            return Disposable.Create(() => modelViewManager.RemoveSectionView());
        }
    }
}

Add observable that fires when a section view is about to be created


using System.Web.Mvc;

namespace OdeToFood.Controllers
{
    public class CuisineController : Controller
    {
        //
        // GET: /Cuisine/

        // Without HTTP verbs, invoking search is ambiguous. (Note that the
        // MVC framework finds the request ambiguous even though R#
        // reports that the version of Search with the optional parameter
        // is **hidden** by the parameterless version.)
        public ActionResult Search(string name = "french")
        {
            // Back to returning simple content.
            var encodedName = Server.HtmlEncode(name);
            return Content(encodedName);
        }

        public ActionResult Search()
        {
            return Content("Search!");
        }

    }
}

using System.Web.Mvc;

namespace OdeToFood.Controllers
{
    public class CuisineController : Controller
    {
        //
        // GET: /Cuisine/

        // Using HTTP verbs allows the framework to resolve the ambiguity.
        [HttpPost]
        public ActionResult Search(string name = "french")
        {
            // Back to returning simple content.
            var encodedName = Server.HtmlEncode(name);
            return Content(encodedName);
        }

        [HttpGet]
        public ActionResult Search()
        {
            return Content("Search!");
        }

    }
}

Resolve ambiguity by using HTTP verbs.

Resolve ambiguity by using HTTP verbs.


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

using osu.Game.Beatmaps;
using osu.Game.Online.API.Requests.Responses;

namespace osu.Game.Online.API.Requests
{
    public class GetBeatmapRequest : APIRequest<APIBeatmap>
    {
        private readonly BeatmapInfo beatmapInfo;

        public GetBeatmapRequest(BeatmapInfo beatmapInfo)
        {
            this.beatmapInfo = beatmapInfo;
        }

        protected override string Target => $@"beatmaps/lookup?id={beatmapInfo.OnlineBeatmapID}&checksum={beatmapInfo.MD5Hash}&filename={System.Uri.EscapeUriString(beatmapInfo.Path ?? string.Empty)}";
    }
}

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

using osu.Game.Beatmaps;
using osu.Game.Online.API.Requests.Responses;

#nullable enable

namespace osu.Game.Online.API.Requests
{
    public class GetBeatmapRequest : APIRequest<APIBeatmap>
    {
        private readonly IBeatmapInfo beatmapInfo;

        private readonly string filename;

        public GetBeatmapRequest(IBeatmapInfo beatmapInfo)
        {
            this.beatmapInfo = beatmapInfo;

            filename = (beatmapInfo as BeatmapInfo)?.Path ?? string.Empty;
        }

        protected override string Target => $@"beatmaps/lookup?id={beatmapInfo.OnlineID}&checksum={beatmapInfo.MD5Hash}&filename={System.Uri.EscapeUriString(filename)}";
    }
}

Allow API beatmap requests using interface type


using System;

namespace ValveResourceFormat
{
    public enum BlockType
    {
#pragma warning disable 1591
        RERL = 1,
        REDI,
        NTRO,
        DATA,
        VBIB,
        VXVS,
        SNAP,
#pragma warning restore 1591
    }
}

using System;

namespace ValveResourceFormat
{
    public enum BlockType
    {
#pragma warning disable 1591
        RERL = 1,
        REDI,
        NTRO,
        DATA,
        VBIB,
        VXVS,
        SNAP,
        CTRL,
        MDAT,
        MBUF,
        ANIM,
        ASEQ,
        AGRP,
        PHYS,
#pragma warning restore 1591
    }
}

Add new block types to the enum

Add new block types to the enum


namespace DesktopWidgets.Widgets.LatencyMonitor
{
    public static class Metadata
    {
        public const string FriendlyName = "Latency Monitor";
    }
}

namespace DesktopWidgets.Widgets.LatencyMonitor
{
    public static class Metadata
    {
        public const string FriendlyName = "Network Monitor";
    }
}

Rename "Latency Monitor" widget to "Network Monitor"


using System;
using System.Xml;
using Magecrawl.GameEngine.Effects.EffectResults;

namespace Magecrawl.GameEngine.Effects
{
    internal class ShortTermEffect : StatusEffect
    {
        public ShortTermEffect()
        {
            CTLeft = 0;
            m_effectResult = null;
        }

        public ShortTermEffect(EffectResult effect)
        {
            CTLeft = 0;
            m_effectResult = effect;
        }

        public int CTLeft { get; set; }

        public void Extend(double ratio)
        {
            CTLeft = (int)(CTLeft * ratio);
        }

        public virtual void DecreaseCT(int decrease)
        {
            CTLeft -= decrease;
        }

        internal override void Dismiss()
        {
            CTLeft = 0;
        }

        internal override void SetDefaults()
        {
            CTLeft = m_effectResult.DefaultEffectLength;
        }

        #region IXmlSerializable Members

        public override void ReadXml(XmlReader reader)
        {
            base.ReadXml(reader);
            CTLeft = reader.ReadElementContentAsInt();
        }

        public override void WriteXml(XmlWriter writer)
        {
            base.WriteXml(writer);
            writer.WriteElementString("CTLeft", CTLeft.ToString());
        }

        #endregion
    }
}

using System;
using System.Xml;
using Magecrawl.GameEngine.Effects.EffectResults;

namespace Magecrawl.GameEngine.Effects
{
    internal class ShortTermEffect : StatusEffect
    {
        public ShortTermEffect()
        {
            CTLeft = 0;
            m_effectResult = null;
        }

        public ShortTermEffect(EffectResult effect)
        {
            CTLeft = 0;
            m_effectResult = effect;
        }

        public int CTLeft { get; set; }

        public void Extend(double ratio)
        {
            CTLeft = (int)(CTLeft * ratio);
        }

        public virtual void DecreaseCT(int decrease)
        {
            CTLeft -= decrease;
            m_effectResult.DecreaseCT(decrease, CTLeft);
        }

        internal override void Dismiss()
        {
            CTLeft = 0;
        }

        internal override void SetDefaults()
        {
            CTLeft = m_effectResult.DefaultEffectLength;
        }

        #region IXmlSerializable Members

        public override void ReadXml(XmlReader reader)
        {
            base.ReadXml(reader);
            CTLeft = reader.ReadElementContentAsInt();
        }

        public override void WriteXml(XmlWriter writer)
        {
            base.WriteXml(writer);
            writer.WriteElementString("CTLeft", CTLeft.ToString());
        }

        #endregion
    }
}

Fix poison and short term effects that weren't working due to missing call to effectResult on DecreaseCT.