using MarkdownLog;
using NBi.Core.ResultSet;
using NBi.Core.ResultSet.Lookup;
using NBi.Core.ResultSet.Lookup.Violation;
using NBi.Framework.FailureMessage.Common;
using NBi.Framework.FailureMessage.Common.Helper;
using NBi.Framework.FailureMessage.Markdown.Helper;
using NBi.Framework.Sampling;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBi.Framework.FailureMessage.Markdown
{
    class LookupExistsViolationMessageMarkdown : LookupViolationMessageMarkdown
    {

        public LookupExistsViolationMessageMarkdown(IDictionary<string, ISampler<DataRow>> samplers)
            : base(samplers) { }

        protected override void RenderAnalysis(LookupViolationCollection violations, IEnumerable<ColumnMetadata> metadata, ISampler<DataRow> sampler, ColumnMappingCollection keyMappings, ColumnMappingCollection valueMappings, MarkdownContainer container)
        {
            container.Append("Analysis".ToMarkdownHeader());
            var state = violations.Values.Select(x => x.State).First();
            container.Append(GetExplanationText(violations, state).ToMarkdownParagraph());

            var rows = violations.Values.Where(x => x is LookupExistsViolationInformation)
                        .Cast<LookupExistsViolationInformation>()
                        .SelectMany(x => x.CandidateRows);
            sampler.Build(rows);

            var tableHelper = new StandardTableHelperMarkdown(rows, metadata, sampler);
            tableHelper.Render(container);
        }
    }
}

using MarkdownLog;
using NBi.Core.ResultSet;
using NBi.Core.ResultSet.Lookup;
using NBi.Core.ResultSet.Lookup.Violation;
using NBi.Framework.FailureMessage.Common;
using NBi.Framework.FailureMessage.Common.Helper;
using NBi.Framework.FailureMessage.Markdown.Helper;
using NBi.Framework.Sampling;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBi.Framework.FailureMessage.Markdown
{
    class LookupExistsViolationMessageMarkdown : LookupViolationMessageMarkdown
    {

        public LookupExistsViolationMessageMarkdown(IDictionary<string, ISampler<DataRow>> samplers)
            : base(samplers) { }

        protected override void RenderAnalysis(LookupViolationCollection violations, IEnumerable<ColumnMetadata> metadata, ISampler<DataRow> sampler, ColumnMappingCollection keyMappings, ColumnMappingCollection valueMappings, MarkdownContainer container)
        {
            if (violations.Values.Any())
            {
                container.Append("Analysis".ToMarkdownHeader());
                var state = violations.Values.Select(x => x.State).First();
                container.Append(GetExplanationText(violations, state).ToMarkdownParagraph());

                var rows = violations.Values.Where(x => x is LookupExistsViolationInformation)
                            .Cast<LookupExistsViolationInformation>()
                            .SelectMany(x => x.CandidateRows);
                sampler.Build(rows);

                var tableHelper = new StandardTableHelperMarkdown(rows, metadata, sampler);
                tableHelper.Render(container);
            }
        }
    }
}

Fix issue when the error messages are rendered in Markdown with an Always configuration


using System;

namespace Urho {
	public partial class BillboardSet
    {
        public BillboardWrapper GetBillboardSafe (uint index)
		{
			unsafe {
                Billboard* result = BillboardSet_GetBillboard (handle, index);
				if (result == null)
					return null;
				return new BillboardWrapper(result);
			}
		}
	}
}

using System;

namespace Urho {
	public partial class BillboardSet
    {
        public BillboardWrapper GetBillboardSafe (uint index)
		{
			unsafe {
                Billboard* result = BillboardSet_GetBillboard (handle, index);
				if (result == null)
					return null;
				return new BillboardWrapper(this, result);
			}
		}
	}
}

[Bindings] Fix BillboardWrapper, prevent bb from collecting by GC


using System.Web.Mvc;
using System.Web.Routing;

namespace RestfulRouting
{
	public abstract class Mapper
	{
		protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods)
		{
			return new Route(path,
				new RouteValueDictionary(new { controller, action }),
				new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }),
				new MvcRouteHandler());
		}
	}
}

using System.Web.Mvc;
using System.Web.Routing;

namespace RestfulRouting
{
	public abstract class Mapper
	{
		private readonly IRouteHandler _routeHandler;

		protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods)
		{
			return new Route(path,
				new RouteValueDictionary(new { controller, action }),
				new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }),
				new MvcRouteHandler());
		}
	}
}

Add new private field for the route handler


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Contentful.Core.Models.Management
{
    /// <summary>
    /// Encapsulates information about a Contentful Ui Extension
    /// </summary>
    public class UiExtension : IContentfulResource
    {
        /// <summary>
        /// Common system managed metadata properties.
        /// </summary>
        [JsonProperty("sys")]
        public SystemProperties SystemProperties { get; set; }

        /// <summary>
        /// The source URL for html file for the extension.
        /// </summary>
        public string Src { get; set; }

        /// <summary>
        /// String representation of the widget, e.g. inline HTML.
        /// </summary>
        public string SrcDoc { get; set; }

        /// <summary>
        /// The name of the extension
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// The field types for which this extension applies.
        /// </summary>
        public List<string> FieldTypes { get; set; }

        /// <summary>
        /// Whether or not this is an extension for the Contentful sidebar.
        /// </summary>
        public bool Sidebar { get; set; }
    }
}

using Contentful.Core.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Contentful.Core.Models.Management
{
    /// <summary>
    /// Encapsulates information about a Contentful Ui Extension
    /// </summary>
    [JsonConverter(typeof(ExtensionJsonConverter))]
    public class UiExtension : IContentfulResource
    {
        /// <summary>
        /// Common system managed metadata properties.
        /// </summary>
        [JsonProperty("sys")]
        public SystemProperties SystemProperties { get; set; }

        /// <summary>
        /// The source URL for html file for the extension.
        /// </summary>
        public string Src { get; set; }

        /// <summary>
        /// String representation of the widget, e.g. inline HTML.
        /// </summary>
        public string SrcDoc { get; set; }

        /// <summary>
        /// The name of the extension
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// The field types for which this extension applies.
        /// </summary>
        public List<string> FieldTypes { get; set; }

        /// <summary>
        /// Whether or not this is an extension for the Contentful sidebar.
        /// </summary>
        public bool Sidebar { get; set; }
    }
}

Add jsonconverter to extension model

Add jsonconverter to extension model


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

#if (NETFX || WINDOWS_PHONE)
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
#elif (NETFX_CORE)
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
#elif (XAMARIN)
using Xamarin.Forms;
#endif

namespace ValueConverters
{
    /// <summary>
    /// Value converters which aggregates the results of a sequence of converters: Converter1 >> Converter2 >> Converter3
    /// The output of converter N becomes the input of converter N+1.
    /// </summary>
#if (NETFX || XAMARIN || WINDOWS_PHONE)
    [ContentProperty(nameof(Converters))]
#elif (NETFX_CORE)
    [ContentProperty(Name = nameof(Converters))]
#endif
    public class ValueConverterGroup : SingletonConverterBase<ValueConverterGroup>
    {
        public List<IValueConverter> Converters { get; set; } = new List<IValueConverter>();

        protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return this.Converters?.Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture));
        }

        protected override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return this.Converters?.Reverse<IValueConverter>().Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture));
        }
    }
}

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

#if (NETFX || WINDOWS_PHONE)
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
#elif (NETFX_CORE)
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Markup;
#elif (XAMARIN)
using Xamarin.Forms;
#endif

namespace ValueConverters
{
    /// <summary>
    /// Value converters which aggregates the results of a sequence of converters: Converter1 >> Converter2 >> Converter3
    /// The output of converter N becomes the input of converter N+1.
    /// </summary>
#if (NETFX || XAMARIN || WINDOWS_PHONE)
    [ContentProperty(nameof(Converters))]
#elif (NETFX_CORE)
    [ContentProperty(Name = nameof(Converters))]
#endif
    public class ValueConverterGroup : SingletonConverterBase<ValueConverterGroup>
    {
        public List<IValueConverter> Converters { get; set; } = new List<IValueConverter>();

        protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return this.Converters?.Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture));
        }

        protected override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return this.Converters?.Reverse<IValueConverter>().Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture));
        }
    }
}

Add missing namespace for uwp

Add missing namespace for uwp


using System.IO;
using System.Web;

namespace Bundlr
{
    public class TemplateSource : IContentSource
    {
        private readonly string global;
        private readonly Compiler compiler;
        private readonly TemplateFinder finder;

        public TemplateSource(string global, Compiler compiler, TemplateFinder finder)
        {
            this.global = global;
            this.compiler = compiler;
            this.finder = finder;
        }

        public string GetContent(HttpContextBase httpContext)
        {
            var templates = finder.Find(httpContext);
            using (var writer = new StringWriter())
            {
                writer.WriteLine("!function() {");
                writer.WriteLine("  var templates = {0}.templates = {{}};", global);

                foreach (var template in templates)
                {
                    string name = template.GetName();
                    string content = compiler.Compile(template.GetContent());

                    writer.WriteLine("  templates['{0}'] = {1};", name, content);
                }

                writer.WriteLine("}();");

                return writer.ToString();
            }
        }
    }
}

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

namespace Bundlr
{
    public class TemplateSource : IContentSource
    {
        private readonly string global;
        private readonly Compiler compiler;
        private readonly TemplateFinder finder;

        public TemplateSource(string global, Compiler compiler, TemplateFinder finder)
        {
            this.global = global;
            this.compiler = compiler;
            this.finder = finder;
        }

        public string GetContent(HttpContextBase httpContext)
        {
            var templates = finder.Find(httpContext);
            using (var writer = new StringWriter())
            {
                writer.WriteLine("!function() {");
                writer.WriteLine("  var templates = {0}.templates = {{}};", global);

                var results = Compile(templates);
                foreach (var result in results)
                {
                    writer.WriteLine(result);
                }

                writer.WriteLine("}();");

                return writer.ToString();
            }
        }

        private IEnumerable<string> Compile(IEnumerable<Template> templates)
        {
            return templates.AsParallel().Select(template =>
            {
                string name = template.GetName();
                string content = compiler.Compile(template.GetContent());

                return string.Format("  templates['{0}'] = {1};", name, content);
            });
        }
    }
}

Add parallelism when compiling templates.


using Mindscape.Raygun4Net.Utils;

namespace Mindscape.Raygun4Net.Logging
{
  public class RaygunLogger : Singleton<RaygunLogger>, IRaygunLogger
  {
    public RaygunLogLevel LogLevel { get; set; }

    public void Error(string message)
    {
      Log(RaygunLogLevel.Error, message);
    }

    public void Warning(string message)
    {
      Log(RaygunLogLevel.Warning, message);
    }

    public void Info(string message)
    {
      Log(RaygunLogLevel.Info, message);
    }

    public void Debug(string message)
    {
      Log(RaygunLogLevel.Debug, message);
    }

    public void Verbose(string message)
    {
      Log(RaygunLogLevel.Verbose, message);
    }

    private void Log(RaygunLogLevel level, string message)
    {
      if (LogLevel == RaygunLogLevel.None)
      {
        return;
      }

      if (level <= LogLevel)
      {
        System.Diagnostics.Trace.WriteLine(message);
      }
    }
  }
}

using Mindscape.Raygun4Net.Utils;

namespace Mindscape.Raygun4Net.Logging
{
  public class RaygunLogger : Singleton<RaygunLogger>, IRaygunLogger
  {
    private const string RaygunPrefix = "Raygun: ";

    public RaygunLogLevel LogLevel { get; set; }

    public void Error(string message)
    {
      Log(RaygunLogLevel.Error, message);
    }

    public void Warning(string message)
    {
      Log(RaygunLogLevel.Warning, message);
    }

    public void Info(string message)
    {
      Log(RaygunLogLevel.Info, message);
    }

    public void Debug(string message)
    {
      Log(RaygunLogLevel.Debug, message);
    }

    public void Verbose(string message)
    {
      Log(RaygunLogLevel.Verbose, message);
    }

    private void Log(RaygunLogLevel level, string message)
    {
      if (LogLevel == RaygunLogLevel.None)
      {
        return;
      }

      if (level <= LogLevel)
      {
        System.Diagnostics.Trace.WriteLine($"{RaygunPrefix}{message}");
      }
    }
  }
}

Add a prefix to each log

Add a prefix to each log

Add a prefix to each log


using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;

namespace MultiMiner.Utility.Networking
{
    public class PortScanner
    {
        public static List<IPEndPoint> Find(string ipRange, int startingPort, int endingPort, int connectTimeout = 100)
        {
            if (startingPort >= endingPort)
                throw new ArgumentException();

            List<IPEndPoint> endpoints = new List<IPEndPoint>();

            IEnumerable<IPAddress> ipAddresses = new IPRange(ipRange).GetIPAddresses();

            foreach (IPAddress ipAddress in ipAddresses)
                for (int currentPort = startingPort; currentPort <= endingPort; currentPort++)
                    if (IsPortOpen(ipAddress, currentPort, connectTimeout))
                        endpoints.Add(new IPEndPoint(ipAddress, currentPort));

            return endpoints;
        }

        private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout)
        {
            bool portIsOpen = false;

            using (var tcp = new TcpClient())
            {
                IAsyncResult ar = tcp.BeginConnect(ipAddress, currentPort, null, null);
                using (ar.AsyncWaitHandle)
                {
                    //Wait connectTimeout ms for connection.
                    if (ar.AsyncWaitHandle.WaitOne(connectTimeout, false))
                    {
                        try
                        {
                            tcp.EndConnect(ar);
                            portIsOpen = true;
                            //Connect was successful.
                        }
                        catch
                        {
                            //Server refused the connection.
                        }
                    }
                }
            }

            return portIsOpen;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;

namespace MultiMiner.Utility.Networking
{
    public class PortScanner
    {
        public static List<IPEndPoint> Find(string ipRange, int startingPort, int endingPort, int connectTimeout = 100)
        {
            if (startingPort >= endingPort)
                throw new ArgumentException();

            List<IPEndPoint> endpoints = new List<IPEndPoint>();

            IEnumerable<IPAddress> ipAddresses = new IPRange(ipRange).GetIPAddresses();

            foreach (IPAddress ipAddress in ipAddresses)
                for (int currentPort = startingPort; currentPort <= endingPort; currentPort++)
                    if (IsPortOpen(ipAddress, currentPort, connectTimeout))
                        endpoints.Add(new IPEndPoint(ipAddress, currentPort));

            return endpoints;
        }

        private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout)
        {
            bool portIsOpen = false;

            //use raw Sockets
            //using TclClient along with IAsyncResult can lead to ObjectDisposedException on Linux+Mono
            Socket socket = null;
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);

                IAsyncResult result = socket.BeginConnect(ipAddress.ToString(), currentPort, null, null);
                result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(connectTimeout), true);

                portIsOpen = socket.Connected;
            }
            catch
            {
            }
            finally
            {
                if (socket != null)
                    socket.Close();
            }

            return portIsOpen;
        }
    }
}

Use Socket instead of TcpClient for port scanning Works around ObjectDisposedException on Linux + Mono


namespace TestAppUWP.Samples.Map
{
    public class MapServiceSettings
    {
        public static string Token = string.Empty;
    }
}

namespace TestAppUWP.Samples.Map
{
    public class MapServiceSettings
    {
        public const string TokenUwp1 = "TokenUwp1";

        public const string TokenUwp2 = "TokenUwp2";

        public static string SelectedToken = TokenUwp1;
    }
}

Add multiple bing maps keys

Add multiple bing maps keys


using Microsoft.Speech.Recognition;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace lex4all
{
    public static class EngineControl
    {
        /// <summary>
        /// creates engine and sets properties
        /// </summary>
        /// <returns>
        /// the engine used for recognition
        /// </returns>
        public static SpeechRecognitionEngine getEngine () {

            Console.WriteLine("Building recognition engine");

            SpeechRecognitionEngine sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));

            // set confidence threshold(s)
            sre.UpdateRecognizerSetting("CFGConfidenceRejectionThreshold", 0);

            // add event handlers
            sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);

            Console.WriteLine("Done.");
            return sre;
        }

        /// <summary>
        /// handles the speech recognized event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            Console.WriteLine("Recognized text: " + e.Result.Text);
        }

    }
}

using Microsoft.Speech.Recognition;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace lex4all
{
    public static class EngineControl
    {
        /// <summary>
        /// creates engine and sets properties
        /// </summary>
        /// <returns>
        /// the engine used for recognition
        /// </returns>
        public static SpeechRecognitionEngine getEngine () {

            Console.WriteLine("Building recognition engine");

            SpeechRecognitionEngine sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));

            // set confidence threshold(s)
            sre.UpdateRecognizerSetting("CFGConfidenceRejectionThreshold", 0);

            // add event handlers
            sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);

            Console.WriteLine("Done.");
            return sre;
        }

        /// <summary>
        /// handles the speech recognized event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            //Console.WriteLine("Recognized text: " + e.Result.Text);

        }

    }
}

Change recognized event handler for eval


using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;

namespace OmniSharp
{
    public partial class OmnisharpController
    {
        [HttpPost("autocomplete")]
        public async Task<IActionResult> AutoComplete([FromBody]Request request)
        {
            _workspace.EnsureBufferUpdated(request);

            var completions = Enumerable.Empty<AutoCompleteResponse>();

            var document = _workspace.GetDocument(request.FileName);

            if (document != null)
            {
                var sourceText = await document.GetTextAsync();
                var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));
                var model = await document.GetSemanticModelAsync();
                var symbols = Recommender.GetRecommendedSymbolsAtPosition(model, position, _workspace);

                completions = symbols.Select(MakeAutoCompleteResponse);
            }
            else
            {
                return new HttpNotFoundResult();
            }

            return new ObjectResult(completions);
        }

        private AutoCompleteResponse MakeAutoCompleteResponse(ISymbol symbol)
        {
            var response = new AutoCompleteResponse();
            response.CompletionText = symbol.Name;
            // TODO: Do something more intelligent here
            response.DisplayText = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
            response.Description = symbol.GetDocumentationCommentXml();

            return response;
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;

namespace OmniSharp
{
    public partial class OmnisharpController
    {
        [HttpPost("autocomplete")]
        public async Task<IActionResult> AutoComplete([FromBody]Request request)
        {
            _workspace.EnsureBufferUpdated(request);

            var completions = new List<AutoCompleteResponse>();

            var documents = _workspace.GetDocuments(request.FileName);

            foreach (var document in documents)
            {
                var sourceText = await document.GetTextAsync();
                var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));
                var model = await document.GetSemanticModelAsync();
                var symbols = Recommender.GetRecommendedSymbolsAtPosition(model, position, _workspace);

                completions.AddRange(symbols.Select(MakeAutoCompleteResponse));
            }

            return new ObjectResult(completions);
        }

        private AutoCompleteResponse MakeAutoCompleteResponse(ISymbol symbol)
        {
            var response = new AutoCompleteResponse();
            response.CompletionText = symbol.Name;
            // TODO: Do something more intelligent here
            response.DisplayText = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
            response.Description = symbol.GetDocumentationCommentXml();

            return response;
        }
    }
}

Return completions from all documents

Return completions from all documents

- Return the completions from all documents.
This is a step towards combined intellisense for ASP.NET 5 projects.


using InfinniPlatform.Http;
using InfinniPlatform.IoC;

namespace InfinniPlatform.Auth.HttpService.IoC
{
    public class AuthHttpServiceContainerModule<TUser> : IContainerModule where TUser : AppUser
    {
        public void Load(IContainerBuilder builder)
        {
            builder.RegisterType(typeof(AuthInternalHttpService<>).MakeGenericType(typeof(TUser)))
                   .As<IHttpService>()
                   .SingleInstance();

            builder.RegisterType<UserEventHandlerInvoker>()
                   .AsSelf()
                   .SingleInstance();
        }
    }
}

using InfinniPlatform.Http;
using InfinniPlatform.IoC;

namespace InfinniPlatform.Auth.HttpService.IoC
{
    public class AuthHttpServiceContainerModule<TUser> : IContainerModule where TUser : AppUser
    {
        public void Load(IContainerBuilder builder)
        {
            builder.RegisterType(typeof(AuthInternalHttpService<>).MakeGenericType(typeof(TUser)))
                   .As<IHttpService>()
                   .SingleInstance();

            builder.RegisterType(typeof(AuthExternalHttpService<>).MakeGenericType(typeof(TUser)))
                .As<IHttpService>()
                .SingleInstance();

            builder.RegisterType(typeof(AuthManagementHttpService<>).MakeGenericType(typeof(TUser)))
                .As<IHttpService>()
                .SingleInstance();

            builder.RegisterType<UserEventHandlerInvoker>()
                   .AsSelf()
                   .SingleInstance();
        }
    }
}

Fix auth http services registration

Fix auth http services registration


// 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.Graphics.Containers;
using osu.Game.Overlays.Toolbar;
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;
using System.Linq;
using osu.Framework.MathUtils;

namespace osu.Game.Tests.Visual.UserInterface
{
    public class TestSceneToolbarRulesetSelector : OsuTestScene
    {
        public override IReadOnlyList<Type> RequiredTypes => new[]
        {
            typeof(ToolbarRulesetSelector),
            typeof(ToolbarRulesetTabButton),
        };

        public TestSceneToolbarRulesetSelector()
        {
            ToolbarRulesetSelector selector;

            Add(new Container
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                AutoSizeAxes = Axes.X,
                Height = Toolbar.HEIGHT,
                Child = selector = new ToolbarRulesetSelector()
            });

            AddStep("Select random", () =>
            {
                selector.Current.Value = selector.Items.ElementAt(RNG.Next(selector.Items.Count()));
            });
        }
    }
}

// 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.Graphics.Containers;
using osu.Game.Overlays.Toolbar;
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;
using System.Linq;
using osu.Framework.MathUtils;

namespace osu.Game.Tests.Visual.UserInterface
{
    public class TestSceneToolbarRulesetSelector : OsuTestScene
    {
        public override IReadOnlyList<Type> RequiredTypes => new[]
        {
            typeof(ToolbarRulesetSelector),
            typeof(ToolbarRulesetTabButton),
        };

        public TestSceneToolbarRulesetSelector()
        {
            ToolbarRulesetSelector selector;

            Add(new Container
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                AutoSizeAxes = Axes.X,
                Height = Toolbar.HEIGHT,
                Child = selector = new ToolbarRulesetSelector()
            });

            AddStep("Select random", () =>
            {
                selector.Current.Value = selector.Items.ElementAt(RNG.Next(selector.Items.Count()));
            });
            AddStep("Toggle disabled state", () => selector.Current.Disabled = !selector.Current.Disabled);
        }
    }
}

Make testcase even more useful

Make testcase even more useful


using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RockLib.Logging.DependencyInjection;
using System;

namespace RockLib.Logging
{
    public static class RockLibLoggerExtensions
    {
        public static ILoggingBuilder AddRockLibLoggerProvider(this ILoggingBuilder builder, string rockLibLoggerName = Logger.DefaultName)
        {
            if (builder is null)
                throw new ArgumentNullException(nameof(builder));

            builder.Services.AddRockLibLoggerProvider(rockLibLoggerName);

            return builder;
        }

        public static IServiceCollection AddRockLibLoggerProvider(this IServiceCollection services, string rockLibLoggerName = Logger.DefaultName)
        {
            if (services is null)
                throw new ArgumentNullException(nameof(services));

            services.Add(ServiceDescriptor.Singleton<ILoggerProvider>(serviceProvider =>
            {
                var lookup = serviceProvider.GetRequiredService<LoggerLookup>();
                var options = serviceProvider.GetService<IOptionsMonitor<RockLibLoggerOptions>>();
                return new RockLibLoggerProvider(lookup(rockLibLoggerName), options);
            }));

            return services;
        }
    }
}

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RockLib.Logging.DependencyInjection;
using System;

namespace RockLib.Logging
{
    public static class RockLibLoggerExtensions
    {
        public static ILoggingBuilder AddRockLibLoggerProvider(this ILoggingBuilder builder,
            string rockLibLoggerName = Logger.DefaultName, Action<RockLibLoggerOptions> configureOptions = null)
        {
            if (builder is null)
                throw new ArgumentNullException(nameof(builder));

            builder.Services.AddRockLibLoggerProvider(rockLibLoggerName, configureOptions);

            return builder;
        }

        public static IServiceCollection AddRockLibLoggerProvider(this IServiceCollection services,
            string rockLibLoggerName = Logger.DefaultName, Action<RockLibLoggerOptions> configureOptions = null)
        {
            if (services is null)
                throw new ArgumentNullException(nameof(services));

            services.Add(ServiceDescriptor.Singleton<ILoggerProvider>(serviceProvider =>
            {
                var lookup = serviceProvider.GetRequiredService<LoggerLookup>();
                var options = serviceProvider.GetService<IOptionsMonitor<RockLibLoggerOptions>>();
                return new RockLibLoggerProvider(lookup(rockLibLoggerName), options);
            }));

            if (configureOptions != null)
                services.Configure(configureOptions);

            return services;
        }
    }
}

Add configureOptions parameter to extension methods


using System.Collections.Generic;

namespace Ical.Net.Interfaces.DataTypes
{
    public interface IPeriodList : IEncodableDataType, IList<IPeriod>
    {
        string TzId { get; set; }

        IPeriod this[int index] { get; set; }
        void Add(IDateTime dt);
        void Remove(IDateTime dt);
    }
}

using System.Collections.Generic;

namespace Ical.Net.Interfaces.DataTypes
{
    public interface IPeriodList : IEncodableDataType, IList<IPeriod>
    {
        string TzId { get; set; }

        new IPeriod this[int index] { get; set; }
        void Add(IDateTime dt);
        void Remove(IDateTime dt);
    }
}

Stop hiding indexer on IList

Stop hiding indexer on IList


using System.Threading.Tasks;
using Content.Server.GameObjects.EntitySystems.StationEvents;
using NUnit.Framework;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.Timing;
using Robust.Shared.IoC;

namespace Content.IntegrationTests.Tests.StationEvents
{
    [TestFixture]
    public class StationEventsSystemTest : ContentIntegrationTest
    {
        [Test]
        public async Task Test()
        {
            var server = StartServerDummyTicker();

            server.Assert(() =>
            {
                // Idle each event once
                var stationEventsSystem = EntitySystem.Get<StationEventSystem>();
                var dummyFrameTime = (float) IoCManager.Resolve<IGameTiming>().TickPeriod.TotalSeconds;

                foreach (var stationEvent in stationEventsSystem.StationEvents)
                {
                    stationEvent.Startup();
                    stationEvent.Update(dummyFrameTime);
                    stationEvent.Shutdown();
                    Assert.That(stationEvent.Occurrences == 1);
                }

                stationEventsSystem.ResettingCleanup();

                foreach (var stationEvent in stationEventsSystem.StationEvents)
                {
                    Assert.That(stationEvent.Occurrences == 0);
                }
            });

            await server.WaitIdleAsync();
        }
    }
}

using System.Threading.Tasks;
using Content.Server.GameObjects.EntitySystems.StationEvents;
using NUnit.Framework;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.Timing;
using Robust.Shared.IoC;

namespace Content.IntegrationTests.Tests.StationEvents
{
    [TestFixture]
    public class StationEventsSystemTest : ContentIntegrationTest
    {
        [Test]
        public async Task Test()
        {
            var server = StartServerDummyTicker();

            server.Assert(() =>
            {
                // Idle each event once
                var stationEventsSystem = EntitySystem.Get<StationEventSystem>();
                var dummyFrameTime = (float) IoCManager.Resolve<IGameTiming>().TickPeriod.TotalSeconds;

                foreach (var stationEvent in stationEventsSystem.StationEvents)
                {
                    stationEvent.Startup();
                    stationEvent.Update(dummyFrameTime);
                    stationEvent.Shutdown();
                    Assert.That(stationEvent.Occurrences == 1);
                }

                stationEventsSystem.Reset();

                foreach (var stationEvent in stationEventsSystem.StationEvents)
                {
                    Assert.That(stationEvent.Occurrences == 0);
                }
            });

            await server.WaitIdleAsync();
        }
    }
}

Fix station events system test

Fix station events system test


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

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Script.Config;
using static Microsoft.Azure.Web.DataProtection.Constants;

namespace Microsoft.Azure.WebJobs.Script.WebHost
{
    public sealed class DefaultKeyValueConverterFactory : IKeyValueConverterFactory
    {
        private bool _encryptionSupported;
        private static readonly PlaintextKeyValueConverter PlaintextValueConverter = new PlaintextKeyValueConverter(FileAccess.ReadWrite);
        private static ScriptSettingsManager _settingsManager;

        public DefaultKeyValueConverterFactory(ScriptSettingsManager settingsManager)
        {
            _settingsManager = settingsManager;
            _encryptionSupported = IsEncryptionSupported();
        }

        // In Linux Containers AzureWebsiteLocalEncryptionKey will be set, enabling encryption
        private static bool IsEncryptionSupported() => _settingsManager.IsAppServiceEnvironment || _settingsManager.GetSetting(AzureWebsiteLocalEncryptionKey) != null;

        public IKeyValueReader GetValueReader(Key key)
        {
            if (key.IsEncrypted)
            {
                return new DataProtectionKeyValueConverter(FileAccess.Read);
            }

            return PlaintextValueConverter;
        }

        public IKeyValueWriter GetValueWriter(Key key)
        {
            if (_encryptionSupported)
            {
                return new DataProtectionKeyValueConverter(FileAccess.Write);
            }

            return PlaintextValueConverter;
        }
    }
}

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

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Script.Config;
using static Microsoft.Azure.Web.DataProtection.Constants;

namespace Microsoft.Azure.WebJobs.Script.WebHost
{
    public sealed class DefaultKeyValueConverterFactory : IKeyValueConverterFactory
    {
        private readonly bool _encryptionSupported;
        private static readonly PlaintextKeyValueConverter PlaintextValueConverter = new PlaintextKeyValueConverter(FileAccess.ReadWrite);
        private static ScriptSettingsManager _settingsManager;

        public DefaultKeyValueConverterFactory(ScriptSettingsManager settingsManager)
        {
            _settingsManager = settingsManager;
            _encryptionSupported = IsEncryptionSupported();
        }

        private static bool IsEncryptionSupported()
        {
            if (_settingsManager.IsLinuxContainerEnvironment)
            {
                // TEMP: https://github.com/Azure/azure-functions-host/issues/3035
                return false;
            }

            return _settingsManager.IsAppServiceEnvironment || _settingsManager.GetSetting(AzureWebsiteLocalEncryptionKey) != null;
        }

        public IKeyValueReader GetValueReader(Key key)
        {
            if (key.IsEncrypted)
            {
                return new DataProtectionKeyValueConverter(FileAccess.Read);
            }

            return PlaintextValueConverter;
        }

        public IKeyValueWriter GetValueWriter(Key key)
        {
            if (_encryptionSupported)
            {
                return new DataProtectionKeyValueConverter(FileAccess.Write);
            }

            return PlaintextValueConverter;
        }
    }
}

Use plain text for function secrets in Linux Containers


// 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;
using osu.Framework.Platform;
using osu.Framework.Testing;

namespace osu.Game.Tests.Visual
{
    public abstract class OsuTestCase : TestCase
    {
        public override void RunTest()
        {
            Storage storage;
            using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false))
            {
                storage = host.Storage;
                host.Run(new OsuTestCaseTestRunner(this));
            }

            // clean up after each run
            storage.DeleteDirectory(string.Empty);
        }

        public class OsuTestCaseTestRunner : OsuGameBase
        {
            private readonly OsuTestCase testCase;

            public OsuTestCaseTestRunner(OsuTestCase testCase)
            {
                this.testCase = testCase;
            }

            protected override void LoadComplete()
            {
                base.LoadComplete();
                Add(new TestCaseTestRunner.TestRunner(testCase));
            }
        }
    }
}

// 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;
using osu.Framework.Platform;
using osu.Framework.Testing;

namespace osu.Game.Tests.Visual
{
    public abstract class OsuTestCase : TestCase
    {
        public override void RunTest()
        {
            using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false))
            {
                host.Run(new OsuTestCaseTestRunner(this));
            }

            // clean up after each run
            //storage.DeleteDirectory(string.Empty);
        }

        public class OsuTestCaseTestRunner : OsuGameBase
        {
            private readonly OsuTestCase testCase;

            public OsuTestCaseTestRunner(OsuTestCase testCase)
            {
                this.testCase = testCase;
            }

            protected override void LoadComplete()
            {
                base.LoadComplete();
                Add(new TestCaseTestRunner.TestRunner(testCase));
            }
        }
    }
}

Remove TestCase cleanup temporarily until context disposal is sorted


// Copyright 2016 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 Google.Api.Gax;
using System;
using System.Linq;
using Xunit;

namespace Google.Monitoring.V3
{
    [Collection(nameof(MonitoringFixture))]
    public class GroupServiceClientSnippets
    {
        private readonly MonitoringFixture _fixture;

        public GroupServiceClientSnippets(MonitoringFixture fixture)
        {
            _fixture = fixture;
        }

        /* TODO: Reinstate when ListGroups is present again.
        [Fact]
        public void ListGroups()
        {
            string projectId = _fixture.ProjectId;

            // Snippet: ListGroups
            GroupServiceClient client = GroupServiceClient.Create();
            string projectName = MetricServiceClient.FormatProjectName(projectId);
            IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", "");
            foreach (Group group in groups.Take(10))
            {
                Console.WriteLine($"{group.Name}: {group.DisplayName}");
            }
            // End snippet
        }
        */
    }
}

// Copyright 2016 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 Google.Api.Gax;
using System;
using System.Linq;
using Xunit;

namespace Google.Monitoring.V3
{
    [Collection(nameof(MonitoringFixture))]
    public class GroupServiceClientSnippets
    {
        private readonly MonitoringFixture _fixture;

        public GroupServiceClientSnippets(MonitoringFixture fixture)
        {
            _fixture = fixture;
        }

        /* TODO: Reinstate when ListGroups is present again.
        [Fact]
        public void ListGroups()
        {
            string projectId = _fixture.ProjectId;

            // FIXME:Snippet: ListGroups
            GroupServiceClient client = GroupServiceClient.Create();
            string projectName = MetricServiceClient.FormatProjectName(projectId);
            IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", "");
            foreach (Group group in groups.Take(10))
            {
                Console.WriteLine($"{group.Name}: {group.DisplayName}");
            }
            // End snippet
        }
        */
    }
}

Remove the ListGroups snippet from Monitoring

The code is commented out, but the snippet was still found. Oops.


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("Plugin.MediaManager.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Plugin.MediaManager.Android")]
[assembly: AssemblyCopyright("Copyright ©  2016")]
[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(Android.Manifest.Permission.AccessWifiState)]
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.MediaContentControl)]
[assembly: UsesPermission(Android.Manifest.Permission.WakeLock)]

Set Android permissions through Assemblyinfo


namespace BigEgg.ConsoleExtension.Parameters.Errors
{
    using System;

    internal class CommandHelpRequestError : Error
    {
        public CommandHelpRequestError()
            : base(ErrorType.CommandHelpRequest, true)
        { }

        public string CommandName { get; private set; }

        public bool Existed { get; set; }

        public Type CommandType { get; set; }
    }
}

namespace BigEgg.ConsoleExtension.Parameters.Errors
{
    using System;

    internal class CommandHelpRequestError : Error
    {
        public CommandHelpRequestError(string commandName, bool existed, Type commandType)
            : base(ErrorType.CommandHelpRequest, true)
        {
            CommandName = commandName;
            Existed = existed;
            CommandType = existed ? commandType : null;
        }

        public string CommandName { get; private set; }

        public bool Existed { get; private set; }

        public Type CommandType { get; private set; }
    }
}

Update the Command Help Request Error to get the value


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

using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;

namespace osu.Game.Rulesets.Osu.Beatmaps
{
    public class OsuBeatmap : Beatmap<OsuHitObject>
    {
        public override IEnumerable<BeatmapStatistic> GetStatistics()
        {
            IEnumerable<HitObject> circles = HitObjects.Where(c => c is HitCircle);
            IEnumerable<HitObject> sliders = HitObjects.Where(s => s is Slider);
            IEnumerable<HitObject> spinners = HitObjects.Where(s => s is Spinner);

            return new[]
            {
                new BeatmapStatistic
                {
                    Name = @"Circle Count",
                    Content = circles.Count().ToString(),
                    Icon = FontAwesome.fa_circle_o
                },
                new BeatmapStatistic
                {
                    Name = @"Slider Count",
                    Content = sliders.Count().ToString(),
                    Icon = FontAwesome.fa_circle
                },
                new BeatmapStatistic
                {
                    Name = @"Spinner Count",
                    Content = spinners.Count().ToString(),
                    Icon = FontAwesome.fa_circle
                }
            };
        }
    }
}

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

using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Rulesets.Osu.Objects;

namespace osu.Game.Rulesets.Osu.Beatmaps
{
    public class OsuBeatmap : Beatmap<OsuHitObject>
    {
        public override IEnumerable<BeatmapStatistic> GetStatistics()
        {
            int circles = HitObjects.Count(c => c is HitCircle);
            int sliders = HitObjects.Count(s => s is Slider);
            int spinners = HitObjects.Count(s => s is Spinner);

            return new[]
            {
                new BeatmapStatistic
                {
                    Name = @"Circle Count",
                    Content = circles.ToString(),
                    Icon = FontAwesome.fa_circle_o
                },
                new BeatmapStatistic
                {
                    Name = @"Slider Count",
                    Content = sliders.ToString(),
                    Icon = FontAwesome.fa_circle
                },
                new BeatmapStatistic
                {
                    Name = @"Spinner Count",
                    Content = spinners.ToString(),
                    Icon = FontAwesome.fa_circle
                }
            };
        }
    }
}

Simplify statistics in osu ruleset

Simplify statistics in osu ruleset


using System;
using System.Collections.Generic;
using System.Threading;
using Nancy;
using Nancy.Hosting.Self;

namespace ChildProcessUtil
{
    public class Program
    {
        private const string HttpAddress = "http://localhost:";
        private static NancyHost host;
        private static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("usage: ChildProcessUtil.exe serverPort mainProcessId");
                return;
            }
            StartServer(int.Parse(args[0]), int.Parse(args[1]));
        }

        public static void StartServer(int port, int mainProcessId)
        {
            var hostConfigs = new HostConfiguration
            {
                UrlReservations = new UrlReservations {CreateAutomatically = true}
            };

            var uriString = HttpAddress + port;
            ProcessModule.ActiveProcesses = new List<int>();
            host = new NancyHost(new Uri(uriString), new DefaultNancyBootstrapper(), hostConfigs);
            host.Start();
            new MainProcessWatcher(mainProcessId);
            Thread.Sleep(Timeout.Infinite);
        }

        internal static void StopServer(int port)
        {
            host.Stop();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading;
using Nancy;
using Nancy.Hosting.Self;

namespace ChildProcessUtil
{
    public class Program
    {
        private const string HttpAddress = "http://localhost:";
        private static NancyHost host;
        private static void Main(string[] args)
        {
            Console.WriteLine("Child process watcher and automatic killer");
            if (args.Length != 2)
            {
                Console.WriteLine("usage: ChildProcessUtil.exe serverPort mainProcessId");
                return;
            }
            StartServer(int.Parse(args[0]), int.Parse(args[1]));
        }

        public static void StartServer(int port, int mainProcessId)
        {
            var hostConfigs = new HostConfiguration
            {
                UrlReservations = new UrlReservations {CreateAutomatically = true}
            };

            var uriString = HttpAddress + port;
            ProcessModule.ActiveProcesses = new List<int>();
            host = new NancyHost(new Uri(uriString), new DefaultNancyBootstrapper(), hostConfigs);
            host.Start();
            new MainProcessWatcher(mainProcessId);
            Thread.Sleep(Timeout.Infinite);
        }

        internal static void StopServer(int port)
        {
            host.Stop();
        }
    }
}

Add short desc on main

Add short desc on main


namespace ReimuPlugins.Common
{
    public enum Revision
    {
        Rev1 = 1,
        Rev2
    }

    public enum ErrorCode
    {
        NoFunction = -1,
        AllRight,
        NotSupport,
        FileReadError,
        FileWriteError,
        NoMemory,
        UnknownError,
        DialogCanceled
    }

    public enum TextAlign
    {
        Left = 0,
        Right,
        Center
    }

    public enum SortType
    {
        String = 0,
        Number,
        Float,
        Hex
    }

    public enum SystemInfoType
    {
        String = 0,
        Path,
        Directory,
        Title,
        Extension,
        CreateTime,
        LastAccessTime,
        LastWriteTime,
        FileSize
    }
}

using System.Text;

namespace ReimuPlugins.Common
{
    public enum Revision
    {
        Rev1 = 1,
        Rev2
    }

    public enum ErrorCode
    {
        NoFunction = -1,
        AllRight,
        NotSupport,
        FileReadError,
        FileWriteError,
        NoMemory,
        UnknownError,
        DialogCanceled
    }

    public enum TextAlign
    {
        Left = 0,
        Right,
        Center
    }

    public enum SortType
    {
        String = 0,
        Number,
        Float,
        Hex
    }

    public enum SystemInfoType
    {
        String = 0,
        Path,
        Directory,
        Title,
        Extension,
        CreateTime,
        LastAccessTime,
        LastWriteTime,
        FileSize
    }

    public static class Enc
    {
        public static readonly Encoding SJIS = Encoding.GetEncoding("shift_jis");

        public static readonly Encoding UTF8 = Encoding.UTF8;
    }
}

Add Enc class for convenience

Add Enc class for convenience


/**
Copyright 2014-2017 Robert McNeel and Associates

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 Rhino;
using Rhino.DocObjects;
using Rhino.UI;
using System;
using System.Drawing;

namespace RhinoCycles.Settings
{
	public class OptionsDialogPage : Rhino.UI.OptionsDialogPage
	{
		public OptionsDialogPage() : base(Localization.LocalizeString("Raytraced settings", 37))
		{
			CollapsibleSectionHolder = new OptionsDialogCollapsibleSectionUIPanel();
		}

		public override object PageControl => CollapsibleSectionHolder;

		private OptionsDialogCollapsibleSectionUIPanel CollapsibleSectionHolder { get; }
	}
}

/**
Copyright 2014-2017 Robert McNeel and Associates

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 Rhino;
using Rhino.DocObjects;
using Rhino.UI;
using System;
using System.Drawing;

namespace RhinoCycles.Settings
{
	public class OptionsDialogPage : Rhino.UI.OptionsDialogPage
	{
		public OptionsDialogPage() : base(Localization.LocalizeString("Cycles", 7))
		{
			CollapsibleSectionHolder = new OptionsDialogCollapsibleSectionUIPanel();
		}

		public override object PageControl => CollapsibleSectionHolder;

		private OptionsDialogCollapsibleSectionUIPanel CollapsibleSectionHolder { get; }
	}
}

Rename Raytraced settings Options page to just Cycles.


// 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.Utility
{
    /// <summary>
    /// Exception thrown when data read by Noda Time (such as serialized time zone data) is invalid.
    /// </summary>
    /// <remarks>
    /// This type only exists as <c>InvalidDataException</c> doesn't exist in the Portable Class Library.
    /// Unfortunately, <c>InvalidDataException</c> itself is sealed, so we can't derive from it for the sake
    /// of backward compatibility.
    /// </remarks>
    /// <threadsafety>Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
    /// See the thread safety section of the user guide for more information.
    /// </threadsafety>
#if !PCL
    [Serializable]
#endif
    // TODO: Derive from IOException instead, like EndOfStreamException does?
    public class InvalidNodaDataException : Exception
    {
        /// <summary>
        /// Creates an instance with the given message.
        /// </summary>
        /// <param name="message">The message for the exception.</param>
        public InvalidNodaDataException(string message) : base(message) { }
    }
}

Fix crazy Unix line endings ;)

Fix crazy Unix line endings ;)


using System;

namespace Cake.Yarn
{
    /// <summary>
    /// Yarn Runner command interface
    /// </summary>
    public interface IYarnRunnerCommands
    {
        /// <summary>
        /// execute 'yarn install' with options
        /// </summary>
        /// <param name="configure">options when running 'yarn install'</param>
        IYarnRunnerCommands Install(Action<YarnInstallSettings> configure = null);

        /// <summary>
        /// execute 'yarn add' with options
        /// </summary>
        /// <param name="configure">options when running 'yarn add'</param>
        IYarnRunnerCommands Add(Action<YarnAddSettings> configure = null);

        /// <summary>
        /// execute 'yarn run' with arguments
        /// </summary>
        /// <param name="scriptName">name of the </param>
        /// <param name="configure">options when running 'yarn run'</param>
        IYarnRunnerCommands RunScript(string scriptName, Action<YarnRunSettings> configure = null);

        /// <summary>
        /// execute 'yarn pack' with options
        /// </summary>
        /// <param name="packSettings">options when running 'yarn pack'</param>
        IYarnRunnerCommands Pack(Action<YarnPackSettings> packSettings = null);

        /// <summary>
        /// execute 'yarn version' with options
        /// </summary>
        /// <param name="versionSettings">options when running 'yarn version'</param>
        IYarnRunnerCommands Version(Action<YarnVersionSettings> versionSettings = null);
    }
}

using System;

namespace Cake.Yarn
{
    /// <summary>
    /// Yarn Runner command interface
    /// </summary>
    public interface IYarnRunnerCommands
    {
        /// <summary>
        /// execute 'yarn install' with options
        /// </summary>
        /// <param name="configure">options when running 'yarn install'</param>
        IYarnRunnerCommands Install(Action<YarnInstallSettings> configure = null);

        /// <summary>
        /// execute 'yarn add' with options
        /// </summary>
        /// <param name="configure">options when running 'yarn add'</param>
        IYarnRunnerCommands Add(Action<YarnAddSettings> configure = null);

        /// <summary>
        /// execute 'yarn run' with arguments
        /// </summary>
        /// <param name="scriptName">name of the </param>
        /// <param name="configure">options when running 'yarn run'</param>
        IYarnRunnerCommands RunScript(string scriptName, Action<YarnRunSettings> configure = null);

        /// <summary>
        /// execute 'yarn pack' with options
        /// </summary>
        /// <param name="packSettings">options when running 'yarn pack'</param>
        IYarnRunnerCommands Pack(Action<YarnPackSettings> packSettings = null);

        /// <summary>
        /// execute 'yarn version' with options
        /// </summary>
        /// <param name="versionSettings">options when running 'yarn version'</param>
        IYarnRunnerCommands Version(Action<YarnVersionSettings> versionSettings = null);

        /// <summary>
        /// execute 'yarn audit' with options
        /// </summary>
        /// <param name="auditSettings">options when running 'yarn audit'</param>
        /// <returns></returns>
        IYarnRunnerCommands Audit(Action<YarnAuditSettings> auditSettings = null);
    }
}

Fix 'yarn audit'. Register the Audit alias

Fixes commit cd2e060948ba57c64798fa551b3a33cc6a792314


/* Copyright 2014 Jonathan Holland.
*
*  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 Microsoft.Practices.Unity;
using Wave.Configuration;
using Wave.IoC.Unity;

namespace Wave
{
    public static class FluentConfigurationSourceExtensions
    {
        public static FluentConfigurationSource UseUnity(this FluentConfigurationSource builder, UnityContainer container)
        {
            return builder.UsingContainer(new UnityContainerAdapter(container));
        }
    }
}

/* Copyright 2014 Jonathan Holland.
*
*  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 Microsoft.Practices.Unity;
using Wave.Configuration;
using Wave.IoC.Unity;

namespace Wave
{
    public static class FluentConfigurationSourceExtensions
    {
        public static FluentConfigurationSource UseUnity(this FluentConfigurationSource builder, IUnityContainer container)
        {
            return builder.UsingContainer(new UnityContainerAdapter(container));
        }
    }
}

Use interface, not concrete type, for Unity Fluent extension.


// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
//   https://www.imagemagick.org/script/license.php
//
// 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 ImageMagick;
using Xunit;

namespace Magick.NET.Tests
{
    public partial class MagickImageTests
    {
        public class TheAddNoiseMethod
        {
            [Fact]
            public void ShouldCreateDifferentImagesEachRun()
            {
                using (var imageA = new MagickImage(MagickColors.Black, 10, 10))
                {
                    using (var imageB = new MagickImage(MagickColors.Black, 10, 10))
                    {
                        imageA.AddNoise(NoiseType.Random);
                        imageB.AddNoise(NoiseType.Random);

                        Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared));
                    }
                }
            }
        }
    }
}

// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
//   https://www.imagemagick.org/script/license.php
//
// 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 ImageMagick;
using Xunit;

namespace Magick.NET.Tests
{
    public partial class MagickImageTests
    {
        public class TheAddNoiseMethod
        {
            [Fact]
            public void ShouldCreateDifferentImagesEachRun()
            {
                using (var imageA = new MagickImage(MagickColors.Black, 100, 100))
                {
                    imageA.AddNoise(NoiseType.Random);

                    using (var imageB = new MagickImage(MagickColors.Black, 100, 100))
                    {
                        imageB.AddNoise(NoiseType.Random);

                        Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared));
                    }
                }
            }
        }
    }
}

Test with a slightly larger image.

Test with a slightly larger image.


using System.Collections;
using System.Reflection;
using UnityEngine;

public class CoroutineModComponentSolver : ComponentSolver
{
    public CoroutineModComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller, MethodInfo processMethod, Component commandComponent) :
        base(bombCommander, bombComponent, ircConnection, canceller)
    {
        ProcessMethod = processMethod;
        CommandComponent = commandComponent;
    }

    protected override IEnumerator RespondToCommandInternal(string inputCommand)
    {
        IEnumerator responseCoroutine = (IEnumerator)ProcessMethod.Invoke(CommandComponent, new object[] { inputCommand });
        if (responseCoroutine == null)
        {
            yield break;
        }

        yield return "modcoroutine";

        while (responseCoroutine.MoveNext())
        {
            yield return responseCoroutine.Current;
        }
    }

    private readonly MethodInfo ProcessMethod = null;
    private readonly Component CommandComponent = null;
}

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

public class CoroutineModComponentSolver : ComponentSolver
{
    public CoroutineModComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller, MethodInfo processMethod, Component commandComponent) :
        base(bombCommander, bombComponent, ircConnection, canceller)
    {
        ProcessMethod = processMethod;
        CommandComponent = commandComponent;
    }

    protected override IEnumerator RespondToCommandInternal(string inputCommand)
    {
        IEnumerator responseCoroutine = (IEnumerator)ProcessMethod.Invoke(CommandComponent, new object[] { inputCommand });
        if (responseCoroutine == null)
        {
            yield break;
        }

        yield return "modcoroutine";

        while (responseCoroutine.MoveNext())
        {
            object currentObject = responseCoroutine.Current;
            if (currentObject.GetType() == typeof(KMSelectable))
            {
                KMSelectable selectable = (KMSelectable)currentObject;
                if (HeldSelectables.Contains(selectable))
                {
                    DoInteractionEnd(selectable);
                    HeldSelectables.Remove(selectable);
                }
                else
                {
                    DoInteractionStart(selectable);
                    HeldSelectables.Add(selectable);
                }
            }
            yield return currentObject;
        }
    }

    private readonly MethodInfo ProcessMethod = null;
    private readonly Component CommandComponent = null;
    private readonly List<KMSelectable> HeldSelectables = new List<KMSelectable>();
}

Add option to yield return a KMSelectable to toggle-interact with.


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace AsyncRewriter
{
    /// <summary>
    /// </summary>
    /// <remarks>
    /// http://stackoverflow.com/questions/2961753/how-to-hide-files-generated-by-custom-tool-in-visual-studio
    /// </remarks>
    public class RewriteAsync : Microsoft.Build.Utilities.Task
    {
        [Required]
        public ITaskItem[] InputFiles { get; set; }
        [Required]
        public ITaskItem OutputFile { get; set; }

        readonly Rewriter _rewriter;

        public RewriteAsync()
        {
            _rewriter = new Rewriter(new TaskLoggingAdapter(Log));
        }

        public override bool Execute()
        {
            var asyncCode = _rewriter.RewriteAndMerge(InputFiles.Select(f => f.ItemSpec).ToArray());
            File.WriteAllText(OutputFile.ItemSpec, asyncCode);
            return true;
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace AsyncRewriter
{
    /// <summary>
    /// </summary>
    /// <remarks>
    /// http://stackoverflow.com/questions/2961753/how-to-hide-files-generated-by-custom-tool-in-visual-studio
    /// </remarks>
    public class RewriteAsync : Microsoft.Build.Utilities.Task
    {
        [Required]
        public ITaskItem[] InputFiles { get; set; }
        [Required]
        public ITaskItem OutputFile { get; set; }

        readonly Rewriter _rewriter;

        public RewriteAsync()
        {
            _rewriter = Log == null ? new Rewriter() : new Rewriter(new TaskLoggingAdapter(Log));
        }

        public override bool Execute()
        {
            var asyncCode = _rewriter.RewriteAndMerge(InputFiles.Select(f => f.ItemSpec).ToArray());
            File.WriteAllText(OutputFile.ItemSpec, asyncCode);
            return true;
        }
    }
}

Fix null reference exception when running under Mono

When running under Mono, Log property is null and then, Rewriter throws NullReferenceExceptions when trying to use the underlying Log.

When Log is null, use the default Rewriter constructor which uses a Console logger.


using System;
using System.Diagnostics;
using System.Threading;

namespace Xamarin.Forms.Controls.Issues
{
	public partial class Bugzilla42069_Page : ContentPage
	{
		public const string DestructorMessage = ">>>>>>>>>> Bugzilla42069_Page destructor <<<<<<<<<<";

		public Bugzilla42069_Page()
		{
			InitializeComponent();

			ImageWhichChanges = ImageSource.FromFile("oasissmall.jpg") as FileImageSource;

			ChangingImage.SetBinding(Image.SourceProperty, nameof(ImageWhichChanges));

			Button.Clicked += (sender, args) => Navigation.PopAsync(false);

			Button2.Clicked += (sender, args) =>
			{
				ImageWhichChanges.File = ImageWhichChanges.File == "bank.png" ? "oasissmall.jpg" : "bank.png";
			};

			BindingContext = this;
		}

		~Bugzilla42069_Page()
		{
			Debug.WriteLine(DestructorMessage);
		}

		public FileImageSource ImageWhichChanges { get; set; }
	}
}

using System;
using System.Diagnostics;
using System.Threading;

namespace Xamarin.Forms.Controls.Issues
{
	public partial class Bugzilla42069_Page : ContentPage
	{
		public const string DestructorMessage = ">>>>>>>>>> Bugzilla42069_Page destructor <<<<<<<<<<";

		public Bugzilla42069_Page()
		{
			#if APP
			InitializeComponent();

			ImageWhichChanges = ImageSource.FromFile("oasissmall.jpg") as FileImageSource;

			ChangingImage.SetBinding(Image.SourceProperty, nameof(ImageWhichChanges));

			Button.Clicked += (sender, args) => Navigation.PopAsync(false);

			Button2.Clicked += (sender, args) =>
			{
				ImageWhichChanges.File = ImageWhichChanges.File == "bank.png" ? "oasissmall.jpg" : "bank.png";
			};

			BindingContext = this;
			#endif
		}

		~Bugzilla42069_Page()
		{
			Debug.WriteLine(DestructorMessage);
		}

		public FileImageSource ImageWhichChanges { get; set; }
	}
}

Add missing compiler directives to fix build error


using System;
using Microsoft.Extensions.DependencyInjection;

namespace Castle.Windsor.MsDependencyInjection
{
    public class WindsorServiceProviderFactory : IServiceProviderFactory<IWindsorContainer>
    {
        public IWindsorContainer CreateBuilder(IServiceCollection services)
        {
            var container = services.GetSingletonServiceOrNull<IWindsorContainer>();

            if (container == null)
            {
                container = new WindsorContainer();
                services.AddSingleton(container);
            }

            WindsorRegistrationHelper.AddServices(container, services);

            return container;
        }

        public IServiceProvider CreateServiceProvider(IWindsorContainer containerBuilder)
        {
            return containerBuilder.Resolve<IServiceProvider>();
        }
    }
}

using System;
using Microsoft.Extensions.DependencyInjection;

namespace Castle.Windsor.MsDependencyInjection
{
    public class WindsorServiceProviderFactory : IServiceProviderFactory<IWindsorContainer>
    {
        public IWindsorContainer CreateBuilder(IServiceCollection services)
        {
            var container = services.GetSingletonServiceOrNull<IWindsorContainer>();

            if (container == null)
            {
                container = new WindsorContainer();
                services.AddSingleton(container);
            }

            container.AddServices(services);

            return container;
        }

        public IServiceProvider CreateServiceProvider(IWindsorContainer containerBuilder)
        {
            return containerBuilder.Resolve<IServiceProvider>();
        }
    }
}

Use extension method for WindsorRegistrationHelper.AddServices


using NUnit.Framework;

namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
    public class MyDatabaseSettings
    {
        public string ConnectionString { get; } = $@"{TestContext.CurrentContext.TestDirectory}\Tests.db";
    }
}

using NUnit.Framework;

namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
    public class MyDatabaseSettings : IMyDatabaseSettings
    {
        public string ConnectionString { get; } = $@"Data Source={TestContext.CurrentContext.TestDirectory}\Tests.db;Version=3;New=True;BinaryGUID=False;";
    }
}

Add interface as resharper forgot

Add interface as resharper forgot


using System;
using System.Collections.Generic;

namespace ChamberLib
{
    public interface IModel
    {
        object Tag { get; set; }

        IEnumerable<IMesh> GetMeshes();

        void Draw(Matrix world, Matrix view, Matrix projection,
            IMaterial materialOverride=null,
            LightingData? lightingOverride=null);

        IBone Root { get; set; }

        void SetAmbientLightColor(Vector3 value);
        void SetEmissiveColor(Vector3 value);
        void SetDirectionalLight(DirectionalLight light, int index=0);
        void DisableDirectionalLight(int index);

        void SetAlpha(float alpha);

        void SetTexture(ITexture2D texture);

        void SetBoneTransforms(Matrix[] boneTransforms,
            IMaterial materialOverride=null);

        IEnumerable<Triangle> EnumerateTriangles();
    }

    public static class ModelHelper
    {
        public static Vector3? IntersectClosest(this IModel model, Ray ray)
        {
            Vector3? closest = null;
            float closestDist = -1;

            foreach (var tri in model.EnumerateTriangles())
            {
                var p = tri.Intersects(ray);
                if (!p.HasValue) continue;

                if (!closest.HasValue)
                {
                    closest = p;
                }
                else
                {
                    var dist = (p.Value - ray.Position).LengthSquared();
                    if (dist < closestDist)
                    {
                        closest = p;
                        closestDist = dist;
                    }
                }
            }

            return closest;
        }
    }
}

using System;
using System.Collections.Generic;

namespace ChamberLib
{
    public interface IModel
    {
        object Tag { get; set; }

        IEnumerable<IMesh> GetMeshes();

        void Draw(Matrix world, Matrix view, Matrix projection,
            IMaterial materialOverride=null,
            LightingData? lightingOverride=null);

        IBone Root { get; set; }

        void SetAmbientLightColor(Vector3 value);
        void SetEmissiveColor(Vector3 value);
        void SetDirectionalLight(DirectionalLight light, int index=0);
        void DisableDirectionalLight(int index);

        void SetAlpha(float alpha);

        void SetTexture(ITexture2D texture);

        void SetBoneTransforms(Matrix[] boneTransforms,
            IMaterial materialOverride=null);

        IEnumerable<Triangle> EnumerateTriangles();
    }

    public static class ModelHelper
    {
        public static Vector3? IntersectClosest(this IModel model, Ray ray)
        {
            Vector3? closest = null;
            float closestDist = -1;

            foreach (var tri in model.EnumerateTriangles())
            {
                var p = tri.Intersects(ray);
                if (!p.HasValue) continue;

                if (!closest.HasValue)
                {
                    closest = p;
                    closestDist = (p.Value - ray.Position).LengthSquared();
                }
                else
                {
                    var dist = (p.Value - ray.Position).LengthSquared();
                    if (dist < closestDist)
                    {
                        closest = p;
                        closestDist = dist;
                    }
                }
            }

            return closest;
        }
    }
}

Update the closest known distance.

Update the closest known distance.


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

namespace Microsoft.Diagnostics.EventFlow.Configuration
{
    public class ElasticSearchMappingsConfiguration
    {
        public Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor> Properties { get; private set; }

        public ElasticSearchMappingsConfiguration()
        {
            Properties = new Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor>();
        }

        internal ElasticSearchMappingsConfiguration DeepClone()
        {
            var other = new ElasticSearchMappingsConfiguration();

            foreach (var item in this.Properties)
            {
                other.Properties.Add(item.Key, item.Value.DeepClone());
            }

            return other;
        }
    }
}

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

namespace Microsoft.Diagnostics.EventFlow.Configuration
{
    public class ElasticSearchMappingsConfiguration
    {
        public Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor> Properties { get; set; }

        public ElasticSearchMappingsConfiguration()
        {
            Properties = new Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor>();
        }

        internal ElasticSearchMappingsConfiguration DeepClone()
        {
            var other = new ElasticSearchMappingsConfiguration();

            foreach (var item in this.Properties)
            {
                other.Properties.Add(item.Key, item.Value.DeepClone());
            }

            return other;
        }
    }
}

Make ES mapping configuration Properties setter public

(emphasizes the use of the property during deserialization)


using System.IO;
using JetBrains.Annotations;
using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.FeaturesTestFramework.Daemon;
using JetBrains.ReSharper.Psi;
using XmlDocInspections.Plugin.Highlighting;

namespace XmlDocInspections.Plugin.Tests.Integrative
{
    public abstract class MissingXmlDocHighlightingTestsBase : CSharpHighlightingTestNet4Base
    {
        protected override string RelativeTestDataPath => "Highlighting";

        protected override string GetGoldTestDataPath(string fileName)
        {
            return base.GetGoldTestDataPath(Path.Combine(GetType().Name, fileName));
        }

        protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile sourceFile)
        {
            return highlighting is MissingXmlDocHighlighting;
        }

        protected override void DoTestSolution(params string[] fileSet)
        {
            ExecuteWithinSettingsTransaction(settingsStore =>
            {
                RunGuarded(() => MutateSettings(settingsStore));
                base.DoTestSolution(fileSet);
            });
        }

        protected abstract void MutateSettings([NotNull] IContextBoundSettingsStore settingsStore);
    }
}

using System.IO;
using JetBrains.Annotations;
using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.FeaturesTestFramework.Daemon;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.TestFramework;
using XmlDocInspections.Plugin.Highlighting;

namespace XmlDocInspections.Plugin.Tests.Integrative
{
    [TestNetFramework4]
    public abstract class MissingXmlDocHighlightingTestsBase : CSharpHighlightingTestBase
    {
        protected override string RelativeTestDataPath => "Highlighting";

        protected override string GetGoldTestDataPath(string fileName)
        {
            return base.GetGoldTestDataPath(Path.Combine(GetType().Name, fileName));
        }

        protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile sourceFile)
        {
            return highlighting is MissingXmlDocHighlighting;
        }

        protected override void DoTestSolution(params string[] fileSet)
        {
            ExecuteWithinSettingsTransaction(settingsStore =>
            {
                RunGuarded(() => MutateSettings(settingsStore));
                base.DoTestSolution(fileSet);
            });
        }

        protected abstract void MutateSettings([NotNull] IContextBoundSettingsStore settingsStore);
    }
}

Replace CSharpHighlightingTestBase (will be removed in 2016.2 SDK) usage with TestNetFramework4-attribute


using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure;
using Newtonsoft.Json;
using NLog;
using SFA.DAS.EmployerApprenticeshipsService.Domain;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces;

namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services
{
    public class CompaniesHouseEmployerVerificationService : IEmployerVerificationService
    {
        private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
        private readonly string _apiKey;

        public CompaniesHouseEmployerVerificationService(string apiKey)
        {
            _apiKey = apiKey;
        }

        public async Task<EmployerInformation> GetInformation(string id)
        {
            Logger.Info($"GetInformation({id})");

            var webClient = new WebClient();

            webClient.Headers.Add($"Authorization: Basic {_apiKey}");
            try
            {
                var result = await webClient.DownloadStringTaskAsync($"https://api.companieshouse.gov.uk/company/{id}");

                return JsonConvert.DeserializeObject<EmployerInformation>(result);
            }
            catch (WebException ex)
            {
                Logger.Error(ex, "There was a problem with the call to Companies House");
            }

            return null;
        }
    }
}

using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NLog;
using SFA.DAS.EmployerApprenticeshipsService.Domain;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces;

namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services
{
    public class CompaniesHouseEmployerVerificationService : IEmployerVerificationService
    {
        private readonly EmployerApprenticeshipsServiceConfiguration _configuration;
        private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

        public CompaniesHouseEmployerVerificationService(EmployerApprenticeshipsServiceConfiguration configuration)
        {
            _configuration = configuration;
        }

        public async Task<EmployerInformation> GetInformation(string id)
        {
            Logger.Info($"GetInformation({id})");

            var webClient = new WebClient();

            webClient.Headers.Add($"Authorization: Basic {_configuration.CompaniesHouse.ApiKey}");
            try
            {
                var result = await webClient.DownloadStringTaskAsync($"https://api.companieshouse.gov.uk/company/{id}");

                return JsonConvert.DeserializeObject<EmployerInformation>(result);
            }
            catch (WebException ex)
            {
                Logger.Error(ex, "There was a problem with the call to Companies House");
            }

            return null;
        }
    }
}

Modify the companies house verification service to use the config initalised as a constructor parameter


using AutoMapper;
using Esfa.Vacancy.Api.Types;
using Esfa.Vacancy.Register.Api;
using Esfa.Vacancy.Register.Application.Queries.SearchApprenticeshipVacancies;
using FluentAssertions;
using NUnit.Framework;

namespace Esfa.Vacancy.Register.UnitTests.SearchApprenticeship.Api.GivenSearchApprenticeshipParameters
{
    [TestFixture]
    public class AndPageNumber
    {
        private IMapper _mapper;

        [SetUp]
        public void Setup()
        {
            var config = AutoMapperConfig.Configure();
            _mapper = config.CreateMapper();
        }

        [Test]
        public void WhenProvided_ThenPopulateRequestWithTheGivenValue()
        {
            var expectedPageNumber = 2;
            var parameters = new SearchApprenticeshipParameters() { PageNumber = expectedPageNumber };
            var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters);
            result.PageNumber.Should().Be(expectedPageNumber);
        }

        [Test]
        public void WhenNotProvided_ThenPoplateRequestWithTheDefaultValue()
        {
            var parameters = new SearchApprenticeshipParameters();
            var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters);
            result.PageNumber.Should().Be(1);
        }
    }
}

using AutoMapper;
using Esfa.Vacancy.Api.Types;
using Esfa.Vacancy.Register.Api;
using Esfa.Vacancy.Register.Application.Queries.SearchApprenticeshipVacancies;
using FluentAssertions;
using NUnit.Framework;

namespace Esfa.Vacancy.Register.UnitTests.SearchApprenticeship.Api.GivenSearchApprenticeshipParameters
{
    [TestFixture]
    public class AndPageNumber
    {
        private IMapper _mapper;

        [SetUp]
        public void Setup()
        {
            var config = AutoMapperConfig.Configure();
            _mapper = config.CreateMapper();
        }

        [Test]
        public void WhenProvided_ThenPopulateRequestWithTheGivenValue()
        {
            var expectedPageNumber = 2;
            var parameters = new SearchApprenticeshipParameters() { PageNumber = expectedPageNumber };
            var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters);
            result.PageNumber.Should().Be(expectedPageNumber);
        }

        [Test]
        public void WhenNotProvided_ThenPopulateRequestWithTheDefaultValue()
        {
            var parameters = new SearchApprenticeshipParameters();
            var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters);
            result.PageNumber.Should().Be(1);
        }
    }
}

Fix spelling error in method name

Fix spelling error in method name


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

using System.Text;
using UnityEngine;

namespace HoloToolkit.Unity
{
    public static class TransformExtensions
    {
        /// <summary>
        /// An extension method that will get you the full path to an object.
        /// </summary>
        /// <param name="transform">The transform you wish a full path to.</param>
        /// <param name="delimiter">The delimiter with which each object is delimited in the string.</param>
        /// <param name="prefix">Prefix with which the full path to the object should start.</param>
        /// <returns>A delimited string that is the full path to the game object in the hierarchy.</returns>
        public static string GetFullPath(this Transform transform, string delimiter = ".", string prefix = "/")
        {
            StringBuilder stringBuilder = new StringBuilder();
            if (transform.parent == null)
            {
                stringBuilder.Append(prefix);
                stringBuilder.Append(transform.name);
            }
            else
            {
                stringBuilder.Append(transform.parent.GetFullPath(delimiter, prefix));
                stringBuilder.Append(delimiter);
                stringBuilder.Append(transform.name);
            }

            return stringBuilder.ToString();
        }
    }
}

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

using System.Text;
using UnityEngine;

namespace HoloToolkit.Unity
{
    public static class TransformExtensions
    {
        /// <summary>
        /// An extension method that will get you the full path to an object.
        /// </summary>
        /// <param name="transform">The transform you wish a full path to.</param>
        /// <param name="delimiter">The delimiter with which each object is delimited in the string.</param>
        /// <param name="prefix">Prefix with which the full path to the object should start.</param>
        /// <returns>A delimited string that is the full path to the game object in the hierarchy.</returns>
        public static string GetFullPath(this Transform transform, string delimiter = ".", string prefix = "/")
        {
            StringBuilder stringBuilder = new StringBuilder();
            GetFullPath(stringBuilder, transform, delimiter, prefix);
            return stringBuilder.ToString();
        }

        private static void GetFullPath(StringBuilder stringBuilder, Transform transform, string delimiter = ".", string prefix = "/")
        {
            if (transform.parent == null)
            {
                stringBuilder.Append(prefix);
            }
            else
            {
                GetFullPath(stringBuilder, transform.parent, delimiter, prefix);
                stringBuilder.Append(delimiter);
            }
            stringBuilder.Append(transform.name);
        }
    }
}

Create one single instance of StringBuilder


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;

namespace webscripthook_android
{
    [Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor)]
    public class WebActivity : Activity
    {
        WebView webView;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Window.AddFlags(WindowManagerFlags.KeepScreenOn);
            Window.RequestFeature(WindowFeatures.NoTitle);

            SetContentView(Resource.Layout.Web);

            webView = FindViewById<WebView>(Resource.Id.webView1);
            webView.Settings.JavaScriptEnabled = true;
            webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser

            if (savedInstanceState == null)
            {
                webView.LoadUrl(Intent.GetStringExtra("Address"));
            }
        }

        public override void OnBackPressed()
        {
            if (webView.CanGoBack())
            {
                webView.GoBack();
            }
            else
            {
                base.OnBackPressed();
            }
        }

        protected override void OnSaveInstanceState (Bundle outState)
        {
            base.OnSaveInstanceState(outState);
            webView.SaveState(outState);
        }

        protected override void OnRestoreInstanceState(Bundle savedInstanceState)
        {
            base.OnRestoreInstanceState(savedInstanceState);
            webView.RestoreState(savedInstanceState);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;

namespace webscripthook_android
{
    [Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor,
        ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize)]
    public class WebActivity : Activity
    {
        WebView webView;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Window.AddFlags(WindowManagerFlags.KeepScreenOn);
            Window.RequestFeature(WindowFeatures.NoTitle);

            SetContentView(Resource.Layout.Web);

            webView = FindViewById<WebView>(Resource.Id.webView1);
            webView.Settings.JavaScriptEnabled = true;
            webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser

            if (savedInstanceState == null)
            {
                webView.LoadUrl(Intent.GetStringExtra("Address"));
            }
        }

        public override void OnBackPressed()
        {
            if (webView.CanGoBack())
            {
                webView.GoBack();
            }
            else
            {
                base.OnBackPressed();
            }
        }
    }
}

Stop webview from reloading when rotated


@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel

Login successful

<form id="mainForm" method="post" action="@Model.ResponseFormUri">

Please wait...

    @Html.Raw(Model.ResponseFormFields)

It appears you do not have javascript enabled. Please click the continue button to complete your login.

        <button type="submit" class="button" autofocus="autofocus">Continue</button>

</form>

@section scripts
{

}

@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel
@{
    ViewBag.PageID = "authorize-response";
    ViewBag.Title = "Login Successful";
    ViewBag.HideSigninLink = "true";
}

Login successful

<form id="mainForm" method="post" action="@Model.ResponseFormUri">

Please wait...

    @Html.Raw(Model.ResponseFormFields)

It appears you do not have javascript enabled. Please click the continue button to complete your login.

        <button type="submit" class="button" autofocus="autofocus">Continue</button>

</form>

@section scripts
{

}

Fix h1 class to match other views

Fix h1 class to match other views