using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CasualMeter.Common.Helpers;
using Tera.DamageMeter;

namespace CasualMeter.Common.Formatters
{
    public class DamageTrackerFormatter : Formatter
    {
        public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers)
        {
            var placeHolders = new List<KeyValuePair<string, object>>();
            placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name));
            placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration)));

            Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value);
            FormatProvider = formatHelpers.CultureInfo;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CasualMeter.Common.Helpers;
using Tera.DamageMeter;

namespace CasualMeter.Common.Formatters
{
    public class DamageTrackerFormatter : Formatter
    {
        public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers)
        {
            var placeHolders = new List<KeyValuePair<string, object>>();
            placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name??string.Empty));
            placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration)));

            Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value);
            FormatProvider = formatHelpers.CultureInfo;
        }
    }
}

Fix not pasting stats with no boss name available.


using System;
using System.Threading.Tasks;

namespace Kazyx.RemoteApi.System
{
    public class SystemApiClient : ApiClient
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="endpoint">Endpoint URL of system service.</param>
        public SystemApiClient(Uri endpoint)
            : base(endpoint)
        {
        }

        public async Task SetCurrentTimeAsync(DateTimeOffset time)
        {
            var req = new TimeOffset
            {
                DateTime = time.ToString("yyyy-MM-ddThh:mm:ssZ"),
                TimeZoneOffsetMinute = (int)(time.Offset.TotalMinutes),
                DstOffsetMinute = 0
            };
            await NoValue(RequestGenerator.Serialize("setCurrentTime", ApiVersion.V1_0, req));
        }
    }
}

using System;
using System.Threading.Tasks;

namespace Kazyx.RemoteApi.System
{
    public class SystemApiClient : ApiClient
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="endpoint">Endpoint URL of system service.</param>
        public SystemApiClient(Uri endpoint)
            : base(endpoint)
        {
        }

        public async Task SetCurrentTimeAsync(DateTimeOffset UtcTime, int OffsetInMinute)
        {
            var req = new TimeOffset
            {
                DateTime = UtcTime.ToString("yyyy-MM-ddTHH:mm:ssZ"),
                TimeZoneOffsetMinute = OffsetInMinute,
                DstOffsetMinute = 0
            };
            await NoValue(RequestGenerator.Serialize("setCurrentTime", ApiVersion.V1_0, req));
        }
    }
}

Support to specify UTC and offset separately to setCurrentTimeAsync


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using AutoMapper;
using Umbraco.Core.Models;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Models.Mapping;
using Umbraco.Web.Mvc;
using Umbraco.Web.Editors;

namespace Archetype.Umbraco.Api
{
    [PluginController("ArchetypeApi")]
    public class ArchetypeDataTypeController : UmbracoAuthorizedJsonController
    {
        //pulled from the Core
        public DataTypeDisplay GetById(int id)
        {
            var dataType = Services.DataTypeService.GetDataTypeDefinitionById(id);
            if (dataType == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return Mapper.Map<IDataTypeDefinition, DataTypeDisplay>(dataType);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using AutoMapper;
using Umbraco.Core.Models;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Models.Mapping;
using Umbraco.Web.Mvc;
using Umbraco.Web.Editors;

namespace Archetype.Umbraco.Api
{
    [PluginController("ArchetypeApi")]
    public class ArchetypeDataTypeController : UmbracoAuthorizedJsonController
    {
        //pulled from the Core
        public object GetById(int id)
        {
            var dataType = Services.DataTypeService.GetDataTypeDefinitionById(id);
            if (dataType == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            var dataTypeDisplay = Mapper.Map<IDataTypeDefinition, DataTypeDisplay>(dataType);
            return new { selectedEditor = dataTypeDisplay.SelectedEditor, preValues = dataTypeDisplay.PreValues };
        }
    }
}

Trim down data returned from API

Trim down data returned from API


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Foundation;
using UIKit;

using Xunit.Runner;
using Xunit.Runners.UI;
using Xunit.Sdk;

namespace Couchbase.Lite.Tests.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : RunnerAppDelegate
    {

        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            Couchbase.Lite.Support.iOS.Activate();

            // We need this to ensure the execution assembly is part of the app bundle
            AddExecutionAssembly(typeof(ExtensibilityPointFactory).Assembly);

            // tests can be inside the main assembly
            AddTestAssembly(Assembly.GetExecutingAssembly());
            //AutoStart = true;
            //TerminateAfterExecution = true;
            //using (var str = GetType().Assembly.GetManifestResourceStream("result_ip"))
            //using (var sr = new StreamReader(str)) {
            //    Writer = new TcpTextWriter(sr.ReadToEnd().TrimEnd(), 12345);
            //}

            return base.FinishedLaunching(app, options);
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Foundation;
using UIKit;

using Xunit.Runner;
using Xunit.Runners.UI;
using Xunit.Sdk;

namespace Couchbase.Lite.Tests.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : RunnerAppDelegate
    {

        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            Couchbase.Lite.Support.iOS.Activate();

            // We need this to ensure the execution assembly is part of the app bundle
            AddExecutionAssembly(typeof(ExtensibilityPointFactory).Assembly);

            // tests can be inside the main assembly
            AddTestAssembly(Assembly.GetExecutingAssembly());
            AutoStart = true;
            TerminateAfterExecution = true;
            using (var str = GetType().Assembly.GetManifestResourceStream("result_ip"))
            using (var sr = new StreamReader(str))
            {
                Writer = new TcpTextWriter(sr.ReadToEnd().TrimEnd(), 12345);
            }

            return base.FinishedLaunching(app, options);
        }
    }
}

Rollback mistakenly committed commented lines


using FilterLists.Api.DependencyInjection.Extensions;
using FilterLists.Data.DependencyInjection.Extensions;
using FilterLists.Services.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace FilterLists.Api
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", false, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.RegisterFilterListsRepositories(Configuration);
            services.RegisterFilterListsServices();
            services.RegisterFilterListsApi();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseMvc();
            //TODO: maybe move to Startup() per Scott Allen
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
        }
    }
}

using FilterLists.Api.DependencyInjection.Extensions;
using FilterLists.Data.DependencyInjection.Extensions;
using FilterLists.Services.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace FilterLists.Api
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", false, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
        }

        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.RegisterFilterListsRepositories(Configuration);
            services.RegisterFilterListsServices();
            services.RegisterFilterListsApi();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseMvc();
        }
    }
}

Revert "revert logging config causing bug"

This reverts commit 9f927daf453041b8955e372506943a2c80c198d9.


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

using System.Collections.Generic;
using System.Linq;
using osu.Framework.Input;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.Replays;

namespace osu.Game.Rulesets.Mania.Replays
{
    internal class ManiaFramedReplayInputHandler : FramedReplayInputHandler
    {
        private readonly ManiaRulesetContainer container;

        public ManiaFramedReplayInputHandler(Replay replay, ManiaRulesetContainer container)
            : base(replay)
        {
            this.container = container;
        }

        protected override bool AtImportantFrame => CurrentFrame.MouseX != PreviousFrame.MouseX;

        private ManiaPlayfield playfield;
        public override List<InputState> GetPendingStates()
        {
            var actions = new List<ManiaAction>();

            if (playfield == null)
                playfield = (ManiaPlayfield)container.Playfield;

            int activeColumns = (int)(CurrentFrame.MouseX ?? 0);
            int counter = 0;
            while (activeColumns > 0)
            {
                if ((activeColumns & 1) > 0)
                    actions.Add(playfield.Columns.ElementAt(counter).Action);
                counter++;
                activeColumns >>= 1;
            }

            return new List<InputState> { new ReplayState<ManiaAction> { PressedActions = actions } };
        }
    }
}

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

using System.Collections.Generic;
using System.Linq;
using osu.Framework.Input;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.Replays;

namespace osu.Game.Rulesets.Mania.Replays
{
    internal class ManiaFramedReplayInputHandler : FramedReplayInputHandler
    {
        private readonly ManiaRulesetContainer container;

        public ManiaFramedReplayInputHandler(Replay replay, ManiaRulesetContainer container)
            : base(replay)
        {
            this.container = container;
        }

        private ManiaPlayfield playfield;
        public override List<InputState> GetPendingStates()
        {
            var actions = new List<ManiaAction>();

            if (playfield == null)
                playfield = (ManiaPlayfield)container.Playfield;

            int activeColumns = (int)(CurrentFrame.MouseX ?? 0);
            int counter = 0;
            while (activeColumns > 0)
            {
                if ((activeColumns & 1) > 0)
                    actions.Add(playfield.Columns.ElementAt(counter).Action);
                counter++;
                activeColumns >>= 1;
            }

            return new List<InputState> { new ReplayState<ManiaAction> { PressedActions = actions } };
        }
    }
}

Remove line that shouldn't have been added yet


using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Threading.Tasks;

namespace PackageExplorerViewModel
{
    internal abstract class QueryContextBase<T>
    {
        private int? _totalItemCount;

        public int TotalItemCount
        {
            get
            {
                return _totalItemCount ?? 0;
            }
        }

        protected bool TotalItemCountReady
        {
            get
            {
                return _totalItemCount.HasValue;
            }
        }

        public IQueryable<T> Source { get; private set; }

        protected QueryContextBase(IQueryable<T> source)
        {
            Source = source;
        }

        protected async Task<IEnumerable<T>> LoadData(IQueryable<T> query)
        {
            var dataServiceQuery = query as DataServiceQuery<T>;
            if (!TotalItemCountReady && dataServiceQuery != null)
            {
                var queryResponse = (QueryOperationResponse<T>)
                    await Task.Factory.FromAsync<IEnumerable<T>>(dataServiceQuery.BeginExecute(null, null), dataServiceQuery.EndExecute);

                try
                {
                    _totalItemCount = (int)queryResponse.TotalCount;
                }
                catch (InvalidOperationException)
                {
                    // the server doesn't return $inlinecount value,
                    // fall back to using $count query
                    _totalItemCount = Source.Count();
                }

                return queryResponse;
            }
            else
            {
                if (!TotalItemCountReady)
                {
                    _totalItemCount = Source.Count();
                }

                return query;
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Threading.Tasks;

namespace PackageExplorerViewModel
{
    internal abstract class QueryContextBase<T>
    {
        private int? _totalItemCount;

        public int TotalItemCount
        {
            get
            {
                return _totalItemCount ?? 0;
            }
        }

        protected bool TotalItemCountReady
        {
            get
            {
                return _totalItemCount.HasValue;
            }
        }

        public IQueryable<T> Source { get; private set; }

        protected QueryContextBase(IQueryable<T> source)
        {
            Source = source;
        }

        protected async Task<IEnumerable<T>> LoadData(IQueryable<T> query)
        {
            var dataServiceQuery = query as DataServiceQuery<T>;
            if (dataServiceQuery != null)
            {
                var queryResponse = (QueryOperationResponse<T>)
                    await Task.Factory.FromAsync<IEnumerable<T>>(dataServiceQuery.BeginExecute(null, null), dataServiceQuery.EndExecute);

                try
                {
                    _totalItemCount = (int)queryResponse.TotalCount;
                }
                catch (InvalidOperationException)
                {
                    if (!TotalItemCountReady)
                    {
                        // the server doesn't return $inlinecount value,
                        // fall back to using $count query
                        _totalItemCount = Source.Count();
                    }
                }

                return queryResponse;
            }
            else
            {
                if (!TotalItemCountReady)
                {
                    _totalItemCount = Source.Count();
                }

                return query;
            }
        }
    }
}

Fix bug when moving between pages executing on UI thread.


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

using System;
using Datalust.ClefTool.Pipe;

namespace Datalust.ClefTool.Cli.Features
{
    class InvalidDataHandlingFeature : CommandFeature
    {
        public InvalidDataHandling InvalidDataHandling { get; private set; }

        public override void Enable(OptionSet options)
        {
            options.Add("invalid-data",
                "Specify how invalid data is handled: fail (default), ignore, or report",
                v => InvalidDataHandling = (InvalidDataHandling)Enum.Parse(typeof(InvalidDataHandling), v, ignoreCase: true));
        }
    }
}

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

using System;
using Datalust.ClefTool.Pipe;

namespace Datalust.ClefTool.Cli.Features
{
    class InvalidDataHandlingFeature : CommandFeature
    {
        public InvalidDataHandling InvalidDataHandling { get; private set; }

        public override void Enable(OptionSet options)
        {
            options.Add("invalid-data=",
                "Specify how invalid data is handled: fail (default), ignore, or report",
                v => InvalidDataHandling = (InvalidDataHandling)Enum.Parse(typeof(InvalidDataHandling), v, ignoreCase: true));
        }
    }
}

Add the all-important = sign to make arg passing work


using System;

namespace MiniWebDeploy.Deployer.Features.Discovery
{
    public class AssemblyDetails
    {
        public string Path { get; set; }
        public string BinaryPath { get; set; }
        public Type InstallerType { get; set; }

        public AssemblyDetails(string path, string binaryPath, Type installerType)
        {
            Path = path;
            BinaryPath = binaryPath;
            InstallerType = installerType;
        }
    }
}

using System;

namespace MiniWebDeploy.Deployer.Features.Discovery
{
    public class AssemblyDetails
    {
        public string Path { get; private set; }
        public string BinaryPath { get; private set; }
        public Type InstallerType { get; private set; }

        public AssemblyDetails(string path, string binaryPath, Type installerType)
        {
            Path = path;
            BinaryPath = binaryPath;
            InstallerType = installerType;
        }
    }
}

Make proeprty setters private if they are not being used


namespace Stripe
{
    using Newtonsoft.Json;
    using Stripe.Infrastructure;

    public class BankAccountCreateOptions : BaseOptions
    {
        ///
        /// REQUIRED. Either a token, like the ones returned by
        /// Stripe.js, or a
        /// <see cref="SourceBankAccount"/> instance containing a user’s bank account
        /// details.
        ///
        [JsonProperty("source")]
        [JsonConverter(typeof(AnyOfConverter))]
        public AnyOf<string, SourceBankAccount> Source { get; set; }
    }
}

namespace Stripe
{
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Stripe.Infrastructure;

    public class BankAccountCreateOptions : BaseOptions, IHasMetadata
    {
        ///
        /// A set of key/value pairs that you can attach to an object. It can be useful for storing
        /// additional information about the object in a structured format.
        ///
        [JsonProperty("metadata")]
        public Dictionary<string, string> Metadata { get; set; }

        ///
        /// REQUIRED. Either a token, like the ones returned by
        /// Stripe.js, or a
        /// <see cref="SourceBankAccount"/> instance containing a user’s bank account
        /// details.
        ///
        [JsonProperty("source")]
        [JsonConverter(typeof(AnyOfConverter))]
        public AnyOf<string, SourceBankAccount> Source { get; set; }
    }
}

Add support for metadata on BankAccount creation


@model SvNaum.Web.Models.NewsInputModel

@{
    this.ViewBag.Title = "Add news";
}

Create news:

@using(Html.BeginForm("NewsAdd", "Admin", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    @Html.EditorForModel()

    <input type="submit" value="Save" />
    <input type="button" value="Cancel" onclick="window.location = '/Home/Index';" />
}

@section scripts
{
    @Scripts.Render("~/bundles/jqueryval");
}

Add space to commit again.

Add space to commit again.


namespace ApiTemplate
{
    using System.Reflection;

    public record AssemblyInformation(string Product, string Description, string Version)
    {
        public static readonly AssemblyInformation Current = new(typeof(AssemblyInformation).Assembly);

        public AssemblyInformation(Assembly assembly)
            : this(
                assembly.GetCustomAttribute<AssemblyProductAttribute>()!.Product,
                assembly.GetCustomAttribute<AssemblyDescriptionAttribute>()!.Description,
                assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()!.Version)
        {
        }
    }
}

namespace ApiTemplate
{
    using System.Reflection;

    public record class AssemblyInformation(string Product, string Description, string Version)
    {
        public static readonly AssemblyInformation Current = new(typeof(AssemblyInformation).Assembly);

        public AssemblyInformation(Assembly assembly)
            : this(
                assembly.GetCustomAttribute<AssemblyProductAttribute>()!.Product,
                assembly.GetCustomAttribute<AssemblyDescriptionAttribute>()!.Description,
                assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()!.Version)
        {
        }
    }
}

Switch from record to record class

Switch from record to record class


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

using System;
using Microsoft.AspNet.Cors;
using Microsoft.AspNet.Cors.Core;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.Internal;

namespace Microsoft.Framework.DependencyInjection
{
    /// <summary>
    /// The <see cref="IServiceCollection"/> extensions for enabling CORS support.
    /// </summary>
    public static class CorsServiceCollectionExtensions
    {
        /// <summary>
        /// Can be used to configure services in the <paramref name="serviceCollection"/>.
        /// </summary>
        /// <param name="serviceCollection">The service collection which needs to be configured.</param>
        /// <param name="configure">A delegate which is run to configure the services.</param>
        /// <returns></returns>
        public static IServiceCollection ConfigureCors(
            [NotNull] this IServiceCollection serviceCollection,
            [NotNull] Action<CorsOptions> configure)
        {
            return serviceCollection.Configure(configure);
        }

        /// <summary>
        /// Add services needed to support CORS to the given <paramref name="serviceCollection"/>.
        /// </summary>
        /// <param name="serviceCollection">The service collection to which CORS services are added.</param>
        /// <returns>The updated <see cref="IServiceCollection"/>.</returns>
        public static IServiceCollection AddCors(this IServiceCollection serviceCollection)
        {
            serviceCollection.AddOptions();
            serviceCollection.AddTransient<ICorsService, CorsService>();
            serviceCollection.AddTransient<ICorsPolicyProvider, DefaultCorsPolicyProvider>();
            return serviceCollection;
        }
    }
}

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

using System;
using Microsoft.AspNet.Cors;
using Microsoft.AspNet.Cors.Core;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.Internal;

namespace Microsoft.Framework.DependencyInjection
{
    /// <summary>
    /// The <see cref="IServiceCollection"/> extensions for enabling CORS support.
    /// </summary>
    public static class CorsServiceCollectionExtensions
    {
        /// <summary>
        /// Can be used to configure services in the <paramref name="serviceCollection"/>.
        /// </summary>
        /// <param name="serviceCollection">The service collection which needs to be configured.</param>
        /// <param name="configure">A delegate which is run to configure the services.</param>
        /// <returns></returns>
        public static IServiceCollection ConfigureCors(
            [NotNull] this IServiceCollection serviceCollection,
            [NotNull] Action<CorsOptions> configure)
        {
            return serviceCollection.Configure(configure);
        }

        /// <summary>
        /// Add services needed to support CORS to the given <paramref name="serviceCollection"/>.
        /// </summary>
        /// <param name="serviceCollection">The service collection to which CORS services are added.</param>
        /// <returns>The updated <see cref="IServiceCollection"/>.</returns>
        public static IServiceCollection AddCors(this IServiceCollection serviceCollection)
        {
            serviceCollection.AddOptions();
            serviceCollection.TryAdd(ServiceDescriptor.Transient<ICorsService, CorsService>());
            serviceCollection.TryAdd(ServiceDescriptor.Transient<ICorsPolicyProvider, DefaultCorsPolicyProvider>());
            return serviceCollection;
        }
    }
}

Use TryAdd to add services rather than Add


// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using System;

namespace NodaTime.Testing
{
    /// <summary>
    /// Helper static methods for argument/state validation. Copied from NodaTime.Utility,
    /// as we don't want the Testing assembly to have internal access to NodaTime, but we
    /// don't really want to expose Preconditions publically.
    /// </summary>
    internal static class Preconditions
    {
        /// <summary>
        /// Returns the given argument after checking whether it's null. This is useful for putting
        /// nullity checks in parameters which are passed to base class constructors.
        /// </summary>
        internal static T CheckNotNull<T>(T argument, string paramName) where T : class
        {
            if (argument == null)
            {
                throw new ArgumentNullException(paramName);
            }
            return argument;
        }
    }
}

// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using System;

namespace NodaTime.Testing
{
    /// <summary>
    /// Helper static methods for argument/state validation. Copied from NodaTime.Utility,
    /// as we don't want the Testing assembly to have internal access to NodaTime, but we
    /// don't really want to expose Preconditions publically.
    /// </summary>
    internal static class Preconditions
    {
        /// <summary>
        /// Returns the given argument after checking whether it's null. This is useful for putting
        /// nullity checks in parameters which are passed to base class constructors.
        /// </summary>
        internal static T CheckNotNull<T>(T argument, string paramName) where T : class
        {
            if (argument is null)
            {
                throw new ArgumentNullException(paramName);
            }
            return argument;
        }
    }
}

Change from == null to is null in NodaTime.Testing


using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Telegram.Bot.Types.ReplyMarkups;

namespace Telegram.Bot.Types.InlineQueryResults
{
    /// <summary>
    /// Base Class for inline results send in response to an <see cref="InlineQuery"/>
    /// </summary>
    [JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
    public abstract class InlineQueryResult
    {
        ///  <summary>
        ///  </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        protected InlineQueryResult(string id, InlineQueryResultType type)
        {
            Id = id;
            Type = type;
        }

        /// <summary>
        /// Unique identifier of this result
        /// </summary>
        [JsonProperty(Required = Required.Always)]
        public string Id { get; set; }

        /// <summary>
        /// Type of the result
        /// </summary>
        [JsonProperty(Required = Required.Always)]
        public InlineQueryResultType Type { get; protected set; }

        /// <summary>
        /// Inline keyboard attached to the message
        /// </summary>
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
        public InlineKeyboardMarkup ReplyMarkup { get; set; }
    }
}

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Telegram.Bot.Types.ReplyMarkups;

namespace Telegram.Bot.Types.InlineQueryResults
{
    /// <summary>
    /// Base Class for inline results send in response to an <see cref="InlineQuery"/>
    /// </summary>
    [JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
    public abstract class InlineQueryResult
    {
        ///  <summary>
        ///  </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        protected InlineQueryResult(string id, InlineQueryResultType type)
        {
            Id = id;
            Type = type;
        }

        /// <summary>
        /// Unique identifier of this result
        /// </summary>
        [JsonProperty(Required = Required.Always)]
        public string Id { get; }

        /// <summary>
        /// Type of the result
        /// </summary>
        [JsonProperty(Required = Required.Always)]
        public InlineQueryResultType Type { get; }

        /// <summary>
        /// Inline keyboard attached to the message
        /// </summary>
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
        public InlineKeyboardMarkup ReplyMarkup { get; set; }
    }
}

Remove setters from Id and Type

Remove setters from Id and Type


namespace Pigeon
{
    using System.Linq;
    using System.Net.Mail;

    using Pigeon.Adapters;

    public class Mailer
    {
        private readonly IMailService mailService;

        public Mailer(IMailService mailService)
        {
            this.mailService = mailService;
        }

        public void SendZip(ZipResult result, string emailAddress, string emailFrom, string subject, string attachmentName)
        {

            string body;

            if (result != null && result.Entries.Any())
            {
                body = string.Join("\n\r", result.Entries);
            }
            else
            {
                body = "No files found for range specified";
            }

            var mailMessage = new MailMessage()
                                  {
                                      To = { emailAddress },
                                      From = new MailAddress(emailFrom),
                                      Body = body,
                                      Subject = subject
                                  };

            if (result?.ZipStream != null)
            {
                mailMessage.Attachments.Add(new Attachment(result.ZipStream, attachmentName));
            }

            this.mailService.SendMessage(mailMessage);
        }
    }
}

namespace Pigeon
{
    using System.IO;
    using System.Linq;
    using System.Net.Mail;
    using System.Net.Mime;

    using Pigeon.Adapters;

    public class Mailer
    {
        private readonly IMailService mailService;

        public Mailer(IMailService mailService)
        {
            this.mailService = mailService;
        }

        public void SendZip(ZipResult result, string emailAddress, string emailFrom, string subject, string attachmentName)
        {
            string body;
            if (result != null && result.Entries.Any())
            {
                body = string.Join("\n\r", result.Entries);
            }
            else
            {
                body = "No files found for range specified";
            }
            var mailMessage = new MailMessage()
                                  {
                                      To = { emailAddress },
                                      From = new MailAddress(emailFrom),
                                      Body = body,
                                      Subject = subject
                                  };
            using (mailMessage)
            {
                if (result?.ZipStream != null)
                {
                    result.ZipStream.Position = 0;
                    Attachment attachment = new Attachment(result.ZipStream, attachmentName + ".zip", MediaTypeNames.Application.Zip);
                    mailMessage.Attachments.Add(attachment);
                }

                this.mailService.SendMessage(mailMessage);
            }
        }
    }
}

Add a using and set the position of the stream


using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;

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

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

// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]

using System.Reflection;
using System.Runtime.InteropServices;
using Android;
using Android.App;

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

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

[assembly: UsesPermission(Manifest.Permission.AccessFineLocation)]
[assembly: UsesPermission(Manifest.Permission.AccessCoarseLocation)]
[assembly: UsesPermission(Manifest.Permission.AccessWifiState)]
[assembly: UsesPermission(Manifest.Permission.AccessNetworkState)]
[assembly: UsesPermission(Manifest.Permission.Internet)]
[assembly: UsesPermission(Manifest.Permission.WriteExternalStorage)]

Add permissions to sample app

Add permissions to sample app


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

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

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

namespace cah
{
    class Program
    {
        static void Main(string[] args)
        {
            Client client = new Client();
            client.Connect("frogbox.es", 6667, false, new User("cah"));
            client.OnConnect += client_OnConnect;
            client.OnChannelJoin += client_OnChannelJoin;

            Console.ReadLine();
        }

        static void client_OnConnect(Client client)
        {
            client.JoinChannel(Constants.GAME_CHANNELNAME);
        }

        static void client_OnChannelJoin(Client client, Channel channel)
        {
            channel.OnMessage += channel_OnMessage;
            channel.OnLeave += channel_OnLeave;
        }

        static void channel_OnMessage(Channel source, User user, string message)
        {
            throw new NotImplementedException();
        }

        static void channel_OnLeave(Channel source, User user, string reason)
        {
            throw new NotImplementedException();
        }
    }
}

Connect a NetIRC client to the server

Connect a NetIRC client to the server


using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Markdown.Editor.ContentTypes;
using Microsoft.VisualStudio.R.Package.Packages;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace Microsoft.VisualStudio.R.Packages.Markdown {
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [Guid(MdGuidList.MdPackageGuidString)]
    [ProvideEditorExtension(typeof(MdEditorFactory), ".md", 0x32, NameResourceID = 107)]
    [ProvideEditorExtension(typeof(MdEditorFactory), ".rmd", 0x32, NameResourceID = 107)]
    [ProvideEditorExtension(typeof(MdEditorFactory), ".markdown", 0x32, NameResourceID = 107)]
    [ProvideLanguageService(typeof(MdLanguageService), MdContentTypeDefinition.LanguageName, 107, ShowSmartIndent = false)]
    [ProvideEditorFactory(typeof(MdEditorFactory), 107, CommonPhysicalViewAttributes = 0x2, TrustLevel = __VSEDITORTRUSTLEVEL.ETL_AlwaysTrusted)]
    [ProvideEditorLogicalView(typeof(MdEditorFactory), VSConstants.LOGVIEWID.TextView_string)]
    internal sealed class MdPackage : BasePackage<MdLanguageService> {
        protected override IEnumerable<IVsEditorFactory> CreateEditorFactories() {
            yield return new MdEditorFactory(this);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Markdown.Editor.ContentTypes;
using Microsoft.VisualStudio.R.Package.Packages;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace Microsoft.VisualStudio.R.Packages.Markdown {
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [Guid(MdGuidList.MdPackageGuidString)]
    [ProvideLanguageExtension(MdGuidList.MdLanguageServiceGuidString, MdContentTypeDefinition.FileExtension1)]
    [ProvideLanguageExtension(MdGuidList.MdLanguageServiceGuidString, MdContentTypeDefinition.FileExtension2)]
    [ProvideLanguageExtension(MdGuidList.MdLanguageServiceGuidString, MdContentTypeDefinition.FileExtension3)]
    [ProvideEditorExtension(typeof(MdEditorFactory), ".md", 0x32, NameResourceID = 107)]
    [ProvideEditorExtension(typeof(MdEditorFactory), ".rmd", 0x32, NameResourceID = 107)]
    [ProvideEditorExtension(typeof(MdEditorFactory), ".markdown", 0x32, NameResourceID = 107)]
    [ProvideLanguageService(typeof(MdLanguageService), MdContentTypeDefinition.LanguageName, 107, ShowSmartIndent = false)]
    [ProvideEditorFactory(typeof(MdEditorFactory), 107, CommonPhysicalViewAttributes = 0x2, TrustLevel = __VSEDITORTRUSTLEVEL.ETL_AlwaysTrusted)]
    [ProvideEditorLogicalView(typeof(MdEditorFactory), VSConstants.LOGVIEWID.TextView_string)]
    internal sealed class MdPackage : BasePackage<MdLanguageService> {
        protected override IEnumerable<IVsEditorFactory> CreateEditorFactories() {
            yield return new MdEditorFactory(this);
        }
    }
}

Add ProvideLanguageExtension to markdown formats


// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System.Globalization;

#pragma warning disable SA1313 // Parameter names should begin with lower-case letter

namespace Squidex.Infrastructure.Commands
{
    public sealed record CommandRequest(IAggregateCommand Command, string Culture, string CultureUI)
    {
        public static CommandRequest Create(IAggregateCommand command)
        {
            return new CommandRequest(command,
                CultureInfo.CurrentCulture.Name,
                CultureInfo.CurrentUICulture.Name);
        }

        public void ApplyContext()
        {
            var culture = GetCulture(Culture);

            if (culture != null)
            {
                CultureInfo.CurrentCulture = culture;
            }

            var uiCulture = GetCulture(CultureUI);

            if (uiCulture != null)
            {
                CultureInfo.CurrentUICulture = uiCulture;
            }
        }

        private static CultureInfo? GetCulture(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return null;
            }

            try
            {
                return CultureInfo.GetCultureInfo(name);
            }
            catch (CultureNotFoundException)
            {
                return null;
            }
        }
    }
}

// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System.Globalization;

namespace Squidex.Infrastructure.Commands
{
    public sealed class CommandRequest
    {
        public IAggregateCommand Command { get; }

        public string Culture { get; }

        public string CultureUI { get; }

        public CommandRequest(IAggregateCommand command, string culture, string cultureUI)
        {
            Command = command;

            Culture = culture;
            CultureUI = cultureUI;
        }

        public static CommandRequest Create(IAggregateCommand command)
        {
            return new CommandRequest(command,
                CultureInfo.CurrentCulture.Name,
                CultureInfo.CurrentUICulture.Name);
        }

        public void ApplyContext()
        {
            var culture = GetCulture(Culture);

            if (culture != null)
            {
                CultureInfo.CurrentCulture = culture;
            }

            var uiCulture = GetCulture(CultureUI);

            if (uiCulture != null)
            {
                CultureInfo.CurrentUICulture = uiCulture;
            }
        }

        private static CultureInfo? GetCulture(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return null;
            }

            try
            {
                return CultureInfo.GetCultureInfo(name);
            }
            catch (CultureNotFoundException)
            {
                return null;
            }
        }
    }
}

Revert orleans for backwards compatibility.


using System;
using System.Windows.Forms;

namespace COIME.Common.Control
{
    public class NotifyIconUtil
    {
        /// <summary>
        /// Setup NotifyIcon.
        /// The icon added to the notification area, and then retry until it succeeds.
        /// </summary>
        /// <param name="notifyIcon"></param>
        public static void Setup(NotifyIcon notifyIcon)
        {
            // setup notify icon
            while (true)
            {
                int tickCount = Environment.TickCount;
                notifyIcon.Visible = true;
                tickCount = Environment.TickCount - tickCount;
                if (tickCount < 4000)
                {
                    // Success if less than 4 seconds
                    break;
                }
                // retry
                notifyIcon.Visible = false;
            }
        }
    }
}

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace COIME.Common.Control
{
    public class NotifyIconUtil
    {
        /*
         * for ALT + F4 problem
         * see http://d.hatena.ne.jp/hnx8/20131208/1386486457
         */
        [DllImport("user32")]
        static extern IntPtr GetForegroundWindow();
        [System.Runtime.InteropServices.DllImport("user32")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);
        [System.Runtime.InteropServices.DllImport("user32")]
        static extern IntPtr GetDesktopWindow();

        /// <summary>
        /// Setup NotifyIcon.
        /// The icon added to the notification area, and then retry until it succeeds.
        /// </summary>
        /// <param name="notifyIcon"></param>
        public static void Setup(NotifyIcon notifyIcon)
        {
            AntiAltF4(notifyIcon);
            // setup notify icon
            while (true)
            {
                int tickCount = Environment.TickCount;
                notifyIcon.Visible = true;
                tickCount = Environment.TickCount - tickCount;
                if (tickCount < 4000)
                {
                    // Success if less than 4 seconds
                    break;
                }
                // retry
                notifyIcon.Visible = false;
            }
        }

        private static void AntiAltF4(NotifyIcon notifyIcon)
        {
            var cms = notifyIcon.ContextMenuStrip;
            if (cms != null)
            {
                cms.PreviewKeyDown += (sender, e) =>
                {
                    if (e.Alt)
                    {
                        SetForegroundWindow(GetDesktopWindow());
                    }
                };
                cms.Closing += (sender, e) =>
                {
                    FieldInfo fi = typeof(NotifyIcon).GetField("window", BindingFlags.NonPublic | BindingFlags.Instance);
                    NativeWindow window = fi.GetValue(notifyIcon) as NativeWindow;
                    IntPtr handle = GetForegroundWindow();
                    if (handle == window.Handle)
                    {
                        SetForegroundWindow(GetDesktopWindow());
                    }
                };
            }
        }
    }
}

Add bad know-how for NotifyIcon

Add bad know-how for NotifyIcon


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

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
    internal static class LocationExtensions
    {
        public static SyntaxToken FindToken(this Location location, CancellationToken cancellationToken)
            => location.SourceTree.GetRoot(cancellationToken).FindToken(location.SourceSpan.Start);

        public static SyntaxNode FindNode(this Location location, CancellationToken cancellationToken)
            => location.SourceTree.GetRoot(cancellationToken).FindNode(location.SourceSpan);

        public static SyntaxNode FindNode(this Location location, bool getInnermostNodeForTie, CancellationToken cancellationToken)
            => location.SourceTree.GetRoot(cancellationToken).FindNode(location.SourceSpan, getInnermostNodeForTie: getInnermostNodeForTie);

        public static bool IsVisibleSourceLocation(this Location loc)
        {
            if (!loc.IsInSource)
            {
                return false;
            }

            var tree = loc.SourceTree;
            return !(tree == null || tree.IsHiddenPosition(loc.SourceSpan.Start));
        }
    }
}

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

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
    internal static class LocationExtensions
    {
        public static SyntaxToken FindToken(this Location location, CancellationToken cancellationToken)
            => location.SourceTree.GetRoot(cancellationToken).FindToken(location.SourceSpan.Start);

        public static SyntaxNode FindNode(this Location location, CancellationToken cancellationToken)
            => location.SourceTree.GetRoot(cancellationToken).FindNode(location.SourceSpan);

        public static SyntaxNode FindNode(this Location location, bool getInnermostNodeForTie, CancellationToken cancellationToken)
            => location.SourceTree.GetRoot(cancellationToken).FindNode(location.SourceSpan, getInnermostNodeForTie: getInnermostNodeForTie);

        public static SyntaxNode FindNode(this Location location, bool findInsideTrivia, bool getInnermostNodeForTie, CancellationToken cancellationToken)
            => location.SourceTree.GetRoot(cancellationToken).FindNode(location.SourceSpan, findInsideTrivia, getInnermostNodeForTie);

        public static bool IsVisibleSourceLocation(this Location loc)
        {
            if (!loc.IsInSource)
            {
                return false;
            }

            var tree = loc.SourceTree;
            return !(tree == null || tree.IsHiddenPosition(loc.SourceSpan.Start));
        }
    }
}

Update helper for the case when you want to find a node in structured trivia.


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

using UnityEngine;
using System.Collections.Generic;

namespace Hamster.InputControllers {

  // Class for compositing multile input sources.
  // Useful for normalizing and combining different input sources.
  public class MultiInputController : BasePlayerController {

    List<BasePlayerController> controllerList;

    public MultiInputController() {

      controllerList = new List<BasePlayerController>() {
        new KeyboardController(),
      };
      if (CommonData.inVrMode) {
        controllerList.Add(new DaydreamTiltController());
      } else {
        new TiltController();
      }
    }

    public override Vector2 GetInputVector() {
      Vector2 result = Vector2.zero;
      foreach (BasePlayerController controller in controllerList) {
        result += controller.GetInputVector();
      }
      return result;
    }
  }
}

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

using UnityEngine;
using System.Collections.Generic;

namespace Hamster.InputControllers {

  // Class for compositing multile input sources.
  // Useful for normalizing and combining different input sources.
  public class MultiInputController : BasePlayerController {

    List<BasePlayerController> controllerList;

    public MultiInputController() {

      controllerList = new List<BasePlayerController>() {
        new KeyboardController(),
      };
      if (CommonData.inVrMode) {
        controllerList.Add(new DaydreamTiltController());
      } else {
        controllerList.Add(new TiltController());
      }
    }

    public override Vector2 GetInputVector() {
      Vector2 result = Vector2.zero;
      foreach (BasePlayerController controller in controllerList) {
        result += controller.GetInputVector();
      }
      return result;
    }
  }
}

Fix multi-input controller not adding tilt.

Tested on Android.

Change-Id: I2aad833effbe743a9915ae7dc899feed677a60ec


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Foundatio.Parsers.LuceneQueries.Extensions;
using Foundatio.Parsers.LuceneQueries.Nodes;
using Foundatio.Parsers.LuceneQueries.Visitors;
using Nest;

namespace Foundatio.Parsers.ElasticQueries.Visitors {
    public class GetSortFieldsVisitor : QueryNodeVisitorWithResultBase<IEnumerable<IFieldSort>> {
        private readonly List<IFieldSort> _fields = new List<IFieldSort>();

        public override void Visit(TermNode node, IQueryVisitorContext context) {
            if (String.IsNullOrEmpty(node.Field))
                return;

            var elasticContext = context as IElasticQueryVisitorContext;
            if (elasticContext == null)
                throw new ArgumentException("Context must be of type IElasticQueryVisitorContext", nameof(context));

            string field = elasticContext.GetNonAnalyzedFieldName(node.Field);

            var sort = new SortField { Field = field };
            if (node.IsNodeNegated())
                sort.Order = SortOrder.Descending;

            _fields.Add(sort);
        }

        public override async Task<IEnumerable<IFieldSort>> AcceptAsync(IQueryNode node, IQueryVisitorContext context) {
            await node.AcceptAsync(this, context).ConfigureAwait(false);
            return _fields;
        }

        public static Task<IEnumerable<IFieldSort>> RunAsync(IQueryNode node, IQueryVisitorContext context = null) {
            return new GetSortFieldsVisitor().AcceptAsync(node, context);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Foundatio.Parsers.LuceneQueries.Extensions;
using Foundatio.Parsers.LuceneQueries.Nodes;
using Foundatio.Parsers.LuceneQueries.Visitors;
using Nest;

namespace Foundatio.Parsers.ElasticQueries.Visitors {
    public class GetSortFieldsVisitor : QueryNodeVisitorWithResultBase<IEnumerable<IFieldSort>> {
        private readonly List<IFieldSort> _fields = new List<IFieldSort>();

        public override void Visit(TermNode node, IQueryVisitorContext context) {
            if (String.IsNullOrEmpty(node.Field))
                return;

            var elasticContext = context as IElasticQueryVisitorContext;
            if (elasticContext == null)
                throw new ArgumentException("Context must be of type IElasticQueryVisitorContext", nameof(context));

            string field = elasticContext.GetNonAnalyzedFieldName(node.Field);

            var sort = new SortField { Field = field };
            if (node.IsNodeNegated())
                sort.Order = SortOrder.Descending;

            _fields.Add(sort);
        }

        public override async Task<IEnumerable<IFieldSort>> AcceptAsync(IQueryNode node, IQueryVisitorContext context) {
            await node.AcceptAsync(this, context).ConfigureAwait(false);
            return _fields;
        }

        public static Task<IEnumerable<IFieldSort>> RunAsync(IQueryNode node, IQueryVisitorContext context = null) {
            return new GetSortFieldsVisitor().AcceptAsync(node, context);
        }

        public static IEnumerable<IFieldSort> Run(IQueryNode node, IQueryVisitorContext context = null) {
            return RunAsync(node, context).GetAwaiter().GetResult();
        }
    }
}

Add sync Run helper to sort fields visitor


using Orchard.ContentManagement.Handlers;
using Orchard.PublishLater.Models;
using Orchard.PublishLater.Services;
using Orchard.Tasks.Scheduling;

namespace Orchard.PublishLater.Handlers {
    public class PublishLaterPartHandler : ContentHandler {
        private readonly IPublishLaterService _publishLaterService;

        public PublishLaterPartHandler(
            IPublishLaterService publishLaterService,
            IPublishingTaskManager publishingTaskManager) {
            _publishLaterService = publishLaterService;

            OnLoading<PublishLaterPart>((context, part) => LazyLoadHandlers(part));
            OnVersioning<PublishLaterPart>((context, part, newVersionPart) => LazyLoadHandlers(newVersionPart));
            OnRemoved<PublishLaterPart>((context, part) => publishingTaskManager.DeleteTasks(part.ContentItem));
        }

        protected void LazyLoadHandlers(PublishLaterPart part) {
            part.ScheduledPublishUtc.Loader(() => _publishLaterService.GetScheduledPublishUtc(part));
        }
    }
}

using Orchard.ContentManagement.Handlers;
using Orchard.PublishLater.Models;
using Orchard.PublishLater.Services;
using Orchard.Tasks.Scheduling;

namespace Orchard.PublishLater.Handlers {
    public class PublishLaterPartHandler : ContentHandler {
        private readonly IPublishLaterService _publishLaterService;

        public PublishLaterPartHandler(
            IPublishLaterService publishLaterService,
            IPublishingTaskManager publishingTaskManager) {
            _publishLaterService = publishLaterService;

            OnLoading<PublishLaterPart>((context, part) => LazyLoadHandlers(part));
            OnVersioning<PublishLaterPart>((context, part, newVersionPart) => LazyLoadHandlers(newVersionPart));
            OnRemoved<PublishLaterPart>((context, part) => publishingTaskManager.DeleteTasks(part.ContentItem));
            OnPublishing<PublishLaterPart>((context, part) =>
            {
                var existingPublishTask = publishingTaskManager.GetPublishTask(context.ContentItem);

                //Check if there is already and existing publish task for old version.
                if (existingPublishTask != null)
                {
                    //If exists remove it in order no to override the latest published version.
                    publishingTaskManager.DeleteTasks(context.ContentItem);
                }
            });
        }

        protected void LazyLoadHandlers(PublishLaterPart part) {
            part.ScheduledPublishUtc.Loader(() => _publishLaterService.GetScheduledPublishUtc(part));
        }
    }
}

Delete scheduled task when content is published

Fixes #6840


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

using System;
using System.Linq;
using EOLib.Domain.Character;

namespace EOLib.Domain.Extensions
{
    public static class CharacterRenderPropertiesExtensions
    {
        public static bool IsFacing(this ICharacterRenderProperties renderProperties, params EODirection[] directions)
        {
            return directions.Contains(renderProperties.Direction);
        }

        public static bool IsActing(this ICharacterRenderProperties renderProperties, CharacterActionState action)
        {
            return renderProperties.CurrentAction == action;
        }

        public static int GetDestinationX(this ICharacterRenderProperties renderProperties)
        {
            if (renderProperties.CurrentAction != CharacterActionState.Walking)
                throw new ArgumentException("The character is not currently in the walking state.", "renderProperties");

            var offset = GetXOffset(renderProperties.Direction);
            return renderProperties.MapX + offset;
        }

        public static int GetDestinationY(this ICharacterRenderProperties renderProperties)
        {
            if (renderProperties.CurrentAction != CharacterActionState.Walking)
                throw new ArgumentException("The character is not currently in the walking state.", "renderProperties");

            var offset = GetYOffset(renderProperties.Direction);
            return renderProperties.MapY + offset;
        }

        private static int GetXOffset(EODirection direction)
        {
            return direction == EODirection.Right ? 1 :
                   direction == EODirection.Left ? -1 : 0;
        }

        private static int GetYOffset(EODirection direction)
        {
            return direction == EODirection.Down ? 1 :
                   direction == EODirection.Up ? -1 : 0;
        }
    }
}

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

using System;
using System.Linq;
using EOLib.Domain.Character;

namespace EOLib.Domain.Extensions
{
    public static class CharacterRenderPropertiesExtensions
    {
        public static bool IsFacing(this ICharacterRenderProperties renderProperties, params EODirection[] directions)
        {
            return directions.Contains(renderProperties.Direction);
        }

        public static bool IsActing(this ICharacterRenderProperties renderProperties, CharacterActionState action)
        {
            return renderProperties.CurrentAction == action;
        }

        public static int GetDestinationX(this ICharacterRenderProperties renderProperties)
        {
            var offset = GetXOffset(renderProperties.Direction);
            return renderProperties.MapX + offset;
        }

        public static int GetDestinationY(this ICharacterRenderProperties renderProperties)
        {
            var offset = GetYOffset(renderProperties.Direction);
            return renderProperties.MapY + offset;
        }

        private static int GetXOffset(EODirection direction)
        {
            return direction == EODirection.Right ? 1 :
                   direction == EODirection.Left ? -1 : 0;
        }

        private static int GetYOffset(EODirection direction)
        {
            return direction == EODirection.Down ? 1 :
                   direction == EODirection.Up ? -1 : 0;
        }
    }
}

Remove exceptions from character extensions


using System;
using System.Web.Mvc;

using TeacherPouch.Models;
using TeacherPouch.Providers;
using TeacherPouch.Repositories;

namespace TeacherPouch.Web.Controllers
{
    public partial class SearchController : RepositoryControllerBase
    {
        public SearchController(IRepository repository)
        {
            base.Repository = repository;
        }

        // GET: /Search?q=spring&op=and
        public virtual ViewResult Search(string q, string op)
        {
            if (String.IsNullOrWhiteSpace(q) || q.Length < 2)
                return base.View(Views.NoneFound);

            ViewBag.SearchTerm = q;

            bool allowPrivate = SecurityHelper.UserCanSeePrivateRecords(base.User);

            SearchOperator searchOperator = SearchOperator.Or;
            if (!String.IsNullOrWhiteSpace(op))
            {
                SearchOperator parsed;
                if (Enum.TryParse(op, true, out parsed))
                    searchOperator = parsed;
            }

            if (searchOperator == SearchOperator.Or)
            {
                var results = base.Repository.SearchOr(q, allowPrivate);

                if (results.HasAnyResults)
                    return base.View(Views.SearchResultsOr, results);
                else
                    return base.View(Views.NoneFound);
            }
            else if (searchOperator == SearchOperator.And)
            {
                ViewBag.AndChecked = true;

                var results = base.Repository.SearchAnd(q, allowPrivate);

                if (results.HasAnyResults)
                    return base.View(Views.SearchResultsAnd, results);
                else
                    return base.View(Views.NoneFound);
            }
            else
            {
                throw new ApplicationException("Search operator not found.");
            }
        }
    }
}

using System;
using System.ComponentModel;
using System.Web.Mvc;
using TeacherPouch.Models;
using TeacherPouch.Providers;
using TeacherPouch.Repositories;

namespace TeacherPouch.Web.Controllers
{
    public partial class SearchController : RepositoryControllerBase
    {
        public SearchController(IRepository repository)
        {
            base.Repository = repository;
        }

        // GET: /Search?q=spring&op=and
        public virtual ViewResult Search(string q, SearchOperator op = SearchOperator.Or)
        {
            if (String.IsNullOrWhiteSpace(q) || q.Length < 2)
                return base.View(Views.NoneFound);

            ViewBag.SearchTerm = q;

            bool allowPrivate = SecurityHelper.UserCanSeePrivateRecords(base.User);

            if (op == SearchOperator.Or)
            {
                var results = base.Repository.SearchOr(q, allowPrivate);

                if (results.HasAnyResults)
                    return base.View(Views.SearchResultsOr, results);
                else
                    return base.View(Views.NoneFound);
            }
            else if (op == SearchOperator.And)
            {
                ViewBag.AndChecked = true;

                var results = base.Repository.SearchAnd(q, allowPrivate);

                if (results.HasAnyResults)
                    return base.View(Views.SearchResultsAnd, results);
                else
                    return base.View(Views.NoneFound);
            }
            else
            {
                throw new InvalidEnumArgumentException("Unknown search operator.");
            }
        }
    }
}

Make Search Operator automatically parsed by MVC.


using System.Linq;
using Glimpse.Web;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

namespace Glimpse.Agent.Web
{
    public static class GlimpseAgentWebExtension
    {
        public static IApplicationBuilder UseGlimpseAgent(this IApplicationBuilder app)
        {
            var startups = app.ApplicationServices.GetRequiredService<IExtensionProvider<IAgentStartup>>();
            if (startups.Instances.Any())
            {
                var options = new StartupOptions(app);
                foreach (var startup in startups.Instances)
                {
                    startup.Run(options);
                }
            }

            return app.UseMiddleware<GlimpseAgentWebMiddleware>(app);
        }
    }
}

using System.Linq;
using Glimpse.Web;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

namespace Glimpse.Agent.Web
{
    public static class GlimpseAgentWebExtension
    {
        public static IApplicationBuilder UseGlimpseAgent(this IApplicationBuilder app)
        {
            var manager = app.ApplicationServices.GetRequiredService<IAgentStartupManager>();
            manager.Run(new StartupOptions(app));

            return app.UseMiddleware<GlimpseAgentWebMiddleware>(app);
        }
    }
}

Change over usage of IAgentStartup to use IAgentStartupManager instead


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

using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Game.Configuration;

namespace osu.Game.Graphics.UserInterface
{
    /// <summary>
    /// Handles debouncing hover sounds at a global level to ensure the effects are not overwhelming.
    /// </summary>
    public abstract class HoverSampleDebounceComponent : CompositeDrawable
    {
        /// <summary>
        /// Length of debounce for hover sound playback, in milliseconds.
        /// </summary>
        public double HoverDebounceTime { get; } = 20;

        private Bindable<double?> lastPlaybackTime;

        [BackgroundDependencyLoader]
        private void load(AudioManager audio, SessionStatics statics)
        {
            lastPlaybackTime = statics.GetBindable<double?>(Static.LastHoverSoundPlaybackTime);
        }

        protected override bool OnHover(HoverEvent e)
        {
            bool enoughTimePassedSinceLastPlayback = !lastPlaybackTime.Value.HasValue || Time.Current - lastPlaybackTime.Value >= HoverDebounceTime;

            if (enoughTimePassedSinceLastPlayback)
            {
                PlayHoverSample();
                lastPlaybackTime.Value = Time.Current;
            }

            return false;
        }

        public abstract void PlayHoverSample();
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Game.Configuration;

namespace osu.Game.Graphics.UserInterface
{
    /// <summary>
    /// Handles debouncing hover sounds at a global level to ensure the effects are not overwhelming.
    /// </summary>
    public abstract class HoverSampleDebounceComponent : CompositeDrawable
    {
        /// <summary>
        /// Length of debounce for hover sound playback, in milliseconds.
        /// </summary>
        public double HoverDebounceTime { get; } = 20;

        private Bindable<double?> lastPlaybackTime;

        [BackgroundDependencyLoader]
        private void load(AudioManager audio, SessionStatics statics)
        {
            lastPlaybackTime = statics.GetBindable<double?>(Static.LastHoverSoundPlaybackTime);
        }

        protected override bool OnHover(HoverEvent e)
        {
            // hover sounds shouldn't be played during scroll operations.
            if (e.HasAnyButtonPressed)
                return false;

            bool enoughTimePassedSinceLastPlayback = !lastPlaybackTime.Value.HasValue || Time.Current - lastPlaybackTime.Value >= HoverDebounceTime;

            if (enoughTimePassedSinceLastPlayback)
            {
                PlayHoverSample();
                lastPlaybackTime.Value = Time.Current;
            }

            return false;
        }

        public abstract void PlayHoverSample();
    }
}

Stop hover sounds from playing when dragging (scrolling)


using System;
using FSWActions.Core;
using FSWActions.Core.Config;

namespace FSWActions.ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            WatchersConfiguration configuration = WatchersConfiguration.LoadConfigFromPath("watchers.xml");

            foreach (WatcherConfig watcherConfig in configuration.Watchers)
            {
                foreach (ActionConfig action in watcherConfig.ActionsConfig)
                {
                    Console.WriteLine("{0} [{1}]\t{2}: {3}", watcherConfig.Path, watcherConfig.Filter, action.Event, action.Command);
                }
                Watcher watcher = new Watcher(watcherConfig);
                watcher.StartWatching();
            }

            // Wait for the user to quit the program.
            Console.WriteLine("\n\nPress \'q\' to quit\n");
            while (Console.Read() != 'q') ;
        }
    }
}

using System;
using System.Collections.Generic;
using FSWActions.Core;
using FSWActions.Core.Config;

namespace FSWActions.ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            WatchersConfiguration configuration = WatchersConfiguration.LoadConfigFromPath("watchers.xml");
            List<Watcher> watchers = new List<Watcher>(configuration.Watchers.Count);

            foreach (WatcherConfig watcherConfig in configuration.Watchers)
            {
                foreach (ActionConfig action in watcherConfig.ActionsConfig)
                {
                    Console.WriteLine("{0} [{1}]\t{2}: {3}", watcherConfig.Path, watcherConfig.Filter, action.Event, action.Command);
                }
                Watcher watcher = new Watcher(watcherConfig);
                watchers.Add(watcher);
                watcher.StartWatching();
            }

            // Wait for the user to quit the program.
            Console.WriteLine("\n\nPress \'q\' to quit\n");
            while (Console.Read() != 'q') ;

            // Stop all watchers, not really necessary though...
            foreach (Watcher watcher in watchers)
            {
                watcher.StopWatching();
            }
        }
    }
}

Stop all watchers when exiting

Stop all watchers when exiting


using Newtonsoft.Json;
using System;
using System.Globalization;

namespace Discord.Net.Converters
{
    internal class NullableUInt64Converter : JsonConverter
    {
        public static readonly NullableUInt64Converter Instance = new NullableUInt64Converter();

        public override bool CanConvert(Type objectType) => true;
        public override bool CanRead => true;
        public override bool CanWrite => true;

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            object value = reader.Value;
            if (value != null)
                return ulong.Parse((string)value, NumberStyles.None, CultureInfo.InvariantCulture);
            else
                return null;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value != null)
                writer.WriteValue(((ulong?)value).Value.ToString(CultureInfo.InvariantCulture));
            else
                writer.WriteNull();
        }
    }
}

using Newtonsoft.Json;
using System;
using System.Globalization;

namespace Discord.Net.Converters
{
    internal class NullableUInt64Converter : JsonConverter
    {
        public static readonly NullableUInt64Converter Instance = new NullableUInt64Converter();

        public override bool CanConvert(Type objectType) => true;
        public override bool CanRead => true;
        public override bool CanWrite => true;

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            object value = reader.Value;
            if (value != null)
                return ulong.Parse(value.ToString(), NumberStyles.None, CultureInfo.InvariantCulture);
            else
                return null;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value != null)
                writer.WriteValue(((ulong?)value).Value.ToString(CultureInfo.InvariantCulture));
            else
                writer.WriteNull();
        }
    }
}

Use ToString in converter instead of boxing-cast

In cases where Discord sent a value of `id=0`, this would throw an invalid-cast, where 0u64 cannot be cast to string.


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

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

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

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

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

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

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

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

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

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

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
    // Note - these methods are called in fairly hot paths in the IDE, so we try to be responsible about allocations.
    internal static class SymbolInfoExtensions
    {
        public static ImmutableArray<ISymbol> GetAllSymbols(this SymbolInfo info)
        {
            return GetAllSymbolsWorker(info).Distinct();
        }

        private static ImmutableArray<ISymbol> GetAllSymbolsWorker(this SymbolInfo info)
        {
            if (info.Symbol == null)
            {
                return info.CandidateSymbols;
            }
            else
            {
                var builder = ImmutableArray.CreateBuilder<ISymbol>(info.CandidateSymbols.Length + 1);
                builder.Add(info.Symbol);
                builder.AddRange(info.CandidateSymbols);
                return builder.ToImmutable();
            }
        }

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

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

            return ImmutableArray<ISymbol>.Empty;
        }
    }
}

Convert all of these SymbolInfo extensions to ImmutableArray and reduce allocations.


using System;
using Nancy.ErrorHandling;

namespace Nancy.Testing
{
    public class PassThroughErrorHandler : IErrorHandler
    {
        public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
        {
            var exception = context.Items[NancyEngine.ERROR_EXCEPTION] as Exception;

            return statusCode == HttpStatusCode.InternalServerError && exception != null;
        }

        public void Handle(HttpStatusCode statusCode, NancyContext context)
        {
            throw new Exception("ConfigurableBootstrapper Exception", context.Items[NancyEngine.ERROR_EXCEPTION] as Exception);
        }
    }
}

using System;
using Nancy.ErrorHandling;

namespace Nancy.Testing
{
    public class PassThroughErrorHandler : IErrorHandler
    {
        public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
        {
            if (!context.Items.ContainsKey(NancyEngine.ERROR_EXCEPTION))
            {
                return false;
            }

            var exception = context.Items[NancyEngine.ERROR_EXCEPTION] as Exception;

            return statusCode == HttpStatusCode.InternalServerError && exception != null;
        }

        public void Handle(HttpStatusCode statusCode, NancyContext context)
        {
            throw new Exception("ConfigurableBootstrapper Exception", context.Items[NancyEngine.ERROR_EXCEPTION] as Exception);
        }
    }
}

Fix for failing mspec test

Fix for failing mspec test


using FinancesSharp.Models;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace FinancesSharp.ViewModels
{
    public class RulesViewModel
    {
        public IEnumerable<CategorisationRule> Rules { get; private set; }

        public RulesViewModel(FinanceDb db)
        {
            Rules = db.ActiveRules
                .OrderBy(x => x.Category.Id)
                .AsEnumerable();
        }
    }
}

using FinancesSharp.Models;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace FinancesSharp.ViewModels
{
    public class RulesViewModel
    {
        public IEnumerable<CategorisationRule> Rules { get; private set; }

        public RulesViewModel(FinanceDb db)
        {
            Rules = db.ActiveRules
                .OrderBy(x => x.Category.Id)
                .ToList();
        }
    }
}

Fix multiple open data readers problem.

Fix multiple open data readers problem.


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Logic.Engine;
using Logic.GameObjects;

namespace FeelTheField
{
    class ConsoleAplication
    {
        static void Main()
        {
            char ch1 = 'X';
            char ch2 = '$';

            int row = int.Parse(Console.ReadLine());
            int col = int.Parse(Console.ReadLine());

            char[,] matrix = new char[row, col];

            DrawConsole.FillWithChar(matrix, ch1);
            DrawConsole.PrintField(matrix);

            var engine = Engine.Instance;
            engine.ConfigureGameFieldSize(row, col);

            var gameField = engine.Field; // The Matrix

            DrawConsole.FillWithChar(matrix,'X');

            DrawConsole.PrintField(matrix);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Logic.Engine;
using Logic.Enumerations;
using Logic.GameObjects;

namespace FeelTheField
{
    class ConsoleAplication
    {
        static void Main()
        {
            char closed = 'X';
            char open = '$';

            int row = int.Parse(Console.ReadLine());
            int col = int.Parse(Console.ReadLine());
            Console.Clear();

            char[,] matrix = new char[row, col];

            var engine = Engine.Instance;
            engine.ConfigureGameFieldSize(row, col);

            var gameField = engine.Field; // The Matrix

            DrawConsole.FillWithChar(matrix,'X');

            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    if (gameField.Matrix[i, j].ObjeState == State.Open)
                    {
                        matrix[i, j] = open;
                        //matrix[i, j] = gameField.Matrix[i, j].Body;
                    }
                    else
                    {
                        matrix[i, j] = closed;
                        //matrix[i, j] = gameField.Matrix[i, j].Body;
                    }
                }
            }

            DrawConsole.PrintField(matrix);

        }
    }
}

Change logic in console application to draw game field on console.!


using Kata.GildedRose.CSharp.Console;
using NUnit.Framework;
using System.Collections.Generic;

namespace Kata.GildedRose.CSharp.Unit.Tests
{
    [TestFixture]
    public class WhenTestTheGildedRoseProgram
    {
        string _actualName = "+5 Dexterity Vest";
        int _actualSellin = 10;
        int _actualQuality = 10;
        Item _actualStockItem;

        IList<Item> _stockItems;
        Program GildedRoseProgram;

        [SetUp]
        public void Init()
        {
            _actualStockItem = new Item
            {
                Name = _actualName,
                SellIn = _actualSellin,
                Quality = _actualQuality
            };

            GildedRoseProgram = new Program();
            _stockItems = new List<Item> { _actualStockItem };
        }

        [Test]
        public void ItShouldAllowUsToSetAndRetrieveTheItemsCorrectly()
        {
            Assert.AreEqual(_actualStockItem, GildedRoseProgram.Items[0]);
        }
    }
}

using Kata.GildedRose.CSharp.Console;
using NUnit.Framework;
using System.Collections.Generic;

namespace Kata.GildedRose.CSharp.Unit.Tests
{
    [TestFixture]
    public class WhenTestTheGildedRoseProgram
    {
        string _actualName = "+5 Dexterity Vest";
        int _actualSellin = 10;
        int _actualQuality = 10;
        Item _actualStockItem;

        IList<Item> _stockItems;
        Program GildedRoseProgram;

        [SetUp]
        public void Init()
        {
            _actualStockItem = new Item
            {
                Name = _actualName,
                SellIn = _actualSellin,
                Quality = _actualQuality
            };

            GildedRoseProgram = new Program();
            _stockItems = new List<Item> { _actualStockItem };

        }

        [Test]
        public void ItShouldAllowUsToSetAndRetrieveTheItemsCorrectly()
        {
            GildedRoseProgram.Items = _stockItems;
            Assert.AreEqual(_actualStockItem, GildedRoseProgram.Items[0]);
        }
    }
}

Test Passes - We can get and set Items on Program


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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f429a5d5-a386-4b9d-a369-c1ffec7da00b")]

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

Remove unneeded properties from assembly info

These will now break gitversion


namespace InfinniPlatform.DocumentStorage
{
    /// <summary>
    /// Настройки хранилища документов MongoDB.
    /// </summary>
    public class MongoDocumentStorageOptions
    {
        public const string SectionName = "mongodbDocumentStorage";

        public static MongoDocumentStorageOptions Default = new MongoDocumentStorageOptions();

        public MongoDocumentStorageOptions()
        {
            ConnectionString = "localhost:27017";
        }

        /// <summary>
        /// Строка подключения.
        /// </summary>
        /// <remarks>
        /// Подробнее см. https://docs.mongodb.com/manual/reference/connection-string..
        /// </remarks>
        public string ConnectionString { get; set; }
    }
}

namespace InfinniPlatform.DocumentStorage
{
    /// <summary>
    /// Настройки хранилища документов MongoDB.
    /// </summary>
    public class MongoDocumentStorageOptions
    {
        public const string SectionName = "mongodbDocumentStorage";

        public static MongoDocumentStorageOptions Default = new MongoDocumentStorageOptions();

        public MongoDocumentStorageOptions()
        {
            ConnectionString = "mongodb://localhost:27017";
        }

        /// <summary>
        /// Строка подключения.
        /// </summary>
        /// <remarks>
        /// Подробнее см. https://docs.mongodb.com/manual/reference/connection-string..
        /// </remarks>
        public string ConnectionString { get; set; }
    }
}

Fix default connection string for MongoDB


using Mono.Options;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WalletWasabi.Helpers;
using WalletWasabi.Gui.CrashReport;

namespace WalletWasabi.Gui.CommandLine
{
	internal class CrashReportCommand : Command
	{
		public CrashReportCommand(CrashReporter crashReporter) : base("crashreport", "Activates the internal crash reporting mechanism.")
		{
			CrashReporter = Guard.NotNull(nameof(crashReporter), crashReporter);

			Options = new OptionSet()
			{
				{ "attempt=", "Number of attempts at starting the crash reporter.", x => Attempts = x },
				{ "exception=", "The serialized exception from the previous crash.", x => ExceptionString = x },
			};
		}

		public CrashReporter CrashReporter { get; }
		public string Attempts { get; private set; }
		public string ExceptionString { get; private set; }

		public override Task<int> InvokeAsync(IEnumerable<string> args)
		{
			try
			{
				Options.Parse(args);

				CrashReporter.SetShowCrashReport(ExceptionString, int.Parse(Attempts));
			}
			catch (Exception ex)
			{
				Task.FromException(ex);
			}

			return Task.FromResult(0);
		}
	}
}

using Mono.Options;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WalletWasabi.Helpers;
using WalletWasabi.Gui.CrashReport;

namespace WalletWasabi.Gui.CommandLine
{
	internal class CrashReportCommand : Command
	{
		public CrashReportCommand(CrashReporter crashReporter) : base("crashreport", "Activates the internal crash reporting mechanism.")
		{
			CrashReporter = Guard.NotNull(nameof(crashReporter), crashReporter);

			Options = new OptionSet()
			{
				{ "attempt=", "Number of attempts at starting the crash reporter.", x => Attempts = x },
				{ "exception=", "The serialized exception from the previous crash.", x => ExceptionString = x },
			};
		}

		public CrashReporter CrashReporter { get; }
		public string Attempts { get; private set; }
		public string ExceptionString { get; private set; }

		public override Task<int> InvokeAsync(IEnumerable<string> args)
		{
			try
			{
				Options.Parse(args);

				CrashReporter.SetShowCrashReport(ExceptionString, int.Parse(Attempts));
			}
			catch (Exception ex)
			{
				return Task.FromException<int>(ex);
			}

			return Task.FromResult(0);
		}
	}
}

Fix wrong usage of Task.FromException

[Trivial] Fix wrong usage of Task.FromException


using System;
using OpenQA.Selenium;

namespace ExampleApp.Test.Functional.Models.ExampleAppPages
{
    /// <summary>
    /// Modles the Slinqy Example App Homepage.
    /// </summary>
    public class HomePage : SlinqyExampleWebPage
    {
        public const string RelativePath = "/";

        /// <summary>
        /// Initializes the HomePage with the IWebDriver to use for controlling the page.
        /// </summary>
        /// <param name="webBrowserDriver">
        /// Specifies the IWebDriver to use to interact with the Homepage.
        /// </param>
        public
        HomePage(
            IWebDriver webBrowserDriver)
                : base(webBrowserDriver, new Uri(RelativePath, UriKind.Relative))
        {
        }
    }
}

using System;
using OpenQA.Selenium;

namespace ExampleApp.Test.Functional.Models.ExampleAppPages
{
    /// <summary>
    /// Models the Slinqy Example App Homepage.
    /// </summary>
    public class HomePage : SlinqyExampleWebPage
    {
        public const string RelativePath = "/";

        /// <summary>
        /// Initializes the HomePage with the IWebDriver to use for controlling the page.
        /// </summary>
        /// <param name="webBrowserDriver">
        /// Specifies the IWebDriver to use to interact with the Homepage.
        /// </param>
        public
        HomePage(
            IWebDriver webBrowserDriver)
                : base(webBrowserDriver, new Uri(RelativePath, UriKind.Relative))
        {
        }
    }
}

Fix a typo in a code comment, thanks StyleCop!


         Skip to main content

                    <partial name="HeaderSearchBar" />

<partial name="MobileSearchBar" />

Remove role=navigation on nav tag

fix: Remove role=navigation on nav tag


using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;

namespace Promact.Trappist.Repository.Questions
{
    public class QuestionRepository : IQuestionRepository
    {
        private readonly TrappistDbContext _dbContext;

        public QuestionRepository(TrappistDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// Get all questions
        /// </summary>
        /// <returns>Question list</returns>
        public List<SingleMultipleAnswerQuestion> GetAllQuestions()
        {
            var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
            return questions;
        }
        /// <summary>
        /// Add single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
            _dbContext.SaveChanges();
        }
        /// <summary>
        /// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
            _dbContext.SaveChanges();
        }

    }
}

Update server side API for single multiple answer question