using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IPTables.Net.Exceptions;

namespace IPTables.Net.Iptables
{
    /// <summary>
    /// Data to define the default IPTables tables and chains
    /// </summary>
    internal class IPTablesTables
    {
        static internal Dictionary<String, List<String>> Tables = new Dictionary<string, List<string>>
        {
             { "filter", new List<string>{"INPUT", "FORWARD", "OUTPUT"} },
             { "nat", new List<string>{"PREROUTING", "POSTROUTING", "OUTPUT"} },
             { "raw", new List<string>{"PREROUTING", "POSTROUTING"} },
             { "mangle", new List<string>{"INPUT", "FORWARD", "OUTPUT", "PREROUTING", "POSTROUTING"} },
        };

        internal static List<String> GetInternalChains(String table)
        {
            if (!Tables.ContainsKey(table))
            {
                throw new IpTablesNetException(String.Format("Unknown Table: {0}", table));
            }

            return Tables[table];
        }

        internal static bool IsInternalChain(String table, String chain)
        {
            return GetInternalChains(table).Contains(chain);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IPTables.Net.Exceptions;

namespace IPTables.Net.Iptables
{
    /// <summary>
    /// Data to define the default IPTables tables and chains
    /// </summary>
    internal class IPTablesTables
    {
        static internal Dictionary<String, List<String>> Tables = new Dictionary<string, List<string>>
        {
             { "filter", new List<string>{"INPUT", "FORWARD", "OUTPUT"} },
             { "nat", new List<string>{"PREROUTING", "POSTROUTING", "OUTPUT"} },
             { "raw", new List<string>{"PREROUTING", "POSTROUTING", "OUTPUT"} },
             { "mangle", new List<string>{"INPUT", "FORWARD", "OUTPUT", "PREROUTING", "POSTROUTING"} },
        };

        internal static List<String> GetInternalChains(String table)
        {
            if (!Tables.ContainsKey(table))
            {
                throw new IpTablesNetException(String.Format("Unknown Table: {0}", table));
            }

            return Tables[table];
        }

        internal static bool IsInternalChain(String table, String chain)
        {
            return GetInternalChains(table).Contains(chain);
        }
    }
}

Add OUTPUT chain to raw, remove POSTROUTING


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

namespace osu.Game.Rulesets.Mods
{
    /// <summary>
    /// The usage of this mod to determine whether it's playable in such context.
    /// </summary>
    public enum ModUsage
    {
        /// <summary>
        /// Used for a per-user gameplay session.
        /// Determines whether the mod is playable by an end user.
        /// </summary>
        User,

        /// <summary>
        /// Used in multiplayer but must be applied to all users.
        /// This is generally the case for mods which affect the length of gameplay.
        /// </summary>
        MultiplayerRoomWide,

        /// <summary>
        /// Used in multiplayer either at a room or per-player level (i.e. "free mod").
        /// </summary>
        MultiplayerPerPlayer,
    }
}

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

namespace osu.Game.Rulesets.Mods
{
    /// <summary>
    /// The usage of this mod to determine whether it's playable in such context.
    /// </summary>
    public enum ModUsage
    {
        /// <summary>
        /// Used for a per-user gameplay session.
        /// </summary>
        User,

        /// <summary>
        /// Used in multiplayer but must be applied to all users.
        /// This is generally the case for mods which affect the length of gameplay.
        /// </summary>
        MultiplayerRoomWide,

        /// <summary>
        /// Used in multiplayer either at a room or per-player level (i.e. "free mod").
        /// </summary>
        MultiplayerPerPlayer,
    }
}

Remove redundant line from mod usage

Remove redundant line from mod usage


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

namespace MatterHackers.MatterControl.Testing
{
    public class TestingDispatch
    {
        string errorLogFileName = null;
        public TestingDispatch()
        {
            errorLogFileName = string.Format("ErrorLog - {0:yyyy-MM-dd hh-mmtt}.txt", DateTime.Now);
            string firstLine = string.Format("MatterControl Errors: {0:yyyy-MM-dd hh:mm:ss tt}", DateTime.Now);
            using (StreamWriter file = new StreamWriter(errorLogFileName))
            {
                file.WriteLine(errorLogFileName, firstLine);
            }
        }

        public void RunTests(string[] testCommands)
        {
            try { ReleaseTests.AssertDebugNotDefined(); }
            catch (Exception e) { DumpException(e); }

            try { MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined(); }
            catch (Exception e) { DumpException(e); }
        }

        void DumpException(Exception e)
        {
            using (StreamWriter w = File.AppendText(errorLogFileName))
            {
                w.WriteLine(e.Message);
                w.Write(e.StackTrace);
                w.WriteLine();
            }
        }
    }
}

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

namespace MatterHackers.MatterControl.Testing
{
    public class TestingDispatch
    {
        string errorLogFileName = null;
        public TestingDispatch()
        {
            errorLogFileName = "ErrorLog.txt";
            string firstLine = string.Format("MatterControl Errors: {0:yyyy-MM-dd hh:mm:ss tt}", DateTime.Now);
            using (StreamWriter file = new StreamWriter(errorLogFileName))
            {
                file.WriteLine(errorLogFileName, firstLine);
            }
        }

        public void RunTests(string[] testCommands)
        {
            try { ReleaseTests.AssertDebugNotDefined(); }
            catch (Exception e) { DumpException(e); }

            try { MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined(); }
            catch (Exception e) { DumpException(e); }
        }

        void DumpException(Exception e)
        {
            using (StreamWriter w = File.AppendText(errorLogFileName))
            {
                w.WriteLine(e.Message);
                w.Write(e.StackTrace);
                w.WriteLine();
            }
        }
    }
}

Save as consistent filename to make other scripting easier.


using System;

namespace UnhelpfulDebugger
{
    class Program
    {
        static void Main()
        {
            string awkward1 = "Foo\\Bar";
            string awkward2 = "FindElement";
            float awkward3 = 4.9999995f;

            Console.WriteLine(awkward1);
            PrintString(awkward1);

            Console.WriteLine(awkward2);
            PrintString(awkward2);

            Console.WriteLine(awkward3);
            PrintDouble(awkward3);
        }

        static void PrintString(string text)
        {
            Console.WriteLine($"Text: '{text}'");
            Console.WriteLine($"Length: {text.Length}");
            for (int i = 0; i < text.Length; i++)
            {
                Console.WriteLine($"{i,2} U+{((int)text[i]):0000} '{text[i]}'");
            }
        }

        static void PrintDouble(double value) =>
            Console.WriteLine(DoubleConverter.ToExactString(value));
    }
}

using System;

namespace UnhelpfulDebugger
{
    class Program
    {
        static void Main()
        {
            string awkward1 = "Foo\\Bar";
            string awkward2 = "FindElement";
            double awkward3 = 4.9999999999999995d;

            Console.WriteLine(awkward1);
            PrintString(awkward1);

            Console.WriteLine(awkward2);
            PrintString(awkward2);

            Console.WriteLine(awkward3);
            PrintDouble(awkward3);
        }

        static void PrintString(string text)
        {
            Console.WriteLine($"Text: '{text}'");
            Console.WriteLine($"Length: {text.Length}");
            for (int i = 0; i < text.Length; i++)
            {
                Console.WriteLine($"{i,2} U+{((int)text[i]):0000} '{text[i]}'");
            }
        }

        static void PrintDouble(double value) =>
            Console.WriteLine(DoubleConverter.ToExactString(value));
    }
}

Use double instead of float

Use double instead of float


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

using System;
using Foundation;
using osu.Framework.Input;

namespace osu.Framework.iOS.Input
{
    public class IOSTextInput : ITextInputSource
    {
        private readonly IOSGameView view;

        private string pending = string.Empty;

        public IOSTextInput(IOSGameView view)
        {
            this.view = view;
        }

        public bool ImeActive => false;

        public string GetPendingText()
        {
            try
            {
                return pending;
            }
            finally
            {
                pending = string.Empty;
            }
        }

        private void handleShouldChangeCharacters(NSRange range, string text)
        {
            if (text == " " || text.Trim().Length > 0)
                pending += text;
        }

        public void Deactivate(object sender)
        {
            view.KeyboardTextField.HandleShouldChangeCharacters -= handleShouldChangeCharacters;
            view.KeyboardTextField.UpdateFirstResponder(false);
        }

        public void Activate(object sender)
        {
            view.KeyboardTextField.HandleShouldChangeCharacters += handleShouldChangeCharacters;
            view.KeyboardTextField.UpdateFirstResponder(true);
        }

        public event Action<string> OnNewImeComposition;
        public event Action<string> OnNewImeResult;
    }
}

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

using System;
using Foundation;
using osu.Framework.Input;

namespace osu.Framework.iOS.Input
{
    public class IOSTextInput : ITextInputSource
    {
        private readonly IOSGameView view;

        private string pending = string.Empty;

        public IOSTextInput(IOSGameView view)
        {
            this.view = view;
        }

        public bool ImeActive => false;

        public string GetPendingText()
        {
            try
            {
                return pending;
            }
            finally
            {
                pending = string.Empty;
            }
        }

        private void handleShouldChangeCharacters(NSRange range, string text)
        {
            if (text == " " || text.Trim().Length > 0)
                pending += text;
        }

        public void Deactivate(object sender)
        {
            view.KeyboardTextField.HandleShouldChangeCharacters -= handleShouldChangeCharacters;
            view.KeyboardTextField.UpdateFirstResponder(false);
        }

        public void Activate(object sender)
        {
            view.KeyboardTextField.HandleShouldChangeCharacters += handleShouldChangeCharacters;
            view.KeyboardTextField.UpdateFirstResponder(true);
        }

        public event Action<string> OnNewImeComposition
        {
            add { }
            remove { }
        }
        public event Action<string> OnNewImeResult
        {
            add { }
            remove { }
        }
    }
}

Use empty accessor for unimplemented events.


// 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.Input.StateChanges.Events;
using osu.Framework.Input.States;
using osuTK;

namespace osu.Framework.Input.StateChanges
{
    /// <summary>
    /// Denotes a relative change of mouse scroll.
    /// Pointing devices such as mice provide relative scroll input.
    /// </summary>
    public class MouseScrollRelativeInput : IInput
    {
        /// <summary>
        /// The change in scroll. This is added to the current scroll.
        /// </summary>
        public Vector2 Delta;

        /// <summary>
        /// Whether the change came from a device supporting precision scrolling.
        /// </summary>
        /// <remarks>
        /// In cases this is true, scroll events will generally map 1:1 to user's input, rather than incrementing in large "notches" (as expected of traditional scroll wheels).
        /// </remarks>
        public bool IsPrecise;

        public void Apply(InputState state, IInputStateChangeHandler handler)
        {
            var mouse = state.Mouse;

            if (Delta != Vector2.Zero)
            {
                var lastScroll = mouse.Scroll;
                mouse.Scroll += Delta;
                mouse.LastSource = this;
                handler.HandleInputStateChange(new MouseScrollChangeEvent(state, this, lastScroll, IsPrecise));
            }
        }
    }
}

// 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.Input.StateChanges.Events;
using osu.Framework.Input.States;
using osuTK;

namespace osu.Framework.Input.StateChanges
{
    /// <summary>
    /// Denotes a relative change of mouse scroll.
    /// Pointing devices such as mice provide relative scroll input.
    /// </summary>
    public class MouseScrollRelativeInput : IInput
    {
        /// <summary>
        /// The change in scroll. This is added to the current scroll.
        /// </summary>
        public Vector2 Delta;

        /// <summary>
        /// Whether the change came from a device supporting precision scrolling.
        /// </summary>
        /// <remarks>
        /// In cases this is true, scroll events will generally map 1:1 to user's input, rather than incrementing in large "notches" (as expected of traditional scroll wheels).
        /// </remarks>
        public bool IsPrecise;

        public void Apply(InputState state, IInputStateChangeHandler handler)
        {
            var mouse = state.Mouse;

            if (Delta != Vector2.Zero)
            {
                if (!IsPrecise && Delta.X == 0 && state.Keyboard.ShiftPressed)
                    Delta = new Vector2(Delta.Y, 0);

                var lastScroll = mouse.Scroll;
                mouse.Scroll += Delta;
                mouse.LastSource = this;
                handler.HandleInputStateChange(new MouseScrollChangeEvent(state, this, lastScroll, IsPrecise));
            }
        }
    }
}

Convert vertical scroll to horizontal when shift is held


@using System.Security.Claims

@{
    ViewBag.Title = "Employees Overview";
}

Employees Overview

You can only see this page if you have the employee_read permissions.

@if (ClaimsPrincipal.Current.HasClaim(ClaimTypes.Role, "employee_create"))
{
    Create a new employee
}

Hide or show button in sample application


using System.Collections.Generic;
using System.Drawing;
using System.IO;
using ValveKeyValue;

namespace GUI.Utils
{
    internal static class Settings
    {
        public class AppConfig
        {
            public List<string> GameSearchPaths { get; set; } = new List<string>();
            public string BackgroundColor { get; set; } = string.Empty;
            public string OpenDirectory { get; set; } = string.Empty;
            public string SaveDirectory { get; set; } = string.Empty;
        }

        private const string SettingsFilePath = "settings.txt";

        public static AppConfig Config { get; set; } = new AppConfig();

        public static Color BackgroundColor { get; set; } = Color.FromArgb(60, 60, 60);

        public static void Load()
        {
            if (!File.Exists(SettingsFilePath))
            {
                Save();
                return;
            }

            using (var stream = new FileStream(SettingsFilePath, FileMode.Open, FileAccess.Read))
            {
                Config = KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize<AppConfig>(stream, KVSerializerOptions.DefaultOptions);
            }

            BackgroundColor = ColorTranslator.FromHtml(Config.BackgroundColor);
        }

        public static void Save()
        {
            Config.BackgroundColor = ColorTranslator.ToHtml(BackgroundColor);

            using (var stream = new FileStream(SettingsFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Serialize(stream, Config, nameof(ValveResourceFormat));
            }
        }
    }
}

using System.Collections.Generic;
using System.Drawing;
using System.IO;
using ValveKeyValue;

namespace GUI.Utils
{
    internal static class Settings
    {
        public class AppConfig
        {
            public List<string> GameSearchPaths { get; set; } = new List<string>();
            public string BackgroundColor { get; set; } = string.Empty;
            public string OpenDirectory { get; set; } = string.Empty;
            public string SaveDirectory { get; set; } = string.Empty;
        }

        private static string SettingsFilePath;

        public static AppConfig Config { get; set; } = new AppConfig();

        public static Color BackgroundColor { get; set; } = Color.FromArgb(60, 60, 60);

        public static void Load()
        {
            SettingsFilePath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "settings.txt");

            if (!File.Exists(SettingsFilePath))
            {
                Save();
                return;
            }

            using (var stream = new FileStream(SettingsFilePath, FileMode.Open, FileAccess.Read))
            {
                Config = KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize<AppConfig>(stream, KVSerializerOptions.DefaultOptions);
            }

            BackgroundColor = ColorTranslator.FromHtml(Config.BackgroundColor);
        }

        public static void Save()
        {
            Config.BackgroundColor = ColorTranslator.ToHtml(BackgroundColor);

            using (var stream = new FileStream(SettingsFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Serialize(stream, Config, nameof(ValveResourceFormat));
            }
        }
    }
}

Save settings.txt to same folder as the assembly

Fixes #109


using System;
using System.Linq;
using downr.Services;
using Microsoft.AspNetCore.Mvc;

namespace downr.Controllers
{
    public class HomeController : Controller
    {
        IYamlIndexer _indexer;

        public HomeController(IYamlIndexer indexer)
        {
            _indexer = indexer;
        }

        [Route("{id?}")]
        public IActionResult Index(string id)
        {
            // if no slug was provided show the last one
            if (string.IsNullOrEmpty(id))
                return RedirectToAction("Index", "Posts", new
                {
                    slug = _indexer.Metadata.ElementAt(0).Slug
                });

            // if the slug was provided AND found, redirect to it
            if (_indexer.Metadata.Any(x => x.Slug == id))
                return RedirectToAction("Index", "Posts", new
                {
                    slug = _indexer.Metadata.ElementAt(0).Slug
                });
            else // no match was found, show the last one
                return RedirectToAction("Index", "Posts", new
                {
                    slug = _indexer.Metadata.ElementAt(0).Slug
                });
        }
    }
}

using System;
using System.Linq;
using downr.Services;
using Microsoft.AspNetCore.Mvc;

namespace downr.Controllers
{
    public class HomeController : Controller
    {
        IYamlIndexer _indexer;

        public HomeController(IYamlIndexer indexer)
        {
            _indexer = indexer;
        }

        [Route("{id?}")]
        public IActionResult Index(string id)
        {
            //Go to a slug if provided otherwise go to latest.
            var slug = _indexer.Metadata.FirstOrDefault(x => x.Slug == id)?.Slug;
            return RedirectToAction("Index", "Posts", new
                {
                    slug = slug ?? _indexer.Metadata.ElementAt(0).Slug
                });
        }
    }
}

Fix logic in home index to go to a slug if provided


                GC Handicapping System

                New GC Handicapping System comes into effect 3 April, 2017

                GC Handicapping System

                New GC Handicapping System came into effect 3 April, 2017

Change GC Handicapping sticky note

Change GC Handicapping sticky note


// 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.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServer.CustomProtocol;
using Newtonsoft.Json.Linq;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;

namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests
{
    public class RunCodeActionsHandlerTests : AbstractLiveShareRequestHandlerTests
    {
        [WpfFact]
        public async Task TestRunCodeActionsAsync()
        {
            var markup =
@"class A
{
    void M()
    {
        {|caret:|}int i = 1;
    }
}";
            var (solution, ranges) = CreateTestSolution(markup);
            var codeActionLocation = ranges["caret"].First();

            var results = await TestHandleAsync<LSP.ExecuteCommandParams, object>(solution, CreateExecuteCommandParams(codeActionLocation));
            Assert.True((bool)results);
        }

        private static LSP.ExecuteCommandParams CreateExecuteCommandParams(LSP.Location location)
            => new LSP.ExecuteCommandParams()
            {
                Command = "_liveshare.remotecommand.Roslyn",
                Arguments = new object[]
                {
                    JObject.FromObject(new LSP.Command()
                    {
                        CommandIdentifier = "Roslyn.RunCodeAction",
                        Arguments = new RunCodeActionParams[]
                        {
                            CreateRunCodeActionParams("Use implicit type", location)
                        }
                    })
                }
            };
    }
}

// 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.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServer.CustomProtocol;
using Newtonsoft.Json.Linq;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;

namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests
{
    public class RunCodeActionsHandlerTests : AbstractLiveShareRequestHandlerTests
    {
        [WpfFact]
        public async Task TestRunCodeActionsAsync()
        {
            var markup =
@"class A
{
    void M()
    {
        {|caret:|}int i = 1;
    }
}";
            var (solution, ranges) = CreateTestSolution(markup);
            var codeActionLocation = ranges["caret"].First();

            var results = await TestHandleAsync<LSP.ExecuteCommandParams, object>(solution, CreateExecuteCommandParams(codeActionLocation, "Use implicit type"));
            Assert.True((bool)results);
        }

        private static LSP.ExecuteCommandParams CreateExecuteCommandParams(LSP.Location location, string title)
            => new LSP.ExecuteCommandParams()
            {
                Command = "_liveshare.remotecommand.Roslyn",
                Arguments = new object[]
                {
                    JObject.FromObject(new LSP.Command()
                    {
                        CommandIdentifier = "Roslyn.RunCodeAction",
                        Arguments = new RunCodeActionParams[]
                        {
                            CreateRunCodeActionParams(title, location)
                        },
                        Title = title
                    })
                }
            };
    }
}

Update tests to pass new required title parameter.


using Loupe.Extensibility;
using Loupe.Extensibility.Client;

namespace Loupe.Extension.Export
{
    /// <summary>
    /// Top-level class for integrating with the Loupe framework
    /// </summary>
    [LoupeExtension(ConfigurationEditor = typeof(ExportConfigurationDialog),
        MachineConfiguration = typeof(ExportAddInConfiguration))]
    public class ExtentionDefinition : IExtensionDefinition
    {
        /// <summary>
        /// Called to register the extension.
        /// </summary>
        /// <param name="context">A standard interface to the hosting environment for the Extension, provided to all the different extensions that get loaded.</param><param name="definitionContext">Used to register the various types used by the extension.</param>
        /// <remarks>
        /// <para>
        /// If any exception is thrown during this call this Extension will not be loaded.
        /// </para>
        /// <para>
        /// Register each of the other extension types that should be available to end users through appropriate calls to
        ///             the definitionContext.  These objects will be created and initialized as required and provided the same IExtensionContext object instance provided to this
        ///             method to enable coordination between all of the components.
        /// </para>
        /// <para>
        /// After registration the extension definition object is unloaded and disposed.
        /// </para>
        /// </remarks>
        public void Register(IGlobalContext context, IExtensionDefinitionContext definitionContext)
        {
            //we have to register all of our types during this call or they won't be used at all.
            definitionContext.RegisterSessionAnalyzer(typeof(SessionExporter));
            definitionContext.RegisterSessionCommand(typeof(SessionExporter));
        }
    }
}

using Loupe.Extensibility;
using Loupe.Extensibility.Client;

namespace Loupe.Extension.Export
{
    /// <summary>
    /// Top-level class for integrating with the Loupe framework
    /// </summary>
    [LoupeExtension(ConfigurationEditor = typeof(ExportConfigurationDialog),
        CommonConfiguration = typeof(ExportAddInConfiguration))]
    public class ExtentionDefinition : IExtensionDefinition
    {
        /// <summary>
        /// Called to register the extension.
        /// </summary>
        /// <param name="context">A standard interface to the hosting environment for the Extension, provided to all the different extensions that get loaded.</param><param name="definitionContext">Used to register the various types used by the extension.</param>
        /// <remarks>
        /// <para>
        /// If any exception is thrown during this call this Extension will not be loaded.
        /// </para>
        /// <para>
        /// Register each of the other extension types that should be available to end users through appropriate calls to
        ///             the definitionContext.  These objects will be created and initialized as required and provided the same IExtensionContext object instance provided to this
        ///             method to enable coordination between all of the components.
        /// </para>
        /// <para>
        /// After registration the extension definition object is unloaded and disposed.
        /// </para>
        /// </remarks>
        public void Register(IGlobalContext context, IExtensionDefinitionContext definitionContext)
        {
            //we have to register all of our types during this call or they won't be used at all.
            definitionContext.RegisterSessionAnalyzer(typeof(SessionExporter));
            definitionContext.RegisterSessionCommand(typeof(SessionExporter));
        }
    }
}

Correct extension definition configuration value


using Microsoft.PowerShell.EditorServices.Session;
using Microsoft.PowerShell.EditorServices.Transport.Stdio.Event;
using Microsoft.PowerShell.EditorServices.Transport.Stdio.Message;
using Microsoft.PowerShell.EditorServices.Transport.Stdio.Response;
using Nito.AsyncEx;
using System.Threading.Tasks;

namespace Microsoft.PowerShell.EditorServices.Transport.Stdio.Request
{
    [MessageTypeName("initialize")]
    public class InitializeRequest : RequestBase<InitializeRequestArguments>
    {
        public override async Task ProcessMessage(
            EditorSession editorSession,
            MessageWriter messageWriter)
        {
            // Send the Initialized event first so that we get breakpoints
            await messageWriter.WriteMessage(
                new InitializedEvent());

            // Now send the Initialize response to continue setup
            await messageWriter.WriteMessage(
                this.PrepareResponse(
                    new InitializeResponse()));
        }
    }

    public class InitializeRequestArguments
    {
        public string AdapterId { get; set; }

        public bool LinesStartAt1 { get; set; }

        public string PathFormat { get; set; }

        public bool SourceMaps { get; set; }

        public string GeneratedCodeDirectory { get; set; }
    }
}

using Microsoft.PowerShell.EditorServices.Session;
using Microsoft.PowerShell.EditorServices.Transport.Stdio.Event;
using Microsoft.PowerShell.EditorServices.Transport.Stdio.Message;
using Microsoft.PowerShell.EditorServices.Transport.Stdio.Response;
using Microsoft.PowerShell.EditorServices.Utility;
using Nito.AsyncEx;
using System.Threading.Tasks;

namespace Microsoft.PowerShell.EditorServices.Transport.Stdio.Request
{
    [MessageTypeName("initialize")]
    public class InitializeRequest : RequestBase<InitializeRequestArguments>
    {
        public override async Task ProcessMessage(
            EditorSession editorSession,
            MessageWriter messageWriter)
        {
            // TODO: Remove this behavior in the near future --
            //   Create the debug service log in a separate file
            //   so that there isn't a conflict with the default
            //   log file.
            Logger.Initialize("DebugService.log", LogLevel.Verbose);

            // Send the Initialized event first so that we get breakpoints
            await messageWriter.WriteMessage(
                new InitializedEvent());

            // Now send the Initialize response to continue setup
            await messageWriter.WriteMessage(
                this.PrepareResponse(
                    new InitializeResponse()));
        }
    }

    public class InitializeRequestArguments
    {
        public string AdapterId { get; set; }

        public bool LinesStartAt1 { get; set; }

        public string PathFormat { get; set; }

        public bool SourceMaps { get; set; }

        public string GeneratedCodeDirectory { get; set; }
    }
}

Add separate log file for debugging service

This change adds a new log file for the debugging service called
"DebugService.log".  This log file will be taken back out once we have the
debugging service running in the same process as the language service.


using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;

namespace CORS.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "This is a CORS request.", "That works from any origin." };
        }

        // GET api/values/another
        [HttpGet]
        [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
        public IEnumerable<string> Another()
        {
            return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." };
        }

        public class EstimateQuery
        {
            public string username { get; set; }
        }

        public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
        {
            // All the values in "query" are null or zero
            // Do some stuff with query if there were anything to do
            if(query != null)
            {
                return Ok(query.username);
            }
            else
            {
                return Ok("Add a username!");
            }
        }
    }
}

using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;

namespace CORS.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "This is a CORS request.", "That works from any origin." };
        }

        // GET api/values/another
        [HttpGet]
        [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
        public IEnumerable<string> Another()
        {
            return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." };
        }

        public class EstimateQuery
        {
            public string username { get; set; }
        }

        public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
        {
            // All the values in "query" are null or zero
            // Do some stuff with query if there were anything to do
            if(query != null && query.username != null)
            {
                return Ok(query.username);
            }
            else
            {
                return Ok("Add a username!");
            }
        }
    }
}

Check username for null too.

Check username for null too.


using System;
using System.Text;

namespace Manos.Server {

	public interface IHttpResponse {

		IHttpTransaction Transaction {
			get;
		}

		HttpHeaders Headers {
			get;
		}

		HttpResponseStream Stream {
			get;
		}

		Encoding Encoding {
			get;
		}

		int StatusCode {
			get;
			set;
		}

		bool WriteStatusLine {
			get;
			set;
		}

		bool WriteHeaders {
			get;
			set;
		}

		void Write (string str);
		void Write (string str, params object [] prms);

		void WriteLine (string str);
		void WriteLine (string str, params object [] prms);

		void Write (byte [] data);

		void SendFile (string file);

		void Finish ();

		void SetHeader (string name, string value);

		void SetCookie (string name, HttpCookie cookie);
		HttpCookie SetCookie (string name, string value);
		HttpCookie SetCookie (string name, string value, string domain);
		HttpCookie SetCookie (string name, string value, DateTime expires);
		HttpCookie SetCookie (string name, string value, string domain, DateTime expires);
		HttpCookie SetCookie (string name, string value, TimeSpan max_age);
		HttpCookie SetCookie (string name, string value, string domain, TimeSpan max_age);

		void Redirect (string url);
	}
}

using System;
using System.IO;
using System.Text;

namespace Manos.Server {

	public interface IHttpResponse {

		IHttpTransaction Transaction {
			get;
		}

		HttpHeaders Headers {
			get;
		}

		HttpResponseStream Stream {
			get;
		}

		StreamWriter Writer {
			get;
		}

		Encoding Encoding {
			get;
		}

		int StatusCode {
			get;
			set;
		}

		bool WriteStatusLine {
			get;
			set;
		}

		bool WriteHeaders {
			get;
			set;
		}

		void Write (string str);
		void Write (string str, params object [] prms);

		void WriteLine (string str);
		void WriteLine (string str, params object [] prms);

		void Write (byte [] data);

		void SendFile (string file);

		void Finish ();

		void SetHeader (string name, string value);

		void SetCookie (string name, HttpCookie cookie);
		HttpCookie SetCookie (string name, string value);
		HttpCookie SetCookie (string name, string value, string domain);
		HttpCookie SetCookie (string name, string value, DateTime expires);
		HttpCookie SetCookie (string name, string value, string domain, DateTime expires);
		HttpCookie SetCookie (string name, string value, TimeSpan max_age);
		HttpCookie SetCookie (string name, string value, string domain, TimeSpan max_age);

		void Redirect (string url);
	}
}

Add the writer to the interface.

Add the writer to the interface.


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

namespace Giles.Core.Configuration
{
    [Serializable]
    public class Filter
    {
        public Filter() { }

        public Filter(string convertToFilter)
        {
            foreach (var entry in FilterLookUp.Where(entry => convertToFilter.Contains(entry.Key)))
            {
                Type = entry.Value;
                Name = convertToFilter.Replace(entry.Key, string.Empty).Trim();

                break;
            }

            if (!string.IsNullOrWhiteSpace(Name)) return;

            Name = convertToFilter.Trim();
            Type = FilterType.Inclusive;
        }

        public string Name { get; set; }
        public FilterType Type { get; set; }

        public string NameDll
        {
            get
            {
                return Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? Name : String.Format("{0}.dll", Name);
            }
        }

        public static readonly IDictionary<string, FilterType> FilterLookUp = new Dictionary<string, FilterType>
                                                                           {
                                                                               {"-i", FilterType.Inclusive},
                                                                               {"-e", FilterType.Exclusive}
                                                                           };
    }

    public enum FilterType
    {
        Inclusive,
        Exclusive
    }
}

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

namespace Giles.Core.Configuration
{
    [Serializable]
    public class Filter
    {
        public Filter() { }

        public Filter(string convertToFilter)
        {
            foreach (var entry in FilterLookUp.Where(entry => convertToFilter.Contains(string.Format(" {0}" ,entry.Key))))
            {
                Type = entry.Value;
                Name = convertToFilter.Replace(string.Format(" {0}", entry.Key), string.Empty).Trim();

                break;
            }

            if (!string.IsNullOrWhiteSpace(Name)) return;

            Name = convertToFilter.Trim();
            Type = FilterType.Inclusive;
        }

        public string Name { get; set; }
        public FilterType Type { get; set; }

        public string NameDll
        {
            get
            {
                return Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? Name : String.Format("{0}.dll", Name);
            }
        }

        public static readonly IDictionary<string, FilterType> FilterLookUp = new Dictionary<string, FilterType>
                                                                           {
                                                                               {"-i", FilterType.Inclusive},
                                                                               {"-e", FilterType.Exclusive}
                                                                           };
    }

    public enum FilterType
    {
        Inclusive,
        Exclusive
    }
}

Make sure there is a space between the -* and the filtered namespace to prevent any accidental replacements


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

namespace MVCLibraryManagementSystem.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
}

Fix merge conflict with maitisoumyajit

Fix merge conflict with maitisoumyajit


using System;
using System.Windows;
using System.Windows.Controls;
using vmPing.Classes;

namespace vmPing.Views
{
    /// <summary>
    /// Interaction logic for IsolatedPingWindow.xaml
    /// </summary>
    public partial class IsolatedPingWindow : Window
    {
        private int SelStart = 0;
        private int SelLength = 0;

        public IsolatedPingWindow(Probe pingItem)
        {
            InitializeComponent();
            pingItem.IsolatedWindow = this;
            DataContext = pingItem;
        }

        private void History_TextChanged(object sender, TextChangedEventArgs e)
        {
            History.SelectionStart = SelStart;
            History.SelectionLength = SelLength;
            History.ScrollToEnd();
        }

        private void History_SelectionChanged(object sender, RoutedEventArgs e)
        {
            SelStart = History.SelectionStart;
            SelLength = History.SelectionLength;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            (DataContext as Probe).IsolatedWindow = null;
            DataContext = null;
        }
    }
}

using System;
using System.Windows;
using System.Windows.Controls;
using vmPing.Classes;

namespace vmPing.Views
{
    /// <summary>
    /// Interaction logic for IsolatedPingWindow.xaml
    /// </summary>
    public partial class IsolatedPingWindow : Window
    {
        private int SelStart = 0;
        private int SelLength = 0;

        public IsolatedPingWindow(Probe pingItem)
        {
            InitializeComponent();
            pingItem.IsolatedWindow = this;
            DataContext = pingItem;
        }

        private void History_TextChanged(object sender, TextChangedEventArgs e)
        {
            History.SelectionStart = SelStart;
            History.SelectionLength = SelLength;
            Application.Current.Dispatcher.BeginInvoke(
                new Action(() => History.ScrollToEnd()));
        }

        private void History_SelectionChanged(object sender, RoutedEventArgs e)
        {
            SelStart = History.SelectionStart;
            SelLength = History.SelectionLength;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            (DataContext as Probe).IsolatedWindow = null;
            DataContext = null;
        }
    }
}

Use dispatcher begininvoke for textbox scroll


using System;

namespace NuGet
{
    public static class NuGetConstants
    {
        public static readonly string DefaultFeedUrl = "https://go.microsoft.com/fwlink/?LinkID=230477";
        public static readonly string V1FeedUrl = "https://go.microsoft.com/fwlink/?LinkID=206669";

        public static readonly string DefaultGalleryServerUrl = "http://go.microsoft.com/fwlink/?LinkID=207106";

        public static readonly string DefaultSymbolServerUrl = "http://nuget.gw.symbolsource.org/Public/NuGet";
    }
}

using System;

namespace NuGet
{
    public static class NuGetConstants
    {
        public static readonly string DefaultFeedUrl = "https://go.microsoft.com/fwlink/?LinkID=230477";
        public static readonly string V1FeedUrl = "https://go.microsoft.com/fwlink/?LinkID=206669";

        public static readonly string DefaultGalleryServerUrl = "https://www.nuget.org";

        public static readonly string DefaultSymbolServerUrl = "http://nuget.gw.symbolsource.org/Public/NuGet";
    }
}

Update default publishing url to point to v2 feed.

--HG--
branch : 1.6


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

namespace AppHarbor
{
	class Program
	{
		static void Main(string[] args)
		{
		}
	}
}

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

namespace AppHarbor
{
	class Program
	{
		static void Main(string[] args)
		{
			var container = new WindsorContainer();
		}
	}
}

Initialize a WindowsContainer when program starts


using System.Windows;
using Dogstar.Properties;

namespace Dogstar
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App
	{
		void Application_Startup(object sender, StartupEventArgs e)
		{
			if (Settings.Default.UpgradeCheck)
			{
				Settings.Default.Upgrade();
				Settings.Default.UpgradeCheck = false;
				Settings.Default.Save();
			}

			foreach (var arg in e.Args)
			{
				switch (arg)
				{
					case "-pso2":
						Helper.LaunchGame();
						Shutdown();
						break;
				}
			}
		}

		private void Application_Exit(object sender, ExitEventArgs e)
		{
			if (e.ApplicationExitCode == 0)
			{
				Settings.Default.Save();
			}
		}
	}
}

using System.Windows;
using Dogstar.Properties;

namespace Dogstar
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App
	{
		void Application_Startup(object sender, StartupEventArgs e)
		{
			if (Settings.Default.UpgradeCheck)
			{
				Settings.Default.Upgrade();
				Settings.Default.UpgradeCheck = false;
				Settings.Default.Save();
			}

			foreach (var arg in e.Args)
			{
				switch (arg)
				{
					case "-pso2":
						Helper.LaunchGame();
						Shutdown();
						break;
				}
			}
		}

		private void Application_Exit(object sender, ExitEventArgs e)
		{
			if (e.ApplicationExitCode == 0)
			{
				Settings.Default.Save();

				if (Settings.Default.IsGameInstalled)
				{
					PsoSettings.Save();
				}
			}
		}
	}
}

Save game settings on close.

Save game settings on close.


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

using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
    public class DrawableSpinnerTick : DrawableOsuHitObject
    {
        private bool hasBonusPoints;

        /// <summary>
        /// Whether this judgement has a bonus of 1,000 points additional to the numeric result.
        /// Set when a spin occured after the spinner has completed.
        /// </summary>
        public bool HasBonusPoints
        {
            get => hasBonusPoints;
            internal set
            {
                hasBonusPoints = value;

                Samples.Volume.Value = ((OsuSpinnerTickJudgement)Result.Judgement).HasBonusPoints ? 1 : 0;
            }
        }

        public override bool DisplayResult => false;

        public DrawableSpinnerTick(SpinnerTick spinnerTick)
            : base(spinnerTick)
        {
        }

        /// <summary>
        /// Apply a judgement result.
        /// </summary>
        /// <param name="hit">Whether to apply a <see cref="HitResult.Great"/> result, <see cref="HitResult.Miss"/> otherwise.</param>
        internal void TriggerResult(bool hit)
        {
            HitObject.StartTime = Time.Current;
            ApplyResult(r => r.Type = hit ? HitResult.Great : HitResult.Miss);
        }
    }
}

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

using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
    public class DrawableSpinnerTick : DrawableOsuHitObject
    {
        private bool hasBonusPoints;

        /// <summary>
        /// Whether this judgement has a bonus of 1,000 points additional to the numeric result.
        /// Set when a spin occured after the spinner has completed.
        /// </summary>
        public bool HasBonusPoints
        {
            get => hasBonusPoints;
            internal set
            {
                hasBonusPoints = value;

                ((OsuSpinnerTickJudgement)Result.Judgement).HasBonusPoints = value;
                Samples.Volume.Value = value ? 1 : 0;
            }
        }

        public override bool DisplayResult => false;

        public DrawableSpinnerTick(SpinnerTick spinnerTick)
            : base(spinnerTick)
        {
        }

        /// <summary>
        /// Apply a judgement result.
        /// </summary>
        /// <param name="hit">Whether to apply a <see cref="HitResult.Great"/> result, <see cref="HitResult.Miss"/> otherwise.</param>
        internal void TriggerResult(bool hit)
        {
            HitObject.StartTime = Time.Current;
            ApplyResult(r => r.Type = hit ? HitResult.Great : HitResult.Miss);
        }
    }
}

Fix spinner bonus ticks samples not actually playing


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Configuration;

namespace osu.Game.Overlays.Settings.Sections.Graphics
{
    public class DetailSettings : SettingsSubsection
    {
        protected override string Header => "Detail Settings";

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsCheckbox
                {
                    LabelText = "Storyboards",
                    Bindable = config.GetBindable<bool>(OsuSetting.ShowStoryboard)
                },
                new SettingsCheckbox
                {
                    LabelText = "Rotate cursor when dragging",
                    Bindable = config.GetBindable<bool>(OsuSetting.CursorRotation)
                },
                new SettingsEnumDropdown<ScreenshotFormat>
                {
                    LabelText = "Screenshot format",
                    Bindable = config.GetBindable<ScreenshotFormat>(OsuSetting.ScreenshotFormat)
                },
                new SettingsCheckbox
                {
                    LabelText = "Capture menu cursor",
                    Bindable = config.GetBindable<bool>(OsuSetting.ScreenshotCaptureMenuCursor)
                }
            };
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Configuration;

namespace osu.Game.Overlays.Settings.Sections.Graphics
{
    public class DetailSettings : SettingsSubsection
    {
        protected override string Header => "Detail Settings";

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsCheckbox
                {
                    LabelText = "Storyboards",
                    Bindable = config.GetBindable<bool>(OsuSetting.ShowStoryboard)
                },
                new SettingsCheckbox
                {
                    LabelText = "Rotate cursor when dragging",
                    Bindable = config.GetBindable<bool>(OsuSetting.CursorRotation)
                },
                new SettingsEnumDropdown<ScreenshotFormat>
                {
                    LabelText = "Screenshot format",
                    Bindable = config.GetBindable<ScreenshotFormat>(OsuSetting.ScreenshotFormat)
                },
                new SettingsCheckbox
                {
                    LabelText = "Show menu cursor in screenshots",
                    Bindable = config.GetBindable<bool>(OsuSetting.ScreenshotCaptureMenuCursor)
                }
            };
        }
    }
}

Reword options item to include "screenshot"


using System;
using GAIT.Utilities.Logging;
using NLog;
using Topshelf;
using static GAIT.Utilities.GeneralBootstrapper;

namespace Rik.CodeCamp.Host
{
    internal class CodeCampControl : ServiceControl
    {
        private Bootstrapper _bootstrapper;
        private readonly ILogger _logger;

        public CodeCampControl()
        {
            _logger = LoggingFactory.Create(GetType());
        }

        public bool Start(HostControl hostControl)
        {
            try
            {
                _bootstrapper = new Bootstrapper();
                //var worker = _bootstrapper.Resolve<IWorker>();
                //return worker.Start();
            }
            catch (Exception exception)
            {
                _logger.Fatal(exception, "Start failed!!! ");
            }
            return false;
        }

        public bool Stop(HostControl hostControl)
        {
            try
            {
                _bootstrapper?.Dispose();
                CancelAll.Cancel();
            }
            catch (Exception exception)
            {
                _logger.Fatal(exception, "Stop failed!!! ");
            }
            return false;

        }
    }
}

using System;
using GAIT.Utilities.Logging;
using NLog;
using Rik.CodeCamp.Core;
using Topshelf;
using static GAIT.Utilities.GeneralBootstrapper;

namespace Rik.CodeCamp.Host
{
    internal class CodeCampControl : ServiceControl
    {
        private Bootstrapper _bootstrapper;
        private readonly ILogger _logger;

        public CodeCampControl()
        {
            _logger = LoggingFactory.Create(GetType());
        }

        public bool Start(HostControl hostControl)
        {
            try
            {
                _bootstrapper = new Bootstrapper();
                var worker = _bootstrapper.Resolve<IWorker>();
                return worker.Start();
            }
            catch (Exception exception)
            {
                _logger.Fatal(exception, "Start failed!!! ");
            }
            return false;
        }

        public bool Stop(HostControl hostControl)
        {
            try
            {
                _bootstrapper?.Dispose();
                CancelAll.Cancel();
            }
            catch (Exception exception)
            {
                _logger.Fatal(exception, "Stop failed!!! ");
            }
            return false;

        }
    }
}

Add worker resolve and start Start

Add worker resolve and start Start


using System;
using System.Windows;
using SteamAccountSwitcher.Properties;

namespace SteamAccountSwitcher
{
    /// <summary>
    ///     Interaction logic for Options.xaml
    /// </summary>
    public partial class Options : Window
    {
        public Options()
        {
            InitializeComponent();
            Settings.Default.Save();
        }

        private void menuItemImport_OnClick(object sender, EventArgs e)
        {
            AccountDataHelper.ImportAccounts();
        }

        private void menuItemExport_OnClick(object sender, EventArgs e)
        {
            AccountDataHelper.ExportAccounts();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            SettingsHelper.SaveSettings();
            DialogResult = true;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.Reload();
            DialogResult = true;
        }
    }
}

using System;
using System.Windows;
using SteamAccountSwitcher.Properties;

namespace SteamAccountSwitcher
{
    /// <summary>
    ///     Interaction logic for Options.xaml
    /// </summary>
    public partial class Options : Window
    {
        public Options()
        {
            InitializeComponent();
            Settings.Default.Save();
        }

        private void menuItemImport_OnClick(object sender, EventArgs e)
        {
            AccountDataHelper.ImportAccounts();
        }

        private void menuItemExport_OnClick(object sender, EventArgs e)
        {
            AccountDataHelper.ExportAccounts();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            SettingsHelper.SaveSettings();
            DialogResult = true;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.Reload();
            DialogResult = false;
        }
    }
}

Set DialogResult to false on Options cancel


using System;

namespace FractionCalculator
{
    using Class;
    public class TestProgram
    {
        public static void Main()
        {
            try
            {
                Fraction fraction1 = new Fraction(22, 7);
                Fraction fraction2 = new Fraction(40, 4);
                Fraction result = fraction1 + fraction2;

                Console.WriteLine(result.Numerator);
                Console.WriteLine(result.Denominator);
                Console.WriteLine(result);
            }
            catch (DivideByZeroException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

using System;

namespace FractionCalculator
{
    using Class;
    public class TestProgram
    {
        public static void Main()
        {
            try
            {
                Fraction fraction1 = new Fraction(22, 7);
                Fraction fraction2 = new Fraction(40, 4);
                Fraction result = fraction1 + fraction2;

                Console.WriteLine(result.Numerator);
                Console.WriteLine(result.Denominator);
                Console.WriteLine(result);
            }
            catch (DivideByZeroException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

Add more one catch block for ArgumentException


//-----------------------------------------------------------------------
// <copyright file="AsyncOperationTest.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace AsyncEnum35Sample.Test.Unit
{
    using System;
    using System.Collections.Generic;
    using Xunit;

    public class AsyncOperationTest
    {
        public AsyncOperationTest()
        {
        }

        [Fact]
        public void Set_result_in_ctor_and_break_completes_sync()
        {
            SetResultInCtorOperation op = new SetResultInCtorOperation(1234);
            IAsyncResult result = op.Start(null, null);

            Assert.True(result.IsCompleted);
            Assert.True(result.CompletedSynchronously);
            Assert.Equal(1234, SetResultInCtorOperation.End(result));
        }

        private abstract class TestAsyncOperation : AsyncOperation<int>
        {
            protected TestAsyncOperation()
            {
            }
        }

        private sealed class SetResultInCtorOperation : TestAsyncOperation
        {
            public SetResultInCtorOperation(int result)
            {
                this.Result = result;
            }

            protected override IEnumerator<Step> Steps()
            {
                yield break;
            }
        }
    }
}

//-----------------------------------------------------------------------
// <copyright file="AsyncOperationTest.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace AsyncEnum35Sample.Test.Unit
{
    using System;
    using System.Collections.Generic;
    using Xunit;

    public class AsyncOperationTest
    {
        public AsyncOperationTest()
        {
        }

        [Fact]
        public void Set_result_in_ctor_and_break_completes_sync()
        {
            SetResultInCtorOperation op = new SetResultInCtorOperation(1234);
            IAsyncResult result = op.Start(null, null);

            Assert.True(result.IsCompleted);
            Assert.True(result.CompletedSynchronously);
            Assert.Equal(1234, SetResultInCtorOperation.End(result));
        }

        [Fact]
        public void Set_result_in_enumerator_and_break_completes_sync()
        {
            SetResultInEnumeratorOperation op = new SetResultInEnumeratorOperation(1234);
            IAsyncResult result = op.Start(null, null);

            Assert.True(result.IsCompleted);
            Assert.True(result.CompletedSynchronously);
            Assert.Equal(1234, SetResultInEnumeratorOperation.End(result));
        }

        private abstract class TestAsyncOperation : AsyncOperation<int>
        {
            protected TestAsyncOperation()
            {
            }
        }

        private sealed class SetResultInCtorOperation : TestAsyncOperation
        {
            public SetResultInCtorOperation(int result)
            {
                this.Result = result;
            }

            protected override IEnumerator<Step> Steps()
            {
                yield break;
            }
        }

        private sealed class SetResultInEnumeratorOperation : TestAsyncOperation
        {
            private readonly int result;

            public SetResultInEnumeratorOperation(int result)
            {
                this.result = result;
            }

            protected override IEnumerator<Step> Steps()
            {
                this.Result = this.result;
                yield break;
            }
        }
    }
}

Set result in enumerator and break completes sync


// 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;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
{
    [Export(typeof(IHighlightingService))]
    [Shared]
    internal class HighlightingService : IHighlightingService
    {
        private readonly List<Lazy<IHighlighter, LanguageMetadata>> _highlighters;

        [ImportingConstructor]
        public HighlightingService(
            [ImportMany] IEnumerable<Lazy<IHighlighter, LanguageMetadata>> highlighters)
        {
            _highlighters = highlighters.ToList();
        }

        public IEnumerable<TextSpan> GetHighlights(
             SyntaxNode root, int position, CancellationToken cancellationToken)
        {
            return _highlighters.Where(h => h.Metadata.Language == root.Language)
                               .Select(h => h.Value.GetHighlights(root, position, cancellationToken))
                               .WhereNotNull()
                               .Flatten()
                               .Distinct();
        }
    }
}

// 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;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
{
    [Export(typeof(IHighlightingService))]
    [Shared]
    internal class HighlightingService : IHighlightingService
    {
        private readonly List<Lazy<IHighlighter, LanguageMetadata>> _highlighters;

        [ImportingConstructor]
        public HighlightingService(
            [ImportMany] IEnumerable<Lazy<IHighlighter, LanguageMetadata>> highlighters)
        {
            _highlighters = highlighters.ToList();
        }

        public IEnumerable<TextSpan> GetHighlights(
             SyntaxNode root, int position, CancellationToken cancellationToken)
        {
            try
            {
                return _highlighters.Where(h => h.Metadata.Language == root.Language)
                                   .Select(h => h.Value.GetHighlights(root, position, cancellationToken))
                                   .WhereNotNull()
                                   .Flatten()
                                   .Distinct();
            }
            catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/763988
                // We still couldn't identify the root cause for the linked bug above.
                // Since high lighting failure is not important enough to crash VS, change crash to NFW.
                return SpecializedCollections.EmptyEnumerable<TextSpan>();
            }
        }
    }
}

Change high lighting crash to NFW

Change high lighting crash to NFW


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;

namespace SendEmailWithLogo
{
    class Program
    {
        static void Main(string[] args)
        {
            var toAddress = "somewhere@mailinator.com";
            var fromAddress = "you@host.com";
            var message = "your message goes here";
            // create the email
            var mailMessage = new MailMessage();
            mailMessage.To.Add(toAddress);
            mailMessage.Subject = "Sending emails is easy";
            mailMessage.From = new MailAddress(fromAddress);

            mailMessage.Body = message;

            // send it (settings in web.config / app.config)
            var smtp = new SmtpClient();
            smtp.Send(mailMessage);
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;

namespace SendEmailWithLogo
{
    class Program
    {
        static void Main(string[] args)
        {
            var toAddress = "somewhere@mailinator.com";
            var fromAddress = "you@host.com";
            var pathToLogo = @"Content\logo.png";
            var pathToTemplate = @"Content\Template.html";
            var messageText = File.ReadAllText(pathToTemplate);

            // replace placeholder
            messageText = ReplacePlaceholdersWithValues(messageText);

            // create the email
            var mailMessage = new MailMessage();
            mailMessage.To.Add(toAddress);
            mailMessage.Subject = "Sending emails is easy";
            mailMessage.From = new MailAddress(fromAddress);

            mailMessage.IsBodyHtml = true;
            mailMessage.AlternateViews.Add(CreateHtmlMessage(messageText, pathToLogo));

            // send it (settings in web.config / app.config)
            var smtp = new SmtpClient();
            smtp.Send(mailMessage);
        }

        private static AlternateView CreateHtmlMessage(string messageText, string pathToLogo)
        {
            LinkedResource inline = new LinkedResource(pathToLogo);
            inline.ContentId = "companyLogo";

            AlternateView alternateView = AlternateView.CreateAlternateViewFromString(messageText, null, MediaTypeNames.Text.Html);
            alternateView.LinkedResources.Add(inline);

            return alternateView;
        }

        private static string ReplacePlaceholdersWithValues(string messageText)
        {
            // use the dynamic values instead of the hardcoded ones in this example
            messageText = messageText.Replace("$AMOUNT$", "$12.50");
            messageText = messageText.Replace("$DATE$", DateTime.Now.ToShortDateString());
            messageText = messageText.Replace("$INVOICE$", "25639");
            messageText = messageText.Replace("$TRANSACTION$", "TRX2017-WEB-01");
            return messageText;
        }
    }
}

Include company logo in email

Include company logo in email


using System;
using System.Linq;
using System.ServiceProcess;

namespace PolymeliaDeployController
{
    using System.Configuration;
    using System.Data.Entity;

    using Microsoft.Owin.Hosting;

    using PolymeliaDeploy;
    using PolymeliaDeploy.Controller;
    using PolymeliaDeploy.Data;
    using PolymeliaDeploy.Network;

    static class Program
    {
        static void Main(string[] args)
        {
            Database.SetInitializer<PolymeliaDeployDbContext>(null);
            DeployServices.ReportClient = new ReportLocalClient();

            var service = new Service();

            if (args.Any(arg => arg == "/c"))
            {
                using (CreateServiceHost())
                {
                    Console.WriteLine("Started");
                    Console.ReadKey();
                    Console.WriteLine("Stopping");
                    return;
                }
            }

            ServiceBase.Run(service);
        }

        internal static IDisposable CreateServiceHost()
        {
            var localIpAddress = IPAddressRetriever.LocalIPAddress();

            var portNumber = ConfigurationManager.AppSettings["ControllerPort"];

            var controllUri = string.Format("http://{0}:{1}", localIpAddress, portNumber);

            return WebApplication.Start<Startup>(controllUri);
        }
    }
}

using System;
using System.Linq;
using System.ServiceProcess;

namespace PolymeliaDeployController
{
    using System.Configuration;
    using System.Data.Entity;

    using Microsoft.Owin.Hosting;

    using PolymeliaDeploy;
    using PolymeliaDeploy.Controller;
    using PolymeliaDeploy.Data;
    using PolymeliaDeploy.Network;

    static class Program
    {
        static void Main(string[] args)
        {
            Database.SetInitializer<PolymeliaDeployDbContext>(null);
            DeployServices.ReportClient = new ReportLocalClient();

            var service = new Service();

            if (Environment.UserInteractive)
            {
                using (CreateServiceHost())
                {
                    Console.WriteLine("Started");
                    Console.ReadKey();
                    Console.WriteLine("Stopping");
                    return;
                }
            }

            ServiceBase.Run(service);
        }

        internal static IDisposable CreateServiceHost()
        {
            var localIpAddress = IPAddressRetriever.LocalIPAddress();

            var portNumber = ConfigurationManager.AppSettings["ControllerPort"];

            var controllUri = string.Format("http://{0}:{1}", localIpAddress, portNumber);

            return WebApplication.Start<Startup>(controllUri);
        }
    }
}

Check Environment.UserInteractive instead of /c argument.


using System;
using System.Xml;
using System.Xml.Linq;
using Rainbow.Model;

namespace Rainbow.Diff.Fields
{
	public class XmlComparison : FieldTypeBasedComparison
	{
		public override bool AreEqual(IItemFieldValue field1, IItemFieldValue field2)
		{
			if (string.IsNullOrWhiteSpace(field1.Value) && string.IsNullOrWhiteSpace(field2.Value)) return true;

			if (string.IsNullOrWhiteSpace(field1.Value) || string.IsNullOrWhiteSpace(field2.Value)) return false;

			try
			{
				var x1 = XElement.Parse(field1.Value);
				var x2 = XElement.Parse(field2.Value);

				return XNode.DeepEquals(x1, x2);
			}
			catch (XmlException xe)
			{
				throw new InvalidOperationException($"Unable to compare {field1.NameHint ?? field2.NameHint} field due to invalid XML value.", xe);
			}
		}

		public override string[] SupportedFieldTypes => new[] { "Layout", "Tracking", "Rules" };
	}
}

using System.Xml;
using System.Xml.Linq;
using Rainbow.Model;
using Sitecore.Diagnostics;

namespace Rainbow.Diff.Fields
{
	public class XmlComparison : FieldTypeBasedComparison
	{
		public override bool AreEqual(IItemFieldValue field1, IItemFieldValue field2)
		{
			if (string.IsNullOrWhiteSpace(field1.Value) && string.IsNullOrWhiteSpace(field2.Value)) return true;

			if (string.IsNullOrWhiteSpace(field1.Value) || string.IsNullOrWhiteSpace(field2.Value)) return false;

			try
			{
				var x1 = XElement.Parse(field1.Value);
				var x2 = XElement.Parse(field2.Value);

				return XNode.DeepEquals(x1, x2);
			}
			catch (XmlException xe)
			{
				Log.Error($"Field {field1.NameHint ?? field2.NameHint} contained an invalid XML value. Falling back to string comparison.", xe, this);

				return new DefaultComparison().AreEqual(field1, field2);
			}
		}

		public override string[] SupportedFieldTypes => new[] { "Layout", "Tracking", "Rules" };
	}
}

Fix error that aborted sync when invalid XML was present in an XML formatted field (e.g. a malformed rules field in the stock master db)


using System;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Serilog.Core;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Sinks.Graylog.Core;
using Serilog.Sinks.Graylog.Core.Transport;

namespace Serilog.Sinks.Graylog
{
    public class GraylogSink : ILogEventSink
    {
        private readonly Lazy<IGelfConverter> _converter;
        private readonly Lazy<ITransport> _transport;

        public GraylogSink(GraylogSinkOptions options)
        {
            ISinkComponentsBuilder sinkComponentsBuilder = new SinkComponentsBuilder(options);
            _transport = new Lazy<ITransport>(() => sinkComponentsBuilder.MakeTransport());
            _converter = new Lazy<IGelfConverter>(() => sinkComponentsBuilder.MakeGelfConverter());
        }

        public void Emit(LogEvent logEvent)
        {
            try
            {
                Task.Run(() => EmitAsync(logEvent)).GetAwaiter().GetResult();
            }
            catch (Exception exc)
            {
                SelfLog.WriteLine("Oops something going wrong {0}", exc);
            }
        }

        private Task EmitAsync(LogEvent logEvent)
        {
            JObject json = _converter.Value.GetGelfJson(logEvent);
            string payload = json.ToString(Newtonsoft.Json.Formatting.None);
            return _transport.Value.Send(payload);
        }
    }
}

using System;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Serilog.Core;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Sinks.Graylog.Core;
using Serilog.Sinks.Graylog.Core.Transport;

namespace Serilog.Sinks.Graylog
{
    public class GraylogSink : ILogEventSink, IDisposable
    {
        private readonly Lazy<IGelfConverter> _converter;
        private readonly Lazy<ITransport> _transport;

        public GraylogSink(GraylogSinkOptions options)
        {
            ISinkComponentsBuilder sinkComponentsBuilder = new SinkComponentsBuilder(options);
            _transport = new Lazy<ITransport>(() => sinkComponentsBuilder.MakeTransport());
            _converter = new Lazy<IGelfConverter>(() => sinkComponentsBuilder.MakeGelfConverter());
        }

        public void Dispose()
        {
            _transport.Value.Dispose();
        }

        public void Emit(LogEvent logEvent)
        {
            try
            {
                Task.Run(() => EmitAsync(logEvent)).GetAwaiter().GetResult();
            }
            catch (Exception exc)
            {
                SelfLog.WriteLine("Oops something going wrong {0}", exc);
            }
        }

        private Task EmitAsync(LogEvent logEvent)
        {
            JObject json = _converter.Value.GetGelfJson(logEvent);
            string payload = json.ToString(Newtonsoft.Json.Formatting.None);
            return _transport.Value.Send(payload);
        }
    }
}

Fix increase connections to transport

Fix increase connections to transport


using NServiceBus;

public static class ConfigBuilder
{
    public static EndpointConfiguration BuildDefaultConfig(string endpointName)
    {
        var configuration = new EndpointConfiguration(endpointName);
        configuration.SendFailedMessagesTo("error");
        configuration.UsePersistence<InMemoryPersistence>();
        configuration.UseTransport<LearningTransport>();
        configuration.PurgeOnStartup(true);
        var recoverability = configuration.Recoverability();
        recoverability.Delayed(
            customizations: settings =>
            {
                settings.NumberOfRetries(0);
            });
        recoverability.Immediate(
            customizations: settings =>
            {
                settings.NumberOfRetries(0);
            });
        return configuration;
    }
}

using NServiceBus;

public static class ConfigBuilder
{
    public static EndpointConfiguration BuildDefaultConfig(string endpointName)
    {
        var configuration = new EndpointConfiguration(endpointName);
        configuration.SendFailedMessagesTo("error");
        configuration.UsePersistence<InMemoryPersistence>();
        configuration.UseTransport<LearningTransport>();
        configuration.PurgeOnStartup(true);
        return configuration;
    }
}

Revert "disable retries in tests"

Revert "disable retries in tests"

This reverts commit 4875687e65609b0c13edf8d236a7e88d351d39ca.


using System.Windows;
using System.Windows.Controls;

namespace Certify.UI.Controls.ManagedCertificate
{
    public partial class TestProgress : UserControl
    {
        protected Certify.UI.ViewModel.ManagedCertificateViewModel ItemViewModel => UI.ViewModel.ManagedCertificateViewModel.Current;
        protected Certify.UI.ViewModel.AppViewModel AppViewModel => UI.ViewModel.AppViewModel.Current;

        public TestProgress()
        {
            InitializeComponent();
            DataContext = ItemViewModel;
        }

        private void TextBlock_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // copy text to clipboard
            if (sender != null)
            {
                var text = (sender as TextBlock).Text;
                Clipboard.SetText(text);

                MessageBox.Show("Copied to clipboard");
            }
        }
    }
}

using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Certify.UI.Controls.ManagedCertificate
{
    public partial class TestProgress : UserControl
    {
        protected Certify.UI.ViewModel.ManagedCertificateViewModel ItemViewModel => UI.ViewModel.ManagedCertificateViewModel.Current;
        protected Certify.UI.ViewModel.AppViewModel AppViewModel => UI.ViewModel.AppViewModel.Current;

        public TestProgress()
        {
            InitializeComponent();
            DataContext = ItemViewModel;
        }

        private async Task<bool> WaitForClipboard(string text)
        {
            // if running under terminal services etc the clipboard can take multiple attempts to set
            // https://stackoverflow.com/questions/68666/clipbrd-e-cant-open-error-when-setting-the-clipboard-from-net
            for (var i = 0; i < 10; i++)
            {
                try
                {
                    Clipboard.SetText(text);

                    return true;
                }
                catch { }

                await Task.Delay(50);
            }

            return false;
        }

        private async void TextBlock_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // copy text to clipboard
            if (sender != null)
            {
                var text = (sender as TextBlock).Text;
                var copiedOK = await WaitForClipboard(text);

                if (copiedOK)
                {
                    MessageBox.Show("Copied to clipboard");
                }
                else
                {
                    MessageBox.Show("Another process is preventing access to the clipboard. Please try again.");
                }
            }
        }
    }
}

Fix exception on clipboard access contention


#region License

/*
    Copyright [2011] [Jeffrey Cameron]

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

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

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#endregion

using System;
using System.Globalization;
using gherkin;

namespace PicklesDoc.Pickles
{
    public class LanguageServices
    {
        private readonly CultureInfo currentCulture;

        public LanguageServices(Configuration configuration)
        {
            if (!string.IsNullOrEmpty(configuration.Language))
                this.currentCulture = CultureInfo.GetCultureInfo(configuration.Language);
        }

        private java.util.List GetKeywords(string key)
        {
            return this.GetLanguage().keywords(key);
        }

        public string GetKeyword(string key)
        {
            var keywords = this.GetKeywords("background");

            if (keywords != null && !keywords.isEmpty())
            {
                return keywords.get(0).ToString();
            }

            return null;
        }

        private I18n GetLanguage()
        {
            if (this.currentCulture == null)
                return new I18n("en");

            return new I18n(this.currentCulture.TwoLetterISOLanguageName);
        }
    }
}

#region License

/*
    Copyright [2011] [Jeffrey Cameron]

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

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

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#endregion

using System;
using System.Globalization;
using System.Linq;
using Gherkin3;

namespace PicklesDoc.Pickles
{
    public class LanguageServices
    {
        private readonly CultureInfo currentCulture;
        private readonly GherkinDialectProvider dialectProvider;

        public LanguageServices(Configuration configuration)
        {
            if (!string.IsNullOrEmpty(configuration.Language))
                this.currentCulture = CultureInfo.GetCultureInfo(configuration.Language);

            this.dialectProvider = new GherkinDialectProvider();
        }

        private string[] GetBackgroundKeywords()
        {
            return this.GetLanguage().BackgroundKeywords;
        }

        public string GetKeyword(string key)
        {
            var keywords = this.GetBackgroundKeywords();

            return keywords.FirstOrDefault();
        }

        private GherkinDialect GetLanguage()
        {
            if (this.currentCulture == null)
                return this.dialectProvider.GetDialect("en", null);

            return this.dialectProvider.GetDialect(this.currentCulture.TwoLetterISOLanguageName, null);
        }
    }
}

Use GherkinDialectProvider instead of I18n


namespace BScript.Expressions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using BScript.Language;

    public class NewExpression : IExpression
    {
        private IExpression expression;
        private IList<IExpression> argexprs;

        public NewExpression(IExpression expression, IList<IExpression> argexprs)
        {
            this.expression = expression;
            this.argexprs = argexprs;
        }

        public IExpression Expression { get { return this.expression; } }

        public IList<IExpression> ArgumentExpressions { get { return this.argexprs; } }

        public object Evaluate(Context context)
        {
            var type = (Type)this.expression.Evaluate(context);

            IList<object> args = new List<object>();

            foreach (var argexpr in this.argexprs)
                args.Add(argexpr.Evaluate(context));

            return Activator.CreateInstance(type, args.ToArray());
        }
    }
}

namespace BScript.Expressions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using BScript.Language;
    using BScript.Utilities;

    public class NewExpression : IExpression
    {
        private IExpression expression;
        private IList<IExpression> argexprs;

        public NewExpression(IExpression expression, IList<IExpression> argexprs)
        {
            this.expression = expression;
            this.argexprs = argexprs;
        }

        public IExpression Expression { get { return this.expression; } }

        public IList<IExpression> ArgumentExpressions { get { return this.argexprs; } }

        public object Evaluate(Context context)
        {
            Type type;

            if (this.expression is DotExpression)
                type = TypeUtilities.GetType(((DotExpression)this.expression).FullName);
            else
                type = (Type)this.expression.Evaluate(context);

            IList<object> args = new List<object>();

            foreach (var argexpr in this.argexprs)
                args.Add(argexpr.Evaluate(context));

            return Activator.CreateInstance(type, args.ToArray());
        }
    }
}

Fix new expression with dot name

Fix new expression with dot name


using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core.Etl;
using NBi.Xml.Items;
using System.IO;
using NBi.Core.Batch;
using NBi.Xml.Settings;

namespace NBi.Xml.Decoration.Command
{
    public class SqlRunXml : DecorationCommandXml, IBatchRunCommand
    {
        [XmlAttribute("name")]
        public string Name { get; set; }

        [XmlAttribute("path")]
        public string InternalPath { get; set; }

        [XmlIgnore]
        public string FullPath
        {
            get
            {
                var fullPath = string.Empty;
                if (!Path.IsPathRooted(InternalPath) || string.IsNullOrEmpty(Settings.BasePath))
                    fullPath = InternalPath + Name;
                else
                    fullPath = Settings.BasePath + InternalPath + Name;

                return fullPath;
            }
        }

        [XmlAttribute("connectionString")]
        public string SpecificConnectionString { get; set; }

        [XmlIgnore]
        public string ConnectionString
        {
            get
            {
                if (!String.IsNullOrWhiteSpace(SpecificConnectionString))
                    return SpecificConnectionString;
                if (Settings != null && Settings.GetDefault(SettingsXml.DefaultScope.Decoration) != null)
                    return Settings.GetDefault(SettingsXml.DefaultScope.Decoration).ConnectionString;
                return string.Empty;
            }
        }

        public SqlRunXml()
        {

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core.Etl;
using NBi.Xml.Items;
using System.IO;
using NBi.Core.Batch;
using NBi.Xml.Settings;

namespace NBi.Xml.Decoration.Command
{
    public class SqlRunXml : DecorationCommandXml, IBatchRunCommand
    {
        [XmlAttribute("name")]
        public string Name { get; set; }

        [XmlAttribute("path")]
        public string InternalPath { get; set; }

        [XmlIgnore]
        public string FullPath
        {
            get
            {
                var fullPath = string.Empty;
                if (!Path.IsPathRooted(InternalPath) || string.IsNullOrEmpty(Settings.BasePath))
                    fullPath = InternalPath + Name;
                else
                    fullPath = Settings.BasePath + InternalPath + Name;

                return fullPath;
            }
        }

        [XmlAttribute("connectionString")]
        public string SpecificConnectionString { get; set; }

        [XmlIgnore]
        public string ConnectionString
        {
            get
            {
                if (!string.IsNullOrEmpty(SpecificConnectionString) && SpecificConnectionString.StartsWith("@"))
                    return Settings.GetReference(SpecificConnectionString.Remove(0, 1)).ConnectionString;
                if (!String.IsNullOrWhiteSpace(SpecificConnectionString))
                    return SpecificConnectionString;
                if (Settings != null && Settings.GetDefault(SettingsXml.DefaultScope.Decoration) != null)
                    return Settings.GetDefault(SettingsXml.DefaultScope.Decoration).ConnectionString;
                return string.Empty;
            }
        }

        public SqlRunXml()
        {

        }
    }
}

Fix it also for sql-run

Fix it also for sql-run


@model System.Linq.IQueryable<ForumSystem.Web.ViewModels.Answers.AnswerViewModel>

@using ForumSystem.Web.ViewModels.Answers;

@foreach (var answer in Model)
{

                @answer.Post.Title

@Html.Raw(answer.Content)

                @if (@answer.Author != null)
                {

@answer.Author.Email

                }
                else
                {
                    @Html.Display("Anonymous")
                }

            <button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" title="Tooltip on left">
                @Html.ActionLink("Delete", "Delete", "Answer", new { id = answer.Id }, null)
            </button>

}

@model System.Linq.IQueryable<ForumSystem.Web.ViewModels.Answers.AnswerViewModel>

@using ForumSystem.Web.ViewModels.Answers;

            @Html.ActionLink(Model.FirstOrDefault().Post.Title, "Display", "Questions", new { id = Model.FirstOrDefault().PostId, url = "new" }, null)

            @foreach (var answer in Model)
            {

@Html.Raw(answer.Content)

                    @if (@answer.Author != null)
                    {

@answer.Author.Email

                    }
                    else
                    {
                        @Html.Display("Anonymous")
                    }

            <button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" title="Tooltip on left">
                @Html.ActionLink("Delete", "Delete", "Answer", new { id = answer.Id }, null)
            </button>
            }

Update view of all answers

Update view of all answers


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

using osu.Game.Beatmaps.Formats;

namespace osu.Game.Skinning
{
    public class LegacySkinDecoder : LegacyDecoder<LegacySkinConfiguration>
    {
        public LegacySkinDecoder()
            : base(1)
        {
        }

        protected override void ParseLine(LegacySkinConfiguration skin, Section section, string line)
        {
            if (section != Section.Colours)
            {
                line = StripComments(line);

                var pair = SplitKeyVal(line);

                switch (section)
                {
                    case Section.General:
                        switch (pair.Key)
                        {
                            case @"Name":
                                skin.SkinInfo.Name = pair.Value;
                                return;

                            case @"Author":
                                skin.SkinInfo.Creator = pair.Value;
                                return;

                            case @"Version":
                                if (pair.Value == "latest" || pair.Value == "User")
                                    skin.LegacyVersion = LegacySkinConfiguration.LATEST_VERSION;
                                else if (decimal.TryParse(pair.Value, out var version))
                                    skin.LegacyVersion = version;

                                return;
                        }

                        break;
                }

                if (!string.IsNullOrEmpty(pair.Key))
                    skin.ConfigDictionary[pair.Key] = pair.Value;
            }

            base.ParseLine(skin, section, line);
        }
    }
}

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

using osu.Game.Beatmaps.Formats;

namespace osu.Game.Skinning
{
    public class LegacySkinDecoder : LegacyDecoder<LegacySkinConfiguration>
    {
        public LegacySkinDecoder()
            : base(1)
        {
        }

        protected override void ParseLine(LegacySkinConfiguration skin, Section section, string line)
        {
            if (section != Section.Colours)
            {
                line = StripComments(line);

                var pair = SplitKeyVal(line);

                switch (section)
                {
                    case Section.General:
                        switch (pair.Key)
                        {
                            case @"Name":
                                skin.SkinInfo.Name = pair.Value;
                                return;

                            case @"Author":
                                skin.SkinInfo.Creator = pair.Value;
                                return;

                            case @"Version":
                                if (pair.Value == "latest")
                                    skin.LegacyVersion = LegacySkinConfiguration.LATEST_VERSION;
                                else if (decimal.TryParse(pair.Value, out var version))
                                    skin.LegacyVersion = version;

                                return;
                        }

                        break;
                }

                if (!string.IsNullOrEmpty(pair.Key))
                    skin.ConfigDictionary[pair.Key] = pair.Value;
            }

            base.ParseLine(skin, section, line);
        }
    }
}

Fix incorrect skin version case

Fix incorrect skin version case


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

namespace kafka_tests.Fakes
{
    public class FakeKafkaConnection : IKafkaConnection
    {
        private Uri _address;

        public Func<ProduceResponse> ProduceResponseFunction;
        public Func<MetadataResponse> MetadataResponseFunction;

        public FakeKafkaConnection(Uri address)
        {
            _address = address;
        }

        public int MetadataRequestCallCount { get; set; }
        public int ProduceRequestCallCount { get; set; }

        public Uri KafkaUri
        {
            get { return _address; }
        }

        public bool ReadPolling
        {
            get { return true; }
        }

        public Task SendAsync(byte[] payload)
        {
            throw new NotImplementedException();
        }

        public Task<List<T>> SendAsync<T>(IKafkaRequest<T> request)
        {
            var tcs = new TaskCompletionSource<List<T>>();

            if (typeof(T) == typeof(ProduceResponse))
            {
                ProduceRequestCallCount++;
                tcs.SetResult(new List<T> { (T)(object)ProduceResponseFunction() });
            }
            else if (typeof(T) == typeof(MetadataResponse))
            {
                MetadataRequestCallCount++;
                tcs.SetResult(new List<T> { (T)(object)MetadataResponseFunction() });
            }

            return tcs.Task;
        }

        public void Dispose()
        {

        }
    }
}

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

namespace kafka_tests.Fakes
{
    public class FakeKafkaConnection : IKafkaConnection
    {
        private Uri _address;

        public Func<ProduceResponse> ProduceResponseFunction;
        public Func<MetadataResponse> MetadataResponseFunction;

        public FakeKafkaConnection(Uri address)
        {
            _address = address;
        }

        public int MetadataRequestCallCount { get; set; }
        public int ProduceRequestCallCount { get; set; }

        public Uri KafkaUri
        {
            get { return _address; }
        }

        public bool ReadPolling
        {
            get { return true; }
        }

        public Task SendAsync(byte[] payload)
        {
            throw new NotImplementedException();
        }

        public Task<List<T>> SendAsync<T>(IKafkaRequest<T> request)
        {
            var task = new Task<List<T>>(() =>
            {
                if (typeof(T) == typeof(ProduceResponse))
                {
                    ProduceRequestCallCount++;
                    return new List<T> { (T)(object)ProduceResponseFunction() };
                }
                else if (typeof(T) == typeof(MetadataResponse))
                {
                    MetadataRequestCallCount++;
                    return new List<T> { (T)(object)MetadataResponseFunction() };
                }

                return null;
            });

            task.Start();
            return task;
        }

        public void Dispose()
        {

        }
    }
}

Fix fake not replicating actual behaviour