using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace NElasticsearch.Models
{
    /// <summary>
    /// Individual hit response from ElasticSearch.
    /// </summary>
    [DebuggerDisplay("{_type} in {_index} id {_id}")]
    public class Hit<T>
    {
        public string _index { get; set; }
        public string _type { get; set; }
        public string _id { get; set; }
        public double? _score { get; set; }

        public T _source { get; set; }
        //public Dictionary<String, JToken> fields = new Dictionary<string, JToken>();
    }
}

using System.Collections.Generic;
using System.Diagnostics;

namespace NElasticsearch.Models
{
    /// <summary>
    /// Individual hit response from ElasticSearch.
    /// </summary>
    [DebuggerDisplay("{_type} in {_index} id {_id}")]
    public class Hit<T>
    {
        public string _index { get; set; }
        public string _type { get; set; }
        public string _id { get; set; }
        public double? _score { get; set; }

        public T _source { get; set; }
        public Dictionary<string, IEnumerable<object>> fields = new Dictionary<string, IEnumerable<object>>();

        public Dictionary<string, IEnumerable<string>> highlight;
    }
}

Support fields and highlights in responses


using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using wslib;
using wslib.Protocol;

namespace LocalServer
{
    class Program
    {
        static void Main(string[] args)
        {
            TaskScheduler.UnobservedTaskException += LogUnobservedTaskException;

            var listenerOptions = new WebSocketListenerOptions { Endpoint = new IPEndPoint(IPAddress.Loopback, 8080) };
            using (var listener = new WebSocketListener(listenerOptions, appFunc))
            {
                listener.StartAccepting();
                Console.ReadLine();
            }
        }

        private static void LogUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
        {
            throw new NotImplementedException(); // TODO: log
        }

        private static async Task appFunc(IWebSocket webSocket)
        {
            while (webSocket.IsConnected())
            {
                using (var msg = await webSocket.ReadMessageAsync(CancellationToken.None))
                {
                    if (msg != null)
                    {
                        using (var ms = new MemoryStream())
                        {
                            await msg.ReadStream.CopyToAsync(ms);
                            var text = Encoding.UTF8.GetString(ms.ToArray());

                            using (var w = await webSocket.CreateMessageWriter(MessageType.Text, CancellationToken.None))
                            {
                                await w.WriteMessageAsync(ms.ToArray(), 0, (int)ms.Length, CancellationToken.None);
                            }
                        }
                    }
                }
            }
        }
    }
}

using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using wslib;

namespace LocalServer
{
    class Program
    {
        static void Main(string[] args)
        {
            TaskScheduler.UnobservedTaskException += LogUnobservedTaskException;

            var listenerOptions = new WebSocketListenerOptions { Endpoint = new IPEndPoint(IPAddress.Loopback, 8080) };
            using (var listener = new WebSocketListener(listenerOptions, appFunc))
            {
                listener.StartAccepting();
                Console.ReadLine();
            }
        }

        private static void LogUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
        {
            //Console.WriteLine(unobservedTaskExceptionEventArgs.Exception);
        }

        private static async Task appFunc(IWebSocket webSocket)
        {
            while (webSocket.IsConnected())
            {
                using (var msg = await webSocket.ReadMessageAsync(CancellationToken.None))
                {
                    if (msg == null) continue;

                    using (var ms = new MemoryStream())
                    {
                        await msg.ReadStream.CopyToAsync(ms);
                        byte[] array = ms.ToArray();
                        using (var w = await webSocket.CreateMessageWriter(msg.Type, CancellationToken.None))
                        {
                            await w.WriteMessageAsync(array, 0, array.Length, CancellationToken.None);
                        }
                    }
                }
            }
        }
    }
}

Update local echo server to work with binary messages


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

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

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

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

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

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

Set Treenumerable version to 1.0.0

Set Treenumerable version to 1.0.0


namespace UnwindMC.Analysis
{
    public class Function
    {
        public Function(ulong address)
        {
            Address = address;
            Status = FunctionStatus.Created;
        }

        public ulong Address { get; }
        public FunctionStatus Status { get; set; }
    }

    public enum FunctionStatus
    {
        Created,
        BoundsResolved,
        BoundsNotResolvedInvalidAddress,
        BoundsNotResolvedIncompleteGraph,
    }
}

using System;
using System.Collections.Generic;
using UnwindMC.Analysis.Flow;
using UnwindMC.Analysis.IL;

namespace UnwindMC.Analysis
{
    public class Function
    {
        private List<IBlock> _blocks;

        public Function(ulong address)
        {
            Address = address;
            Status = FunctionStatus.Created;
        }

        public ulong Address { get; }
        public FunctionStatus Status { get; set; }
        public IReadOnlyList<IBlock> Blocks => _blocks;
        public ILInstruction FirstInstruction
        {
            get
            {
                if (_blocks == null || _blocks.Count == 0)
                {
                    return null;
                }
                var seq = _blocks[0] as SequentialBlock;
                if (seq != null)
                {
                    return seq.Instructions[0];
                }
                var loop = _blocks[0] as LoopBlock;
                if (loop != null)
                {
                    return loop.Condition;
                }
                var cond = _blocks[0] as ConditionalBlock;
                if (cond != null)
                {
                    return cond.Condition;
                }
                throw new InvalidOperationException("Unknown block type");
            }
        }

        public void ResolveBody(InstructionGraph graph)
        {
            if (Status != FunctionStatus.BoundsResolved)
            {
                throw new InvalidOperationException("Cannot resolve function body when bounds are not resolved");
            }
            _blocks = FlowAnalyzer.Analyze(ILDecompiler.Decompile(graph, Address));
            Status = FunctionStatus.BodyResolved;
        }
    }

    public enum FunctionStatus
    {
        Created,
        BoundsResolved,
        BoundsNotResolvedInvalidAddress,
        BoundsNotResolvedIncompleteGraph,
        BodyResolved,
    }
}

Add flow tree body to the function

Add flow tree body to the function


using System;
using System.Text;

namespace SCPI.Display
{
    public class DISPLAY_GRID : ICommand
    {
        public string Description => "Set or query the grid type of screen display.";

        public string Grid { get; private set; }

        private readonly string[] gridRange = new string[] { "FULL", "HALF", "NONE" };

        public string Command(params string[] parameters)
        {
            var cmd = ":DISPlay:GRID";

            if (parameters.Length > 0)
            {
                var grid = parameters[0];
                cmd = $"{cmd} {grid}";
            }
            else
            {
                cmd += "?";
            }

            return cmd;
        }

        public string HelpMessage()
        {
            var syntax = nameof(DISPLAY_GRID) + "\n" +
                         nameof(DISPLAY_GRID) + " <grid>";
            var parameters = " <grid> = {"+ string.Join("|", gridRange) +"}\n";
            var example = "Example: " + nameof(DISPLAY_GRID) + "?";

            return $"{syntax}\n{parameters}\n{example}";
        }

        public bool Parse(byte[] data)
        {
            if (data != null)
            {
                Grid = Encoding.ASCII.GetString(data).Trim();
                if (Array.Exists(gridRange, g => g.Equals(Grid)))
                {
                    return true;
                }
            }

            Grid = null;

            return false;
        }
    }
}

using System;
using System.Text;

namespace SCPI.Display
{
    public class DISPLAY_GRID : ICommand
    {
        public string Description => "Set or query the grid type of screen display.";

        public string Grid { get; private set; }

        private readonly string[] gridRange = new string[] { "FULL", "HALF", "NONE" };

        public string Command(params string[] parameters)
        {
            var cmd = ":DISPlay:GRID";

            if (parameters.Length > 0)
            {
                var grid = parameters[0];
                cmd = $"{cmd} {grid}";
            }
            else
            {
                cmd += "?";
            }

            return cmd;
        }

        public string HelpMessage()
        {
            var syntax = nameof(DISPLAY_GRID) + "\n" +
                         nameof(DISPLAY_GRID) + " <grid>";
            var parameters = " <grid> = {"+ string.Join("|", gridRange) +"}\n";
            var example = "Example: " + nameof(DISPLAY_GRID) + " FULL";

            return $"{syntax}\n{parameters}\n{example}";
        }

        public bool Parse(byte[] data)
        {
            if (data != null)
            {
                Grid = Encoding.ASCII.GetString(data).Trim();
                if (Array.Exists(gridRange, g => g.Equals(Grid)))
                {
                    return true;
                }
            }

            Grid = null;

            return false;
        }
    }
}

Change example to contain default values


using CroquetAustralia.Domain.Features.TournamentEntry.Events;

namespace CroquetAustralia.QueueProcessor.Email.EmailGenerators
{
    public class U21WorldsEOIEmailGenerator : BaseEmailGenerator
    {
        /* todo: remove hard coding of email addresses */
        private static readonly EmailAddress U21Coordinator = new EmailAddress("ndu21c@croquet-australia.com.au", "Croquet Australia - National Co-ordinator Under 21 Croquet");

        private static readonly EmailAddress[] BCC =
        {
            U21Coordinator,
            new EmailAddress("admin@croquet-australia.com.au", "Croquet Australia")
        };

        public U21WorldsEOIEmailGenerator(EmailMessageSettings emailMessageSettings)
            : base(emailMessageSettings, U21Coordinator, BCC)
        {
        }

        protected override string GetTemplateName(EntrySubmitted entrySubmitted)
        {
            return "EOI";
        }
    }
}

using System.Linq;
using CroquetAustralia.Domain.Features.TournamentEntry.Events;

namespace CroquetAustralia.QueueProcessor.Email.EmailGenerators
{
    public class U21WorldsEOIEmailGenerator : BaseEmailGenerator
    {
        /* todo: remove hard coding of email addresses */
        private static readonly EmailAddress U21Coordinator = new EmailAddress("ndu21c@croquet-australia.com.au", "Croquet Australia - National Co-ordinator Under 21 Croquet");

        private static readonly EmailAddress[] BCC =
        {
            U21Coordinator,
            new EmailAddress("admin@croquet-australia.com.au", "Croquet Australia")
        };

        public U21WorldsEOIEmailGenerator(EmailMessageSettings emailMessageSettings)
            : base(emailMessageSettings, U21Coordinator, GetBCC(emailMessageSettings))
        {
        }

        protected override string GetTemplateName(EntrySubmitted entrySubmitted)
        {
            return "EOI";
        }

        private static EmailAddress[] GetBCC(EmailMessageSettings emailMessageSettings)
        {
            return emailMessageSettings.Bcc.Any() ? BCC : new EmailAddress[] {};
        }
    }
}

Fix BCC for EOI emails

Fix BCC for EOI emails


namespace TraktApiSharp.Tests
{
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class TraktConfigurationTests
    {
        [TestMethod]
        public void TestTraktConfigurationDefaultConstructor()
        {
            var client = new TraktClient();

            client.Configuration.ApiVersion.Should().Be(2);
            client.Configuration.UseStagingApi.Should().BeFalse();
            client.Configuration.BaseUrl.Should().Be("https://api-v2launch.trakt.tv/");

            client.Configuration.UseStagingApi = true;
            client.Configuration.BaseUrl.Should().Be("https://api-staging.trakt.tv/");
        }
    }
}

namespace TraktApiSharp.Tests
{
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class TraktConfigurationTests
    {
        [TestMethod]
        public void TestTraktConfigurationDefaultConstructor()
        {
            var client = new TraktClient();

            client.Configuration.ApiVersion.Should().Be(2);
            client.Configuration.UseStagingUrl.Should().BeFalse();
            client.Configuration.BaseUrl.Should().Be("https://api-v2launch.trakt.tv/");

            client.Configuration.UseStagingUrl = true;
            client.Configuration.BaseUrl.Should().Be("https://api-staging.trakt.tv/");
        }
    }
}

Fix issues due to merge conflict.

Fix issues due to merge conflict.


using System;
using FormsToolkit;
using Xamarin.Forms;

namespace ToolkitTests
{
    public class App : Application
    {
        public App()
        {

            var messagingCenter = new Button
            {
                Text = "Messaging Center",
                Command = new Command(()=>MainPage.Navigation.PushAsync(new MessagingServicePage()))
            };

			var line = new EntryLine
			{
				Placeholder = "This nifty place for entering text!",
				HorizontalTextAlignment = TextAlignment.Center,
				HorizontalOptions = LayoutOptions.FillAndExpand,
				Text = "",
                FontSize = 30,
				BorderColor = Color.Red
			};

            // The root page of your application
            MainPage = new NavigationPage(new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
					Padding = new Thickness(32,32,32,32),
                    Children =
                    {
                        messagingCenter,
						line
                    }
                }
            });
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

using System;
using FormsToolkit;
using Xamarin.Forms;

namespace ToolkitTests
{
    public class App : Application
    {
        public App()
        {

            var messagingCenter = new Button
            {
                Text = "Messaging Center",
                Command = new Command(()=>MainPage.Navigation.PushAsync(new MessagingServicePage()))
            };

			var line = new EntryLine
			{
				Placeholder = "This nifty place for entering text!",
				HorizontalTextAlignment = TextAlignment.Center,
				HorizontalOptions = LayoutOptions.FillAndExpand,
				Text = "",
                FontSize = 30,
				BorderColor = Color.Red
			};

            var trigger = new Trigger(typeof(EntryLine));
            trigger.Property = EntryLine.IsFocusedProperty;
            trigger.Value = true;
            Setter setter = new Setter();
            setter.Property = EntryLine.BorderColorProperty;
            setter.Value = Color.Yellow;

            trigger.Setters.Add(setter);

            line.Triggers.Add(trigger);

            var line2 = new EntryLine
            {
                PlaceholderColor = Color.Orange,
                Placeholder = "This nifty place for entering text!",
                HorizontalTextAlignment = TextAlignment.Center,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                Text = "",
                FontSize = 10,
                BorderColor = Color.Red
            };

            // The root page of your application
            MainPage = new NavigationPage(new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
					Padding = new Thickness(32,32,32,32),
                    Children =
                    {
                        messagingCenter,
						line,
                        line2
                    }
                }
            });
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

Add sample of data trigger

Add sample of data trigger


using BusinessObjects.Validators;

namespace FatturaElettronicaPA.Validators
{
    /// <summary>
    /// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
    /// </summary>
    public class FModalitaPagamentoValidator : DomainValidator
    {

        private const string BrokenDescription = "Valori ammessi [MP01], [MP02], [..], [MP17].";

        /// <summary>
        /// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
        /// </summary>
        public FModalitaPagamentoValidator() : this(null, BrokenDescription) { }
        public FModalitaPagamentoValidator(string propertyName) : this(propertyName, BrokenDescription) { }
        public FModalitaPagamentoValidator(string propertyName, string description) : base(propertyName, description)
        {
            Domain = new[]
            {
                "MP01", "MP02", "MP03", "MP04", "MP06", "MP07", "MP08", "MP09", "MP10", "MP11", "MP12", "MP13",
                "MP14", "MP15", "MP16", "MP17"
            };
        }
    }
}

using BusinessObjects.Validators;

namespace FatturaElettronicaPA.Validators
{
    /// <summary>
    /// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
    /// </summary>
    public class FModalitaPagamentoValidator : DomainValidator
    {

        private const string BrokenDescription = "Valori ammessi [MP01], [MP02], [..], [MP21].";

        /// <summary>
        /// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
        /// </summary>
        public FModalitaPagamentoValidator() : this(null, BrokenDescription) { }
        public FModalitaPagamentoValidator(string propertyName) : this(propertyName, BrokenDescription) { }
        public FModalitaPagamentoValidator(string propertyName, string description) : base(propertyName, description)
        {
            Domain = new[]
            {
                "MP01", "MP02", "MP03", "MP04", "MP06", "MP07", "MP08", "MP09", "MP10", "MP11", "MP12", "MP13",
                "MP14", "MP15", "MP16", "MP17", "MP18", "MP19", "MP20", "MP21"
            };
        }
    }
}

Update ModalitaPagamento validator with MP18..21 values


// Copyright 2013 Xamarin Inc.

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

using MonoMac.ObjCRuntime;

namespace MonoMac.Foundation {

	public partial class NSUrlCredential {

		public NSUrlCredential (IntPtr trust, bool ignored) : base (NSObjectFlag.Empty)
		{
			if (IsDirectBinding) {
				Handle = MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithTrust:"), trust);
			} else {
				Handle = MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithTrust:"), trust);
			}
		}
	}
}

// Copyright 2013 Xamarin Inc.

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

using MonoMac.ObjCRuntime;

namespace MonoMac.Foundation {

	public partial class NSUrlCredential {

		public NSUrlCredential (IntPtr trust, bool ignored) : base (NSObjectFlag.Empty)
		{
			if (IsDirectBinding) {
				Handle = Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithTrust:"), trust);
			} else {
				Handle = Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithTrust:"), trust);
			}
		}
	}
}

Fix MonoMac/MonoTouch (for MonoMac builds)


using System;

namespace DesktopWidgets.Helpers
{
    public static class DateTimeSyncHelper
    {
        public static DateTime SyncNext(this DateTime dateTime, bool syncYear, bool syncMonth, bool syncDay,
            bool syncHour, bool syncMinute, bool syncSecond)
        {
            var endDateTime = dateTime;
            endDateTime = new DateTime(
                syncYear
                    ? DateTime.Now.Year
                    : endDateTime.Year,
                syncMonth
                    ? DateTime.Now.Month
                    : endDateTime.Month,
                syncDay
                    ? DateTime.Now.Day
                    : endDateTime.Day,
                syncHour
                    ? DateTime.Now.Hour
                    : endDateTime.Hour,
                syncMinute
                    ? DateTime.Now.Minute
                    : endDateTime.Minute,
                syncSecond
                    ? DateTime.Now.Second
                    : endDateTime.Second,
                endDateTime.Kind);

            if (syncYear && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddYears(1);

            if (syncMonth && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddMonths(1);

            if (syncDay && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddDays(1);

            if (syncHour && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddHours(1);

            if (syncMinute && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddMinutes(1);

            if (syncSecond && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddSeconds(1);

            return endDateTime;
        }
    }
}

using System;

namespace DesktopWidgets.Helpers
{
    public static class DateTimeSyncHelper
    {
        public static DateTime SyncNext(this DateTime dateTime, bool syncYear, bool syncMonth, bool syncDay,
            bool syncHour, bool syncMinute, bool syncSecond)
        {
            var endDateTime = dateTime;
            endDateTime = new DateTime(
                syncYear
                    ? DateTime.Now.Year
                    : endDateTime.Year,
                syncMonth
                    ? DateTime.Now.Month
                    : endDateTime.Month,
                syncDay
                    ? DateTime.Now.Day
                    : endDateTime.Day,
                syncHour
                    ? DateTime.Now.Hour
                    : endDateTime.Hour,
                syncMinute
                    ? DateTime.Now.Minute
                    : endDateTime.Minute,
                syncSecond
                    ? DateTime.Now.Second
                    : endDateTime.Second,
                endDateTime.Kind);

            if (syncSecond && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddSeconds(1);

            if (syncMinute && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddMinutes(1);

            if (syncHour && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddHours(1);

            if (syncDay && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddDays(1);

            if (syncMonth && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddMonths(1);

            if (syncYear && endDateTime < DateTime.Now)
                endDateTime = endDateTime.AddYears(1);

            return endDateTime;
        }
    }
}

Change "Countdown" syncing priority order


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PhotoLife.Data.Contracts;
using PhotoLife.Models;
using PhotoLife.Services.Contracts;

namespace PhotoLife.Services
{
    public class PostsService: IPostService
    {
        private readonly IRepository<Post> postsRepository;
        private readonly IUnitOfWork unitOfWork;

        public PostsService(
            IRepository<Post> postsRepository,
            IUnitOfWork unitOfWork)
        {
            if (postsRepository == null)
            {
                throw new ArgumentNullException("postsRepository");
            }

            if (unitOfWork == null)
            {
                throw new ArgumentNullException("unitOfWorks");
            }

            this.postsRepository = postsRepository;
            this.unitOfWork = unitOfWork;
        }
        public Post GetPostById(string id)
        {
            return this.postsRepository.GetById(id);
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PhotoLife.Data.Contracts;
using PhotoLife.Models;
using PhotoLife.Services.Contracts;

namespace PhotoLife.Services
{
    public class PostsService : IPostService
    {
        private readonly IRepository<Post> postsRepository;
        private readonly IUnitOfWork unitOfWork;

        public PostsService(
            IRepository<Post> postsRepository,
            IUnitOfWork unitOfWork)
        {
            if (postsRepository == null)
            {
                throw new ArgumentNullException("postsRepository");
            }

            if (unitOfWork == null)
            {
                throw new ArgumentNullException("unitOfWorks");
            }

            this.postsRepository = postsRepository;
            this.unitOfWork = unitOfWork;
        }
        public Post GetPostById(string id)
        {
            return this.postsRepository.GetById(id);
        }

        public IEnumerable<Post> GetTopPosts(int countOfPosts)
        {
            var res =
                this.postsRepository.GetAll(
                    (Post post) => true,
                    (Post post) => post.Votes, true)
                    .Take(countOfPosts);

            return res;
        }

    }
}

Add get top to service

Add get top to service


namespace SilentHunter
{
	public static class Encoding
	{
		/// <summary>
		/// The default encoding to use for parsing Silent Hunter game files.
		/// </summary>
		public static System.Text.Encoding ParseEncoding { get; } = System.Text.Encoding.GetEncoding(1252);
	}
}

namespace SilentHunter
{
	public static class Encoding
	{
		/// <summary>
		/// The default encoding to use for parsing Silent Hunter game files.
		/// </summary>
		public static System.Text.Encoding ParseEncoding { get; } = System.Text.Encoding.GetEncoding("ISO-8859-1");
	}
}

Use ISO encoding, for cross platform

Use ISO encoding, for cross platform


using MQTTnet.Client.Connecting;
using MQTTnet.Exceptions;

namespace MQTTnet.Adapter
{
    public class MqttConnectingFailedException : MqttCommunicationException
    {
        public MqttConnectingFailedException(MqttClientAuthenticateResult resultCode)
            : base($"Connecting with MQTT server failed ({resultCode.ToString()}).")
        {
            Result = resultCode;
        }

        public MqttClientAuthenticateResult Result { get; }
        public MqttClientConnectResultCode ResultCode => Result.ResultCode;
    }
}

using MQTTnet.Client.Connecting;
using MQTTnet.Exceptions;

namespace MQTTnet.Adapter
{
    public class MqttConnectingFailedException : MqttCommunicationException
    {
        public MqttConnectingFailedException(MqttClientAuthenticateResult resultCode)
            : base($"Connecting with MQTT server failed ({resultCode.ResultCode.ToString()}).")
        {
            Result = resultCode;
        }

        public MqttClientAuthenticateResult Result { get; }
        public MqttClientConnectResultCode ResultCode => Result.ResultCode;
    }
}

Correct to print right result

Correct to print right result

Lost a change while moving from my developement branch to here.


using System;
using Xunit;

namespace CSharpInternals.ExceptionHandling
{
    public class Basics
    {
        [Fact]
        public void Test()
        {
            Assert.Throws<NullReferenceException>(() => ThrowsNullReferenceException());
        }

        // Fact - ToString allocates a lot, especially with AggregateException
        // http://referencesource.microsoft.com/#mscorlib/system/AggregateException.cs,448

        private static void ThrowsNullReferenceException() => throw null;
    }
}

using System;
using Xunit;

namespace CSharpInternals.ExceptionHandling
{
    public class Basics
    {
        [Fact]
        public void ThrowsNull()
        {
            Assert.Throws<NullReferenceException>(() => ThrowsNullReferenceException());
        }

        // Fact - ToString allocates a lot, especially with AggregateException
        // http://referencesource.microsoft.com/#mscorlib/system/AggregateException.cs,448

        private static void ThrowsNullReferenceException() => throw null;
    }
}

Use more proper name for test

Use more proper name for test


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

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

namespace EOLib.Graphics
{
    public sealed class PEFileCollection : Dictionary<GFXTypes, IPEFile>, IPEFileCollection
    {
        public void PopulateCollectionWithStandardGFX()
        {
            var gfxTypes = Enum.GetValues(typeof(GFXTypes)).OfType<GFXTypes>();
            var modules = gfxTypes.ToDictionary(type => type, CreateGFXFile);
            foreach(var modulePair in modules)
                Add(modulePair.Key, modulePair.Value);
        }

        private IPEFile CreateGFXFile(GFXTypes file)
        {
            var number = ((int)file).ToString("D3");
            var fName = Path.Combine("gfx", "gfx" + number + ".egf");

            return new PEFile(fName);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~PEFileCollection()
        {
            Dispose(false);
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
                foreach (var pair in this)
                    pair.Value.Dispose();
        }
    }

    public interface IPEFileCollection : IDictionary<GFXTypes, IPEFile>, IDisposable
    {
        void PopulateCollectionWithStandardGFX();
    }
}

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

using System;
using System.Collections.Generic;
using System.IO;
using PELoaderLib;

namespace EOLib.Graphics
{
    public sealed class PEFileCollection : Dictionary<GFXTypes, IPEFile>, IPEFileCollection
    {
        public void PopulateCollectionWithStandardGFX()
        {
            var gfxTypes = (GFXTypes[])Enum.GetValues(typeof(GFXTypes));
            foreach (var type in gfxTypes)
                Add(type, CreateGFXFile(type));
        }

        private IPEFile CreateGFXFile(GFXTypes file)
        {
            var number = ((int)file).ToString("D3");
            var fName = Path.Combine("gfx", "gfx" + number + ".egf");

            return new PEFile(fName);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~PEFileCollection()
        {
            Dispose(false);
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
                foreach (var pair in this)
                    pair.Value.Dispose();
        }
    }

    public interface IPEFileCollection : IDictionary<GFXTypes, IPEFile>, IDisposable
    {
        void PopulateCollectionWithStandardGFX();
    }
}

Fix resource leak that occurred when any GFX files were missing from GFX folder


// 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 osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Localisation;
using osu.Game.Overlays.Settings.Sections.Maintenance;

namespace osu.Game.Overlays.Settings.Sections
{
    public class MaintenanceSection : SettingsSection
    {
        public override LocalisableString Header => MaintenanceSettingsStrings.MaintenanceSectionHeader;

        public override Drawable CreateIcon() => new SpriteIcon
        {
            Icon = FontAwesome.Solid.Wrench
        };

        public MaintenanceSection()
        {
            Children = new Drawable[]
            {
                new BeatmapSettings(),
                new SkinSettings(),
                new CollectionsSettings(),
                new ScoreSettings()
            };
        }
    }
}

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

using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Localisation;
using osu.Game.Overlays.Settings.Sections.Maintenance;

namespace osu.Game.Overlays.Settings.Sections
{
    public class MaintenanceSection : SettingsSection
    {
        public override LocalisableString Header => MaintenanceSettingsStrings.MaintenanceSectionHeader;

        public override Drawable CreateIcon() => new SpriteIcon
        {
            Icon = FontAwesome.Solid.Wrench
        };

        public MaintenanceSection()
        {
            Children = new Drawable[]
            {
                new BeatmapSettings(),
                new SkinSettings(),
                new CollectionsSettings(),
                new ScoreSettings()
            };
        }
    }
}

Remove one more nullable disable

Remove one more nullable disable


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

/*
 * Currently if you have a .cshtml file in a project with <Project Sdk="Microsoft.NET.Sdk.Web">,
 * Visual Studio will run design-time builds for the .cshtml file that assume certain ASP.NET MVC
 * APIs exist. Since those namespaces and types wouldn't normally exist for Blazor client apps,
 * this leads to spurious errors in the Errors List pane, even though there aren't actually any
 * errors on build. As a workaround, we define here a minimal set of namespaces/types that satisfy
 * the design-time build.
 *
 * TODO: Track down what is triggering the unwanted design-time build and find out how to disable it.
 * Then this file can be removed entirely.
 */

using System;

namespace Microsoft.AspNetCore.Mvc
{
    public interface IUrlHelper { }
    public interface IViewComponentHelper { }
}

namespace Microsoft.AspNetCore.Mvc.Razor
{
    public class RazorPage<T> { }

    namespace Internal
    {
        public class RazorInjectAttributeAttribute : Attribute { }
    }
}

namespace Microsoft.AspNetCore.Mvc.Rendering
{
    public interface IJsonHelper { }
    public interface IHtmlHelper<T> { }
}

namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
    public interface IModelExpressionProvider { }
}

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

/*
 * Currently if you have a .cshtml file in a project with <Project Sdk="Microsoft.NET.Sdk.Web">,
 * Visual Studio will run design-time builds for the .cshtml file that assume certain ASP.NET MVC
 * APIs exist. Since those namespaces and types wouldn't normally exist for Blazor client apps,
 * this leads to spurious errors in the Errors List pane, even though there aren't actually any
 * errors on build. As a workaround, we define here a minimal set of namespaces/types that satisfy
 * the design-time build.
 *
 * TODO: Track down what is triggering the unwanted design-time build and find out how to disable it.
 * Then this file can be removed entirely.
 */

using System;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Mvc
{
    public interface IUrlHelper { }
    public interface IViewComponentHelper { }
}

namespace Microsoft.AspNetCore.Mvc.Razor
{
    public class RazorPage<T> {

        // This needs to be defined otherwise the VS tooling complains that there's no ExecuteAsync method to override.
        public virtual Task ExecuteAsync()
            => throw new NotImplementedException($"Blazor components do not implement {nameof(ExecuteAsync)}.");

    }

    namespace Internal
    {
        public class RazorInjectAttributeAttribute : Attribute { }
    }
}

namespace Microsoft.AspNetCore.Mvc.Rendering
{
    public interface IJsonHelper { }
    public interface IHtmlHelper<T> { }
}

namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
    public interface IModelExpressionProvider { }
}

Stop spurious VS "cannot override ExecuteAsync" errors even if you don't specify a base class


using System.Windows;

namespace OpenSage.DataViewer
{
    public partial class App : Application
    {

    }
}

using System.Windows;
using System.Globalization;
using System.Threading;

namespace OpenSage.DataViewer
{
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;

            base.OnStartup(e);
        }
    }
}

Set thread culture to InvariantCulture on startup

Fixes the data viewer in locales which use the decimal comma.


// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Perspex;
using Perspex.Controls;
using Perspex.Controls.Presenters;
using System;
using System.Collections.Generic;

namespace Core2D.Perspex.Presenters
{
    public class CachedContentPresenter : ContentPresenter
    {
        private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>();

        private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>();

        public static void Register(Type type, Func<Control> create) => _factory[type] = create;

        public CachedContentPresenter()
        {
            this.GetObservable(DataContextProperty).Subscribe((value) => SetContent(value));
        }

        public Control GetControl(Type type)
        {
            Control control;
            _cache.TryGetValue(type, out control);
            if (control == null)
            {
                Func<Control> createInstance;
                _factory.TryGetValue(type, out createInstance);
                control = createInstance?.Invoke();
                if (control != null)
                {
                    _cache[type] = control;
                }
            }
            return control;
        }

        public void SetContent(object value)
        {
            Control control = null;
            if (value != null)
            {
                control = GetControl(value.GetType());
            }
            this.Content = control;
        }
    }
}

// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Perspex;
using Perspex.Controls;
using Perspex.Controls.Presenters;
using System;
using System.Collections.Generic;

namespace Core2D.Perspex.Presenters
{
    public class CachedContentPresenter : ContentPresenter
    {
        private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>();

        private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>();

        public static void Register(Type type, Func<Control> create) => _factory[type] = create;

        public CachedContentPresenter()
        {
            this.GetObservable(DataContextProperty).Subscribe((value) => SetContent(value));
        }

        public Control GetControl(Type type)
        {
            Control control;
            _cache.TryGetValue(type, out control);
            if (control == null)
            {
                Func<Control> createInstance;
                _factory.TryGetValue(type, out createInstance);
                control = createInstance?.Invoke();
                if (control != null)
                {
                    _cache[type] = control;
                }
                else
                {
                    throw new Exception($"Can not find factory method for type: {type}");
                }
            }
            return control;
        }

        public void SetContent(object value)
        {
            Control control = null;
            if (value != null)
            {
                control = GetControl(value.GetType());
            }
            this.Content = control;
        }
    }
}

Throw excpetion when type is not found

Throw excpetion when type is not found


using AVKit;

namespace MediaManager.Platforms.Ios.Video
{
    public class PlayerViewController : AVPlayerViewController
    {
        protected MediaManagerImplementation MediaManager => CrossMediaManager.Apple;

        public override void ViewWillDisappear(bool animated)
        {
            base.ViewWillDisappear(animated);

            if (MediaManager.MediaPlayer.VideoView == View.Superview)
            {
                MediaManager.MediaPlayer.VideoView = null;
            }

            Player = null;
        }
    }
}

using AVKit;

namespace MediaManager.Platforms.Ios.Video
{
    public class PlayerViewController : AVPlayerViewController
    {
        protected static MediaManagerImplementation MediaManager => CrossMediaManager.Apple;

        public override void ViewWillDisappear(bool animated)
        {
            base.ViewWillDisappear(animated);

            if (MediaManager.MediaPlayer.VideoView == View.Superview)
            {
                MediaManager.MediaPlayer.VideoView = null;
            }

            Player = null;
        }
    }
}

Make MediaManager a static property

Make MediaManager a static property


using RimWorld;
using Verse;

namespace MTW_AncestorSpirits
{
    class ThoughtWorker_NoShrineRoom : ThoughtWorker
    {
        private static RoomRoleDef shrineRoomDef = DefDatabase<RoomRoleDef>.GetNamed("MTW_ShrineRoom");

        protected override ThoughtState CurrentStateInternal(Pawn p)
        {
            // TODO: There's gotta be a better way of doin' this!
            if (!AncestorUtils.IsAncestor(p)) { return ThoughtState.Inactive; }

            var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner;
            if (shrine == null) { return ThoughtState.Inactive; }

            // HACK ALERT! Change Shrines to have an Interaction cell, and use that instead of a random one!
            var room = RoomQuery.RoomAtFast(shrine.RandomAdjacentCellCardinal());
            if (room == null)
            {
                return ThoughtState.ActiveAtStage(1);
            }
            else if (room.Role != shrineRoomDef)
            {
                return ThoughtState.ActiveAtStage(1);
            }
            else
            {
                return ThoughtState.Inactive;
            }
        }
    }
}

using RimWorld;
using Verse;

namespace MTW_AncestorSpirits
{
    class ThoughtWorker_NoShrineRoom : ThoughtWorker
    {
        private static RoomRoleDef shrineRoomDef = DefDatabase<RoomRoleDef>.GetNamed("MTW_ShrineRoom");

        protected override ThoughtState CurrentStateInternal(Pawn p)
        {
            // TODO: There's gotta be a better way of doin' this!
            if (!AncestorUtils.IsAncestor(p)) { return ThoughtState.Inactive; }

            var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner;
            if (shrine == null) { return ThoughtState.ActiveAtStage(1); }

            // HACK ALERT! Change Shrines to have an Interaction cell, and use that instead of a random one!
            var room = RoomQuery.RoomAtFast(shrine.RandomAdjacentCellCardinal());
            if (room == null)
            {
                return ThoughtState.ActiveAtStage(1);
            }
            else if (room.Role != shrineRoomDef)
            {
                return ThoughtState.ActiveAtStage(1);
            }
            else
            {
                return ThoughtState.Inactive;
            }
        }
    }
}

Fix NoShrineRoom logic if shrine is null

If for some reason the Shrine is destroyed, should keep the thought
penalty.


using System.Collections.Generic;
using System.IO;
namespace LINQToTTreeLib.ExecutionCommon
{
    /// <summary>
    /// Runs an execution request
    /// </summary>
    interface IQueryExectuor
    {
        /// <summary>
        /// Run request, and return the results
        /// </summary>
        /// <param name="remotePacket"></param>
        /// <returns></returns>
        IDictionary<string, ROOTNET.Interface.NTObject> Execute(
            FileInfo templateFile,
            DirectoryInfo queryDirectory,
            IEnumerable<KeyValuePair<string, object>> varsToTransfer);

        /// <summary>
        /// Set the execution envrionment. Must be done before the call, should not
        /// change after the first setting.
        /// </summary>
        ExecutionEnvironment Environment { set; }
    }
}

using System.Collections.Generic;
using System.IO;
namespace LINQToTTreeLib.ExecutionCommon
{
    /// <summary>
    /// Runs an execution request
    /// </summary>
    interface IQueryExectuor
    {
        /// <summary>
        /// Run request, and return the results
        /// </summary>
        /// <param name="queryDirectory"></param>
        /// <param name="templateFile">Path to the main runner file</param>
        /// <param name="varsToTransfer">A list of variables that are used as input to the routine.</param>
        /// <returns>A list of objects and names pulled from the output root file</returns>
        IDictionary<string, ROOTNET.Interface.NTObject> Execute(
            FileInfo templateFile,
            DirectoryInfo queryDirectory,
            IEnumerable<KeyValuePair<string, object>> varsToTransfer);

        /// <summary>
        /// Set the execution envrionment. Must be done before the call, should not
        /// change after the first setting.
        /// </summary>
        ExecutionEnvironment Environment { set; }
    }
}

Improve comments on the interface.

Improve comments on the interface.


using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using WeCantSpell.Tests.Utilities;
using Xunit;

namespace WeCantSpell.Tests.Integration.CSharp
{
    public class CommentSpellingTests : CSharpTestBase
    {
        public static IEnumerable<object[]> can_find_mistakes_in_comments_data
        {
            get
            {
                yield return new object[] { "aardvark", 660 };
                yield return new object[] { "simple", 1186 };
                yield return new object[] { "under", 1235 };
            }
        }

        [Theory, MemberData(nameof(can_find_mistakes_in_comments_data))]
        public async Task can_find_mistakes_in_comments(string expectedWord, int expectedStart)
        {
            var expectedEnd = expectedStart + expectedWord.Length;

            var analyzer = new SpellingAnalyzerCSharp(new WrongWordChecker(expectedWord));
            var project = await ReadCodeFileAsProjectAsync("XmlDoc.SimpleExamples.cs");

            var diagnostics = await GetDiagnosticsAsync(project, analyzer);

            diagnostics.Should().ContainSingle()
                .Subject.Should()
                .HaveId("SP3112")
                .And.HaveLocation(expectedStart, expectedEnd, "XmlDoc.SimpleExamples.cs")
                .And.HaveMessageContaining(expectedWord);
        }
    }
}

using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using WeCantSpell.Tests.Utilities;
using Xunit;

namespace WeCantSpell.Tests.Integration.CSharp
{
    public class CommentSpellingTests : CSharpTestBase
    {
        public static IEnumerable<object[]> can_find_mistakes_in_comments_data
        {
            get
            {
                yield return new object[] { "aardvark", 660 };
                yield return new object[] { "simple", 1186 };
                yield return new object[] { "under", 1235 };
                yield return new object[] { "inline", 111 };
                yield return new object[] { "tag", 320 };
                yield return new object[] { "Here", 898 };
                yield return new object[] { "Just", 1130 };
            }
        }

        [Theory, MemberData(nameof(can_find_mistakes_in_comments_data))]
        public async Task can_find_mistakes_in_comments(string expectedWord, int expectedStart)
        {
            var expectedEnd = expectedStart + expectedWord.Length;

            var analyzer = new SpellingAnalyzerCSharp(new WrongWordChecker(expectedWord));
            var project = await ReadCodeFileAsProjectAsync("XmlDoc.SimpleExamples.cs");

            var diagnostics = await GetDiagnosticsAsync(project, analyzer);

            diagnostics.Should().ContainSingle()
                .Subject.Should()
                .HaveId("SP3112")
                .And.HaveLocation(expectedStart, expectedEnd, "XmlDoc.SimpleExamples.cs")
                .And.HaveMessageContaining(expectedWord);
        }
    }
}

Add a few more tests

Add a few more tests


namespace WebScriptHook.Framework.Messages.Outputs
{
    /// <summary>
    /// Sent by the component to request a channel for itself on the server.
    /// This tells the server the name of this component, as well as the maximum number of requests
    /// the component can handle per tick.
    /// Once the server receives this message, a channel will be created, registered under this component's name.
    /// Inputs sent by web clients will then be delivered to this component.
    /// </summary>
    class ChannelRequest : WebOutput
    {
        const char HEADER_CACHE = 'n';

        public ChannelRequest(string ComponentName, int InputQueueLimit)
            : base(HEADER_CACHE, new object[] { ComponentName, InputQueueLimit }, null)
        {
        }
    }
}

namespace WebScriptHook.Framework.Messages.Outputs
{
    /// <summary>
    /// Sent by the component to request a channel for itself on the server.
    /// This tells the server the name of this component, as well as the maximum number of requests
    /// the component can handle per tick.
    /// Once the server receives this message, a channel will be created, registered under this component's name.
    /// Inputs sent by web clients will then be delivered to this component.
    /// </summary>
    class ChannelRequest : WebOutput
    {
        const char HEADER_CHANNEL = 'n';

        public ChannelRequest(string ComponentName, int InputQueueLimit)
            : base(HEADER_CHANNEL, new object[] { ComponentName, InputQueueLimit }, null)
        {
        }
    }
}

Fix a typo in const name

Fix a typo in const name


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

using System.ComponentModel;
using Microsoft.AspNetCore.ResponseCaching.Internal;

namespace Microsoft.AspNetCore.Builder
{
    public class ResponseCacheOptions
    {
        /// <summary>
        /// The largest cacheable size for the response body in bytes. The default is set to 1 MB.
        /// </summary>
        public long MaximumBodySize { get; set; } = 1024 * 1024;

        /// <summary>
        /// <c>true</c> if request paths are case-sensitive; otherwise <c>false</c>. The default is to treat paths as case-insensitive.
        /// </summary>
        public bool UseCaseSensitivePaths { get; set; } = false;

        /// <summary>
        /// For testing purposes only.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        internal ISystemClock SystemClock { get; set; } = new SystemClock();
    }
}

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

using System.ComponentModel;
using Microsoft.AspNetCore.ResponseCaching.Internal;

namespace Microsoft.AspNetCore.Builder
{
    public class ResponseCacheOptions
    {
        /// <summary>
        /// The largest cacheable size for the response body in bytes. The default is set to 64 MB.
        /// </summary>
        public long MaximumBodySize { get; set; } = 64 * 1024 * 1024;

        /// <summary>
        /// <c>true</c> if request paths are case-sensitive; otherwise <c>false</c>. The default is to treat paths as case-insensitive.
        /// </summary>
        public bool UseCaseSensitivePaths { get; set; } = false;

        /// <summary>
        /// For testing purposes only.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        internal ISystemClock SystemClock { get; set; } = new SystemClock();
    }
}

Update default Max Body Size

Update default Max Body Size


using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Data;
using Tera.Game;

namespace DamageMeter.UI
{
    /// <summary>
    ///     Logique d'interaction pour HistoryLink.xaml
    /// </summary>
    public partial class HistoryLink
    {
        public HistoryLink(string link, NpcEntity boss)
        {
            InitializeComponent();
            Boss.Content = boss.Info.Name;
            Boss.Tag = link;
            if (link.StartsWith("!"))
            {
                Boss.Foreground = Brushes.Red;
                Boss.ToolTip = link;
                return;
            }
            Link.Source = BasicTeraData.Instance.ImageDatabase.Link.Source;
        }

        private void Click_Link(object sender, MouseButtonEventArgs e)
        {
            if (Boss.Tag.ToString().StartsWith("http://"))
                Process.Start("explorer.exe", Boss.Tag.ToString());
        }

        private void Sender_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var w = Window.GetWindow(this);
            try
            {
                w?.DragMove();
            }
            catch
            {
                Console.WriteLine(@"Exception move");
            }
        }
    }
}

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Data;
using Tera.Game;

namespace DamageMeter.UI
{
    /// <summary>
    ///     Logique d'interaction pour HistoryLink.xaml
    /// </summary>
    public partial class HistoryLink
    {
        public HistoryLink(string link, NpcEntity boss)
        {
            InitializeComponent();
            Boss.Content = boss.Info.Name;
            Boss.Tag = link;
            if (link.StartsWith("!"))
            {
                Boss.Foreground = Brushes.Red;
                Boss.ToolTip = link;
                return;
            }
            Link.Source = BasicTeraData.Instance.ImageDatabase.Link.Source;
        }

        private void Click_Link(object sender, MouseButtonEventArgs e)
        {
            if (Boss.Tag.ToString().StartsWith("http://"))
                Process.Start("explorer.exe", "\""+Boss.Tag+"\"");
        }

        private void Sender_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var w = Window.GetWindow(this);
            try
            {
                w?.DragMove();
            }
            catch
            {
                Console.WriteLine(@"Exception move");
            }
        }
    }
}

Fix encounter url not opening

Fix encounter url not opening


using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
// ReSharper disable AccessToDisposedClosure

namespace VGAudio.Cli
{
    internal static class Batch
    {
        public static bool BatchConvert(Options options)
        {
            if (options.Job != JobType.Batch) return false;

            SearchOption searchOption = options.Recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
            string[] files = ContainerTypes.ExtensionList
                .SelectMany(x => Directory.GetFiles(options.InDir, $"*.{x}", searchOption))
                .ToArray();

            using (var progress = new ProgressBar())
            {
                progress.SetTotal(files.Length);

                Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount - 1 }, inPath =>
                {
                    string relativePath = inPath.Substring(options.InDir.Length).TrimStart('\\');
                    string outPath = Path.ChangeExtension(Path.Combine(options.OutDir, relativePath), options.OutTypeName);

                    var jobFiles = new JobFiles();
                    jobFiles.InFiles.Add(new AudioFile(inPath));
                    jobFiles.OutFiles.Add(new AudioFile(outPath));

                    try
                    {
                        progress.LogMessage(Path.GetFileName(inPath));
                        Convert.ConvertFile(options, jobFiles, false);
                    }
                    catch (Exception ex)
                    {
                        progress.LogMessage($"Error converting {Path.GetFileName(inPath)}");
                        progress.LogMessage(ex.ToString());
                    }

                    progress.ReportAdd(1);
                });
            }

            return true;
        }
    }
}

using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
// ReSharper disable AccessToDisposedClosure

namespace VGAudio.Cli
{
    internal static class Batch
    {
        public static bool BatchConvert(Options options)
        {
            if (options.Job != JobType.Batch) return false;

            SearchOption searchOption = options.Recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
            string[] files = ContainerTypes.ExtensionList
                .SelectMany(x => Directory.GetFiles(options.InDir, $"*.{x}", searchOption))
                .ToArray();

            using (var progress = new ProgressBar())
            {
                progress.SetTotal(files.Length);

                Parallel.ForEach(files,
                    new ParallelOptions { MaxDegreeOfParallelism = Math.Max(Environment.ProcessorCount - 1, 1) },
                    inPath =>
                    {
                        string relativePath = inPath.Substring(options.InDir.Length).TrimStart('\\');
                        string outPath = Path.ChangeExtension(Path.Combine(options.OutDir, relativePath), options.OutTypeName);

                        var jobFiles = new JobFiles();
                        jobFiles.InFiles.Add(new AudioFile(inPath));
                        jobFiles.OutFiles.Add(new AudioFile(outPath));

                        try
                        {
                            progress.LogMessage(Path.GetFileName(inPath));
                            Convert.ConvertFile(options, jobFiles, false);
                        }
                        catch (Exception ex)
                        {
                            progress.LogMessage($"Error converting {Path.GetFileName(inPath)}");
                            progress.LogMessage(ex.ToString());
                        }

                        progress.ReportAdd(1);
                    });
            }

            return true;
        }
    }
}

Fix single core batch processing

CLI: Fix single core batch processing

An oversight caused the batch converter to try to use '0' cores when running on a single-core processor


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

using BenchmarkDotNet.Attributes;
using osu.Game.Online.API;
using osu.Game.Rulesets.Osu;

namespace osu.Game.Benchmarks
{
    public class BenchmarkRuleset : BenchmarkTest
    {
        private OsuRuleset ruleset;
        private APIMod apiModDoubleTime;
        private APIMod apiModDifficultyAdjust;

        public override void SetUp()
        {
            base.SetUp();
            ruleset = new OsuRuleset();
            apiModDoubleTime = new APIMod { Acronym = "DT" };
            apiModDifficultyAdjust = new APIMod { Acronym = "DA" };
        }

        [Benchmark]
        public void BenchmarkToModDoubleTime()
        {
            apiModDoubleTime.ToMod(ruleset);
        }

        [Benchmark]
        public void BenchmarkToModDifficultyAdjust()
        {
            apiModDifficultyAdjust.ToMod(ruleset);
        }

        [Benchmark]
        public void BenchmarkGetAllMods()
        {
            ruleset.GetAllMods();
        }
    }
}

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

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
using osu.Game.Online.API;
using osu.Game.Rulesets.Osu;

namespace osu.Game.Benchmarks
{
    public class BenchmarkRuleset : BenchmarkTest
    {
        private OsuRuleset ruleset;
        private APIMod apiModDoubleTime;
        private APIMod apiModDifficultyAdjust;

        public override void SetUp()
        {
            base.SetUp();
            ruleset = new OsuRuleset();
            apiModDoubleTime = new APIMod { Acronym = "DT" };
            apiModDifficultyAdjust = new APIMod { Acronym = "DA" };
        }

        [Benchmark]
        public void BenchmarkToModDoubleTime()
        {
            apiModDoubleTime.ToMod(ruleset);
        }

        [Benchmark]
        public void BenchmarkToModDifficultyAdjust()
        {
            apiModDifficultyAdjust.ToMod(ruleset);
        }

        [Benchmark]
        public void BenchmarkGetAllMods()
        {
            ruleset.GetAllMods().Consume(new Consumer());
        }
    }
}

Fix enumerable not being consumed

Fix enumerable not being consumed


using System.IO;

namespace DevTyr.Gullap.Model
{
    public static class MetaContentExtensions
    {
        public static string GetTargetFileName(this MetaContent content, SitePaths paths)
        {
            var isPage = content.Page != null;

			string userDefinedFileName = content.GetOverriddenFileName();
			string targetFileName = string.IsNullOrWhiteSpace(userDefinedFileName) ? Path.GetFileNameWithoutExtension(content.FileName) + ".html" : userDefinedFileName;
            string targetDirectory;

            if (isPage)
            {
                targetDirectory = Path.GetDirectoryName(targetFileName.Replace(paths.PagesPath, paths.OutputPath));
            }
            else
            {
                targetDirectory =
                    Path.GetDirectoryName(content.FileName.Replace(paths.PostsPath,
                        Path.Combine(paths.OutputPath, SitePaths.PostsDirectoryName)));
            }

            var targetPath = Path.Combine(targetDirectory, targetFileName);
            return targetPath;
        }
    }
}

using System.IO;

namespace DevTyr.Gullap.Model
{
    public static class MetaContentExtensions
    {
        public static string GetTargetFileName(this MetaContent content, SitePaths paths)
        {
            var isPage = content.Page != null;

			string userDefinedFileName = content.GetOverriddenFileName();
			string targetFileName = string.IsNullOrWhiteSpace(userDefinedFileName) ? Path.GetFileNameWithoutExtension(content.FileName) + ".html" : userDefinedFileName;
            string targetDirectory;

            if (isPage)
            {
                targetDirectory = Path.GetDirectoryName(content.FileName.Replace(paths.PagesPath, paths.OutputPath));
            }
            else
            {
                targetDirectory =
                    Path.GetDirectoryName(content.FileName.Replace(paths.PostsPath,
                        Path.Combine(paths.OutputPath, SitePaths.PostsDirectoryName)));
            }

            var targetPath = Path.Combine(targetDirectory, targetFileName);
            return targetPath;
        }
    }
}

Fix target file name generation

Fix target file name generation


using Glimpse.Agent.Web;
using Microsoft.AspNet.Builder;
using Glimpse.Host.Web.AspNet;
using Microsoft.Framework.DependencyInjection;

namespace Glimpse.Agent.AspNet.Sample
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGlimpse()
                .RunningAgent()
                    .ForWeb()
                        .Configure<GlimpseAgentWebOptions>(options =>
                        {
                            //options.IgnoredStatusCodes.Add(200);
                        })
                .WithRemoteStreamAgent();
                //.WithRemoteHttpAgent();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseGlimpse();

            app.UseWelcomePage();
        }
    }
}

using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using Glimpse.Agent.Web;
using Glimpse.Agent.Web.Framework;
using Glimpse.Agent.Web.Options;
using Microsoft.AspNet.Builder;
using Glimpse.Host.Web.AspNet;
using Microsoft.Framework.DependencyInjection;

namespace Glimpse.Agent.AspNet.Sample
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            /* Example of how to use fixed provider

            TODO: This should be cleanned up with help of extenion methods

            services.AddSingleton<IIgnoredRequestProvider>(x =>
            {
                var activator = x.GetService<ITypeActivator>();

                var urlPolicy = activator.CreateInstances<IIgnoredRequestPolicy>(new []
                    {
                        typeof(UriIgnoredRequestPolicy).GetTypeInfo(),
                        typeof(ContentTypeIgnoredRequestPolicy).GetTypeInfo()
                    });

                var provider = new FixedIgnoredRequestProvider(urlPolicy);

                return provider;
            });
            */

            services.AddGlimpse()
                .RunningAgent()
                    .ForWeb()
                        .Configure<GlimpseAgentWebOptions>(options =>
                        {
                            //options.IgnoredStatusCodes.Add(200);
                        })
                .WithRemoteStreamAgent();
                //.WithRemoteHttpAgent();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseGlimpse();

            app.UseWelcomePage();
        }
    }
}

Add example of using fixed provider

Add example of using fixed provider

This is to be cleaned up


@{
    Layout = "~/Views/Shared/_LayoutPublic.cshtml";
}

@section metaPage
{
  <meta property="og:type" content="website">
  <meta property="og:image" content="@(AppConfiguration.Value.SiteUrl + "/content/images/logo-og.jpg")">
}

@RenderBody()

@{
    Layout = "~/Views/Shared/_LayoutPublic.cshtml";
}

@section metaPage
{
  <meta property="og:type" content="website">
  <meta property="og:image" content="@(AppConfiguration.Value.SiteUrl + "/images/logo-og.jpg")">
}

@RenderBody()

Fix og:image path for home page

Fix og:image path for home page


using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace SqlDiffFramework
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new MainForm());
		}
	}
}

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using SqlDiffFramework.Forms;

namespace SqlDiffFramework
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new MainForm());
		}
	}
}

Reorganize forms into project subfolder

Reorganize forms into project subfolder


namespace WeatherDataFunctionApp
{
    using System;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.Azure.WebJobs.Host;

    public static class WeatherDataService
    {
        private static readonly HttpClient WeatherDataHttpClient = new HttpClient();

        private static readonly string ApiUrl;

        static WeatherDataService()
        {
            string apiKey = System.Configuration.ConfigurationManager.AppSettings["ApiKey"];
            ApiUrl = $"https://api.apixu.com/v1/current.json?key={apiKey}&q={{0}}";
        }

        [FunctionName("WeatherDataService")]
        public static async Task<HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "WeatherDataService/Current/{location}")]HttpRequestMessage req, string location, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            HttpResponseMessage responseMessage = await GetCurrentWeatherDataForLocation(location);

            if (responseMessage.IsSuccessStatusCode)
                return req.CreateResponse(HttpStatusCode.OK, responseMessage.Content.ReadAsAsync(typeof(object)).Result);

            log.Error($"Error occurred while trying to retrieve weather data for {req.Content.ReadAsStringAsync().Result}");
            return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "Internal Server Error.");
        }

        private static async Task<HttpResponseMessage> GetCurrentWeatherDataForLocation(string location)
        {
            return await WeatherDataHttpClient.GetAsync(String.Format(ApiUrl, location));
        }
    }
}

namespace WeatherDataFunctionApp
{
    using System;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.Azure.WebJobs.Host;

    public static class WeatherDataService
    {
        private static readonly HttpClient WeatherDataHttpClient = new HttpClient();

        private static readonly string ApiUrl;

        static WeatherDataService()
        {
            string apiKey = System.Configuration.ConfigurationManager.AppSettings["ApiKey"];
            ApiUrl = $"https://api.apixu.com/v1/current.json?key={apiKey}&q={{0}}";
        }

        [FunctionName("WeatherDataService")]
        public static async Task<HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            var queryNameValuePairs = req.GetQueryNameValuePairs();
            var location = queryNameValuePairs.Where(pair => pair.Key.Equals("location", StringComparison.InvariantCultureIgnoreCase)).Select(queryParam => queryParam.Value).FirstOrDefault();

            HttpResponseMessage responseMessage = await GetCurrentWeatherDataForLocation(location);

            if (responseMessage.IsSuccessStatusCode)
                return req.CreateResponse(HttpStatusCode.OK, responseMessage.Content.ReadAsAsync(typeof(object)).Result);

            log.Error($"Error occurred while trying to retrieve weather data for {req.Content.ReadAsStringAsync().Result}");
            return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "Internal Server Error.");
        }

        private static async Task<HttpResponseMessage> GetCurrentWeatherDataForLocation(string location)
        {
            return await WeatherDataHttpClient.GetAsync(String.Format(ApiUrl, location));
        }
    }
}

Read querystring instead of using route patterns


using Microsoft.Web.Administration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace Launcher
{
    public class ExecutionMetadata
    {
        [JsonProperty("start_command")]
        public string DetectedStartCommand { get; set; }

        [JsonProperty("start_command_args")]
        public string[] StartCommandArgs { get; set; }
    }

    class Program
    {
        static int Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.Error.WriteLine("Launcher was run with insufficient arguments. The arguments were: {0}",
                    String.Join(" ", args));
                return 1;
            }

            ExecutionMetadata executionMetadata = null;

            try
            {
                executionMetadata = JsonConvert.DeserializeObject<ExecutionMetadata>(args[2]);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(
                    "Launcher was run with invalid JSON for the metadata argument. The JSON was: {0}", args[2]);
                return 1;
            }

            var startInfo = new ProcessStartInfo
            {
                UseShellExecute = false,
                FileName = executionMetadata.DetectedStartCommand,
                Arguments = ArgumentEscaper.Escape(executionMetadata.StartCommandArgs),
            };

            var process = Process.Start(startInfo);

            process.WaitForExit();

            return process.ExitCode;
        }
    }
}

using Microsoft.Web.Administration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace Launcher
{
    public class ExecutionMetadata
    {
        [JsonProperty("start_command")]
        public string DetectedStartCommand { get; set; }

        [JsonProperty("start_command_args")]
        public string[] StartCommandArgs { get; set; }
    }

    class Program
    {
        static int Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.Error.WriteLine("Launcher was run with insufficient arguments. The arguments were: {0}",
                    String.Join(" ", args));
                return 1;
            }

            ExecutionMetadata executionMetadata = null;

            try
            {
                executionMetadata = JsonConvert.DeserializeObject<ExecutionMetadata>(args[2]);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(
                    "Launcher was run with invalid JSON for the metadata argument. The JSON was: {0}", args[2]);
                return 1;
            }

            var startInfo = new ProcessStartInfo
            {
                UseShellExecute = false,
                FileName = executionMetadata.DetectedStartCommand,
                Arguments = ArgumentEscaper.Escape(executionMetadata.StartCommandArgs),
            };

            Console.Out.WriteLine("Run {0} :with: {1}", startInfo.FileName, startInfo.Arguments);

            var process = Process.Start(startInfo);

            process.WaitForExit();

            return process.ExitCode;
        }
    }
}

Add informational logging to launcher

Add informational logging to launcher


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

namespace CreviceApp.Threading
{
    // http://www.codeguru.com/csharp/article.php/c18931/Understanding-the-NET-Task-Parallel-Library-TaskScheduler.htm
    public class SingleThreadScheduler : TaskScheduler, IDisposable
    {
        private readonly BlockingCollection<Task> tasks = new BlockingCollection<Task>();
        private readonly Thread thread;

        public SingleThreadScheduler() : this(ThreadPriority.Normal) { }

        public SingleThreadScheduler(ThreadPriority priority)
        {
            this.thread = new Thread(new ThreadStart(Main));
            this.thread.Priority = priority;
            this.thread.Start();
        }

        private void Main()
        {
            Verbose.Print("SingleThreadScheduler was started; Thread ID: 0x{0:X}", Thread.CurrentThread.ManagedThreadId);
            foreach (var t in tasks.GetConsumingEnumerable())
            {
                TryExecuteTask(t);
            }
        }

        protected override IEnumerable<Task> GetScheduledTasks()
        {
            return tasks.ToArray();
        }

        protected override void QueueTask(Task task)
        {
            tasks.Add(task);
        }

        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
        {
            return false;
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
            tasks.CompleteAdding();
        }

        ~SingleThreadScheduler()
        {
            Dispose();
        }
    }
}

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

namespace CreviceApp.Threading
{
    // http://www.codeguru.com/csharp/article.php/c18931/Understanding-the-NET-Task-Parallel-Library-TaskScheduler.htm
    public class SingleThreadScheduler : TaskScheduler, IDisposable
    {
        private readonly BlockingCollection<Task> tasks = new BlockingCollection<Task>();
        private readonly Thread thread;

        public SingleThreadScheduler() : this(ThreadPriority.Normal) { }

        public SingleThreadScheduler(ThreadPriority priority)
        {
            this.thread = new Thread(new ThreadStart(Main));
            this.thread.Priority = priority;
            this.thread.Start();
        }

        private void Main()
        {
            Verbose.Print("SingleThreadScheduler(ThreadID: 0x{0:X}) was started.", Thread.CurrentThread.ManagedThreadId);
            foreach (var t in tasks.GetConsumingEnumerable())
            {
                TryExecuteTask(t);
            }
        }

        protected override IEnumerable<Task> GetScheduledTasks()
        {
            return tasks.ToArray();
        }

        protected override void QueueTask(Task task)
        {
            tasks.Add(task);
        }

        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
        {
            return false;
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
            tasks.CompleteAdding();
        }

        ~SingleThreadScheduler()
        {
            Dispose();
        }
    }
}

Refactor verbose log of SingleThreadScheduler.


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

using ecologylab.serialization;
using ecologylab.attributes;

namespace ecologylabFundamentalTestCases.Polymorphic
{
    /**
      *
      * <configuration>
             <pref_double name="index_thumb_dist" value="200"/>
        </configuration>
      *
      */

    public class Configuration : ElementState
    {

        [simpl_nowrap]
        [simpl_scope("testScope")]
        //[simpl_classes(new Type[] { typeof(Pref), typeof(PrefDouble) })]
        [simpl_map]
        public Dictionary<String, Pref> prefs = new Dictionary<string, Pref>();

        #region GetterSetters

        public Dictionary<String, Pref> Preferences
        {
            get { return prefs; }
            set { prefs = value; }
        }
        #endregion

        internal void fillDictionary()
        {
            PrefDouble prefDouble = new PrefDouble();
            prefDouble.Name = "index_thumb_dist";
            prefDouble.Value = 200;

            Pref pref = new Pref();
            pref.Name = "test_name";

            prefs.Add(prefDouble.Name, prefDouble);
            prefs.Add(pref.Name, pref);
        }
    }
}

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

using ecologylab.serialization;
using ecologylab.attributes;

namespace ecologylabFundamentalTestCases.Polymorphic
{
    /**
      *
      * <configuration>
             <pref_double name="index_thumb_dist" value="200"/>
        </configuration>
      *
      */

    public class Configuration : ElementState
    {

        [simpl_nowrap]
        [simpl_scope("testScope")]
        //[simpl_classes(new Type[] { typeof(Pref), typeof(PrefDouble) })]
        [simpl_map]
        public Dictionary<String, Pref> prefs = new Dictionary<string, Pref>();

        #region GetterSetters

        public Dictionary<String, Pref> Preferences
        {
            get { return prefs; }
            set { prefs = value; }
        }
        #endregion

        internal void fillDictionary()
        {
            PrefDouble prefDouble = new PrefDouble();
            prefDouble.Name = "index_thumb_dist \"now with a double quote\" and a 'single quote' ";
            prefDouble.Value = 200;

            Pref pref = new Pref();
            pref.Name = "test_name";

            prefs.Add(prefDouble.Name, prefDouble);
            prefs.Add(pref.Name, pref);
        }
    }
}

Test case includes string with quotes.

Test case includes string with quotes.


using System;
using osu.Framework.Configuration;
using osu.Framework.Graphics.UserInterface;

namespace osu.Game.Overlays.Options
{
    public class CheckBoxOption : BasicCheckBox
    {
        private Bindable<bool> bindable;

        public Bindable<bool> Bindable
        {
            set
            {
                if (bindable != null)
                    bindable.ValueChanged -= bindableValueChanged;
                bindable = value;
                if (bindable != null)
                {
                    bool state = State == CheckBoxState.Checked;
                    if (state != bindable.Value)
                        State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked;
                    bindable.ValueChanged += bindableValueChanged;
                }
            }
        }

        private void bindableValueChanged(object sender, EventArgs e)
        {
            State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked;
        }

        protected override void Dispose(bool isDisposing)
        {
            if (bindable != null)
                bindable.ValueChanged -= bindableValueChanged;
            base.Dispose(isDisposing);
        }

        protected override void OnChecked()
        {
            if (bindable != null)
                bindable.Value = true;
            base.OnChecked();
        }

        protected override void OnUnchecked()
        {
            if (bindable != null)
                bindable.Value = false;
            base.OnChecked();
        }
    }
}

using System;
using osu.Framework.Configuration;
using osu.Framework.Graphics.UserInterface;

namespace osu.Game.Overlays.Options
{
    public class CheckBoxOption : BasicCheckBox
    {
        private Bindable<bool> bindable;

        public Bindable<bool> Bindable
        {
            set
            {
                if (bindable != null)
                    bindable.ValueChanged -= bindableValueChanged;
                bindable = value;
                if (bindable != null)
                {
                    bool state = State == CheckBoxState.Checked;
                    if (state != bindable.Value)
                        State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked;
                    bindable.ValueChanged += bindableValueChanged;
                }
            }
        }

        private void bindableValueChanged(object sender, EventArgs e)
        {
            State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked;
        }

        protected override void Dispose(bool isDisposing)
        {
            if (bindable != null)
                bindable.ValueChanged -= bindableValueChanged;
            base.Dispose(isDisposing);
        }

        protected override void OnChecked()
        {
            if (bindable != null)
                bindable.Value = true;
            base.OnChecked();
        }

        protected override void OnUnchecked()
        {
            if (bindable != null)
                bindable.Value = false;
            base.OnUnchecked();
        }
    }
}

Fix checkbox not updating correctly.

Fix checkbox not updating correctly.


using System;
using System.Threading;
using NUnit.Framework;

namespace Atata.WebDriverExtras.Tests
{
    [TestFixture]
    [Parallelizable(ParallelScope.None)]
    public class SafeWaitTests
    {
        private SafeWait<object> wait;

        [SetUp]
        public void SetUp()
        {
            wait = new SafeWait<object>(new object())
            {
                Timeout = TimeSpan.FromSeconds(.3),
                PollingInterval = TimeSpan.FromSeconds(.05)
            };
        }

        [Test]
        public void SafeWait_Success_Immediate()
        {
            using (StopwatchAsserter.Within(0, .01))
                wait.Until(_ =>
                {
                    return true;
                });
        }

        [Test]
        public void SafeWait_Timeout()
        {
            using (StopwatchAsserter.Within(.3, .015))
                wait.Until(_ =>
                {
                    return false;
                });
        }

        [Test]
        public void SafeWait_PollingInterval()
        {
            using (StopwatchAsserter.Within(.3, .2))
                wait.Until(_ =>
                {
                    Thread.Sleep(TimeSpan.FromSeconds(.1));
                    return false;
                });
        }

        [Test]
        public void SafeWait_PollingInterval_GreaterThanTimeout()
        {
            wait.PollingInterval = TimeSpan.FromSeconds(1);

            using (StopwatchAsserter.Within(.3, .015))
                wait.Until(_ =>
                {
                    return false;
                });
        }
    }
}

using System;
using System.Threading;
using NUnit.Framework;

namespace Atata.WebDriverExtras.Tests
{
    [TestFixture]
    [Parallelizable(ParallelScope.None)]
    public class SafeWaitTests
    {
        private SafeWait<object> wait;

        [SetUp]
        public void SetUp()
        {
            wait = new SafeWait<object>(new object())
            {
                Timeout = TimeSpan.FromSeconds(.3),
                PollingInterval = TimeSpan.FromSeconds(.05)
            };
        }

        [Test]
        public void SafeWait_Success_Immediate()
        {
            using (StopwatchAsserter.Within(0, .01))
                wait.Until(_ =>
                {
                    return true;
                });
        }

        [Test]
        public void SafeWait_Timeout()
        {
            using (StopwatchAsserter.Within(.3, .015))
                wait.Until(_ =>
                {
                    return false;
                });
        }

        [Test]
        public void SafeWait_PollingInterval()
        {
            using (StopwatchAsserter.Within(.3, .2))
                wait.Until(_ =>
                {
                    Thread.Sleep(TimeSpan.FromSeconds(.1));
                    return false;
                });
        }

        [Test]
        public void SafeWait_PollingInterval_GreaterThanTimeout()
        {
            wait.PollingInterval = TimeSpan.FromSeconds(1);

            using (StopwatchAsserter.Within(.3, .02))
                wait.Until(_ =>
                {
                    return false;
                });
        }
    }
}

Increase toleranceSeconds in SafeWait_PollingInterval_GreaterThanTimeout test


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Paymetheus
{
    /// <summary>
    /// Interaction logic for Send.xaml
    /// </summary>
    public partial class Send : Page
    {
        public Send()
        {
            InitializeComponent();
        }

        private void OutputAmountTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = e.Text.All(ch => !((ch >= '0' && ch <= '9') || ch == '.'));
        }
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Paymetheus
{
    /// <summary>
    /// Interaction logic for Send.xaml
    /// </summary>
    public partial class Send : Page
    {
        string decimalSep = CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;

        public Send()
        {
            InitializeComponent();
        }

        private void OutputAmountTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = e.Text.All(ch => !((ch >= '0' && ch <= '9') || decimalSep.Contains(ch)));
        }
    }
}

Use locale's decimal separator instead of hardcoding period.

Fixes #130.


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="WinAPI.NET">
//   Copyright (c) Marek Dzikiewicz, All Rights Reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")]

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="WinAPI.NET">
//   Copyright (c) Marek Dzikiewicz, All Rights Reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")]

// Assembly is CLS-compliant
[assembly: CLSCompliant(true)]

Set WinApiNet assembly as CLS-compliant

Set WinApiNet assembly as CLS-compliant


using Silk.Data.SQL.Expressions;
using Silk.Data.SQL.Queries;
using System.Threading.Tasks;

namespace Silk.Data.SQL.ORM.Operations
{
	public abstract class DataOperation
	{
		/// <summary>
		/// Gets a value indicating if the operation can be executed as part of a batch operation.
		/// </summary>
		public abstract bool CanBeBatched { get; }

		/// <summary>
		/// Gets the SQL query needed to run the DataOperation.
		/// </summary>
		/// <returns></returns>
		public abstract QueryExpression GetQuery();

		/// <summary>
		/// Process the result QueryResult set to the correct result set.
		/// </summary>
		public abstract void ProcessResult(QueryResult queryResult);

		/// <summary>
		/// Process the result QueryResult set to the correct result set.
		/// </summary>
		public abstract Task ProcessResultAsync(QueryResult queryResult);
	}

	public abstract class DataOperationWithResult<T> : DataOperation
	{
		/// <summary>
		/// Gets the result of the data operation.
		/// </summary>
		public abstract T Result { get; }
	}
}

using Silk.Data.SQL.Expressions;
using Silk.Data.SQL.Queries;
using System.Threading.Tasks;

namespace Silk.Data.SQL.ORM.Operations
{
	public abstract class DataOperation
	{
		/// <summary>
		/// Gets a value indicating if the operation can be executed as part of a batch operation.
		/// </summary>
		public abstract bool CanBeBatched { get; }

		/// <summary>
		/// Gets the SQL query needed to run the DataOperation.
		/// </summary>
		/// <returns></returns>
		public abstract QueryExpression GetQuery();

		/// <summary>
		/// Process the result QueryResult set to the correct result set.
		/// </summary>
		public abstract void ProcessResult(QueryResult queryResult);

		/// <summary>
		/// Process the result QueryResult set to the correct result set.
		/// </summary>
		public abstract Task ProcessResultAsync(QueryResult queryResult);
	}

	public abstract class DataOperationWithResult : DataOperation
	{
		/// <summary>
		/// Gets the result of the data operation without a known static type.
		/// </summary>
		public abstract object UntypedResult { get; }
	}

	public abstract class DataOperationWithResult<T> : DataOperationWithResult
	{
		/// <summary>
		/// Gets the result of the data operation.
		/// </summary>
		public abstract T Result { get; }

		public override object UntypedResult => Result;
	}
}

Add an API for getting the result of an operation without knowing it's type.