using System;
using Grpc.Core;
using Hello;

namespace HelloClient
{
	class Program
	{
		public static void Main(string[] args)
		{
			Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);

			var client = new HelloService.HelloServiceClient(channel);
			String user = "Euler";

			var reply = client.SayHello(new HelloReq { Name = user });
			Console.WriteLine(reply.Result);

			channel.ShutdownAsync().Wait();
			Console.WriteLine("Press any key to exit...");
			Console.ReadKey();
		}
	}
}

using System;
using Grpc.Core;
using Hello;

namespace HelloClient
{
	class Program
	{
		public static void Main(string[] args)
		{
			Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);

			var client = new HelloService.HelloServiceClient(channel);
			// ideally you should check for errors here too
			var reply = client.SayHello(new HelloReq { Name = "Euler" });
			Console.WriteLine(reply.Result);

			try
			{
				reply = client.SayHelloStrict(new HelloReq { Name = "Leonhard Euler" });
				Console.WriteLine(reply.Result);
			}
			catch (RpcException e)
			{
				// ouch!
				// lets print the gRPC error message
				// which is "Length of `Name` cannot be more than 10 characters"
				Console.WriteLine(e.Status.Detail);
				// lets access the error code, which is `INVALID_ARGUMENT`
				Console.WriteLine(e.Status.StatusCode);
				// Want its int version for some reason?
				// you shouldn't actually do this, but if you need for debugging,
				// you can access `e.Status.StatusCode` which will give you `3`
				Console.WriteLine((int)e.Status.StatusCode);
				// Want to take specific action based on specific error?
				if (e.Status.StatusCode == Grpc.Core.StatusCode.InvalidArgument) {
					// do your thing
				}
			}

			channel.ShutdownAsync().Wait();
			Console.WriteLine("Press any key to exit...");
			Console.ReadKey();
		}
	}
}

Add error handling for the client

Add error handling for the client


@model IEnumerable

@{
    ViewData["Title"] = "Home Page";
}

Home

Kentico Cloud

Sign up

Kentico Cloud Boilerplate

Let's Get Started

This boilerplate includes a set of features and best practices to kick off your website development with Kentico Cloud smoothly. Take a look into the code how this page works.

Read the Quick Start

Articles from the Dancing Goat Sample Site

    @*
        This MVC helper method ensures that current model is rendered
        with suitable view from /Views/Shared/DisplayTemplates
    *@
    @Html.DisplayForModel()

@model IEnumerable

@{
    ViewData["Title"] = "Home Page";
}

Home

Kentico Cloud

Sign up

Kentico Cloud Boilerplate

Let's Get Started

This boilerplate includes a set of features and best practices to kick off your website development with Kentico Cloud smoothly. Take a look into the code to see how it works.

Read the Quick Start

Articles from the Dancing Goat Sample Site

    @*
        This MVC helper method ensures that current model is rendered
        with suitable view from /Views/Shared/DisplayTemplates
    *@
    @Html.DisplayForModel()

Correct copy on the home page

Correct copy on the home page

The last sentence in the jumbotron on home page is missing a verb.


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

namespace Manatee.Json.Serialization.Internal.AutoRegistration
{
	internal class StackSerializationDelegateProvider : SerializationDelegateProviderBase
	{
		public override bool CanHandle(Type type)
		{
			return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>);
		}

		private static JsonValue _Encode<T>(Stack<T> stack, JsonSerializer serializer)
		{
			var array = new JsonArray();
			for (int i = 0; i < stack.Count; i++)
			{
				array.Add(serializer.Serialize(stack.ElementAt(i)));
			}
			return array;
		}
		private static Stack<T> _Decode<T>(JsonValue json, JsonSerializer serializer)
		{
			var stack = new Stack<T>();
			for (int i = 0; i < json.Array.Count; i++)
			{
				stack.Push(serializer.Deserialize<T>(json.Array[i]));
			}
			return stack;
		}
	}
}

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

namespace Manatee.Json.Serialization.Internal.AutoRegistration
{
	internal class StackSerializationDelegateProvider : SerializationDelegateProviderBase
	{
		public override bool CanHandle(Type type)
		{
			return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>);
		}

		private static JsonValue _Encode<T>(Stack<T> stack, JsonSerializer serializer)
		{
			var values = new JsonValue[stack.Count];
			for (int i = 0; i < values.Length; i++)
			{
				values[0] = serializer.Serialize(stack.ElementAt(i));
			}
			return new JsonArray(values);
		}
		private static Stack<T> _Decode<T>(JsonValue json, JsonSerializer serializer)
		{
			var array = json.Array;
			var values = new T[array.Count];
			for (int i = 0; i < values.Length; i++)
			{
				values[i] = serializer.Deserialize<T>(array[i]);
			}
			return new Stack<T>(values);
		}
	}
}

Decrease allocations in stack serializer


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace HeadRaceTimingSite.Models
{
    public class Crew
    {
        public int CrewId { get; set; }
        public string Name { get; set; }
        public int StartNumber { get; set; }

        public List<Result> Results { get; set; }

        public int CompetitionId { get; set; }
        public Competition Competition { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace HeadRaceTimingSite.Models
{
    public class Crew
    {
        public int CrewId { get; set; }
        public string Name { get; set; }
        public int StartNumber { get; set; }

        public TimeSpan? RunTime(TimingPoint startPoint, TimingPoint finishPoint)
        {
            Result start = Results.First(r => r.TimingPointId == startPoint.TimingPointId);
            Result finish = Results.First(r => r.TimingPointId == finishPoint.TimingPointId);

            if (start != null && finish != null)
                return finish.TimeOfDay - start.TimeOfDay;
            else
                return null;
        }

        public List<Result> Results { get; set; }

        public int CompetitionId { get; set; }
        public Competition Competition { get; set; }
    }
}

Add method to calculate time

Add method to calculate time


#if NETFX_CORE
namespace HelixToolkit.UWP
#else
namespace HelixToolkit.Wpf.SharpDX
#endif
{
    using Model.Scene;
    /// <summary>
    /// Highlight the border of meshes
    /// </summary>
    public class PostEffectMeshBorderHighlight : PostEffectMeshOutlineBlur
    {
        protected override SceneNode OnCreateSceneNode()
        {
            return new NodePostEffectMeshOutlineBlur();
        }
    }
}

#if NETFX_CORE
namespace HelixToolkit.UWP
#else
namespace HelixToolkit.Wpf.SharpDX
#endif
{
    using Model.Scene;
    /// <summary>
    /// Highlight the border of meshes
    /// </summary>
    public class PostEffectMeshBorderHighlight : PostEffectMeshOutlineBlur
    {
        protected override SceneNode OnCreateSceneNode()
        {
            return new NodePostEffectBorderHighlight();
        }
    }
}

Fix border highlight effects gets the wrong effect node


#region Copyright 2014 Exceptionless

// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//     http://www.gnu.org/licenses/agpl-3.0.html

#endregion

using System;
using System.Threading.Tasks;
using CodeSmith.Core.Component;
using Exceptionless.Core.Messaging;
using Exceptionless.Core.Messaging.Models;
using Exceptionless.Core.Plugins.EventProcessor;

namespace Exceptionless.Core.Pipeline {
    [Priority(80)]
    public class NotifySignalRAction : EventPipelineActionBase {
        private readonly IMessagePublisher _publisher;

        public NotifySignalRAction(IMessagePublisher publisher) {
            _publisher = publisher;
        }

        protected override bool ContinueOnError {
            get { return true; }
        }

        public override void Process(EventContext ctx) {
            Task.Factory.StartNewDelayed(1000, () => _publisher.Publish(new EventOccurrence {
                Id = ctx.Event.Id,
                OrganizationId = ctx.Event.OrganizationId,
                ProjectId = ctx.Event.ProjectId,
                StackId = ctx.Event.StackId,
                Type = ctx.Event.Type,
                IsHidden = ctx.Event.IsHidden,
                IsFixed = ctx.Event.IsFixed,
                IsNotFound = ctx.Event.IsNotFound(),
                IsRegression = ctx.IsRegression
            }));
        }
    }
}

#region Copyright 2014 Exceptionless

// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//     http://www.gnu.org/licenses/agpl-3.0.html

#endregion

using System;
using System.Threading.Tasks;
using CodeSmith.Core.Component;
using Exceptionless.Core.Messaging;
using Exceptionless.Core.Messaging.Models;
using Exceptionless.Core.Plugins.EventProcessor;

namespace Exceptionless.Core.Pipeline {
    [Priority(80)]
    public class NotifySignalRAction : EventPipelineActionBase {
        private readonly IMessagePublisher _publisher;

        public NotifySignalRAction(IMessagePublisher publisher) {
            _publisher = publisher;
        }

        protected override bool ContinueOnError {
            get { return true; }
        }

        public override void Process(EventContext ctx) {
            Task.Factory.StartNewDelayed(1500, () => _publisher.Publish(new EventOccurrence {
                Id = ctx.Event.Id,
                OrganizationId = ctx.Event.OrganizationId,
                ProjectId = ctx.Event.ProjectId,
                StackId = ctx.Event.StackId,
                Type = ctx.Event.Type,
                IsHidden = ctx.Event.IsHidden,
                IsFixed = ctx.Event.IsFixed,
                IsNotFound = ctx.Event.IsNotFound(),
                IsRegression = ctx.IsRegression
            }));
        }
    }
}

Increase the message notification delay slightly.


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

namespace Battlezeppelins.Controllers
{
    public class GameController : BaseController
    {
        public ActionResult Metadata()
        {
            Game game = Game.GetInstance(base.GetPlayer());

            if (game != null)
            {
                return Json(new { playing = true, opponent = game.opponent.name }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { playing = false }, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult Surrender()
        {
            Game game = Game.GetInstance(base.GetPlayer());

            if (game != null)
            {
                game.Surrender();
            }

            return null;
        }

        public ActionResult AddZeppelin()
        {
            Game game = Game.GetInstance(base.GetPlayer());

            string typeStr = Request.Form["type"];
            ZeppelinType type = (ZeppelinType)Enum.Parse(typeof(ZeppelinType), typeStr, true);
            int x = Int32.Parse(Request.Form["x"]);
            int y = Int32.Parse(Request.Form["y"]);
            bool rotDown = Boolean.Parse(Request.Form["rotDown"]);

            Zeppelin zeppelin = new Zeppelin(type, x, y, rotDown);
            bool zeppelinAdded = game.AddZeppelin(zeppelin);

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

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

namespace Battlezeppelins.Controllers
{
    public class GameController : BaseController
    {
        public ActionResult Metadata()
        {
            Game game = Game.GetInstance(base.GetPlayer());

            if (game != null)
            {
                return Json(new {
                    playing = true,
                    opponent = game.opponent.name,
                    gameState = game.gameState.ToString() }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { playing = false }, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult Surrender()
        {
            Game game = Game.GetInstance(base.GetPlayer());

            if (game != null)
            {
                game.Surrender();
            }

            return null;
        }

        public ActionResult AddZeppelin()
        {
            Game game = Game.GetInstance(base.GetPlayer());

            string typeStr = Request.Form["type"];
            ZeppelinType type = (ZeppelinType)Enum.Parse(typeof(ZeppelinType), typeStr, true);
            int x = Int32.Parse(Request.Form["x"]);
            int y = Int32.Parse(Request.Form["y"]);
            bool rotDown = Boolean.Parse(Request.Form["rotDown"]);

            Zeppelin zeppelin = new Zeppelin(type, x, y, rotDown);
            bool zeppelinAdded = game.AddZeppelin(zeppelin);

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

Send game state to client.

Send game state to client.


namespace Ductus.FluentDocker.Model.HostEvents
{
    /// <summary>
    /// Base evnet emitte by the docker dameon using e.g. docker events.
    /// </summary>
    /// <remarks>
    /// See docker documentation https://docs.docker.com/engine/reference/commandline/events/
    /// </remarks>
    public class Event
    {
        /// <summary>
        /// The type of the event.
        /// </summary>
        public EventType Type { get; set; }
        /// <summary>
        /// The event action
        /// </summary>
        public EventAction Action { get; set; }
    }
}

Fix formatting in events so it will build


namespace FakeItEasy.Core
{
    using System;
    using static FakeItEasy.ObjectMembers;

    internal class StrictFakeRule : IFakeObjectCallRule
    {
        private readonly StrictFakeOptions options;

        public StrictFakeRule(StrictFakeOptions options)
        {
            this.options = options;
        }

        public int? NumberOfTimesToCall => null;

        public bool IsApplicableTo(IFakeObjectCall fakeObjectCall)
        {
            if (fakeObjectCall.Method.IsSameMethodAs(EqualsMethod))
            {
                return !this.HasOption(StrictFakeOptions.AllowEquals);
            }

            if (fakeObjectCall.Method.IsSameMethodAs(GetHashCodeMethod))
            {
                return !this.HasOption(StrictFakeOptions.AllowGetHashCode);
            }

            if (fakeObjectCall.Method.IsSameMethodAs(ToStringMethod))
            {
                return !this.HasOption(StrictFakeOptions.AllowToString);
            }

            if (EventCall.TryGetEventCall(fakeObjectCall, out _))
            {
                return !this.HasOption(StrictFakeOptions.AllowEvents);
            }

            return true;
        }

        public void Apply(IInterceptedFakeObjectCall fakeObjectCall)
        {
            string message = ExceptionMessages.CallToUnconfiguredMethodOfStrictFake(fakeObjectCall);

            if (EventCall.TryGetEventCall(fakeObjectCall, out _))
            {
                message += Environment.NewLine + ExceptionMessages.HandleEventsOnStrictFakes;
            }

            throw new ExpectationException(message);
        }

        private bool HasOption(StrictFakeOptions flag) => (flag & this.options) == flag;
    }
}

namespace FakeItEasy.Core
{
    using System;
    using static FakeItEasy.ObjectMembers;

    internal class StrictFakeRule : IFakeObjectCallRule
    {
        private readonly StrictFakeOptions options;

        public StrictFakeRule(StrictFakeOptions options)
        {
            this.options = options;
        }

        public int? NumberOfTimesToCall => null;

        public bool IsApplicableTo(IFakeObjectCall fakeObjectCall)
        {
            if (fakeObjectCall.Method.HasSameBaseMethodAs(EqualsMethod))
            {
                return !this.HasOption(StrictFakeOptions.AllowEquals);
            }

            if (fakeObjectCall.Method.HasSameBaseMethodAs(GetHashCodeMethod))
            {
                return !this.HasOption(StrictFakeOptions.AllowGetHashCode);
            }

            if (fakeObjectCall.Method.HasSameBaseMethodAs(ToStringMethod))
            {
                return !this.HasOption(StrictFakeOptions.AllowToString);
            }

            if (EventCall.TryGetEventCall(fakeObjectCall, out _))
            {
                return !this.HasOption(StrictFakeOptions.AllowEvents);
            }

            return true;
        }

        public void Apply(IInterceptedFakeObjectCall fakeObjectCall)
        {
            string message = ExceptionMessages.CallToUnconfiguredMethodOfStrictFake(fakeObjectCall);

            if (EventCall.TryGetEventCall(fakeObjectCall, out _))
            {
                message += Environment.NewLine + ExceptionMessages.HandleEventsOnStrictFakes;
            }

            throw new ExpectationException(message);
        }

        private bool HasOption(StrictFakeOptions flag) => (flag & this.options) == flag;
    }
}

Allow strict Fake to permit access to overridden Object methods


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace OpenKh.Tools.LayoutViewer {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public global::System.Drawing.Color BackgroundColor {
            get {
                return ((global::System.Drawing.Color)(this["BackgroundColor"]));
            }
            set {
                this["BackgroundColor"] = value;
            }
        }
    }
}

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace OpenKh.Tools.LayoutViewer {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValue("Magenta")]
        public global::System.Drawing.Color BackgroundColor {
            get {
                return ((global::System.Drawing.Color)(this["BackgroundColor"]));
            }
            set {
                this["BackgroundColor"] = value;
            }
        }
    }
}

Set default value to BackgroundColor

Set default value to BackgroundColor


using Espera.Network;
using Newtonsoft.Json;
using System;

namespace Espera.Core
{
    public class SoundCloudSong : Song
    {
        public SoundCloudSong()
            : base(String.Empty, TimeSpan.Zero)
        { }

        [JsonProperty("artwork_url")]
        public Uri ArtworkUrl { get; set; }

        public string Description { get; set; }

        [JsonProperty("duration")]
        public int DurationMilliseconds
        {
            get { return (int)this.Duration.TotalMilliseconds; }
            set { this.Duration = TimeSpan.FromMilliseconds(value); }
        }

        public int Id { get; set; }

        [JsonProperty("streamable")]
        public bool IsStreamable { get; set; }

        public override bool IsVideo
        {
            get { return false; }
        }

        public override NetworkSongSource NetworkSongSource
        {
            get { return NetworkSongSource.Youtube; }
        }

        [JsonProperty("permalink_url")]
        public Uri PermaLinkUrl
        {
            get { return new Uri(this.OriginalPath); }
            set { this.OriginalPath = value.ToString(); }
        }

        [JsonProperty("stream_url")]
        public Uri StreamUrl
        {
            get { return new Uri(this.PlaybackPath); }
            set { this.PlaybackPath = value.ToString(); }
        }

        public User User { get; set; }
    }

    public class User
    {
        public string Username { get; set; }
    }
}

using Espera.Network;
using Newtonsoft.Json;
using System;

namespace Espera.Core
{
    public class SoundCloudSong : Song
    {
        private User user;

        public SoundCloudSong()
            : base(String.Empty, TimeSpan.Zero)
        { }

        [JsonProperty("artwork_url")]
        public Uri ArtworkUrl { get; set; }

        public string Description { get; set; }

        [JsonProperty("duration")]
        public int DurationMilliseconds
        {
            get { return (int)this.Duration.TotalMilliseconds; }
            set { this.Duration = TimeSpan.FromMilliseconds(value); }
        }

        public int Id { get; set; }

        [JsonProperty("streamable")]
        public bool IsStreamable { get; set; }

        public override bool IsVideo
        {
            get { return false; }
        }

        public override NetworkSongSource NetworkSongSource
        {
            get { return NetworkSongSource.Youtube; }
        }

        [JsonProperty("permalink_url")]
        public Uri PermaLinkUrl
        {
            get { return new Uri(this.OriginalPath); }
            set { this.OriginalPath = value.ToString(); }
        }

        [JsonProperty("stream_url")]
        public Uri StreamUrl
        {
            get { return new Uri(this.PlaybackPath); }
            set { this.PlaybackPath = value.ToString(); }
        }

        public User User
        {
            get { return this.user; }
            set
            {
                this.user = value;
                this.Artist = value.Username;
            }
        }
    }

    public class User
    {
        public string Username { get; set; }
    }
}

Set the artist to the username

Set the artist to the username


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

namespace WinUsbInit
{
    class DeviceArrivalListener : NativeWindow
    {
        // Constant value was found in the "windows.h" header file.
        private const int WM_DEVICECHANGE = 537;

        private const int DBT_DEVICEARRIVAL = 0x8000;

        private readonly WinUsbInitForm _parent;

        public DeviceArrivalListener(WinUsbInitForm parent)
        {
            parent.HandleCreated += OnHandleCreated;
            parent.HandleDestroyed += OnHandleDestroyed;
            _parent = parent;
        }

        // Listen for the control's window creation and then hook into it.
        internal void OnHandleCreated(object sender, EventArgs e)
        {
            // Window is now created, assign handle to NativeWindow.
            AssignHandle(((WinUsbInitForm)sender).Handle);
        }

        internal void OnHandleDestroyed(object sender, EventArgs e)
        {
            // Window was destroyed, release hook.
            ReleaseHandle();
        }

        protected override void WndProc(ref Message m)
        {
            // Listen for operating system messages
            if (m.Msg == WM_DEVICECHANGE && (int) m.WParam == DBT_DEVICEARRIVAL)
            {
                // Notify the form that this message was received.
                _parent.DeviceInserted();
            }
            base.WndProc(ref m);
        }
    }
}

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

namespace WinUsbInit
{
    class DeviceArrivalListener : NativeWindow
    {
        // Constant values was found in the "windows.h" header file.
        private const int WM_DEVICECHANGE = 0x219;
        private const int DBT_DEVICEARRIVAL = 0x8000;

        private readonly WinUsbInitForm _parent;

        public DeviceArrivalListener(WinUsbInitForm parent)
        {
            parent.HandleCreated += OnHandleCreated;
            parent.HandleDestroyed += OnHandleDestroyed;
            _parent = parent;
        }

        // Listen for the control's window creation and then hook into it.
        internal void OnHandleCreated(object sender, EventArgs e)
        {
            // Window is now created, assign handle to NativeWindow.
            AssignHandle(((WinUsbInitForm)sender).Handle);
        }

        internal void OnHandleDestroyed(object sender, EventArgs e)
        {
            // Window was destroyed, release hook.
            ReleaseHandle();
        }

        protected override void WndProc(ref Message m)
        {
            // Listen for operating system messages
            if (m.Msg == WM_DEVICECHANGE && (int) m.WParam == DBT_DEVICEARRIVAL)
            {
                // Notify the form that this message was received.
                _parent.DeviceInserted();
            }
            base.WndProc(ref m);
        }
    }
}

Change WM_DEVICECHANGE value to hexadecimal


using System;
using Gtk;

namespace LynnaLab
{
    [System.ComponentModel.ToolboxItem(true)]
    public partial class SpinButtonHexadecimal : Gtk.SpinButton
    {
        public SpinButtonHexadecimal() : base(0,100,1)
        {
            this.Numeric = false;
        }

        protected override int OnOutput() {
            this.Numeric = false;
            Text = "0x" + ValueAsInt.ToString("X" + Digits);
            return 1;
        }
        protected override int OnInput(out double value) {
            try {
                value = Convert.ToInt32(Text);
            }
            catch (Exception e) {
                try {
                    value = Convert.ToInt32(Text.Substring(2),16);
                }
                catch (Exception) {
                    value = Value;
                }
            }
            return 1;
        }
    }
}

using System;
using Gtk;

namespace LynnaLab
{
    [System.ComponentModel.ToolboxItem(true)]
    public partial class SpinButtonHexadecimal : Gtk.SpinButton
    {
        public SpinButtonHexadecimal() : base(0,100,1)
        {
            this.Numeric = false;
        }

        protected override int OnOutput() {
            this.Numeric = false;
            Text = "$" + ValueAsInt.ToString("X" + Digits);
            return 1;
        }
        protected override int OnInput(out double value) {
            string text = Text.Trim();
            bool success = false;
            value = Value;
            try {
                value = Convert.ToInt32(text);
                success = true;
            }
            catch (Exception e) {
            }
            try {
                if (text.Length > 0 && text[0] == '$') {
                    value = Convert.ToInt32(text.Substring(1),16);
                    success = true;
                }
            }
            catch (Exception) {
            }
            if (!success)
                value = Value;
            return 1;
        }
    }
}

Use $ for hex symbol to match wla

Use $ for hex symbol to match wla


using System;
using System.Collections.Generic;

namespace Graph
{
    /// <summary>
    /// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>.
    /// </summary>
    /// <typeparam name="V">
    /// The type used to create vertex (node) labels.
    /// </typeparam>
    /// <typeparam name="W">
    /// The type used for the edge weight.
    /// </typeparam>
    public interface IUndirectedEdge<V, W> : IEdge<V, W>, IEquatable<IUndirectedEdge<V, W>>
        where V : struct, IEquatable<V>
        where W : struct, IComparable<W>, IEquatable<W>
    {
        /// <summary>
        /// The vertices comprising the <see cref="IUndirectedEdge{V}"/>.
        /// </summary>
        ISet<V> Vertices { get; }
    }
}

using System;
using System.Collections.Generic;

namespace Graph
{
    /// <summary>
    /// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>.
    /// </summary>
    /// <typeparam name="V">
    /// The type used to create vertex (node) labels.
    /// </typeparam>
    /// <typeparam name="W">
    /// The type used for the edge weight.
    /// </typeparam>
    public interface IUndirectedEdge<V, W> : IEdge<V, W>, IEquatable<IUndirectedEdge<V, W>>
        where V : struct, IEquatable<V>
        where W : struct, IComparable<W>, IEquatable<W>
    {
    }
}

Fix signature of undirected edge

Fix signature of undirected edge


using System;
using Newtonsoft.Json;

namespace Toggl.Phoebe.Data
{
    public class ForeignKeyJsonConverter : JsonConverter
    {
        public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
        {
            var model = (Model)value;

            if (model == null) {
                writer.WriteNull ();
                return;
            }

            writer.WriteValue (model.RemoteId);
        }

        public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null) {
                return null;
            }

            var remoteId = Convert.ToInt64 (reader.Value);
            var model = Model.Manager.GetByRemoteId (objectType, remoteId);
            if (model == null) {
                model = (Model)Activator.CreateInstance (objectType);
                model.RemoteId = remoteId;
                model = Model.Update (model);
            }

            return model;
        }

        public override bool CanConvert (Type objectType)
        {
            return objectType.IsSubclassOf (typeof(Model));
        }
    }
}

using System;
using Newtonsoft.Json;

namespace Toggl.Phoebe.Data
{
    public class ForeignKeyJsonConverter : JsonConverter
    {
        public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
        {
            var model = (Model)value;

            if (model == null) {
                writer.WriteNull ();
                return;
            }

            writer.WriteValue (model.RemoteId);
        }

        public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null) {
                return null;
            }

            var remoteId = Convert.ToInt64 (reader.Value);
            var model = Model.Manager.GetByRemoteId (objectType, remoteId);
            if (model == null) {
                model = (Model)Activator.CreateInstance (objectType);
                model.RemoteId = remoteId;
                model.ModifiedAt = new DateTime ();
                model = Model.Update (model);
            }

            return model;
        }

        public override bool CanConvert (Type objectType)
        {
            return objectType.IsSubclassOf (typeof(Model));
        }
    }
}

Fix temporary models for relations.

Fix temporary models for relations.

ForeignKeyJsonConverter creates temporary models for relations when they
don't exist. However, the change in 64362cd changed the default
ModifiedAt for models, thus the temporary models became the dominant
ones and sync couldn't update them with correct data from server.


using System;
using Android.App;
using Android.Content;
using Android.Support.V4.Content;

namespace Toggl.Joey.Net
{
    [BroadcastReceiver (Permission = "com.google.android.c2dm.permission.SEND")]
    [IntentFilter (new string[] { "com.google.android.c2dm.intent.RECEIVE" },
        Categories = new string[]{ "com.toggl.timer" })]
    public class GcmBroadcastReceiver : WakefulBroadcastReceiver
    {
        public override void OnReceive (Context context, Intent intent)
        {
            var comp = new ComponentName (context,
                           Java.Lang.Class.FromType (typeof(GcmService)));
            StartWakefulService (context, (intent.SetComponent (comp)));

            ResultCode = Result.Ok;
        }
    }
}

using System;
using Android.App;
using Android.Content;
using Android.Support.V4.Content;

namespace Toggl.Joey.Net
{
    [BroadcastReceiver (Permission = "com.google.android.c2dm.permission.SEND")]
    [IntentFilter (new string[] { "com.google.android.c2dm.intent.RECEIVE" },
        Categories = new string[]{ "com.toggl.timer" })]
    public class GcmBroadcastReceiver : WakefulBroadcastReceiver
    {
        public override void OnReceive (Context context, Intent intent)
        {
            var serviceIntent = new Intent (context, typeof(GcmService));
            serviceIntent.ReplaceExtras (intent.Extras);
            StartWakefulService (context, serviceIntent);

            ResultCode = Result.Ok;
        }
    }
}

Use new intent instead of reusing broadcast one.


using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MarkdownDeep;
using SIL.IO;

namespace SIL.Windows.Forms.ReleaseNotes
{
	/// <summary>
	/// Shows a dialog for release notes; accepts html and markdown
	/// </summary>
	public partial class ShowReleaseNotesDialog : Form
	{
		private readonly string _path;
		private TempFile _temp;
		private readonly Icon _icon;

		public ShowReleaseNotesDialog(Icon icon, string path)
		{
			_path = path;
			_icon = icon;
			InitializeComponent();
		}

		private void ShowReleaseNotesDialog_Load(object sender, EventArgs e)
		{
			string contents = File.ReadAllText(_path);

			var md = new Markdown();
			_temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp
			File.WriteAllText(_temp.Path, md.Transform(contents));
			_browser.Url = new Uri(_temp.Path);
		}

		protected override void OnHandleCreated(EventArgs e)
		{
			base.OnHandleCreated(e);

			// a bug in Mono requires us to wait to set Icon until handle created.
			Icon = _icon;
		}
	}
}

using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MarkdownDeep;
using SIL.IO;

namespace SIL.Windows.Forms.ReleaseNotes
{
	///
	/// Shows a dialog for release notes; accepts html and markdown
	///
	public partial class ShowReleaseNotesDialog : Form
	{
		private readonly string _path;
		private TempFile _temp;
		private readonly Icon _icon;

		public ShowReleaseNotesDialog(Icon icon, string path)
		{
			_path = path;
			_icon = icon;
			InitializeComponent();
		}

		private void ShowReleaseNotesDialog_Load(object sender, EventArgs e)
		{
			string contents = File.ReadAllText(_path);

			var md = new Markdown();
			_temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp
			File.WriteAllText(_temp.Path, GetBasicHtmlFromMarkdown(md.Transform(contents)));
			_browser.Url = new Uri(_temp.Path);
		}

		protected override void OnHandleCreated(EventArgs e)
		{
			base.OnHandleCreated(e);

			// a bug in Mono requires us to wait to set Icon until handle created.
			Icon = _icon;
		}

		private string GetBasicHtmlFromMarkdown(string markdownHtml)
		{
			return string.Format("<meta charset=\"utf-8\"/>{0}", markdownHtml);
		}
	}
}

Set character encoding when displaying html from markdown (BL-3785)


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

namespace VasysRomanNumeralsKata
{
    public class RomanNumeral
    {
        private int? _baseTenRepresentation = null;
        public RomanNumeral(int baseTenNumber)
        {
            _baseTenRepresentation = baseTenNumber;
        }

        public string GenerateRomanNumeralRepresntation()
        {
            StringBuilder romanNumeralBuilder = new StringBuilder();
            int numberOfThousands = (int)_baseTenRepresentation / 1000;
            if (numberOfThousands > 0)
            {
                for(int i = 0; i < numberOfThousands; i++)
                {
                    romanNumeralBuilder.Append("M");
                }
            }
            int remainder = (int)_baseTenRepresentation % 1000;

            if (remainder >= 900)
            {
                romanNumeralBuilder.Append("CM");
                remainder -= 900;
            }

            if(remainder >= 500)
            {
                romanNumeralBuilder.Append("D");
                remainder -= 500;
            }

            if (remainder >= 400)
            {
                romanNumeralBuilder.Append("CD");
                remainder -= 400;
            }

            while(remainder >= 100)
            {
                romanNumeralBuilder.Append("C");
                remainder -= 100;
            }

            int numberOfTens = remainder / 10;
            if (numberOfTens > 0)
            {
                for (int i = 0; i < numberOfTens; i++)
                {
                    romanNumeralBuilder.Append("X");
                }
            }
            return romanNumeralBuilder.ToString();
        }
    }
}

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

namespace VasysRomanNumeralsKata
{
    public class RomanNumeral
    {
        private int? _baseTenRepresentation = null;
        public RomanNumeral(int baseTenNumber)
        {
            _baseTenRepresentation = baseTenNumber;
        }

        public string GenerateRomanNumeralRepresntation()
        {
            StringBuilder romanNumeralBuilder = new StringBuilder();
            int remainder = (int)_baseTenRepresentation;
            while(remainder / 1000 > 0)
            {
                romanNumeralBuilder.Append("M");
                remainder -= 1000;
            }

            if (remainder >= 900)
            {
                romanNumeralBuilder.Append("CM");
                remainder -= 900;
            }

            if(remainder >= 500)
            {
                romanNumeralBuilder.Append("D");
                remainder -= 500;
            }

            if (remainder >= 400)
            {
                romanNumeralBuilder.Append("CD");
                remainder -= 400;
            }

            while(remainder >= 100)
            {
                romanNumeralBuilder.Append("C");
                remainder -= 100;
            }

            int numberOfTens = remainder / 10;
            if (numberOfTens > 0)
            {
                for (int i = 0; i < numberOfTens; i++)
                {
                    romanNumeralBuilder.Append("X");
                }
            }
            return romanNumeralBuilder.ToString();
        }
    }
}

Refactor logic for thousands (M, MM, MMM).


using System;
using System.Reflection;

namespace AssemblyInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args != null && args.Length > 0)
            {
                Assembly asm = null;
                var name = args[0];

                try
                {
                    if (name.Substring(name.Length - 4, 4) != ".dll")
                        name += ".dll";

                    asm = Assembly.LoadFrom(name);
                }
                catch
                {
                    try
                    {
                        var path = AppDomain.CurrentDomain.BaseDirectory + @"\" + name;

                        asm = Assembly.LoadFrom(path);
                    }
                    catch (Exception e)
                    {
                        System.Console.WriteLine(e.Message);

                        return;
                    }
                }

                var x = asm.GetName();

                System.Console.WriteLine("CodeBase: {0}", x.CodeBase);
                System.Console.WriteLine("ContentType: {0}", x.ContentType);
                System.Console.WriteLine("CultureInfo: {0}", x.CultureInfo);
                System.Console.WriteLine("CultureName: {0}", x.CultureName);
                System.Console.WriteLine("FullName: {0}", x.FullName);
                System.Console.WriteLine("Name: {0}", x.Name);
                System.Console.WriteLine("Version: {0}", x.Version);
                System.Console.WriteLine("VersionCompatibility: {0}", x.VersionCompatibility);
            }
            else
            {
                System.Console.WriteLine("Usage: asminfo.exe assembly");
            }
        }
    }
}

using System;
using System.Reflection;

namespace AssemblyInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args != null && args.Length > 0)
            {
                Assembly asm = null;
                var name = args[0];

                try
                {
                    if (name.Substring(name.Length - 4, 4) != ".dll")
                    {
                        name += ".dll";
                    }

                    asm = Assembly.LoadFrom(name);
                }
                catch
                {
                    try
                    {
                        var path = AppDomain.CurrentDomain.BaseDirectory + @"\" + name;

                        asm = Assembly.LoadFrom(path);
                    }
                    catch (Exception e)
                    {
                        System.Console.WriteLine(e.Message);

                        return;
                    }
                }

                var x = asm.GetName();

                System.Console.WriteLine("CodeBase: {0}", x.CodeBase);
                System.Console.WriteLine("ContentType: {0}", x.ContentType);
                System.Console.WriteLine("CultureInfo: {0}", x.CultureInfo);
                System.Console.WriteLine("CultureName: {0}", x.CultureName);
                System.Console.WriteLine("FullName: {0}", x.FullName);
                System.Console.WriteLine("Name: {0}", x.Name);
                System.Console.WriteLine("Version: {0}", x.Version);
                System.Console.WriteLine("VersionCompatibility: {0}", x.VersionCompatibility);
            }
            else
            {
                System.Console.WriteLine("Usage: asminfo.exe assembly");
            }
        }
    }
}

Add braces for the 'if (name.Substring(... '


using System;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;

// Adapted from
// https://blogs.msdn.microsoft.com/ericwhite/2010/03/04/validate-open-xml-documents-using-the-open-xml-sdk-2-0/

namespace XlsxValidator
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			if (args.Count() == 0)
			{
				Console.WriteLine("No document given");
				return;
			}
			using (SpreadsheetDocument doc = SpreadsheetDocument.Open(args[0], false))
			{
				var validator = new OpenXmlValidator();
				var errors = validator.Validate(doc);
				if (errors.Count() == 0)
				{
					Console.WriteLine("Document is valid");
				}
				else
				{
					Console.WriteLine("Document is not valid");
				}
				Console.WriteLine();
				foreach (var error in errors)
				{
					Console.WriteLine("Error description: {0}", error.Description);
					Console.WriteLine("Content type of part with error: {0}", error.Part.ContentType);
					Console.WriteLine("Location of error: {0}", error.Path.XPath);
					Console.WriteLine();
				}
			}
		}
	}
}

using System;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;

// Adapted from
// https://blogs.msdn.microsoft.com/ericwhite/2010/03/04/validate-open-xml-documents-using-the-open-xml-sdk-2-0/

namespace XlsxValidator
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			if (args.Count() == 0)
			{
				Console.WriteLine("No document given");
				return;
			}
			var path = args[0];

			using (SpreadsheetDocument doc = SpreadsheetDocument.Open(path, false))
			{
				var validator = new OpenXmlValidator();
				var errors = validator.Validate(doc);
				if (errors.Count() == 0)
				{
					Console.WriteLine("Document is valid");
				}
				else
				{
					Console.WriteLine("Document is not valid");
				}
				Console.WriteLine();
				foreach (var error in errors)
				{
					Console.WriteLine("File: {0}", path);
					Console.WriteLine("Error: {0}", error.Description);
					Console.WriteLine("ContentType: {0}", error.Part.ContentType);
					Console.WriteLine("XPath: {0}", error.Path.XPath);
					Console.WriteLine();
				}
			}
		}
	}
}

Print filename with each error

Print filename with each error


using Microsoft.AspNetCore.Mvc;
using Xunit;

using DiceApi.WebApi.Controllers;

namespace DiceApi.WebApi.Tests
{

    /// <summary>
    /// Test class for <see cref="DieController" />.
    /// </summary>
    public class DieControllerTest
    {
        /// <summary>
        /// Verifies that Get() returns a BadRequestResult when given an invalid number
        /// of sides for the die to roll.
        /// </summary>
        [Fact]
        public void Get_GivenSidesLessThanZero_ReturnsBadRequestResult()
        {
            var sut = new DieController();

            var result = sut.Get(-1);

            Assert.Equal(typeof(BadRequestResult), result.GetType());
        }

        /// <summary>
        /// Verifies that Get() returns an OkObjectResult when given an valid number
        /// of sides for the die to roll.
        /// </summary>
        [Fact]
        public void Get_GivenValidSizeValue_ReturnsOkResult()
        {
            var sut = new DieController();

            var result = sut.Get(6);

            Assert.Equal(typeof(OkObjectResult), result.GetType());
        }
    }
}

using Microsoft.AspNetCore.Mvc;
using Xunit;

using DiceApi.WebApi.Controllers;

namespace DiceApi.WebApi.Tests
{

    /// <summary>
    /// Test class for <see cref="DieController" />.
    /// </summary>
    public class DieControllerTest
    {
        /// <summary>
        /// Verifies that Get() returns a BadRequestResult when given an invalid number
        /// of sides for the die to roll.
        /// </summary>
        [Fact]
        public void Get_GivenSidesLessThanZero_ReturnsBadRequestResult()
        {
            var sut = new DieController();

            var result = sut.Get(-1);

            Assert.Equal(typeof(BadRequestResult), result.GetType());
        }

        /// <summary>
        /// Verifies that Get() returns an OkObjectResult when given an valid number
        /// of sides for the die to roll.
        /// </summary>
        [Fact]
        public void Get_GivenValidSizeValue_ReturnsOkResult()
        {
            var sut = new DieController();

            var result = sut.Get(6);

            Assert.Equal(typeof(OkObjectResult), result.GetType());
            Assert.Equal(typeof(int), ((OkObjectResult)result).Value.GetType());
        }
    }
}

Add extra check on result type

Add extra check on result type


using System;
using Serilog;
using Serilog.Events;
using SerilogWeb.Classic;

namespace SerilogWeb.Test
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            ApplicationLifecycleModule.FormDataLoggingLevel = LogEventLevel.Debug;
            ApplicationLifecycleModule.LogPostedFormData = LogPostedFormDataOption.OnMatch;
            ApplicationLifecycleModule.ShouldLogPostedFormData = context => context.Response.StatusCode >= 400;

            // ReSharper disable once PossibleNullReferenceException
            ApplicationLifecycleModule.RequestFilter = context => context.Request.Url.PathAndQuery.StartsWith("/__browserLink");

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Trace(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}" )
                .CreateLogger();
        }
    }
}

using System;
using Serilog;
using Serilog.Events;
using SerilogWeb.Classic;

namespace SerilogWeb.Test
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            // ReSharper disable once PossibleNullReferenceException
            SerilogWebClassic.Configuration
                    .IgnoreRequestsMatching(ctx => ctx.Request.Url.PathAndQuery.StartsWith("/__browserLink"))
                    .EnableFormDataLogging(formData => formData
                                                .AtLevel(LogEventLevel.Debug)
                                                .OnMatch(ctx => ctx.Response.StatusCode >= 400));

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Trace(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}" )
                .CreateLogger();
        }
    }
}

Update sample app to use newer config API


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

namespace BrightstarDB.InternalTests
{
    internal static class TestConfiguration
    {
        public static string DataLocation = "..\\..\\Data\\";
    }
}

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

namespace BrightstarDB.InternalTests
{
    internal static class TestConfiguration
    {
        public static string DataLocation = "..\\..\\..\\Data\\";
    }
}

Fix path to internal test data location

Fix path to internal test data location


// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;

namespace CefSharp
{
	/// <summary>
	/// Event arguments to the IsBrowserInitializedChanged event handler.
	/// </summary>
	public class IsBrowserInitializedChangedEventArgs : EventArgs
	{
		public bool IsBrowserInitialized { get; private set; }

		public IsBrowserInitializedChangedEventArgs(bool isBrowserInitialized)
		{
			IsBrowserInitialized = isBrowserInitialized;
		}
	}
    };

    /// <summary>
    /// A delegate type used to listen to IsBrowserInitializedChanged events.
    /// </summary>
    public delegate void IsBrowserInitializedChangedEventHandler(object sender, IsBrowserInitializedChangedEventArgs args);
}

Fix cherry pick, spaces not tabs and remove unused delegate


using Evolve.Migration;
using System.Collections.Generic;
using Evolve.Utilities;
using Evolve.Connection;

namespace Evolve.Metadata
{
    public abstract class MetadataTable : IEvolveMetadata
    {
        protected IWrappedConnection _wrappedConnection;

        public MetadataTable(string schema, string tableName, IWrappedConnection wrappedConnection)
        {
            Schema = Check.NotNullOrEmpty(schema, nameof(schema));
            TableName = Check.NotNullOrEmpty(schema, nameof(tableName));
            _wrappedConnection = Check.NotNull(wrappedConnection, nameof(wrappedConnection));
        }

        public string Schema { get; private set; }

        public string TableName { get; private set; }

        public abstract void Lock();

        public abstract bool CreateIfNotExists();

        public void AddMigrationMetadata(MigrationScript migration, bool success)
        {
            CreateIfNotExists();
            InternalAddMigrationMetadata(migration, success);
        }

        public IEnumerable<MigrationMetadata> GetAllMigrationMetadata()
        {
            CreateIfNotExists();
            return InternalGetAllMigrationMetadata();
        }

        protected abstract bool IsExists();

        protected abstract void Create();

        protected abstract void InternalAddMigrationMetadata(MigrationScript migration, bool success);

        protected abstract IEnumerable<MigrationMetadata> InternalGetAllMigrationMetadata();
    }
}

using Evolve.Migration;
using System.Collections.Generic;
using Evolve.Utilities;
using Evolve.Connection;

namespace Evolve.Metadata
{
    public abstract class MetadataTable : IEvolveMetadata
    {
        protected IWrappedConnection _wrappedConnection;

        public MetadataTable(string schema, string tableName, IWrappedConnection wrappedConnection)
        {
            Schema = Check.NotNullOrEmpty(schema, nameof(schema));
            TableName = Check.NotNullOrEmpty(tableName, nameof(tableName));
            _wrappedConnection = Check.NotNull(wrappedConnection, nameof(wrappedConnection));
        }

        public string Schema { get; private set; }

        public string TableName { get; private set; }

        public abstract void Lock();

        public abstract bool CreateIfNotExists();

        public void AddMigrationMetadata(MigrationScript migration, bool success)
        {
            CreateIfNotExists();
            InternalAddMigrationMetadata(migration, success);
        }

        public IEnumerable<MigrationMetadata> GetAllMigrationMetadata()
        {
            CreateIfNotExists();
            return InternalGetAllMigrationMetadata();
        }

        protected abstract bool IsExists();

        protected abstract void Create();

        protected abstract void InternalAddMigrationMetadata(MigrationScript migration, bool success);

        protected abstract IEnumerable<MigrationMetadata> InternalGetAllMigrationMetadata();
    }
}

Fix tableName not correctly saved

Fix tableName not correctly saved


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

using System;
using System.IO;
using System.Runtime.InteropServices;
using PInvoke;
using Xunit;
using static PInvoke.Kernel32;

public partial class Kernel32Facts
{
    [Fact]
    public void GetTickCount_Nonzero()
    {
        uint result = GetTickCount();
        Assert.NotEqual(0u, result);
    }

    [Fact]
    public void GetTickCount64_Nonzero()
    {
        ulong result = GetTickCount64();
        Assert.NotEqual(0ul, result);
    }

    [Fact]
    public void SetLastError_ImpactsMarshalGetLastWin32Error()
    {
        SetLastError(2);
        Assert.Equal(2, Marshal.GetLastWin32Error());
    }

    [Fact]
    public unsafe void GetStartupInfo_Title()
    {
        var startupInfo = STARTUPINFO.Create();
        GetStartupInfo(ref startupInfo);
        Assert.NotNull(startupInfo.Title);
        Assert.NotEqual(0, startupInfo.Title.Length);
    }
}

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

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using PInvoke;
using Xunit;
using static PInvoke.Kernel32;

public partial class Kernel32Facts
{
    [Fact]
    public void GetTickCount_Nonzero()
    {
        uint result = GetTickCount();
        Assert.NotEqual(0u, result);
    }

    [Fact]
    public void GetTickCount64_Nonzero()
    {
        ulong result = GetTickCount64();
        Assert.NotEqual(0ul, result);
    }

    [Fact]
    public void SetLastError_ImpactsMarshalGetLastWin32Error()
    {
        SetLastError(2);
        Assert.Equal(2, Marshal.GetLastWin32Error());
    }

    [Fact]
    public unsafe void GetStartupInfo_Title()
    {
        var startupInfo = STARTUPINFO.Create();
        GetStartupInfo(ref startupInfo);
        Assert.NotNull(startupInfo.Title);
        Assert.NotEqual(0, startupInfo.Title.Length);
    }

    [Fact]
    public void GetHandleInformation_DoesNotThrow()
    {
        var manualResetEvent = new ManualResetEvent(false);
        GetHandleInformation(manualResetEvent.SafeWaitHandle, out var lpdwFlags);
    }

    [Fact]
    public void SetHandleInformation_DoesNotThrow()
    {
        var manualResetEvent = new ManualResetEvent(false);
        SetHandleInformation(
            manualResetEvent.SafeWaitHandle,
            HandleFlags.HANDLE_FLAG_INHERIT | HandleFlags.HANDLE_FLAG_PROTECT_FROM_CLOSE,
            HandleFlags.HANDLE_FLAG_NONE);
    }
}

Add tests for `kernel32!SetHandleInformation` and `kernel32!GetHandleInformation`


using UnityEngine;
using System.Collections;
using strange.extensions.context.impl;
using strange.extensions.context.api;

public class RootContext : MVCSContext, IRootContext
{

    public RootContext(MonoBehaviour view) : base(view)
    {

    }

    public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags)
    {

    }

    protected override void mapBindings()
    {
        base.mapBindings();

        GameObject managers = GameObject.Find("Managers");

        injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext();

        EventManager eventManager = managers.GetComponent<EventManager>();
        injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext();

        ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>();
        injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext();

        IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>();
        injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext();
    }

    public void Inject(Object o)
    {
        injectionBinder.injector.Inject(o);
    }
}

using UnityEngine;
using System.Collections;
using strange.extensions.context.impl;
using strange.extensions.context.api;

public class RootContext : MVCSContext, IRootContext
{

    public RootContext(MonoBehaviour view) : base(view)
    {

    }

    public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags)
    {

    }

    protected override void mapBindings()
    {
        base.mapBindings();

        GameObject managers = GameObject.Find("Managers");

        injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext();

        EventManager eventManager = managers.GetComponent<EventManager>();
        injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext();

        IMaterialManager materialManager = managers.GetComponent<MaterialManager>();
        injectionBinder.Bind<IMaterialManager>().ToValue(materialManager).ToSingleton().CrossContext();

        ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>();
        injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext();

        IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>();
        injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext();
    }

    public void Inject(Object o)
    {
        injectionBinder.injector.Inject(o);
    }
}

Add the Material Manager to the context for injection.


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

#nullable disable

using System;
using System.Linq;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Extensions;
using osu.Game.Rulesets;
using osu.Game.Scoring.Legacy;

namespace osu.Game.Scoring
{
    public class LegacyDatabasedScore : Score
    {
        public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store)
        {
            ScoreInfo = score;

            string replayFilename = score.Files.FirstOrDefault(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase))?.File.GetStoragePath();

            if (replayFilename == null)
                return;

            using (var stream = store.GetStream(replayFilename))
                Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay;
        }
    }
}

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

#nullable disable

using System;
using System.Linq;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Extensions;
using osu.Game.Rulesets;
using osu.Game.Scoring.Legacy;

namespace osu.Game.Scoring
{
    public class LegacyDatabasedScore : Score
    {
        public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store)
        {
            ScoreInfo = score;

            string replayFilename = score.Files.FirstOrDefault(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase))?.File.GetStoragePath();

            if (replayFilename == null)
                return;

            using (var stream = store.GetStream(replayFilename))
            {
                if (stream == null)
                    return;

                Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay;
            }
        }
    }
}

Fix crash when attempting to watch a replay when the storage file doesn't exist


using System;
using System.Net;
using Arango.fastJSON;

namespace Arango.Client.Protocol
{
    internal class Response
    {
        internal int StatusCode { get; set; }
        internal WebHeaderCollection Headers { get; set; }
        internal string Body { get; set; }
        internal DataType DataType { get; set; }
        internal object Data { get; set; }
        internal Exception Exception { get; set; }
        internal AEerror Error { get; set; }

        internal void DeserializeBody()
        {
            if (string.IsNullOrEmpty(Body))
            {
                DataType = DataType.Null;
                Data = null;
            }
            else
            {
                var trimmedBody = Body.Trim();

                // body contains JSON array
                if (trimmedBody[0] == '[')
                {
                    DataType = DataType.List;
                }
                // body contains JSON object
                else if (trimmedBody[0] == '{')
                {
                    DataType = DataType.Document;
                }
                else
                {
                    DataType = DataType.Primitive;
                }

                Data = JSON.Parse(trimmedBody);
            }
        }
    }
}

using System;
using System.Net;
using Arango.fastJSON;

namespace Arango.Client.Protocol
{
    internal class Response
    {
        internal int StatusCode { get; set; }
        internal WebHeaderCollection Headers { get; set; }
        internal string Body { get; set; }
        internal DataType DataType { get; set; }
        internal object Data { get; set; }
        internal Exception Exception { get; set; }
        internal AEerror Error { get; set; }

        internal void DeserializeBody()
        {
            if (string.IsNullOrEmpty(Body))
            {
                DataType = DataType.Null;
                Data = null;
            }
            else
            {
                var trimmedBody = Body.Trim();

                switch (trimmedBody[0])
                {
                    // body contains JSON array
                    case '[':
                        DataType = DataType.List;
                        break;
                    // body contains JSON object
                    case '{':
                        DataType = DataType.Document;
                        break;
                    default:
                        DataType = DataType.Primitive;
                        break;
                }

                Data = JSON.Parse(trimmedBody);
            }
        }
    }
}

Put body data type check into switch statement


using AutoMapper;
using SnittListan.Models;
using SnittListan.ViewModels;

namespace SnittListan.Infrastructure
{
	public class MatchProfile : Profile
	{
		protected override void Configure()
		{
			Mapper.CreateMap<Match, MatchViewModel>()
				.ForMember(x => x.Date, o => o.MapFrom(y => y.Date.ToShortDateString()))
				.ForMember(x => x.Results, o => o.MapFrom(y => y.FormattedLaneScore()))
				.ForMember(x => x.Teams, o => o.MapFrom(y => string.Format("{0}-{1}", y.HomeTeam, y.OppTeam)));
		}
	}
}

using System.Threading;
using AutoMapper;
using SnittListan.Models;
using SnittListan.ViewModels;

namespace SnittListan.Infrastructure
{
	public class MatchProfile : Profile
	{
		protected override void Configure()
		{
			Mapper.CreateMap<Match, MatchViewModel>()
				.ForMember(x => x.Date, o => o.MapFrom(y => y.Date.ToString(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern, Thread.CurrentThread.CurrentCulture)))
				.ForMember(x => x.Results, o => o.MapFrom(y => y.FormattedLaneScore()))
				.ForMember(x => x.Teams, o => o.MapFrom(y => string.Format("{0}-{1}", y.HomeTeam, y.OppTeam)));
		}
	}
}

Format date with user culture

Format date with user culture

Date will be formatted as short date string with user preferred culture.


using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

namespace Harmony
{
	public static class Transpilers
	{
		public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null)
		{
			if (from == null)
				throw new ArgumentException("Unexpected null argument", nameof(from));
			if (to == null)
				throw new ArgumentException("Unexpected null argument", nameof(to));

			foreach (var instruction in instructions)
			{
				var method = instruction.operand as MethodBase;
				if (method == from)
				{
					instruction.opcode = callOpcode ?? OpCodes.Call;
					instruction.operand = to;
				}
				yield return instruction;
			}
		}

		public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
		{
			yield return new CodeInstruction(OpCodes.Ldstr, text);
			yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
			foreach (var instruction in instructions) yield return instruction;
		}

		// more added soon
	}
}

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

namespace Harmony
{
	public static class Transpilers
	{
		public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to)
		{
			if (from == null)
				throw new ArgumentException("Unexpected null argument", nameof(from));
			if (to == null)
				throw new ArgumentException("Unexpected null argument", nameof(to));

			foreach (var instruction in instructions)
			{
				var method = instruction.operand as MethodBase;
				if (method == from)
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = to;
				}
				yield return instruction;
			}
		}

		public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
		{
			yield return new CodeInstruction(OpCodes.Ldstr, text);
			yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
			foreach (var instruction in instructions) yield return instruction;
		}

		// more added soon
	}
}

Revert back to old signature (transpilers get confused with multiple version); add opcode=Call


// Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.Website
{
    using System;
    using Extensions;
    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Hosting;

    /// <summary>
    /// A class representing the entry-point to the application. This class cannot be inherited.
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// The main entry-point to the application.
        /// </summary>
        /// <param name="args">The arguments to the application.</param>
        /// <returns>
        /// The exit code from the application.
        /// </returns>
        public static int Main(string[] args)
        {
            try
            {
                using (var host = BuildWebHost(args))
                {
                    host.Run();
                }

                return 0;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"Unhandled exception: {ex}");
                return -1;
            }
        }

        private static IWebHost BuildWebHost(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                .UseKestrel((p) => p.AddServerHeader = false)
                .UseAutofac()
                .UseAzureAppServices()
                .UseApplicationInsights()
                .UseStartup<Startup>()
                .CaptureStartupErrors(true)
                .Build();
        }
    }
}

// Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.Website
{
    using System;
    using System.Threading.Tasks;
    using Extensions;
    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Hosting;

    /// <summary>
    /// A class representing the entry-point to the application. This class cannot be inherited.
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// The main entry-point to the application.
        /// </summary>
        /// <param name="args">The arguments to the application.</param>
        /// <returns>
        /// A <see cref="Task{TResult}"/> that returns the exit code from the application.
        /// </returns>
        public static async Task<int> Main(string[] args)
        {
            try
            {
                using (var host = BuildWebHost(args))
                {
                    await host.RunAsync();
                }

                return 0;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"Unhandled exception: {ex}");
                return -1;
            }
        }

        private static IWebHost BuildWebHost(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                .UseKestrel((p) => p.AddServerHeader = false)
                .UseAutofac()
                .UseAzureAppServices()
                .UseApplicationInsights()
                .UseStartup<Startup>()
                .CaptureStartupErrors(true)
                .Build();
        }
    }
}

Convert Main to be async

Convert Main to be async

Convert the Main() method to be asynchronous.


using System.Windows;

namespace MilitaryPlanner.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            //InitializeComponent();
        }
    }
}

using System.Windows;

namespace MilitaryPlanner.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            //InitializeComponent();
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            base.OnClosing(e);
            // if window is minimized, restore to avoid opening minimized on next run
            if(WindowState == System.Windows.WindowState.Minimized)
            {
                WindowState = System.Windows.WindowState.Normal;
            }
        }
    }
}

Fix for saving window state while minimized on closing


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ExprOpt = Microsoft.FSharp.Core.FSharpOption<AST.Expression>;
using Expr = AST.Expression;

namespace ParcelTest
{
    [TestClass]
    class PrecedenceTests
    {
        [TestMethod]
        public void MultiplicationVsAdditionPrecedenceTest()
        {
            var mwb = MockWorkbook.standardMockWorkbook();
            var e = mwb.envForSheet(1);

            var f = "=2*3+1";

            ExprOpt asto = Parcel.parseFormula(f, e.Path, e.WorkbookName, e.WorksheetName);

            Expr correct =
                Expr.NewBinOpExpr(
                    "+",
                    Expr.NewBinOpExpr(
                        "*",
                        Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 2.0)),
                        Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 3.0))
                    ),
                    Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 1.0))
                );

            try
            {
                Expr ast = asto.Value;
                Assert.AreEqual(correct, ast);
            }
            catch (NullReferenceException nre)
            {
                Assert.Fail("Parse error: " + nre.Message);
            }
        }
    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ExprOpt = Microsoft.FSharp.Core.FSharpOption<AST.Expression>;
using Expr = AST.Expression;

namespace ParcelTest
{
    [TestClass]
    public class PrecedenceTests
    {
        [TestMethod]
        public void MultiplicationVsAdditionPrecedenceTest()
        {
            var mwb = MockWorkbook.standardMockWorkbook();
            var e = mwb.envForSheet(1);

            var f = "=2*3+1";

            ExprOpt asto = Parcel.parseFormula(f, e.Path, e.WorkbookName, e.WorksheetName);

            Expr correct =
                Expr.NewBinOpExpr(
                    "+",
                    Expr.NewBinOpExpr(
                        "*",
                        Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 2.0)),
                        Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 3.0))
                    ),
                    Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 1.0))
                );

            try
            {
                Expr ast = asto.Value;
                Assert.AreEqual(correct, ast);
            }
            catch (NullReferenceException nre)
            {
                Assert.Fail("Parse error: " + nre.Message);
            }
        }
    }
}

Make precedence test public to be discoverable by test runner.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Nest.Resolvers.Converters;
using Newtonsoft.Json;

namespace Nest
{

	[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
	[JsonConverter(typeof(ReadAsTypeConverter<MatchAllQuery>))]
	public interface IMatchAllQuery : IQuery
	{
		[JsonProperty(PropertyName = "boost")]
		double? Boost { get; set; }

		[JsonProperty(PropertyName = "norm_field")]
		string NormField { get; set; }
	}

	public class MatchAllQuery : QueryBase, IMatchAllQuery
	{
		public double? Boost { get;  set; }
		public string NormField { get;  set; }

		bool IQuery.Conditionless => false;

		protected override void WrapInContainer(IQueryContainer container)
		{
			container.MatchAllQuery = this;
		}
	}

	public class MatchAllQueryDescriptor
		: QueryDescriptorBase<MatchAllQueryDescriptor, IMatchAllQuery>
			, IMatchAllQuery
	{
		bool IQuery.Conditionless => false;

		string IQuery.Name { get; set; }

		double? IMatchAllQuery.Boost { get; set; }

		string IMatchAllQuery.NormField { get; set; }

		public MatchAllQueryDescriptor Boost(double? boost) => Assign(a => a.Boost = boost);

		public MatchAllQueryDescriptor NormField(string normField) => Assign(a => a.NormField = normField);
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Nest.Resolvers.Converters;
using Newtonsoft.Json;

namespace Nest
{

	[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
	[JsonConverter(typeof(ReadAsTypeConverter<MatchAllQuery>))]
	public interface IMatchAllQuery : IQuery
	{
		[JsonProperty(PropertyName = "norm_field")]
		string NormField { get; set; }
	}

	public class MatchAllQuery : QueryBase, IMatchAllQuery
	{
		public string NormField { get;  set; }

		bool IQuery.Conditionless => false;

		protected override void WrapInContainer(IQueryContainer container)
		{
			container.MatchAllQuery = this;
		}
	}

	public class MatchAllQueryDescriptor
		: QueryDescriptorBase<MatchAllQueryDescriptor, IMatchAllQuery>
		, IMatchAllQuery
	{
		bool IQuery.Conditionless => false;

		string IMatchAllQuery.NormField { get; set; }

		public MatchAllQueryDescriptor NormField(string normField) => Assign(a => a.NormField = normField);
	}
}

Fix post filter test after boost/descriptor refactoring


using System;
using System.Text;
using ModIso8583.Parse;
using ModIso8583.Util;
using Xunit;

namespace ModIso8583.Test.Parse
{
    public class TestEncoding
    {
        [Fact(Skip = "character encoding issue")]
        public void WindowsToUtf8()
        {
            string data = "05ácido";
            Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
            if (OsUtil.IsLinux())
                encoding = Encoding.Default;
            sbyte[] buf = data.GetSbytes(encoding);
            LlvarParseInfo parser = new LlvarParseInfo
            {
                Encoding = Encoding.Default
            };
            IsoValue  field = parser.Parse(1, buf, 0, null);
            Assert.Equal(field.Value, data.Substring(2));
            parser.Encoding = encoding;
            field = parser.Parse(1, buf, 0, null);
            Assert.Equal(data.Substring(2), field.Value);
        }
    }
}

using System;
using System.Text;
using ModIso8583.Parse;
using ModIso8583.Util;
using Xunit;

namespace ModIso8583.Test.Parse
{
    public class TestEncoding
    {
        [Fact]
        public void WindowsToUtf8()
        {
            string data = "05ácido";
            Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
            if (OsUtil.IsLinux())
                encoding = Encoding.UTF8;
            sbyte[] buf = data.GetSbytes(encoding);
            LlvarParseInfo parser = new LlvarParseInfo
            {
                Encoding = Encoding.Default
            };

            if (OsUtil.IsLinux())
                parser.Encoding = Encoding.UTF8;

            IsoValue  field = parser.Parse(1, buf, 0, null);
            Assert.Equal(field.Value, data.Substring(2));
            parser.Encoding = encoding;
            field = parser.Parse(1, buf, 0, null);
            Assert.Equal(data.Substring(2), field.Value);
        }
    }
}

Fix OS based character Encoding issue

Fix OS based character Encoding issue


using Abp.AspNetCore.Mvc.Controllers;
using Abp.IdentityFramework;
using Microsoft.AspNetCore.Identity;

namespace Repairis.Controllers
{
    public abstract class RepairisControllerBase: AbpController
    {
        protected RepairisControllerBase()
        {
            LocalizationSourceName = RepairisConsts.LocalizationSourceName;
        }

        protected void CheckErrors(IdentityResult identityResult)
        {
            identityResult.CheckErrors(LocalizationManager);
        }
    }
}

using Abp.AspNetCore.Mvc.Controllers;
using Abp.IdentityFramework;
using Abp.Runtime.Validation;
using Microsoft.AspNetCore.Identity;

namespace Repairis.Controllers
{
    [DisableValidation]
    public abstract class RepairisControllerBase: AbpController
    {
        protected RepairisControllerBase()
        {
            LocalizationSourceName = RepairisConsts.LocalizationSourceName;
        }

        protected void CheckErrors(IdentityResult identityResult)
        {
            identityResult.CheckErrors(LocalizationManager);
        }
    }
}

Disable exception throwing when ModelState is not valid


using ReactiveUI;
using Windows.UI.Xaml;

namespace Ets.Mobile.Pages.Main
{
    public sealed partial class MainPage
    {
        partial void PartialInitialize()
        {
            // Ensure to hide the status bar
            var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
            statusBar.BackgroundOpacity = 0;
            statusBar.HideAsync().GetResults();

            // Grade Presenter
            // NOTE: Do not remove this code, can't bind to the presenter's source
            this.OneWayBind(ViewModel, x => x.GradesPresenter, x => x.Grade.DataContext);

            // Handle the button visibility according to Pivot Context (SelectedIndex)
            Loaded += (s, e) =>
            {
                MainPivot.SelectionChanged += (sender, e2) =>
                {
                    RefreshToday.Visibility = Visibility.Collapsed;
                    RefreshGrade.Visibility = Visibility.Collapsed;

                    switch (MainPivot.SelectedIndex)
                    {
                        case (int)MainPivotItem.Today:
                            RefreshToday.Visibility = Visibility.Visible;
                            break;
                        case (int)MainPivotItem.Grade:
                            RefreshGrade.Visibility = Visibility.Visible;
                            break;
                    }
                };
            };
        }
    }
}

using System;
using Windows.UI.Xaml;
using EventsMixin = Windows.UI.Xaml.Controls.EventsMixin;

namespace Ets.Mobile.Pages.Main
{
    public sealed partial class MainPage
    {
        partial void PartialInitialize()
        {
            // Ensure to hide the status bar
            var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
            statusBar.BackgroundOpacity = 0;
            statusBar.HideAsync().GetResults();

            // Handle the button visibility according to Pivot Context (SelectedIndex)
            this.Events().Loaded.Subscribe(e =>
            {
                EventsMixin.Events(MainPivot).SelectionChanged.Subscribe(e2 =>
                {
                    RefreshToday.Visibility = Visibility.Collapsed;
                    RefreshGrade.Visibility = Visibility.Collapsed;

                    switch (MainPivot.SelectedIndex)
                    {
                        case (int)MainPivotItem.Today:
                            RefreshToday.Visibility = Visibility.Visible;
                            break;
                        case (int)MainPivotItem.Grade:
                            RefreshGrade.Visibility = Visibility.Visible;
                            break;
                    }
                });
            });
        }
    }
}

Use ReactiveUI Events for Loaded and SelectionChanged


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

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

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

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

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

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

        public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
        {
            // All the values in "query" are null or zero
            // Do some stuff with query if there were anything to do
            return new string[] { "This is a CORS request.", "That works from any origin." };
        }
    }
}

Add GetTititleEstimate that accepts data from URI.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Sandbox.Game.World;
using Torch.Managers.PatchManager;
using Torch.Mod;
using VRage.Game;

namespace Torch.Patches
{
    [PatchShim]
    internal class SessionDownloadPatch
    {
        internal static void Patch(PatchContext context)
        {
            context.GetPattern(typeof(MySession).GetMethod(nameof(MySession.GetWorld))).Suffixes.Add(typeof(SessionDownloadPatch).GetMethod(nameof(SuffixGetWorld), BindingFlags.Static | BindingFlags.NonPublic));
        }

        // ReSharper disable once InconsistentNaming
        private static void SuffixGetWorld(ref MyObjectBuilder_World __result)
        {
            if (!__result.Checkpoint.Mods.Any(m => m.PublishedFileId == TorchModCore.MOD_ID))
                __result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(TorchModCore.MOD_ID));
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Sandbox.Game.World;
using Torch.Managers.PatchManager;
using Torch.Mod;
using VRage.Game;

namespace Torch.Patches
{
    [PatchShim]
    internal static class SessionDownloadPatch
    {
        internal static void Patch(PatchContext context)
        {
            context.GetPattern(typeof(MySession).GetMethod(nameof(MySession.GetWorld))).Suffixes.Add(typeof(SessionDownloadPatch).GetMethod(nameof(SuffixGetWorld), BindingFlags.Static | BindingFlags.NonPublic));
        }

        // ReSharper disable once InconsistentNaming
        private static void SuffixGetWorld(ref MyObjectBuilder_World __result)
        {
            if (!__result.Checkpoint.Mods.Any(m => m.PublishedFileId == TorchModCore.MOD_ID))
                __result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(TorchModCore.MOD_ID));
        }
    }
}

Stop Equinox complaining about session download patch not being static


namespace Colore.Tests
{
    using System;

    using NUnit.Framework;

    [TestFixture]
    public class ColoreExceptionTests
    {
        [Test]
        public void ShouldSetMessage()
        {
            const string Expected = "Test message.";
            Assert.AreEqual(Expected, new ColoreException("Test message."));
        }

        [Test]
        public void ShouldSetInnerException()
        {
            var expected = new Exception("Expected.");
            var actual = new ColoreException(null, new Exception("Expected.")).InnerException;
            Assert.AreEqual(expected.GetType(), actual.GetType());
            Assert.AreEqual(expected.Message, actual.Message);
        }
    }
}

namespace Colore.Tests
{
    using System;

    using NUnit.Framework;

    [TestFixture]
    public class ColoreExceptionTests
    {
        [Test]
        public void ShouldSetMessage()
        {
            const string Expected = "Test message.";
            Assert.AreEqual(Expected, new ColoreException("Test message.").Message);
        }

        [Test]
        public void ShouldSetInnerException()
        {
            var expected = new Exception("Expected.");
            var actual = new ColoreException(null, new Exception("Expected.")).InnerException;
            Assert.AreEqual(expected.GetType(), actual.GetType());
            Assert.AreEqual(expected.Message, actual.Message);
        }
    }
}

Fix ColoreException test performing wrong comparison.


@model IEnumerable<Soldier>

Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })

            @Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)
            @Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)
            @Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)
            @Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)

        @foreach (var soldier in Model)
        {

                @Html.DisplayFor(s => soldier.Rank)
                @Html.DisplayFor(s => soldier.LastName)
                @Html.DisplayFor(s => soldier.FirstName)
                @Html.DisplayFor(s => soldier.Unit)
                @Html.ActionLink("Details", "Details", new { soldier.Id })

                    @Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id })
                    @Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id })

        }

@model IEnumerable<Soldier>

Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })

            @Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)
            @Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)
            @Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)
            @Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)

        @foreach (var soldier in Model)
        {

                @Html.ActionLink("Details", "Details", new { soldier.Id })
                @Html.DisplayFor(s => soldier.Rank)
                @Html.DisplayFor(s => soldier.LastName)
                @Html.DisplayFor(s => soldier.FirstName)
                @Html.DisplayFor(s => soldier.Unit)

                    @Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id }, new { @class = "btn btn-default" })
                    @Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id }, new { @class = "btn btn-default" })

        }

Move details to first in list

Move details to first in list


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

namespace Faker
{
	public static class NumberFaker
	{
		private static Random _random = new Random();

		public static int Number()
		{
			return _random.Next();
		}

		public static int Number(int maxValue)
		{
			return _random.Next(maxValue);
		}

		public static int Number(int minValue, int maxValue)
		{
			return _random.Next(minValue, maxValue);
		}
	}
}

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

namespace Faker
{
    public static class NumberFaker
    {
        private static readonly RNGCryptoServiceProvider Global = new RNGCryptoServiceProvider();

        [ThreadStatic]
        private static Random _local;

        private static Random Local
        {
            get
            {
                Random inst = _local;
                if (inst == null)
                {
                    byte[] buffer = new byte[4];
                    Global.GetBytes(buffer);
                    _local = inst = new Random(
                        BitConverter.ToInt32(buffer, 0));
                }

                return inst;
            }
        }

        public static int Number()
        {
            return Local.Next();
        }

        public static int Number(int maxValue)
        {
            return Local.Next(maxValue);
        }

        public static int Number(int minValue, int maxValue)
        {
            return Local.Next(minValue, maxValue);
        }
    }
}

Add thread-safe random number instance

Add thread-safe random number instance


@model IEnumerable<(GommeHDnetForumAPI.Models.Entities.UserInfo UserInfo, Discord.WebSocket.SocketGuild Guild)>

Verifizierungen

					@Html.DisplayNameFor(model => model.UserInfo.Username)

					@Html.DisplayNameFor(model => model.Guild.Name)

			@foreach(var (userInfo, guild) in Model) {

						@if(!string.IsNullOrWhiteSpace(userInfo.AvatarUrl)) {

						}

						@(string.IsNullOrWhiteSpace(userInfo.Username) ? userInfo.UrlPath : userInfo.Username)

						@guild.Name

			}

@model IEnumerable<(GommeHDnetForumAPI.Models.Entities.UserInfo UserInfo, Discord.WebSocket.SocketGuild Guild)>

Verifizierungen

					@Html.DisplayNameFor(model => model.UserInfo.Username)

					@Html.DisplayNameFor(model => model.Guild.Name)

			@foreach(var (userInfo, guild) in Model) {

						@if(!string.IsNullOrWhiteSpace(userInfo.AvatarUrl)) {

						}

						@(string.IsNullOrWhiteSpace(userInfo.Username) ? userInfo.Url : userInfo.Username)

						@guild.Name

			}

Use Url instead of UrlPath.

Use Url instead of UrlPath.


using System;

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

using DomainCore;
using DomainCore.Interfaces;

namespace Application.Interfaces
{
    /// <summary>
    /// Primary application interface
    /// </summary>
    public interface IInventoryService
    {
        /* ReadModel  */
        // Get all
        Task<IEnumerable<InventoryItemDto>> InventoryAsync();

        // Get one
        Task<InventoryItemDto> GetItemAsync(Guid id);

        Task<IEnumerable<AInventoryItemEvent>> InventoryEventsAsync(Guid id);

		/* Commands */
		// Create Item
		Task PostItemAsync(InventoryItemDto item);

        // Update Full Item
		Task PutItemAsync(InventoryItemDto item);

        // Delete Item
        Task DeleteItemAsync(Guid id);

		// Edit Item
		Task PatchItemCountAsync(Guid id, int count, string reason);
		Task PatchItemNameAsync(Guid id, string name, string reason);
		Task PatchItemNoteAsync(Guid id, string note, string reason);

        // Increase Item count
        Task IncreaseInventory(Guid id, uint amount, string reason);

		// Decrease Item count
		Task DecreaseInventory(Guid id, uint amount, string reason);

		// Activate Item
		Task ActivateItem(Guid id, string reason);

        // Deactivate Item
        Task DisableItem(Guid id, string reason);
	}
}

using System;

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

using DomainCore;

namespace Application.Interfaces
{
    public interface IInventoryService
    {
        /* ReadModel  */
        // Get all
        Task<IEnumerable<InventoryItemDto>> InventoryAsync();

        // Get one
        Task<InventoryItemDto> GetItemAsync(Guid id);

        Task<IEnumerable<InventoryItemEvent>> InventoryEventsAsync(Guid id);

		/* Commands */
		// Create Item
		Task PostItemAsync(InventoryItemDto item);

        // Update Full Item
		Task PutItemAsync(InventoryItemDto item);

        // Delete Item
        Task DeleteItemAsync(Guid id);

		// Edit Item
		Task PatchItemCountAsync(Guid id, int count, string reason);
		Task PatchItemNameAsync(Guid id, string name, string reason);
		Task PatchItemNoteAsync(Guid id, string note, string reason);

        // Increase Item count
        Task IncreaseInventory(Guid id, uint amount, string reason);

		// Decrease Item count
		Task DecreaseInventory(Guid id, uint amount, string reason);

		// Activate Item
		Task ActivateItem(Guid id, string reason);

        // Deactivate Item
        Task DisableItem(Guid id, string reason);
	}
}

Revert "Changed generic object to a system object"

This reverts commit 8338aa76f30a6e3898d79110494c66b167661eda.


namespace TraktApiSharp.Objects.Get.Movies
{
    using Basic;
    using Newtonsoft.Json;

    public class TraktMovieImages
    {
        [JsonProperty(PropertyName = "fanart")]
        public TraktImageSet FanArt { get; set; }

        [JsonProperty(PropertyName = "poster")]
        public TraktImageSet Poster { get; set; }

        [JsonProperty(PropertyName = "logo")]
        public TraktImage Logo { get; set; }

        [JsonProperty(PropertyName = "clearart")]
        public TraktImage ClearArt { get; set; }

        [JsonProperty(PropertyName = "banner")]
        public TraktImage Banner { get; set; }

        [JsonProperty(PropertyName = "thumb")]
        public TraktImage Thumb { get; set; }
    }
}

namespace TraktApiSharp.Objects.Get.Movies
{
    using Basic;
    using Newtonsoft.Json;

    /// A collection of images and image sets for a Trakt movie.
    public class TraktMovieImages
    {
        /// Gets or sets the fan art image set.
        [JsonProperty(PropertyName = "fanart")]
        public TraktImageSet FanArt { get; set; }

        /// Gets or sets the poster image set.
        [JsonProperty(PropertyName = "poster")]
        public TraktImageSet Poster { get; set; }

        /// Gets or sets the loge image.
        [JsonProperty(PropertyName = "logo")]
        public TraktImage Logo { get; set; }

        /// Gets or sets the clear art image.
        [JsonProperty(PropertyName = "clearart")]
        public TraktImage ClearArt { get; set; }

        /// Gets or sets the banner image.
        [JsonProperty(PropertyName = "banner")]
        public TraktImage Banner { get; set; }

        /// Gets or sets the thumb image.
        [JsonProperty(PropertyName = "thumb")]
        public TraktImage Thumb { get; set; }
    }
}

Add documentation for movie images.

Add documentation for movie images.