using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace LMP.MasterServer
{
    public class Helper
    {
        public static string GetOwnIpAddress()
        {
            var currentIpAddress = TryGetIpAddress("http://ip.42.pl/raw");

            if (string.IsNullOrEmpty(currentIpAddress))
                currentIpAddress = TryGetIpAddress("https://api.ipify.org/");
            if (string.IsNullOrEmpty(currentIpAddress))
                currentIpAddress = TryGetIpAddress("http://httpbin.org/ip");
            if (string.IsNullOrEmpty(currentIpAddress))
                currentIpAddress = TryGetIpAddress("http://checkip.dyndns.org");

            return currentIpAddress;
        }

        private static string TryGetIpAddress(string url)
        {
            using (var client = new WebClient())
            using (var stream = client.OpenRead(url))
            {
                if (stream == null) return null;
                using (var reader = new StreamReader(stream))
                {
                    var ipRegEx = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
                    var result = ipRegEx.Matches(reader.ReadToEnd());

                    if (IPAddress.TryParse(result[0].Value, out var ip))
                        return ip.ToString();
                }
            }
            return null;
        }
    }
}

using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace LMP.MasterServer
{
    public class Helper
    {
        public static string GetOwnIpAddress()
        {
            var currentIpAddress = TryGetIpAddress("http://ip.42.pl/raw");

            if (string.IsNullOrEmpty(currentIpAddress))
                currentIpAddress = TryGetIpAddress("https://api.ipify.org/");
            if (string.IsNullOrEmpty(currentIpAddress))
                currentIpAddress = TryGetIpAddress("http://httpbin.org/ip");
            if (string.IsNullOrEmpty(currentIpAddress))
                currentIpAddress = TryGetIpAddress("http://checkip.dyndns.org");

            return currentIpAddress;
        }

        private static string TryGetIpAddress(string url)
        {
            try
            {
                using (var client = new WebClient())
                using (var stream = client.OpenRead(url))
                {
                    if (stream == null) return null;
                    using (var reader = new StreamReader(stream))
                    {
                        var ipRegEx = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
                        var result = ipRegEx.Matches(reader.ReadToEnd());

                        if (IPAddress.TryParse(result[0].Value, out var ip))
                            return ip.ToString();
                    }
                }
            }
            catch
            {
                // ignored
            }

            return null;
        }
    }
}

Fix master server address retrieve

Fix master server address retrieve


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Manifest;
using Umbraco.Web.UI.JavaScript;

namespace Umbraco.Tests.AngularIntegration
{
    [TestFixture]
    public class JsInitializationTests
    {

        [Test]
        public void Get_Default_Init()
        {
            var init = JsInitialization.GetDefaultInitialization();
            Assert.IsTrue(init.Any());
        }

        [Test]
        public void Parse_Main()
        {
            var result = JsInitialization.ParseMain(new[] {"[World]", "Hello" });

            Assert.AreEqual(@"
yepnope({
    load: [
         'lib/jquery/jquery-2.0.3.min.js',
         'lib/angular/1.1.5/angular.min.js',
         'lib/underscore/underscore.js',
    ],
    complete: function () {
        yepnope({
            load: [World],
            complete: function () {

                //we need to set the legacy UmbClientMgr path
                UmbClientMgr.setUmbracoPath('Hello');

                jQuery(document).ready(function () {
                    angular.bootstrap(document, ['umbraco']);
                });
            }
        });
    }
});", result);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Manifest;
using Umbraco.Web.UI.JavaScript;

namespace Umbraco.Tests.AngularIntegration
{
    [TestFixture]
    public class JsInitializationTests
    {

        [Test]
        public void Get_Default_Init()
        {
            var init = JsInitialization.GetDefaultInitialization();
            Assert.IsTrue(init.Any());
        }

        [Test]
        public void Parse_Main()
        {
            var result = JsInitialization.ParseMain(new[] {"[World]", "Hello" });

            Assert.AreEqual(@"LazyLoad.js([World], function () {
    //we need to set the legacy UmbClientMgr path
    UmbClientMgr.setUmbracoPath('Hello');

    jQuery(document).ready(function () {
        angular.bootstrap(document, ['umbraco']);
    });
});", result);
        }
    }
}

Fix unit test that was failing after moving from yepnope to LazyLoad.js


using Robust.Client.GameObjects;
using Robust.Client.Interfaces.GameObjects.Components;
using static Content.Shared.GameObjects.Components.SharedWiresComponent;

namespace Content.Client.GameObjects.Components.Wires
{
    public class WiresVisualizer : AppearanceVisualizer
    {
        public override void OnChangeData(AppearanceComponent component)
        {
            base.OnChangeData(component);

            var sprite = component.Owner.GetComponent<ISpriteComponent>();
            if (component.TryGetData<bool>(WiresVisuals.MaintenancePanelState, out var state))
            {
                sprite.LayerSetVisible(WiresVisualLayers.MaintenancePanel, state);
            }
        }

        public enum WiresVisualLayers
        {
            MaintenancePanel,
        }
    }
}

using Robust.Client.GameObjects;
using Robust.Client.Interfaces.GameObjects.Components;
using static Content.Shared.GameObjects.Components.SharedWiresComponent;

namespace Content.Client.GameObjects.Components.Wires
{
    public class WiresVisualizer : AppearanceVisualizer
    {
        public override void OnChangeData(AppearanceComponent component)
        {
            base.OnChangeData(component);

            if (component.Owner.Deleted)
                return;

            var sprite = component.Owner.GetComponent<ISpriteComponent>();
            if (component.TryGetData<bool>(WiresVisuals.MaintenancePanelState, out var state))
            {
                sprite.LayerSetVisible(WiresVisualLayers.MaintenancePanel, state);
            }
        }

        public enum WiresVisualLayers
        {
            MaintenancePanel,
        }
    }
}

Fix rare crash when deleting airlock while the deny animation is playing


#region

using System.Diagnostics;
using System.IO;
using System.Threading;
using SteamAccountSwitcher.Properties;

#endregion

namespace SteamAccountSwitcher
{
    internal class SteamClient
    {
        public static void LogIn(Account account)
        {
            Process.Start(Settings.Default.SteamPath,
                $"{Resources.SteamLoginArgument} \"{account.Username}\" \"{account.Password}\"");
        }

        public static void LogOut()
        {
            Process.Start(Settings.Default.SteamPath, Resources.SteamShutdownArgument);
        }

        public static bool LogOutAuto()
        {
            var timeout = 0;
            const int maxtimeout = 5000;
            const int waitstep = 500;
            if (IsSteamOpen())
            {
                LogOut();
                while (IsSteamOpen())
                {
                    if (timeout >= maxtimeout)
                    {
                        Popup.Show("Logout operation has timed out. Please force close steam and try again.");
                        return false;
                    }
                    Thread.Sleep(waitstep);
                    timeout += waitstep;
                }
            }
            return true;
        }

        public static string ResolvePath()
        {
            if (File.Exists(Resources.SteamPath32))
                return Resources.SteamPath32;
            if (File.Exists(Resources.SteamPath64))
                return Resources.SteamPath64;
            Popup.Show("Default Steam path could not be located.\r\n\r\nPlease enter Steam executable location.");
            var dia = new SteamPath();
            dia.ShowDialog();
            return dia.Path;
        }

        public static bool IsSteamOpen()
        {
            return (Process.GetProcessesByName(Resources.Steam).Length > 0);
        }
    }
}

#region

using System.Diagnostics;
using System.IO;
using System.Threading;
using SteamAccountSwitcher.Properties;

#endregion

namespace SteamAccountSwitcher
{
    internal class SteamClient
    {
        public static void LogIn(Account account)
        {
            Process.Start(Settings.Default.SteamPath,
                $"{Resources.SteamLoginArgument} \"{account.Username}\" \"{account.Password}\"");
        }

        public static void LogOut()
        {
            Process.Start(Settings.Default.SteamPath, Resources.SteamShutdownArgument);
        }

        public static bool LogOutAuto()
        {
            var timeout = 0;
            const int maxtimeout = 10000;
            const int waitstep = 100;
            if (IsSteamOpen())
            {
                LogOut();
                while (IsSteamOpen())
                {
                    if (timeout >= maxtimeout)
                    {
                        Popup.Show("Logout operation has timed out. Please force close steam and try again.");
                        return false;
                    }
                    Thread.Sleep(waitstep);
                    timeout += waitstep;
                }
            }
            return true;
        }

        public static string ResolvePath()
        {
            if (File.Exists(Resources.SteamPath32))
                return Resources.SteamPath32;
            if (File.Exists(Resources.SteamPath64))
                return Resources.SteamPath64;
            Popup.Show("Default Steam path could not be located.\r\n\r\nPlease enter Steam executable location.");
            var dia = new SteamPath();
            dia.ShowDialog();
            return dia.Path;
        }

        public static bool IsSteamOpen()
        {
            return (Process.GetProcessesByName(Resources.Steam).Length > 0);
        }
    }
}

Change Steam switch timeout and check time


// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using Perspex.Platform;

namespace Perspex.Gtk
{
    /// <summary>
    /// Loads assets compiled into the application binary.
    /// </summary>
    public class AssetLoader : IAssetLoader
    {
        /// <summary>
        /// Opens the resource with the requested URI.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns>A stream containing the resource contents.</returns>
        /// <exception cref="FileNotFoundException">
        /// The resource was not found.
        /// </exception>
        public Stream Open(Uri uri)
        {
            var assembly = Assembly.GetEntryAssembly();
            var resourceName = assembly.GetName().Name + ".g";
            var manager = new ResourceManager(resourceName, assembly);

            using (var resourceSet = manager.GetResourceSet(CultureInfo.CurrentCulture, true, true))
            {
                var stream = (Stream)resourceSet.GetObject(uri.ToString(), true);

                if (stream == null)
                {
                    throw new FileNotFoundException($"The requested asset could not be found: {uri}");
                }

                return stream;
            }
        }
    }
}

// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using Perspex.Platform;

namespace Perspex.Gtk
{
    /// <summary>
    /// Loads assets compiled into the application binary.
    /// </summary>
    public class AssetLoader : IAssetLoader
    {
        /// <summary>
        /// Opens the resource with the requested URI.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns>A stream containing the resource contents.</returns>
        /// <exception cref="FileNotFoundException">
        /// The resource was not found.
        /// </exception>
        public Stream Open(Uri uri)
        {
            var assembly = Assembly.GetEntryAssembly();
            return assembly.GetManifestResourceStream(uri.ToString());
        }
    }
}

Load from embedded resources on GTK too.


                Patron's Trophy

                Entries for Parton's Trophy close Thursday, 2nd June 2016. Learn more or enter now!

                Recent Updates

Link to Association Croquet World Rankings added to resources.

Link to Golf Croquet World Rankings added to resources.

Remove sticky note 'Patron's Trophy'

Remove sticky note 'Patron's Trophy'


using Microsoft.Extensions.Configuration;
using RockLib.Messaging;

namespace RockLib.Configuration.MessagingProvider
{
    public static class RockLibMessagingProviderExtensions
    {
        public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, string scenarioName) =>
            builder.AddRockLibMessagingProvider(MessagingScenarioFactory.CreateReceiver(scenarioName));

        public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, IReceiver receiver) =>
            builder.Add(new MessagingConfigurationSource(receiver));
    }
}

using Microsoft.Extensions.Configuration;
using RockLib.Messaging;

namespace RockLib.Configuration.MessagingProvider
{
    public static class RockLibMessagingProviderExtensions
    {
        public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, string scenarioName) =>
            builder.AddRockLibMessagingProvider(builder.Build().GetSection("RockLib.Messaging").CreateReceiver(scenarioName));

        public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, IReceiver receiver) =>
            builder.Add(new MessagingConfigurationSource(receiver));
    }
}

Build the builder in order to create the receiver

Don't access MessagingScenarioFactory.Configuration unnecessarily.


@model IEnumerable<Zk.Models.Crop>

@{
    ViewBag.Title = "Gewassen";
}

Dit zijn de gewassen in de database:

    	Id	Naam	Ras	Categorie	Opp. per 1
    		Opp. per zak	Prijs per zakje	Zaaimaanden	Oogstmaanden

		@foreach (var crop in Model) {

	    	@crop.Id	@crop.Name	@crop.Race	@crop.Category	@crop.AreaPerCrop
	    		@crop.AreaPerBag	@crop.PricePerBag
	    		@crop.SowingMonths	@crop.HarvestingMonths

		}

Terug naar thuis.

@model IEnumerable<Zk.Models.Crop>

@{
    ViewBag.Title = "Gewassen";
}

Dit zijn de gewassen in de database:

    	Id	Naam	Ras	Categorie	Opp. per 1
    		Opp. per zak	Prijs per zakje	Zaaimaanden	Oogstmaanden

		@foreach (var crop in Model) {

	    	@crop.Id	@crop.Name	@crop.Race	@crop.Category	@crop.AreaPerCrop
	    		@crop.AreaPerBag	@crop.PricePerBag
	    		@crop.SowingMonths	@crop.HarvestingMonths

		}

@Html.ActionLink("Terug naar thuis", "Index",  "Home",  null, null)

Adjust font size of data list page

Adjust font size of data list page


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SerializationDummyFactory.cs" company="OBeautifulCode">
//   Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// <auto-generated>
//   Sourced from NuGet package. Will be overwritten with package update except in OBeautifulCode.Serialization.Test source.
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------

namespace OBeautifulCode.Serialization.Test
{
    using FakeItEasy;
    using OBeautifulCode.AutoFakeItEasy;

    using OBeautifulCode.Serialization;

    /// <summary>
    /// A Dummy Factory for types in <see cref="OBeautifulCode.Serialization"/>.
    /// </summary>
#if !OBeautifulCodeSerializationSolution
    [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    [System.CodeDom.Compiler.GeneratedCode("OBeautifulCode.Serialization.Test", "See package version number")]
    internal
#else
    public
#endif
    class SerializationDummyFactory : DefaultSerializationDummyFactory
    {
        public SerializationDummyFactory()
        {
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationKind.Invalid, SerializationKind.Proprietary);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationFormat.Invalid, SerializationFormat.Null);

            #if OBeautifulCodeSerializationSolution
            AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<KeyOrValueObjectHierarchyBase>();
            AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<TestBase>();
            #endif

            AutoFixtureBackedDummyFactory.AddDummyCreator(()=> new TestEvent1(A.Dummy<short>(), A.Dummy<UtcDateTime>()));
            AutoFixtureBackedDummyFactory.AddDummyCreator(()=> new TestEvent2(A.Dummy<short>(), A.Dummy<UtcDateTime>()));
        }
    }
}

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SerializationDummyFactory.cs" company="OBeautifulCode">
//   Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// <auto-generated>
//   Sourced from NuGet package. Will be overwritten with package update except in OBeautifulCode.Serialization.Test source.
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------

namespace OBeautifulCode.Serialization.Test
{
    using OBeautifulCode.AutoFakeItEasy;

    using OBeautifulCode.Serialization;

    /// <summary>
    /// A Dummy Factory for types in <see cref="OBeautifulCode.Serialization"/>.
    /// </summary>
#if !OBeautifulCodeSerializationSolution
    [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    [System.CodeDom.Compiler.GeneratedCode("OBeautifulCode.Serialization.Test", "See package version number")]
    internal
#else
    public
#endif
    class SerializationDummyFactory : DefaultSerializationDummyFactory
    {
        public SerializationDummyFactory()
        {
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationKind.Invalid, SerializationKind.Proprietary);
            AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationFormat.Invalid, SerializationFormat.Null);

            #if OBeautifulCodeSerializationSolution
            AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<KeyOrValueObjectHierarchyBase>();
            AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<TestBase>();
            #endif
        }
    }
}

Revert "unit test bug fix"

Revert "unit test bug fix"

This reverts commit 47cf11fbc23ddabc98b7c008ba122a63c344f3fb.


using NUnit.Framework;

namespace TagLib.Tests.Images.Validators
{
	/// <summary>
	///    This class tests the modification of the Comment field,
	///    regardless of which metadata format is used.
	/// </summary>
	public class CommentModificationValidator : IMetadataModificationValidator
	{
		string orig_comment;
		readonly string test_comment = "This is a TagLib# &Test?Comment%$@_ ";

		public CommentModificationValidator (string orig_comment)
		{
			this.orig_comment = orig_comment;
		}

		/// <summary>
		///    Check if the original comment is found.
		/// </summary>
		public virtual void ValidatePreModification (Image.File file) {
			Assert.AreEqual (orig_comment, GetTag (file).Comment);
		}

		/// <summary>
		///    Changes the comment.
		/// </summary>
		public virtual void ModifyMetadata (Image.File file) {
			GetTag (file).Comment = test_comment;
		}

		/// <summary>
		///    Validates if changes survived a write.
		/// </summary>
		public void ValidatePostModification (Image.File file) {
			Assert.AreEqual (test_comment, GetTag (file).Comment);
		}

		/// <summary>
		///    Returns the tag that should be tested. Default
		///    behavior is no specific tag.
		/// </summary>
		public virtual Image.ImageTag GetTag (Image.File file) {
			return file.ImageTag;
		}
	}
}

using System;
using NUnit.Framework;

namespace TagLib.Tests.Images.Validators
{
	/// <summary>
	///    This class tests the modification of the Comment field,
	///    regardless of which metadata format is used.
	/// </summary>
	public class CommentModificationValidator : IMetadataModificationValidator
	{
		string orig_comment;
		readonly string test_comment = "This is a TagLib# &Test?Comment%$@_ ";

		public CommentModificationValidator () : this (String.Empty) { }

		public CommentModificationValidator (string orig_comment)
		{
			this.orig_comment = orig_comment;
		}

		/// <summary>
		///    Check if the original comment is found.
		/// </summary>
		public virtual void ValidatePreModification (Image.File file) {
			Assert.AreEqual (orig_comment, GetTag (file).Comment);
		}

		/// <summary>
		///    Changes the comment.
		/// </summary>
		public virtual void ModifyMetadata (Image.File file) {
			GetTag (file).Comment = test_comment;
		}

		/// <summary>
		///    Validates if changes survived a write.
		/// </summary>
		public void ValidatePostModification (Image.File file) {
			Assert.AreEqual (test_comment, GetTag (file).Comment);
		}

		/// <summary>
		///    Returns the tag that should be tested. Default
		///    behavior is no specific tag.
		/// </summary>
		public virtual Image.ImageTag GetTag (Image.File file) {
			return file.ImageTag;
		}
	}
}

Add empty constructor for files that don't have a comment yet.


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

using System;
using System.Threading;

namespace RazorWebSite
{
    public class WaitService
    {
        private static readonly TimeSpan _waitTime = TimeSpan.FromSeconds(10);
        private readonly ManualResetEventSlim _serverResetEvent = new ManualResetEventSlim();
        private readonly ManualResetEventSlim _clientResetEvent = new ManualResetEventSlim();

        public void NotifyClient()
        {
            _clientResetEvent.Set();
        }

        public void WaitForClient()
        {
            _clientResetEvent.Set();
            _serverResetEvent.Wait(_waitTime);
            _serverResetEvent.Reset();
        }

        public void WaitForServer()
        {
            _serverResetEvent.Set();
            _clientResetEvent.Wait(_waitTime);
            _clientResetEvent.Reset();
        }
    }
}

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

using System;
using System.Threading;

namespace RazorWebSite
{
    public class WaitService
    {
        private static readonly TimeSpan _waitTime = TimeSpan.FromSeconds(60);
        private readonly ManualResetEventSlim _serverResetEvent = new ManualResetEventSlim();
        private readonly ManualResetEventSlim _clientResetEvent = new ManualResetEventSlim();

        public void NotifyClient()
        {
            _clientResetEvent.Set();
        }

        public void WaitForClient()
        {
            _clientResetEvent.Set();

            if (!_serverResetEvent.Wait(_waitTime))
            {
                throw new InvalidOperationException("Timeout exceeded");
            }

            _serverResetEvent.Reset();
        }

        public void WaitForServer()
        {
            _serverResetEvent.Set();

            if (!_clientResetEvent.Wait(_waitTime))
            {
                throw new InvalidOperationException("Timeout exceeded");
            }

            _clientResetEvent.Reset();
        }
    }
}

Make wait service not timeout without yelling, and making the timeout longer


/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation.
 *
 * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
 * copy of the license can be found in the License.html file at the root of this distribution. If
 * you cannot locate the Apache License, Version 2.0, please send an email to
 * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
 * by the terms of the Apache License, Version 2.0.
 *
 * You must not remove this notice, or any other, from this software.
 *
 * ***************************************************************************/

using System;
using System.Runtime.InteropServices;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio.Shell;

namespace Microsoft.PythonTools.InterpreterList {
    [Guid(PythonConstants.InterpreterListToolWindowGuid)]
    class InterpreterListToolWindow : ToolWindowPane {
        const string Title = "Python Interpreters";

        public InterpreterListToolWindow() {
            Caption = Title;

            Content = new InterpreterList(
                PythonToolsPackage.ComponentModel.GetService<IInterpreterOptionsService>(),
                PythonToolsPackage.Instance);
        }
    }
}

/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation.
 *
 * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
 * copy of the license can be found in the License.html file at the root of this distribution. If
 * you cannot locate the Apache License, Version 2.0, please send an email to
 * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
 * by the terms of the Apache License, Version 2.0.
 *
 * You must not remove this notice, or any other, from this software.
 *
 * ***************************************************************************/

using System;
using System.Runtime.InteropServices;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Project;
using Microsoft.VisualStudio.Shell;

namespace Microsoft.PythonTools.InterpreterList {
    [Guid(PythonConstants.InterpreterListToolWindowGuid)]
    class InterpreterListToolWindow : ToolWindowPane {
        public InterpreterListToolWindow() {
            Caption = SR.GetString(SR.Interpreters);

            Content = new InterpreterList(
                PythonToolsPackage.ComponentModel.GetService<IInterpreterOptionsService>(),
                PythonToolsPackage.Instance);
        }
    }
}

Fix caption of Python Environments window.


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

using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
    internal static class SymbolInfoExtensions
    {
        public static IEnumerable<ISymbol> GetAllSymbols(this SymbolInfo info)
        {
            return info.Symbol == null && info.CandidateSymbols.Length == 0
                ? SpecializedCollections.EmptyEnumerable<ISymbol>()
                : GetAllSymbolsWorker(info).Distinct();
        }

        private static IEnumerable<ISymbol> GetAllSymbolsWorker(this SymbolInfo info)
        {
            if (info.Symbol != null)
            {
                yield return info.Symbol;
            }

            foreach (var symbol in info.CandidateSymbols)
            {
                yield return symbol;
            }
        }

        public static ISymbol GetAnySymbol(this SymbolInfo info)
        {
            return info.GetAllSymbols().FirstOrDefault();
        }

        public static IEnumerable<ISymbol> GetBestOrAllSymbols(this SymbolInfo info)
        {
            if (info.Symbol != null)
            {
                return SpecializedCollections.SingletonEnumerable(info.Symbol);
            }
            else if (info.CandidateSymbols.Length > 0)
            {
                return info.CandidateSymbols;
            }

            return SpecializedCollections.EmptyEnumerable<ISymbol>();
        }
    }
}

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

using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
    internal static class SymbolInfoExtensions
    {
        public static IEnumerable<ISymbol> GetAllSymbols(this SymbolInfo info)
        {
            return info.Symbol == null && info.CandidateSymbols.Length == 0
                ? SpecializedCollections.EmptyEnumerable<ISymbol>()
                : GetAllSymbolsWorker(info).Distinct();
        }

        private static IEnumerable<ISymbol> GetAllSymbolsWorker(this SymbolInfo info)
        {
            if (info.Symbol != null)
            {
                yield return info.Symbol;
            }

            foreach (var symbol in info.CandidateSymbols)
            {
                yield return symbol;
            }
        }

        public static ISymbol GetAnySymbol(this SymbolInfo info)
        {
            return info.Symbol != null
                ? info.Symbol
                : info.CandidateSymbols.FirstOrDefault();
        }

        public static IEnumerable<ISymbol> GetBestOrAllSymbols(this SymbolInfo info)
        {
            if (info.Symbol != null)
            {
                return SpecializedCollections.SingletonEnumerable(info.Symbol);
            }
            else if (info.CandidateSymbols.Length > 0)
            {
                return info.CandidateSymbols;
            }

            return SpecializedCollections.EmptyEnumerable<ISymbol>();
        }
    }
}

Unwind some Linq in a relatively hot path


using FBCore.Concurrency;
using ImagePipeline.Image;
using ImagePipeline.Memory;
using ImagePipeline.Request;
using System.IO;
using System.Threading.Tasks;

namespace ImagePipeline.Producers
{
    /// <summary>
    /// Represents a local file fetch producer.
    /// </summary>
    public class LocalFileFetchProducer : LocalFetchProducer
    {
        internal const string PRODUCER_NAME = "LocalFileFetchProducer";

        /// <summary>
        /// Instantiates the <see cref="LocalFileFetchProducer"/>.
        /// </summary>
        public LocalFileFetchProducer(
            IExecutorService executor,
            IPooledByteBufferFactory pooledByteBufferFactory) : base(
                executor,
                pooledByteBufferFactory)
        {
        }

        /// <summary>
        /// Gets the encoded image.
        /// </summary>
        protected override Task<EncodedImage> GetEncodedImage(ImageRequest imageRequest)
        {
            FileInfo file = (FileInfo)imageRequest.SourceFile;
            return Task.FromResult(GetEncodedImage(file.OpenRead(), (int)(file.Length)));
        }

        /// <summary>
        /// The name of the Producer.
        /// </summary>
        protected override string ProducerName
        {
            get
            {
                return PRODUCER_NAME;
            }
        }
    }
}

using FBCore.Concurrency;
using ImagePipeline.Image;
using ImagePipeline.Memory;
using ImagePipeline.Request;
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;

namespace ImagePipeline.Producers
{
    /// <summary>
    /// Represents a local file fetch producer.
    /// </summary>
    public class LocalFileFetchProducer : LocalFetchProducer
    {
        internal const string PRODUCER_NAME = "LocalFileFetchProducer";

        /// <summary>
        /// Instantiates the <see cref="LocalFileFetchProducer"/>.
        /// </summary>
        public LocalFileFetchProducer(
            IExecutorService executor,
            IPooledByteBufferFactory pooledByteBufferFactory) : base(
                executor,
                pooledByteBufferFactory)
        {
        }

        /// <summary>
        /// Gets the encoded image.
        /// </summary>
        protected override Task<EncodedImage> GetEncodedImage(ImageRequest imageRequest)
        {
            Task<StorageFile> uriToFilePathTask = StorageFile.GetFileFromApplicationUriAsync(imageRequest.SourceUri).AsTask();
            return uriToFilePathTask.ContinueWith<EncodedImage>((filepathTask) => {
                FileInfo file = new FileInfo(filepathTask.Result.Path);
                return GetEncodedImage(file.OpenRead(), (int)(file.Length));
            });
        }

        /// <summary>
        /// The name of the Producer.
        /// </summary>
        protected override string ProducerName
        {
            get
            {
                return PRODUCER_NAME;
            }
        }
    }
}

Use GetFileFromApplicationUriAsync to convert from a Uri to a system file path.


using System.Collections.Generic;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Fluid.Ast;

namespace Fluid
{
    public class BaseFluidTemplate<T> : IFluidTemplate where T : IFluidTemplate, new()
    {
        static BaseFluidTemplate()
        {
            // Necessary to force the custom template class static constructor
            // c.f. https://github.com/sebastienros/fluid/issues/19
            new T();
        }

        public static FluidParserFactory Factory { get; } = new FluidParserFactory();

        public IList<Statement> Statements { get; set; } = new List<Statement>();

        public static bool TryParse(string template, out T result, out IEnumerable<string> errors)
        {
            if (Factory.CreateParser().TryParse(template, out var statements, out errors))
            {
                result = new T();
                result.Statements = statements;
                return true;
            }
            else
            {
                result = default(T);
                return false;
            }
        }

        public static bool TryParse(string template, out T result)
        {
            return TryParse(template, out result, out var errors);
        }

        public async Task RenderAsync(TextWriter writer, TextEncoder encoder, TemplateContext context)
        {
            foreach (var statement in Statements)
            {
                await statement.WriteToAsync(writer, encoder, context);
            }
        }
    }
}

using System.Collections.Generic;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Fluid.Ast;

namespace Fluid
{
    public class BaseFluidTemplate<T> : IFluidTemplate where T : IFluidTemplate, new()
    {
        static BaseFluidTemplate()
        {
            // Necessary to force the custom template class static constructor
            // as the only member accessed is defined on this class
            System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle);
        }

        public static FluidParserFactory Factory { get; } = new FluidParserFactory();

        public IList<Statement> Statements { get; set; } = new List<Statement>();

        public static bool TryParse(string template, out T result, out IEnumerable<string> errors)
        {
            if (Factory.CreateParser().TryParse(template, out var statements, out errors))
            {
                result = new T();
                result.Statements = statements;
                return true;
            }
            else
            {
                result = default(T);
                return false;
            }
        }

        public static bool TryParse(string template, out T result)
        {
            return TryParse(template, out result, out var errors);
        }

        public async Task RenderAsync(TextWriter writer, TextEncoder encoder, TemplateContext context)
        {
            foreach (var statement in Statements)
            {
                await statement.WriteToAsync(writer, encoder, context);
            }
        }
    }
}

Use RunClassConstructor to initialize templates


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

namespace _10.PythagoreanNumbers
{
    class PythagoreanNumbers
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] nums = new int[n];
            for (int i = 0; i < n; i++)
            {
                nums[i] = int.Parse(Console.ReadLine());
            }

            Array.Sort(nums);
            bool any = false;
            for (int a = 0; a < n; a++)
            {
                for (int b = 0; b < n; b++)
                {
                    for (int c = 0; c < n; c++)
                    {
                        if (a < b && (nums[a] * nums[a] + nums[b] * nums[b] == nums[c] * nums[c]))
                        {
                            Console.WriteLine("{0}*{0} + {1}*{1} = {2}*{2}", nums[a], nums[b], nums[c]);
                            any = true;
                        }
                    }
                }
            }
            if (!any)
            {
                Console.WriteLine("No");
            }
        }
    }
}

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

namespace _10.PythagoreanNumbers
{
    class PythagoreanNumbers
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] nums = new int[n];
            for (int i = 0; i < n; i++)
            {
                nums[i] = int.Parse(Console.ReadLine());
            }

            Array.Sort(nums);
            bool any = false;
            for (int a = 0; a < n; a++)
            {
                for (int b = a; b < n; b++)
                {
                    for (int c = b; c < n; c++)
                    {
                        if (a <= b && (nums[a] * nums[a] + nums[b] * nums[b] == nums[c] * nums[c]))
                        {
                            Console.WriteLine("{0}*{0} + {1}*{1} = {2}*{2}", nums[a], nums[b], nums[c]);
                            any = true;
                        }
                    }
                }
            }
            if (!any)
            {
                Console.WriteLine("No");
            }
        }
    }
}

Add optimizations to problem 10

Add optimizations to problem 10


using System;
using System.Threading;

namespace ProcessTest_ConsoleApp
{
    class Program
    {
        static int Main(string[] args)
        {
            try
            {
                if (args.Length > 0)
                {
                    if (args[0].Equals("infinite"))
                    {
                        // To avoid potential issues with orphaned processes (say, the test exits before
                        // exiting the process, we'll say "infinite" is actually 30 seconds.

                        Console.WriteLine("ProcessTest_ConsoleApp.exe started with an endless loop");
                        Thread.Sleep(30 * 1000);
                    }
                    if (args[0].Equals("error"))
                    {
                        Exception ex = new Exception("Intentional Exception thrown");
                        throw ex;
                    }
                    if (args[0].Equals("input"))
                    {
                        string str = Console.ReadLine();
                    }
                }
                else
                {
                    Console.WriteLine("ProcessTest_ConsoleApp.exe started");
                    Console.WriteLine("ProcessTest_ConsoleApp.exe closed");
                }

                return 100;
            }
            catch (Exception toLog)
            {
                // We're testing STDERR streams, not the JIT debugger.
                // This makes the process behave just like a crashing .NET app, but without the WER invocation
                // nor the blocking dialog that comes with it, or the need to suppress that.
                Console.Error.WriteLine(string.Format("Unhandled Exception: {0}", toLog.ToString()));
                return 1;
            }

        }
    }
}

using System;
using System.Threading;

namespace ProcessTest_ConsoleApp
{
    class Program
    {
        static int Main(string[] args)
        {
            try
            {
                if (args.Length > 0)
                {
                    if (args[0].Equals("infinite"))
                    {
                        // To avoid potential issues with orphaned processes (say, the test exits before
                        // exiting the process), we'll say "infinite" is actually 30 seconds.

                        Console.WriteLine("ProcessTest_ConsoleApp.exe started with an endless loop");
                        Thread.Sleep(30 * 1000);
                    }
                    if (args[0].Equals("error"))
                    {
                        Exception ex = new Exception("Intentional Exception thrown");
                        throw ex;
                    }
                    if (args[0].Equals("input"))
                    {
                        string str = Console.ReadLine();
                    }
                }
                else
                {
                    Console.WriteLine("ProcessTest_ConsoleApp.exe started");
                    Console.WriteLine("ProcessTest_ConsoleApp.exe closed");
                }

                return 100;
            }
            catch (Exception toLog)
            {
                // We're testing STDERR streams, not the JIT debugger.
                // This makes the process behave just like a crashing .NET app, but without the WER invocation
                // nor the blocking dialog that comes with it, or the need to suppress that.
                Console.Error.WriteLine(string.Format("Unhandled Exception: {0}", toLog.ToString()));
                return 1;
            }

        }
    }
}

Add missed paren in comment.

Add missed paren in comment.


using System;
using System.Reflection;
using System.Reflection.Emit;

namespace AspectCore.Lite.Abstractions.Generator
{
    public abstract class PropertyGenerator : AbstractGenerator<TypeBuilder, PropertyBuilder>
    {
        public abstract string PropertyName { get; }

        public abstract PropertyAttributes PropertyAttributes { get; }

        public abstract CallingConventions CallingConventions { get; }

        public abstract Type ReturnType { get; }

        public abstract bool CanRead { get; }

        public abstract bool CanWrite { get; }

        public virtual Type[] ParameterTypes
        {
            get
            {
                return Type.EmptyTypes;
            }
        }

        public PropertyGenerator(TypeBuilder declaringMember) : base(declaringMember)
        {
        }

        protected override PropertyBuilder ExecuteBuild()
        {
            var propertyBuilder = DeclaringMember.DefineProperty(PropertyName, PropertyAttributes, CallingConventions, ReturnType, ParameterTypes);

            if (CanRead)
            {
                var readMethodGenerator = GetReadMethodGenerator(DeclaringMember);
                propertyBuilder.SetGetMethod(readMethodGenerator.Build());
            }

            if (CanWrite)
            {
                var writeMethodGenerator = GetWriteMethodGenerator(DeclaringMember);
                propertyBuilder.SetSetMethod(writeMethodGenerator.Build());
            }

            return propertyBuilder;
        }

        protected abstract MethodGenerator GetReadMethodGenerator(TypeBuilder declaringType);

        protected abstract MethodGenerator GetWriteMethodGenerator(TypeBuilder declaringType);
    }
}

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace AspectCore.Lite.Abstractions.Generator
{
    public abstract class PropertyGenerator : AbstractGenerator<TypeBuilder, PropertyBuilder>
    {
        public abstract string PropertyName { get; }

        public abstract PropertyAttributes PropertyAttributes { get; }

        public abstract CallingConventions CallingConventions { get; }

        public abstract Type ReturnType { get; }

        public abstract bool CanRead { get; }

        public abstract bool CanWrite { get; }

        public abstract MethodInfo GetMethod { get; }

        public abstract MethodInfo SetMethod { get; }

        public virtual Type[] ParameterTypes
        {
            get
            {
                return Type.EmptyTypes;
            }
        }

        public PropertyGenerator(TypeBuilder declaringMember) : base(declaringMember)
        {
        }

        protected override PropertyBuilder ExecuteBuild()
        {
            var propertyBuilder = DeclaringMember.DefineProperty(PropertyName, PropertyAttributes, CallingConventions, ReturnType, ParameterTypes);

            if (CanRead)
            {
                var readMethodGenerator = GetReadMethodGenerator(DeclaringMember);
                propertyBuilder.SetGetMethod(readMethodGenerator.Build());
            }

            if (CanWrite)
            {
                var writeMethodGenerator = GetWriteMethodGenerator(DeclaringMember);
                propertyBuilder.SetSetMethod(writeMethodGenerator.Build());
            }

            return propertyBuilder;
        }

        protected abstract MethodGenerator GetReadMethodGenerator(TypeBuilder declaringType);

        protected abstract MethodGenerator GetWriteMethodGenerator(TypeBuilder declaringType);
    }
}

Add SetMethod & GetMethod Property

Add SetMethod & GetMethod Property


namespace NSec.Cryptography
{
    public enum KeyBlobFormat
    {
        None = 0,

        // --- Secret Key Formats ---

        RawSymmetricKey = -1,
        RawPrivateKey = -2,

        NSecSymmetricKey = -101,
        NSecPrivateKey = -102,

        // --- Public Key Formats ---

        RawPublicKey = 1,

        NSecPublicKey = 101,
    }
}

namespace NSec.Cryptography
{
    public enum KeyBlobFormat
    {
        None = 0,

        // --- Secret Key Formats ---

        RawSymmetricKey = -1,
        RawPrivateKey = -2,

        NSecSymmetricKey = -101,
        NSecPrivateKey = -102,

        PkixPrivateKey = -202,
        PkixPrivateKeyText = -203,

        // --- Public Key Formats ---

        RawPublicKey = 1,

        NSecPublicKey = 101,

        PkixPublicKey = 201,
        PkixPublicKeyText = 202,
    }
}

Add PKIX key blob formats

Add PKIX key blob formats


using System;
using System.Collections.Generic;
using System.Security.Cryptography;

namespace LanguageExt
{
    public static partial class Prelude
    {
        readonly static RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
        readonly static byte[] target = new byte[4096];

        /// <summary>
        /// Thread-safe cryptographically strong random number generator
        /// </summary>
        /// <param name="max">Maximum value to return + 1</param>
        /// <returns>A non-negative random number, less than the value specified.</returns>
        public static int random(int max)
        {
            lock (rnd)
            {
                rnd.GetBytes(target);
                return Math.Abs(BitConverter.ToInt32(target, 0)) % max;
            }
        }

        /// <summary>
        /// Thread-safe cryptographically strong random base-64 string generator
        /// </summary>
        /// <param name="count">bytesCount - number of bytes generated that are then
        /// returned Base64 encoded</param>
        /// <returns>Base64 encoded random string</returns>
        public static string randomBase64(int bytesCount)
        {
            if (bytesCount < 1) throw new ArgumentException($"The minimum value for {nameof(bytesCount)} is 1");
            if (bytesCount > 4096) throw new ArgumentException($"The maximum value for {nameof(bytesCount)} is 4096");

            lock (rnd)
            {
                rnd.GetBytes(target);
                return Convert.ToBase64String(target);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Security.Cryptography;

namespace LanguageExt
{
    public static partial class Prelude
    {
        readonly static RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
        readonly static byte[] inttarget = new byte[4];

        /// <summary>
        /// Thread-safe cryptographically strong random number generator
        /// </summary>
        /// <param name="max">Maximum value to return + 1</param>
        /// <returns>A non-negative random number, less than the value specified.</returns>
        public static int random(int max)
        {
            lock (rnd)
            {
                rnd.GetBytes(inttarget);
                return Math.Abs(BitConverter.ToInt32(inttarget, 0)) % max;
            }
        }

        /// <summary>
        /// Thread-safe cryptographically strong random base-64 string generator
        /// </summary>
        /// <param name="count">bytesCount - number of bytes generated that are then
        /// returned Base64 encoded</param>
        /// <returns>Base64 encoded random string</returns>
        public static string randomBase64(int bytesCount)
        {
            if (bytesCount < 1) throw new ArgumentException($"The minimum value for {nameof(bytesCount)} is 1");

            var bytes = new byte[bytesCount];
            rnd.GetBytes(bytes);
            return Convert.ToBase64String(bytes);
        }
    }
}

Fix for randomBase64, it was filling a full internal array unnecessarily.


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]

// 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("c8cd805d-f17a-4919-9adb-b5f50d72f32a")]

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: AssemblyConfiguration("")]

// 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("c8cd805d-f17a-4919-9adb-b5f50d72f32a")]

[assembly: InternalsVisibleTo("TMDbLibTests")]

Make tests of converters possible

Make tests of converters possible


namespace Microsoft.Build.Logging.StructuredLogger
{
    public class BinaryLog
    {
        public static Build ReadBuild(string filePath)
        {
            var eventSource = new BinaryLogReplayEventSource();

            byte[] sourceArchive = null;

            eventSource.OnBlobRead += (kind, bytes) =>
            {
                if (kind == BinaryLogRecordKind.SourceArchive)
                {
                    sourceArchive = bytes;
                }
            };

            StructuredLogger.SaveLogToDisk = false;
            StructuredLogger.CurrentBuild = null;
            var structuredLogger = new StructuredLogger();
            structuredLogger.Parameters = "build.buildlog";
            structuredLogger.Initialize(eventSource);

            eventSource.Replay(filePath);

            var build = StructuredLogger.CurrentBuild;
            StructuredLogger.CurrentBuild = null;

            build.SourceFilesArchive = sourceArchive;

            return build;
        }
    }
}

using System.Diagnostics;

namespace Microsoft.Build.Logging.StructuredLogger
{
    public class BinaryLog
    {
        public static Build ReadBuild(string filePath)
        {
            var eventSource = new BinaryLogReplayEventSource();

            byte[] sourceArchive = null;

            eventSource.OnBlobRead += (kind, bytes) =>
            {
                if (kind == BinaryLogRecordKind.SourceArchive)
                {
                    sourceArchive = bytes;
                }
            };

            StructuredLogger.SaveLogToDisk = false;
            StructuredLogger.CurrentBuild = null;
            var structuredLogger = new StructuredLogger();
            structuredLogger.Parameters = "build.buildlog";
            structuredLogger.Initialize(eventSource);

            var sw = Stopwatch.StartNew();
            eventSource.Replay(filePath);
            var elapsed = sw.Elapsed;

            var build = StructuredLogger.CurrentBuild;
            StructuredLogger.CurrentBuild = null;

            build.SourceFilesArchive = sourceArchive;
            // build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });

            return build;
        }
    }
}

Add a way to measure how long it took to read a binlog file.


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

namespace IntelliTect.Coalesce.TypeDefinition
{
    public static class ReflectionExtensions
    {
        /// <summary>
        /// Returns the attributed requested if it exists or null if it does not.
        /// </summary>
        /// <typeparam name="TAttribute"></typeparam>
        /// <returns></returns>
        public static TAttribute GetAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute
        {
            var attributes = member.GetCustomAttributes(typeof(TAttribute), true);
            return attributes.FirstOrDefault() as TAttribute;
        }

        /// <summary>
        /// Returns true if the attribute exists.
        /// </summary>
        /// <typeparam name="TAttribute"></typeparam>
        /// <returns></returns>
        public static bool HasAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute
        {
            return member.GetAttribute<TAttribute>() != null;
        }

        public static Object GetAttributeValue<TAttribute>(this ICustomAttributeProvider member, string valueName) where TAttribute : Attribute
        {
            var attr = member.GetAttribute<TAttribute>();
            if (attr != null)
            {
                var property = attr.GetType().GetProperty(valueName);
                if (property == null) return null;

                // TODO: Some properties throw an exception here. DisplayAttribute.Order. Not sure why.
                try {
                    return property.GetValue(attr, null);
                }
                catch (Exception)
                {
                    return null;
                }
            }
            return null;
        }

    }
}

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

namespace IntelliTect.Coalesce.TypeDefinition
{
    public static class ReflectionExtensions
    {
        /// <summary>
        /// Returns the attributed requested if it exists or null if it does not.
        /// </summary>
        /// <typeparam name="TAttribute"></typeparam>
        /// <returns></returns>
        public static TAttribute GetAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute
        {
            var attributes = member.GetCustomAttributes(typeof(TAttribute), true);
            return attributes.FirstOrDefault() as TAttribute;
        }

        /// <summary>
        /// Returns true if the attribute exists.
        /// </summary>
        /// <typeparam name="TAttribute"></typeparam>
        /// <returns></returns>
        public static bool HasAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute
        {
            return member.IsDefined(typeof(TAttribute), true);
        }

        public static Object GetAttributeValue<TAttribute>(this ICustomAttributeProvider member, string valueName) where TAttribute : Attribute
        {
            var attr = member.GetAttribute<TAttribute>();
            if (attr != null)
            {
                var property = attr.GetType().GetProperty(valueName);
                if (property == null) return null;

                // TODO: Some properties throw an exception here. DisplayAttribute.Order. Not sure why.
                try
                {
                    return property.GetValue(attr, null);
                }
                catch (Exception)
                {
                    return null;
                }
            }
            return null;
        }

    }
}

Use ICustomAttributeProvider.IsDefined in `HasAttribute` to avoid allocations.


namespace Nine.Storage
{
    using System;
    using System.Collections.Generic;
    using Xunit;

    public class PersistedStorageTest : StorageSpec<PersistedStorageTest>
    {
        public override IEnumerable<ITestFactory<IStorage<TestStorageObject>>> GetData()
        {
            return new[]
            {
                new TestFactory<IStorage<TestStorageObject>>(typeof(PersistedStorage<>), () => new PersistedStorage<TestStorageObject>(Guid.NewGuid().ToString())),
            };
        }
    }
}

namespace Nine.Storage
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Xunit;

    public class PersistedStorageTest : StorageSpec<PersistedStorageTest>
    {
        public override IEnumerable<ITestFactory<IStorage<TestStorageObject>>> GetData()
        {
            return new[]
            {
                new TestFactory<IStorage<TestStorageObject>>(typeof(PersistedStorage<>), () => new PersistedStorage<TestStorageObject>(Guid.NewGuid().ToString())),
            };
        }

        [Fact]
        public async Task persisted_storage_put_and_get()
        {
            var storage = new PersistedStorage<TestStorageObject>(Guid.NewGuid().ToString());
            await storage.Put(new TestStorageObject("a"));
            Assert.NotNull(await storage.Get("a"));

            var gets = new ConcurrentBag<TestStorageObject>();
            Parallel.For(0, 100, i =>
            {
                if (i % 2 == 0)
                {
                    storage.Put(new TestStorageObject("a")).Wait();
                }
                else
                {
                    gets.Add(storage.Get("a").Result);
                }
            });
            Assert.All(gets, got => Assert.NotNull(got));
        }
    }
}

Add test case for 69c97371

Add test case for 69c97371


using System;
using System.Reflection;
using slang.Compiler.Clr.Compilation.Definitions;

namespace slang.Tests.IL
{

    static class AssemblyDefinitionExtensions
    {
        public static Type [] GetTypes (this AssemblyDefinition assemblyDefinition)
        {
            return assemblyDefinition.LoadAssembly ().GetTypes ();
        }

        public static Assembly LoadAssembly (this AssemblyDefinition assemblyDefinition)
        {
            return AppDomain.CurrentDomain.Load (new AssemblyName (assemblyDefinition.Name));
        }
    }
}

using System;
using System.Reflection;
using slang.Compiler.Clr.Compilation.Definitions;

namespace slang.Tests.IL
{

    static class AssemblyDefinitionExtensions
    {
        public static Type [] GetTypes (this AssemblyDefinition assemblyDefinition)
        {
            return assemblyDefinition.LoadAssembly ().GetTypes ();
        }

        public static Assembly LoadAssembly (this AssemblyDefinition assemblyDefinition)
        {
            throw new InvalidOperationException("We will no longer be loading dynamic assemblies for disk so this operation is no longer possible.");
        }
    }
}

Stop loading dynamic modules from disk

Stop loading dynamic modules from disk

We are not able to load dynamically defined modules from disk because we
are not able to save them to disk in the first place.

For the moment I've decided to throw an invalid operation exception and
deal with the fallout at a later stage.


@model Wangkanai.Detection.Services.IDetectionService

@{
    ViewData["Title"] = "Detection";
}

UserAgent

@Model.UserAgent

Results

            Resolver
            Type
            Version

            Device
            @Model.Device?.Type

            Platform
            @Model.Platform?.OperatingSystem
            @Model.Platform?.Processor

            Engine
            @Model.Engine?.Type

            Browser
            @Model.Browser?.Type

            Crawler
            @Model.Crawler?.Type.ToString()
            @Model.Crawler?.Version

@model Wangkanai.Detection.Services.IDetectionService

@{
    ViewData["Title"] = "Detection";
}

UserAgent

@Model.UserAgent

Results

            Resolver
            Type
            Version

            Device
            @Model.Device?.Type

            Platform
            @Model.Platform?.OperatingSystem
            @Model.Platform?.Processor

            Engine
            @Model.Engine?.Type

            Browser
            @Model.Browser?.Type

            Crawler
            @Model.Crawler?.Type
            @Model.Crawler?.Version

Update detection sample web app

Update detection sample web app


@functions {
    private string GetCssClass(string actionName, string controllerName)
    {
        var currentControllerName = ViewContext.RouteData.Values["controller"].ToString();

        var isCurrentController = currentControllerName == controllerName;
        if (currentControllerName == "Home")
        {
            return GetHomeControllerLinksCssClass(actionName, isCurrentController);
        }

        return isCurrentController ? "active" : string.Empty;
    }

    private string GetHomeControllerLinksCssClass(string actionName, bool isCurrentController)
    {
        if (!isCurrentController)
        {
            return string.Empty;
        }

        var isCurrentAction = ViewContext.RouteData.Values["action"].ToString() == actionName;

        return isCurrentAction ? "active" : string.Empty;
    }

}

@helper GetMenuBarLink(string linkText, string actionName, string controllerName)
{

@Html.ActionLink(linkText, actionName, controllerName)

}

    @GetMenuBarLink("Home", "Index", "Home")
    @GetMenuBarLink("Concerts", "Index", "Concerts")
    @GetMenuBarLink("Rehearsals", "Index", "Rehearsals")
    @GetMenuBarLink("About", "About", "Home")
    @GetMenuBarLink("Contact", "Contact", "Home")

@functions {
    private string GetCssClass(string actionName, string controllerName)
    {
        var currentControllerName = ViewContext.RouteData.Values["controller"].ToString();

        var isCurrentController = currentControllerName == controllerName;
        if (currentControllerName == "Home")
        {
            return GetHomeControllerLinksCssClass(actionName, isCurrentController);
        }

        return isCurrentController ? "active" : string.Empty;
    }

    private string GetHomeControllerLinksCssClass(string actionName, bool isCurrentController)
    {
        if (!isCurrentController)
        {
            return string.Empty;
        }

        var isCurrentAction = ViewContext.RouteData.Values["action"].ToString() == actionName;

        return isCurrentAction ? "active" : string.Empty;
    }

}

@helper GetMenuBarLink(string linkText, string actionName, string controllerName)
{

        @if (controllerName == "Concerts" && Request.IsAuthenticated)
        {

                @linkText

@Html.ActionLink("Administer Concerts", "List", "Concerts")

        }
        else
        {
            @Html.ActionLink(linkText, actionName, controllerName)
        }

}

    @GetMenuBarLink("Home", "Index", "Home")
    @GetMenuBarLink("Concerts", "Index", "Concerts")
    @GetMenuBarLink("Rehearsals", "Index", "Rehearsals")
    @GetMenuBarLink("About", "About", "Home")
    @GetMenuBarLink("Contact", "Contact", "Home")

Add drop-down menu for concerts.

Add drop-down menu for concerts.

Hacky approach for now, just to get the link displayed.  A controller will be needed to wrap up this logic when the next feature is developed.


using System.Collections.Generic;
using System.Linq.Expressions;
using Jokenizer.Net;

namespace System.Linq.Dynamic {

    public static partial class DynamicQueryable {

        public static IQueryable<T> As<T>(this IQueryable source) {
            return (IQueryable<T>)source;
        }

        public static IQueryable Take(this IQueryable source, int count) {
            if (source == null) throw new ArgumentNullException(nameof(source));

            return source.Provider.CreateQuery(
                Expression.Call(
                    typeof(Queryable),
                    "Take",
                    new[] { source.ElementType },
                    source.Expression,
                    Expression.Constant(count))
                );
        }

        public static IQueryable Skip(this IQueryable source, int count) {
            if (source == null) throw new ArgumentNullException(nameof(source));

            return source.Provider.CreateQuery(
                Expression.Call(
                    typeof(Queryable),
                    "Skip",
                    new[] { source.ElementType },
                    source.Expression,
                    Expression.Constant(count)
                )
            );
        }
    }
}

using System.Collections.Generic;
using System.Linq.Expressions;
using Jokenizer.Net;

namespace System.Linq.Dynamic {

    public static partial class DynamicQueryable {

        public static IQueryable<T> As<T>(this IQueryable source) {
            return (IQueryable<T>)source;
        }

        public static IQueryable Take(this IQueryable source, int count) {
            return HandleConstant(source, "Take", count);
        }

        public static IQueryable Skip(this IQueryable source, int count) {
            return HandleConstant(source, "Skip", count);
        }

        public static IQueryable HandleConstant(this IQueryable source, string method, int count) {
            if (source == null) throw new ArgumentNullException(nameof(source));

            return source.Provider.CreateQuery(
                Expression.Call(
                    typeof(Queryable),
                    method,
                    new[] { source.ElementType },
                    source.Expression,
                    Expression.Constant(count)
                )
            );
        }
    }
}

Refactor - Move Skip, Take duplicate code


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace BTCPayServer.Services
{
    public class PoliciesSettings
    {
        [Display(Name = "Requires a confirmation mail for registering")]
        public bool RequiresConfirmedEmail
        {
            get; set;
        }

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
        [Display(Name = "Disable registration")]
        public bool LockSubscription { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace BTCPayServer.Services
{
    public class PoliciesSettings
    {
        [Display(Name = "Requires a confirmation mail for registering")]
        public bool RequiresConfirmedEmail
        {
            get; set;
        }

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
        [Display(Name = "Disable registration")]
        public bool LockSubscription { get; set; } = true;
    }
}

Set disable registration as default true.


// <copyright file="TextToPythonScript.cs" company="Mark Final">
//  Opus package
// </copyright>
// <summary>XmlUtilities package</summary>
// <author>Mark Final</author>
namespace XmlUtilities
{
    public static class TextToPythonScript
    {
        public static void
        Write(
            System.Text.StringBuilder content,
            string pythonScriptPath,
            string pathToGeneratedFile)
        {
            using (var writer = new System.IO.StreamWriter(pythonScriptPath))
            {
                writer.WriteLine("#!usr/bin/python");

                writer.WriteLine(System.String.Format("with open('{0}', 'wt') as script:", pathToGeneratedFile));
                foreach (var line in content.ToString().Split('\n'))
                {
                    writer.WriteLine("\tscript.write('{0}\\n')", line);
                }
            }
        }
    }
}

// <copyright file="TextToPythonScript.cs" company="Mark Final">
//  Opus package
// </copyright>
// <summary>XmlUtilities package</summary>
// <author>Mark Final</author>
namespace XmlUtilities
{
    public static class TextToPythonScript
    {
        public static void
        Write(
            System.Text.StringBuilder content,
            string pythonScriptPath,
            string pathToGeneratedFile)
        {
            using (var writer = new System.IO.StreamWriter(pythonScriptPath))
            {
                writer.WriteLine("#!usr/bin/python");

                writer.WriteLine(System.String.Format("with open(r'{0}', 'wt') as script:", pathToGeneratedFile));
                foreach (var line in content.ToString().Split('\n'))
                {
                    writer.WriteLine("\tscript.write('{0}\\n')", line);
                }
            }
        }
    }
}

[packages,XmlUtilities,dev] Make paths of text files to write verbatim, so that slashes are not misinterpreted under Windows as escape characters


using System;
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace DesktopWidgets.Actions
{
    public abstract class ActionBase
    {
        [PropertyOrder(0)]
        [DisplayName("Delay")]
        public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0);

        [PropertyOrder(1)]
        [DisplayName("Works If Foreground Is Fullscreen")]
        public bool WorksIfForegroundIsFullscreen { get; set; }

        [PropertyOrder(2)]
        [DisplayName("Works If Muted")]
        public bool WorksIfMuted { get; set; }

        [PropertyOrder(3)]
        [DisplayName("Show Errors")]
        public bool ShowErrors { get; set; } = false;

        public void Execute()
        {
            if (!WorksIfMuted && App.IsMuted ||
                (!WorksIfForegroundIsFullscreen && FullScreenHelper.DoesAnyMonitorHaveFullscreenApp()))
            {
                return;
            }
            DelayedAction.RunAction((int)Delay.TotalMilliseconds, () =>
           {
               try
               {
                   ExecuteAction();
               }
               catch (Exception ex)
               {
                   if (ShowErrors)
                   {
                       Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}",
                           image: MessageBoxImage.Error);
                   }
               }
           });
        }

        protected virtual void ExecuteAction()
        {
        }
    }
}

using System;
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace DesktopWidgets.Actions
{
    public abstract class ActionBase
    {
        [PropertyOrder(0)]
        [DisplayName("Delay")]
        public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0);

        [PropertyOrder(1)]
        [DisplayName("Trigger If Foreground Is Fullscreen")]
        public bool WorksIfForegroundIsFullscreen { get; set; }

        [PropertyOrder(2)]
        [DisplayName("Trigger If Muted")]
        public bool WorksIfMuted { get; set; }

        [PropertyOrder(3)]
        [DisplayName("Show Error Popups")]
        public bool ShowErrors { get; set; } = false;

        public void Execute()
        {
            if (!WorksIfMuted && App.IsMuted ||
                (!WorksIfForegroundIsFullscreen && FullScreenHelper.DoesAnyMonitorHaveFullscreenApp()))
            {
                return;
            }
            DelayedAction.RunAction((int)Delay.TotalMilliseconds, () =>
           {
               try
               {
                   ExecuteAction();
               }
               catch (Exception ex)
               {
                   if (ShowErrors)
                   {
                       Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}",
                           image: MessageBoxImage.Error);
                   }
               }
           });
        }

        protected virtual void ExecuteAction()
        {
        }
    }
}

Rename some base action settings

Rename some base action settings


// 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.AspNetCore.Server.IntegrationTesting
{
    public static class Tfm
    {
        public const string Net461 = "net461";
        public const string NetCoreApp20 = "netcoreapp2.0";
        public const string NetCoreApp21 = "netcoreapp2.1";
        public const string NetCoreApp22 = "netcoreapp2.2";

        public static bool Matches(string tfm1, string tfm2)
        {
            return string.Equals(tfm1, tfm2, StringComparison.OrdinalIgnoreCase);
        }
    }
}

// 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.AspNetCore.Server.IntegrationTesting
{
    public static class Tfm
    {
        public const string Net461 = "net461";
        public const string NetCoreApp20 = "netcoreapp2.0";
        public const string NetCoreApp21 = "netcoreapp2.1";
        public const string NetCoreApp22 = "netcoreapp2.2";
        public const string NetCoreApp30 = "netcoreapp3.0";

        public static bool Matches(string tfm1, string tfm2)
        {
            return string.Equals(tfm1, tfm2, StringComparison.OrdinalIgnoreCase);
        }
    }
}

Update TFM to include netcoreapp3.0

Update TFM to include netcoreapp3.0


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

namespace TeamTasker.Web.Controllers
{
    public class TasksController : Controller
    {
        private TaskerContext db = new TaskerContext();

        [HttpPost]
        public JsonResult Create(string name, DateTime dueDate, string instructions)
        {
            var task = new Task
            {
                Name = name,
                DueDate = dueDate,
                Instructions = instructions
            };

            db.Tasks.Add(task);
            db.SaveChanges();

            return Json(task.Id);
        }

        [HttpPost]
        public JsonResult Assign(int taskId, int memberId)
        {
            var task = db.Tasks.Where(t => t.Id == taskId).Single();

            var member = db.TeamMembers.Where(m => m.Id == memberId).Single();

            task.AssignedMembers.Add(member);

            db.SaveChanges();

            return Json("success");
        }

        [HttpGet]
        public JsonResult AllTasks()
        {
            var tasks = (from t in db.Tasks select new { Id = t.Id, Name = t.Name }).OrderBy(t => t.Name).ToList();

            return Json(tasks);
        }
    }
}

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

namespace TeamTasker.Web.Controllers
{
    public class TasksController : Controller
    {
        private TaskerContext db = new TaskerContext();

        [HttpPost]
        public JsonResult Create(string name, DateTime dueDate, string instructions)
        {
            var task = new Task
            {
                Name = name,
                DueDate = dueDate,
                Instructions = instructions
            };

            db.Tasks.Add(task);
            db.SaveChanges();

            return Json(task.Id);
        }

        [HttpPost]
        public JsonResult Assign(int taskId, int memberId)
        {
            var task = db.Tasks.Where(t => t.Id == taskId).Single();

            var member = db.TeamMembers.Where(m => m.Id == memberId).Single();

            task.AssignedMembers.Add(member);

            db.SaveChanges();

            return Json("success");
        }

        [HttpGet]
        public JsonResult AllTasks()
        {
            var tasks = (from t in db.Tasks select new { Id = t.Id, Name = t.Name }).OrderBy(t => t.Name).ToList();

            return Json(tasks, JsonRequestBehavior.AllowGet);
        }
    }
}

Fix for Get all tasks

Fix for Get all tasks


using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class ShaderBlit : MonoBehaviour {

	public bool					Dirty = true;
	public bool					AlwaysDirtyInEditor = true;
	public Texture				Input;
	public Shader				BlitShader;
	public Material				BlitMaterial;
	public RenderTexture		Output;
	public UnityEngine.Events.UnityEvent	OnClean;

	public void SetDirty()
	{
		Dirty = true;
	}

	void Update ()
	{
		if ( Application.isEditor && !Application.isPlaying && AlwaysDirtyInEditor )
			Dirty = true;

		if ( !Dirty )
			return;

		if ( Input == null )
			return;

		if (BlitShader != null)
		{
			if ( BlitMaterial == null )
				BlitMaterial = new Material( BlitShader );
		}

		if ( BlitMaterial == null )
			return;

		Graphics.Blit( Input, Output, BlitMaterial );

		Dirty = false;

		if ( OnClean != null )
			OnClean.Invoke();

	}
}

using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class ShaderBlit : MonoBehaviour {

	[InspectorButton("Execute")]
	public bool					Dirty = true;
	public bool					AlwaysDirtyInEditor = true;
	public Texture				Input;
	public Shader				BlitShader;
	public Material				BlitMaterial;
	public RenderTexture		Output;
	public UnityEngine.Events.UnityEvent	OnClean;

	public void SetDirty()
	{
		Dirty = true;
	}

	public void Execute()
	{
		if (BlitShader != null)
		{
			if ( BlitMaterial == null )
				BlitMaterial = new Material( BlitShader );
		}

		if ( BlitMaterial == null )
			return;

		Graphics.Blit( Input, Output, BlitMaterial );

	}

	void Update ()
	{
		if ( Application.isEditor && !Application.isPlaying && AlwaysDirtyInEditor )
			Dirty = true;

		if ( !Dirty )
			return;

		if ( Input == null )
			return;

		Execute();

		Dirty = false;

		if ( OnClean != null )
			OnClean.Invoke();

	}
}

Put explicit blit in its own Execute func, added inspector button


// Copyright 2020 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using Google.Protobuf;
using VDrumExplorer.Model;

namespace VDrumExplorer.Proto
{
    internal partial class InstrumentAudio
    {
        internal Model.Audio.InstrumentAudio ToModel(ModuleSchema schema)
        {
            var bank = Preset ? schema.PresetInstruments : schema.UserSampleInstruments;
            var instrument = bank[InstrumentId];
            return new Model.Audio.InstrumentAudio(instrument, AudioData.ToByteArray());
        }

        internal static InstrumentAudio FromModel(Model.Audio.InstrumentAudio audio) =>
            new InstrumentAudio
            {
                AudioData = ByteString.CopyFrom(audio.Audio),
                InstrumentId = audio.Instrument.Id,
                Preset = audio.Instrument.Group != null
            };
    }
}

// Copyright 2020 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using Google.Protobuf;
using VDrumExplorer.Model;

namespace VDrumExplorer.Proto
{
    internal partial class InstrumentAudio
    {
        internal Model.Audio.InstrumentAudio ToModel(ModuleSchema schema)
        {
            var bank = Preset ? schema.PresetInstruments : schema.UserSampleInstruments;
            var instrument = bank[InstrumentId];
            return new Model.Audio.InstrumentAudio(instrument, AudioData.ToByteArray());
        }

        internal static InstrumentAudio FromModel(Model.Audio.InstrumentAudio audio) =>
            new InstrumentAudio
            {
                AudioData = ByteString.CopyFrom(audio.Audio),
                InstrumentId = audio.Instrument.Id,
                Preset = audio.Instrument.Group.Preset
            };
    }
}

Use Instrument.Preset to detect preset instruments rather than a null InstrumentGroup


using Common;
using NUnit.Framework;

namespace Tests.Common
{
    [TestFixture]
    public class TourTest
    {
        private Tour testee;

        [SetUp]
        public void Init()
        {
            testee = new Tour();
            testee.AddGift(new Gift(1, 500, 0, 0));
            testee.AddGift(new Gift(2, 500, 4, 2));
        }

        [Test]
        public void TestValidTourWeight()
        {
            Assert.IsTrue(testee.IsValid());
        }

        [Test]
        public void TestInvalidTourWeight()
        {
            testee.AddGift(new Gift(3, 0.001, 5, 5));
            Assert.IsFalse(testee.IsValid());
        }
    }
}

using Common;
using NUnit.Framework;

namespace Tests.Common
{
    [TestFixture]
    public class TourTest
    {
        private Tour testee;

        [SetUp]
        public void Init()
        {
            testee = new Tour();
            testee.AddGift(new Gift(1, 500, 0, 0));
            testee.AddGift(new Gift(2, 500, 4, 2));
        }

        [Test]
        public void TestValidTourWeight()
        {
            Assert.IsTrue(testee.IsValid());
        }

        [Test]
        public void TestInvalidTourWeight()
        {
            testee.AddGift(new Gift(3, 0.001, 5, 5));
            Assert.IsFalse(testee.IsValid());
        }

        [Test]
        public void TestAddGift()
        {
            int oldCount = testee.Gifts.Count;
            testee.AddGift(new Gift(3, 0.001, 5, 5));
            Assert.AreEqual(oldCount + 1, testee.Gifts.Count);
        }
    }
}

Add test case for gift insertion

Add test case for gift insertion


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataMigrationAppSettings.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;

namespace Microsoft.Azure.Commands.DataMigration.Test
{
    public class DataMigrationAppSettings
    {
        private static volatile DataMigrationAppSettings instance;
        private string configFileName = "appsettings.json";
        private static object lockObj = new Object();
        private JObject config;

        private DataMigrationAppSettings() { }

        public static DataMigrationAppSettings Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockObj)
                    {
                        if (instance == null)
                        {
                            instance = new DataMigrationAppSettings();
                            instance.LoadConfigFile();
                        }
                    }
                }

                return instance;
            }
        }

        private void LoadConfigFile()
        {
            string path = Directory.GetCurrentDirectory();
            string fullFilePath = Path.Combine(path, configFileName);
            if (!File.Exists(fullFilePath))
            {
                // Because of File.Delete doesn't throw any exception in case file not found
                throw new FileNotFoundException("appsettings.json File Not Found");
            }

            config = (JObject)JsonConvert.DeserializeObject(File.ReadAllText(fullFilePath));
        }

        public string GetValue(string configName)
        {
            string value = (string) config[configName];

            if (string.IsNullOrEmpty(value))
            {
                string message = "Cannot not find config : " + configName;
                throw new ArgumentException(message);
            }

            return value;
        }

    }
}

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataMigrationAppSettings.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;

namespace Microsoft.Azure.Commands.DataMigration.Test
{
    public class DataMigrationAppSettings
    {
        private static volatile DataMigrationAppSettings instance;
        private string configFileName = "appsettings.json";
        private static object lockObj = new Object();
        private JObject config;

        private DataMigrationAppSettings() { }

        public static DataMigrationAppSettings Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockObj)
                    {
                        if (instance == null)
                        {
                            instance = new DataMigrationAppSettings();
                            instance.LoadConfigFile();
                        }
                    }
                }

                return instance;
            }
        }

        private void LoadConfigFile()
        {
            string fullFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFileName);
            if (!File.Exists(fullFilePath))
            {
                instance = null;
                throw new FileNotFoundException("appsettings.json File Not Found");
            }

            config = (JObject)JsonConvert.DeserializeObject(File.ReadAllText(fullFilePath));
        }

        public string GetValue(string configName)
        {
            string value = (string) config[configName];

            if (string.IsNullOrEmpty(value))
            {
                string message = "Cannot not find config : " + configName;
                throw new ArgumentException(message);
            }

            return value;
        }

    }
}

Use proper path for settings file

Use proper path for settings file


namespace NFig.Tests.Common
{
    public enum Tier
    {
        Any = 0,
        Local = 1,
        Dev = 2,
        Prod = 3,
    }

    public enum DataCenter
    {
        Any = 0,
        Local = 1,
        Dev = 2,
        Prod = 3,
    }
}

namespace NFig.Tests.Common
{
    public enum Tier
    {
        Any = 0,
        Local = 1,
        Dev = 2,
        Prod = 3,
    }

    public enum DataCenter
    {
        Any = 0,
        Local = 1,
        East = 2,
        West = 3,
    }
}

Fix DataCenter enum in tests project

Fix DataCenter enum in tests project


@{
	Layout = "_Layout";
	ViewData["Title"] = "Analysen";
}

				Unbekannte Translationkeys

		@RenderBody()

@using System.Linq
@inject MitternachtWeb.Areas.Analysis.Services.UnknownKeyRequestsService UnknownKeyRequestsService
@{
	Layout = "_Layout";
	ViewData["Title"] = "Analysen";
}

					Unbekannte Translationkeys
					@UnknownKeyRequestsService.UnknownKeyRequests.Values.Aggregate(0ul, (r, i) => r+i)

		@RenderBody()

Add badge for unknown key request count.


using System;

namespace TAPCfg {
	public class EthernetFrame {
		private byte[] data;
		private byte[] src = new byte[6];
		private byte[] dst = new byte[6];
		private int etherType;

		public EthernetFrame(byte[] data) {
			this.data = data;
			Array.Copy(data, 0, dst, 0, 6);
			Array.Copy(data, 6, src, 0, 6);
			etherType = (data[12] << 8) | data[13];
		}

		public byte[] Data {
			get { return data; }
		}

		public int Length {
			get { return data.Length; }
		}

		public byte[] SourceAddress {
			get { return src; }
		}

		public byte[] DestinationAddress {
			get { return dst; }
		}

		public int EtherType {
			get { return etherType; }
		}

		public byte[] Payload {
			get {
				byte[] ret = new byte[data.Length - 14];
				Array.Copy(data, 14, ret, 0, ret.Length);
				return ret;
			}
		}
	}
}

using System;

namespace TAPCfg {
	public enum EtherType : int {
		InterNetwork   = 0x0800,
		ARP            = 0x0806,
		RARP           = 0x8035,
		AppleTalk      = 0x809b,
		AARP           = 0x80f3,
		InterNetworkV6 = 0x86dd,
		CobraNet       = 0x8819,
	}

	public class EthernetFrame {
		private byte[] data;
		private byte[] src = new byte[6];
		private byte[] dst = new byte[6];
		private int etherType;

		public EthernetFrame(byte[] data) {
			this.data = data;
			Array.Copy(data, 0, dst, 0, 6);
			Array.Copy(data, 6, src, 0, 6);
			etherType = (data[12] << 8) | data[13];
		}

		public byte[] Data {
			get { return data; }
		}

		public int Length {
			get { return data.Length; }
		}

		public byte[] SourceAddress {
			get { return src; }
		}

		public byte[] DestinationAddress {
			get { return dst; }
		}

		public int EtherType {
			get { return etherType; }
		}

		public byte[] Payload {
			get {
				byte[] ret = new byte[data.Length - 14];
				Array.Copy(data, 14, ret, 0, ret.Length);
				return ret;
			}
		}
	}
}

Add EtherType enumeration for some types (not all)

git-svn-id: 8d82213adbbc6b1538a984bace977d31fcb31691@31 2f5d681c-ba19-11dd-a503-ed2d4bea8bb5


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

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

namespace osu.Game.Rulesets.Catch.Objects.Drawables
{
    /// <summary>
    /// Provides a visual state of a <see cref="PalpableCatchHitObject"/>.
    /// </summary>
    public interface IHasCatchObjectState
    {
        PalpableCatchHitObject HitObject { get; }
        Bindable<Color4> AccentColour { get; }
        Bindable<bool> HyperDash { get; }

        Vector2 DisplaySize { get; }
        float DisplayRotation { get; }
    }
}

Add some spacing to interface class

Add some spacing to interface class


using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace IdentitySample
{
    public static class Program
    {
        public static void Main(string[] args) => BuildWebHost(args).Run();

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}

using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace IdentitySample
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

Revert "use WebHost.CreateDefaultBuilder in IdentitySample.Mvc"

This reverts commit 20ec50d5d26f2052afcfcf640c69c6049208e799.


//------------------------------------------------------------------------------
// <copyright
//  file="CommonAssemblyInfo.cs"
//  company="enckse">
//  Copyright (c) All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.CompilerServices;

[assembly: AssemblyDescription("")]

[assembly: AssemblyConfiguration("")]

[assembly: AssemblyVersion("1.3.0.0")]

[assembly: System.CLSCompliant(true)]

[assembly: System.Runtime.InteropServices.ComVisible(false)]

[assembly: AssemblyFileVersion("1.3.0.0")]

//------------------------------------------------------------------------------
// <copyright
//  file="CommonAssemblyInfo.cs"
//  company="enckse">
//  Copyright (c) All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.CompilerServices;

[assembly: AssemblyDescription("")]

[assembly: AssemblyConfiguration("")]

[assembly: AssemblyVersion("1.3.0.0")]

[assembly: System.CLSCompliant(true)]

[assembly: System.Runtime.InteropServices.ComVisible(false)]

[assembly: AssemblyFileVersion("1.3.1.0")]

Update assembly file version for next release


using System;
using Abp.AspNetCore.Configuration;
using Abp.Configuration.Startup;
using Microsoft.AspNet.OData.Builder;
using Microsoft.AspNet.OData.Extensions;

namespace Abp.AspNetCore.OData.Configuration
{
    internal class AbpAspNetCoreODataModuleConfiguration : IAbpAspNetCoreODataModuleConfiguration
    {
        public ODataConventionModelBuilder ODataModelBuilder { get; set; }

        public Action<IAbpStartupConfiguration> MapAction { get; set; }

        public AbpAspNetCoreODataModuleConfiguration()
        {
            MapAction = configuration =>
            {
                configuration.Modules.AbpAspNetCore().RouteBuilder.MapODataServiceRoute(
                    routeName: "ODataRoute",
                    routePrefix: "odata",
                    model: configuration.Modules.AbpAspNetCoreOData().ODataModelBuilder.GetEdmModel()
                );
            };
        }
    }
}

using System;
using Abp.AspNetCore.Configuration;
using Abp.Configuration.Startup;
using Microsoft.AspNet.OData;
using Microsoft.AspNet.OData.Builder;
using Microsoft.AspNet.OData.Extensions;

namespace Abp.AspNetCore.OData.Configuration
{
    internal class AbpAspNetCoreODataModuleConfiguration : IAbpAspNetCoreODataModuleConfiguration
    {
        public ODataConventionModelBuilder ODataModelBuilder { get; set; }

        public Action<IAbpStartupConfiguration> MapAction { get; set; }

        public AbpAspNetCoreODataModuleConfiguration()
        {
            MapAction = configuration =>
            {
                configuration.Modules.AbpAspNetCore().RouteBuilder.MapODataServiceRoute(
                    routeName: "ODataRoute",
                    routePrefix: "odata",
                    model: configuration.Modules.AbpAspNetCoreOData().ODataModelBuilder.GetEdmModel()
                );

                // Workaround: https://github.com/OData/WebApi/issues/1175
                configuration.Modules.AbpAspNetCore().RouteBuilder.EnableDependencyInjection();
            };
        }
    }
}

Add workaround required after MapODataServiceRoute