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

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using WcfTestBridgeCommon;

namespace WcfService.TestResources
{
    internal class BasicAuthResource : EndpointResource<WcfUserNameService, IWcfCustomUserNameService>
    {
        protected override string Address { get { return "https-basic"; } }

        protected override string Protocol { get { return BaseAddressResource.Https; } }

        protected override int GetPort(ResourceRequestContext context)
        {
            return context.BridgeConfiguration.BridgeHttpsPort;
        }

        protected override Binding GetBinding()
        {
            var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
            return binding;
        }

        private ServiceCredentials GetServiceCredentials()
        {
            var serviceCredentials = new ServiceCredentials();
            serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
            serviceCredentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator();
            return serviceCredentials;
        }

        protected override void ModifyBehaviors(ServiceDescription desc)
        {
            base.ModifyBehaviors(desc);

            desc.Behaviors.Remove<ServiceCredentials>();
            desc.Behaviors.Add(GetServiceCredentials());
        }
    }
}

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

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using WcfService.CertificateResources;
using WcfTestBridgeCommon;

namespace WcfService.TestResources
{
    internal class BasicAuthResource : EndpointResource<WcfUserNameService, IWcfCustomUserNameService>
    {
        protected override string Address { get { return "https-basic"; } }

        protected override string Protocol { get { return BaseAddressResource.Https; } }

        protected override int GetPort(ResourceRequestContext context)
        {
            return context.BridgeConfiguration.BridgeHttpsPort;
        }

        protected override Binding GetBinding()
        {
            var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
            return binding;
        }

        private ServiceCredentials GetServiceCredentials()
        {
            var serviceCredentials = new ServiceCredentials();
            serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
            serviceCredentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator();
            return serviceCredentials;
        }

        protected override void ModifyBehaviors(ServiceDescription desc)
        {
            base.ModifyBehaviors(desc);

            desc.Behaviors.Remove<ServiceCredentials>();
            desc.Behaviors.Add(GetServiceCredentials());
        }

        protected override void ModifyHost(ServiceHost serviceHost, ResourceRequestContext context)
        {
            // Ensure the https certificate is installed before this endpoint resource is used
            CertificateResourceHelpers.EnsureSslPortCertificateInstalled(context.BridgeConfiguration);

            base.ModifyHost(serviceHost, context);
        }
    }
}

Fix test failure when BasicAuth tests were first to run

The Https BasicAuthentication tests failed were they were the first
scenario tests run after a fresh start of the Bridge.  But they succeeded
when other scenario tests ran first.

Root cause was that the BasicAuthResource was not explicitly ensuring
the SSL port certificate was installed.  It passed if another scenario
test did that first.

The fix was to duplicate what the other Https test resources do and
explicitly ensure the SSL port certificate is installed.

Fixes #788


using System;

namespace FluentAssertions.Common
{
    internal static class Guard
    {
        public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName)
        {
            if (obj is null)
            {
                throw new ArgumentNullException(paramName);
            }
        }

        public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName, string message)
        {
            if (obj is null)
            {
                throw new ArgumentNullException(paramName, message);
            }
        }

        public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName)
        {
            if (string.IsNullOrEmpty(str))
            {
                throw new ArgumentNullException(paramName);
            }
        }

        public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName, string message)
        {
            if (string.IsNullOrEmpty(str))
            {
                throw new ArgumentNullException(paramName, message);
            }
        }

        /// <summary>
        /// Workaround to make dotnet_code_quality.null_check_validation_methods work
        /// https://github.com/dotnet/roslyn-analyzers/issues/3451#issuecomment-606690452
        /// </summary>
        [AttributeUsage(AttributeTargets.Parameter)]
        private sealed class ValidatedNotNullAttribute : Attribute
        {
        }
    }
}

using System;

namespace FluentAssertions.Common
{
    internal static class Guard
    {
        public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName)
        {
            if (obj is null)
            {
                throw new ArgumentNullException(paramName);
            }
        }

        public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName, string message)
        {
            if (obj is null)
            {
                throw new ArgumentNullException(paramName, message);
            }
        }

        public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName)
        {
            if (string.IsNullOrEmpty(str))
            {
                throw new ArgumentNullException(paramName);
            }
        }

        public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName, string message)
        {
            if (string.IsNullOrEmpty(str))
            {
                throw new ArgumentNullException(paramName, message);
            }
        }

        public static void ThrowIfArgumentIsOutOfRange<T>([ValidatedNotNull] T value, string paramName)
            where T : Enum
        {
            if (!Enum.IsDefined(typeof(T), value))
            {
                throw new ArgumentOutOfRangeException(paramName);
            }
        }

        public static void ThrowIfArgumentIsOutOfRange<T>([ValidatedNotNull] T value, string paramName, string message)
            where T : Enum
        {
            if (!Enum.IsDefined(typeof(T), value))
            {
                throw new ArgumentOutOfRangeException(paramName, message);
            }
        }

        /// <summary>
        /// Workaround to make dotnet_code_quality.null_check_validation_methods work
        /// https://github.com/dotnet/roslyn-analyzers/issues/3451#issuecomment-606690452
        /// </summary>
        [AttributeUsage(AttributeTargets.Parameter)]
        private sealed class ValidatedNotNullAttribute : Attribute
        {
        }
    }
}

Add guard methods for Enum Argument OutOfRange check


@model IEnumerable<RightpointLabs.Pourcast.Web.Areas.Admin.Models.TapModel>

@{
    ViewBag.Title = "Index";
}

Taps

@foreach (var tap in Model)
{

@tap.Name

        @if (null == tap.Keg)
        {

No Keg On Tap

        }
        else
        {

@tap.Keg.BeerName

                Amount of Beer Remaining: @tap.Keg.AmountOfBeerRemaining

                Percent Left: @tap.Keg.PercentRemaining

        }

            @Html.ActionLink("Edit", "Edit", new {id = tap.Id})

}

     |
    @Html.ActionLink("Back to List", "Index")

@model IEnumerable<RightpointLabs.Pourcast.Web.Areas.Admin.Models.TapModel>

@{
    ViewBag.Title = "Index";
}

Taps

@foreach (var tap in Model)
{

@tap.Name

        @if (null == tap.Keg)
        {

No Keg On Tap

        }
        else
        {

@tap.Keg.BeerName

                Amount of Beer Remaining: @tap.Keg.AmountOfBeerRemaining

                Percent Left: @tap.Keg.PercentRemaining

        }

            @Html.ActionLink("Edit", "Edit", new {id = tap.Id}, new { @class = "btn"})
            @if (null != tap.Keg)
            {
                Pour
            }

}

     |
    @Html.ActionLink("Back to List", "Index")

@section scripts {

}

Add fake pour buttons in admin

Add fake pour buttons in admin

They follow the same API as the Netduino will: 1 StartPour when pressed,
0-N Pouring while button held down, 1 StopPour when button released.


using System.Text.RegularExpressions;

namespace MarekMotykaBot.ExtensionsMethods
{
	public static class StringExtensions
	{
		public static string RemoveRepeatingChars(this string inputString)
		{
			string newString = string.Empty;
			char[] charArray = inputString.ToCharArray();

			for (int i = 0; i < charArray.Length; i++)
			{
				if (string.IsNullOrEmpty(newString))
					newString += charArray[i].ToString();
				else if (newString[newString.Length - 1] != charArray[i])
					newString += charArray[i].ToString();
			}

			return newString;
		}

		public static string RemoveEmojis(this string inputString)
		{
			return Regex.Replace(inputString, @"[^a-zA-Z0-9żźćńółęąśŻŹĆĄŚĘŁÓŃ\s\?\.\,\!\-\']+", "", RegexOptions.Compiled);
		}

		public static string RemoveEmotes(this string inputString)
		{
			return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled);
		}

		public static string RemoveEmojisAndEmotes(this string inputString)
		{
			return inputString.RemoveEmotes().RemoveEmojis();
		}
	}
}

using System.Text.RegularExpressions;

namespace MarekMotykaBot.ExtensionsMethods
{
	public static class StringExtensions
	{
		public static string RemoveRepeatingChars(this string inputString)
		{
			string newString = string.Empty;
			char[] charArray = inputString.ToCharArray();

			for (int i = 0; i < charArray.Length; i++)
			{
				if (string.IsNullOrEmpty(newString))
					newString += charArray[i].ToString();
				else if (newString[newString.Length - 1] != charArray[i])
					newString += charArray[i].ToString();
			}

			return newString;
		}

		public static string RemoveEmojis(this string inputString)
		{
			return Regex.Replace(inputString, @"[^a-zA-Z0-9żźćńółęąśŻŹĆĄŚĘŁÓŃ\s\?\.\,\!\-]+", "", RegexOptions.Compiled);
		}

		public static string RemoveEmotes(this string inputString)
		{
			return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled);
		}

		public static string RemoveEmojisAndEmotes(this string inputString)
		{
			return inputString.RemoveEmotes().RemoveEmojis();
		}
	}
}

Fix regex pattern in removing emotes.

Fix regex pattern in removing emotes.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace api
{
    public class CommaDelimitedArrayModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelMetadata.IsEnumerableType)
            {
                var key = bindingContext.ModelName;
                var value = bindingContext.ValueProvider.GetValue(key).ToString();

                if (!string.IsNullOrWhiteSpace(value))
                {
                    var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0];
                    var converter = TypeDescriptor.GetConverter(elementType);

                    var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => converter.ConvertFromString(x.Trim()))
                        .ToArray();

                    var typedValues = Array.CreateInstance(elementType, values.Length);

                    values.CopyTo(typedValues, 0);

                    bindingContext.Result = ModelBindingResult.Success(typedValues);
                }
                else
                {
                    Console.WriteLine("string was empty");
                    // change this line to null if you prefer nulls to empty arrays
                    bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0));
                }

                return Task.CompletedTask;
            }
            Console.WriteLine("Not enumerable");
            return Task.CompletedTask;
        }
    }
}

using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace api
{
    public class CommaDelimitedArrayModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelMetadata.IsEnumerableType)
            {
                var key = bindingContext.ModelName;
                var value = bindingContext.ValueProvider.GetValue(key).ToString();

                if (!string.IsNullOrWhiteSpace(value))
                {
                    var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0];
                    var converter = TypeDescriptor.GetConverter(elementType);

                    var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => converter.ConvertFromString(x.Trim()))
                        .ToArray();

                    var typedValues = Array.CreateInstance(elementType, values.Length);

                    values.CopyTo(typedValues, 0);

                    bindingContext.Result = ModelBindingResult.Success(typedValues);
                }
                else
                {
                    Console.WriteLine("string was empty");
                    // change this line to null if you prefer nulls to empty arrays
                    bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0));
                }

                return Task.CompletedTask;
            }
            Console.WriteLine("Not enumerable");
            return Task.CompletedTask;
        }
    }
}

Add input binder to allow for comma-separated list inputs for API routes

Signed-off-by: Max Cairney-Leeming <d90f0d0190ac210d40c0e06a2594c771efeb4f5b@gmail.com>


using Core;
using StructureMap;
using System.Diagnostics;
using Xunit;

namespace Tests
{
    public class TroubleshootingTests
    {
        [Fact]
        public void ShowBuildPlan()
        {
            var container = new Container(x =>
            {
                x.For<IService>().Use<Service>();
            });

            var buildPlan = container.Model.For<IService>()
                .Default
                .DescribeBuildPlan();

            var expectedBuildPlan =
@"PluginType: Core.IService
Lifecycle: Transient
new Service()
";

            Assert.Equal(expectedBuildPlan, buildPlan);
        }

        [Fact]
        public void WhatDoIHave()
        {
            var container = new Container(x =>
            {
                x.For<IService>().Use<Service>();
            });

            var whatDoIHave = container.WhatDoIHave();
            Trace.Write(whatDoIHave);
        }
    }
}

using Core;
using StructureMap;
using Xunit;

namespace Tests
{
    public class TroubleshootingTests
    {
        [Fact]
        public void ShowBuildPlan()
        {
            var container = new Container(x =>
            {
                x.For<IService>().Use<Service>();
            });

            var buildPlan = container.Model.For<IService>()
                .Default
                .DescribeBuildPlan();

            var expectedBuildPlan =
@"PluginType: Core.IService
Lifecycle: Transient
new Service()
";

            Assert.Equal(expectedBuildPlan, buildPlan);
        }

        [Fact]
        public void WhatDoIHave()
        {
            var container = new Container(x =>
            {
                x.For<IService>().Use<Service>();
            });

            var whatDoIHave = container.WhatDoIHave();

            var expectedWhatDoIHave = @"

===================================================================================================
PluginType           Namespace        Lifecycle     Description                           Name
---------------------------------------------------------------------------------------------------
Func<TResult>        System           Transient     Open Generic Template for Func<>      (Default)
---------------------------------------------------------------------------------------------------
Func<T, TResult>     System           Transient     Open Generic Template for Func<,>     (Default)
---------------------------------------------------------------------------------------------------
IContainer           StructureMap     Singleton     Object:  StructureMap.Container       (Default)
---------------------------------------------------------------------------------------------------
IService             Core             Transient     Core.Service                          (Default)
---------------------------------------------------------------------------------------------------
Lazy<T>              System           Transient     Open Generic Template for Func<>      (Default)
===================================================================================================";

            Assert.Equal(expectedWhatDoIHave, whatDoIHave);
        }
    }
}

Modify WhatDoIHave to show expected result


namespace Mollie.Api.Models.Payment {
    public static class PaymentMethod {
        public const string Bancontact = "bancontact";
        public const string BankTransfer = "banktransfer";
        public const string Belfius = "belfius";
        public const string CreditCard = "creditcard";
        public const string DirectDebit = "directdebit";
        public const string Eps = "eps";
        public const string GiftCard = "giftcard";
        public const string Giropay = "giropay";
        public const string Ideal = "ideal";
        public const string IngHomePay = "inghomepay";
        public const string Kbc = "kbc";
        public const string PayPal = "paypal";
        public const string PaySafeCard = "paysafecard";
        public const string Sofort = "sofort";
        public const string Refund = "refund";
        public const string KlarnaPayLater = "klarnapaylater";
        public const string KlarnaSliceIt = "klarnasliceit";
        public const string Przelewy24 = "przelewy24";
        public const string ApplePay = "applepay";
        public const string MealVoucher = "mealvoucher";
    }
}

namespace Mollie.Api.Models.Payment {
    public static class PaymentMethod {
        public const string Bancontact = "bancontact";
        public const string BankTransfer = "banktransfer";
        public const string Belfius = "belfius";
        public const string CreditCard = "creditcard";
        public const string DirectDebit = "directdebit";
        public const string Eps = "eps";
        public const string GiftCard = "giftcard";
        public const string Giropay = "giropay";
        public const string Ideal = "ideal";
        public const string IngHomePay = "inghomepay";
        public const string Kbc = "kbc";
        public const string PayPal = "paypal";
        public const string PaySafeCard = "paysafecard";
        public const string Sofort = "sofort";
        public const string Refund = "refund";
        public const string KlarnaPayLater = "klarnapaylater";
        public const string KlarnaSliceIt = "klarnasliceit";
        public const string Przelewy24 = "przelewy24";
        public const string ApplePay = "applepay";
        public const string MealVoucher = "mealvoucher";
        public const string In3 = "in3";
    }
}

Add support for the new upcoming in3 payment method


using Rescuer.Management.Rescuers;

namespace Rescuer.Management.Controller
{
    public class RescuerController : IRescuerController
    {
        private readonly IRescuerFactory _factory;

        public RescuerController(IRescuerFactory factory)
        {
            _factory = factory;
        }

        public IRescuer[] IntializeRescuers(string[] monitoredEntities)
        {
            var rescuers = new IRescuer[monitoredEntities.Length];
            for (int i = 0; i < rescuers.Length; i++)
            {
                rescuers[i] = _factory.Create();
                rescuers[i].Connect(monitoredEntities[i]);
            }

            return rescuers;
        }

        public void DoWork(IRescuer[] rescuers)
        {
            for (int i = 0; i < rescuers.Length; i++)
            {
                rescuers[i].MonitorAndRescue();
            }
        }

    }
}

using System;
using System.Text;
using Rescuer.Management.Rescuers;

namespace Rescuer.Management.Controller
{
    public class RescuerController : IRescuerController
    {
        private readonly IRescuerFactory _factory;

        public RescuerController(IRescuerFactory factory)
        {
            _factory = factory;
        }

        public IRescuer[] IntializeRescuers(string[] monitoredEntities)
        {
            var rescuers = new IRescuer[monitoredEntities.Length];
            for (int i = 0; i < rescuers.Length; i++)
            {
                if (String.IsNullOrWhiteSpace(monitoredEntities[i]))
                {
                    var entitiesString = ToFlatString(monitoredEntities);
                    throw new ArgumentException($"monitored entity name can't be null or empty! FailedIndex: {i} Array: [{entitiesString}]");
                }

                rescuers[i] = _factory.Create();
                rescuers[i].Connect(monitoredEntities[i]);
            }

            return rescuers;
        }

        public void DoWork(IRescuer[] rescuers)
        {
            for (int i = 0; i < rescuers.Length; i++)
            {
                rescuers[i].MonitorAndRescue();
            }
        }

        private static string ToFlatString(string[] array)
        {
            var builder = new StringBuilder();

            foreach (var entity in array)
            {
                builder.Append(entity);
                builder.Append(",");
            }
            var str = builder.ToString();

            return str.Remove(str.Length - 1, 1);
        }
    }
}

Handle empty entity name in rescuer

Handle empty entity name in rescuer


namespace ReamQuery.Test
{
    using System;
    using Xunit;
    using ReamQuery.Helpers;
    using Microsoft.CodeAnalysis.Text;

    public class Helpers
    {
        [Fact]
        public void String_InsertTextAt()
        {
            var inp = "\r\n  text\r\n";
            var exp = "\r\n new text\r\n";
            var output = inp.InsertTextAt("new", 1, 1);

            Assert.Equal(exp, output);
        }

        [Fact]
        public void String_NormalizeNewlines_And_InsertTextAt()
        {
            var inp = "\r\n  text\n";
            var exp = "\r\n new text\r\n";
            var output = inp.NormalizeNewlines().InsertTextAt("new", 1, 1);

            Assert.Equal(exp, output);
        }

        [Fact]
        public void String_NormalizeNewlines()
        {
            var inp = "\r\n text\n";
            var exp = Environment.NewLine + " text" + Environment.NewLine;
            var output = inp.NormalizeNewlines();

            Assert.Equal(exp, output);
        }

        [Fact]
        public void String_ReplaceToken()
        {
            var inp = Environment.NewLine + Environment.NewLine + " token " + Environment.NewLine;
            var exp = Environment.NewLine + Environment.NewLine + "  " + Environment.NewLine;
            LinePosition pos;
            var output = inp.ReplaceToken("token", string.Empty, out pos);

            Assert.Equal(new LinePosition(2, 1), pos);
            Assert.Equal(exp, output);
        }
    }
}

namespace ReamQuery.Test
{
    using System;
    using Xunit;
    using ReamQuery.Helpers;
    using Microsoft.CodeAnalysis.Text;

    public class Helpers
    {
        [Fact]
        public void String_InsertTextAt()
        {
            var inp = Environment.NewLine + "  text" + Environment.NewLine;
            var exp = Environment.NewLine + " new text" + Environment.NewLine;
            var output = inp.InsertTextAt("new", 1, 1);

            Assert.Equal(exp, output);
        }

        [Fact]
        public void String_NormalizeNewlines_And_InsertTextAt()
        {
            var inp = "\r\n  text\n";
            var exp = Environment.NewLine + " new text" + Environment.NewLine;
            var output = inp.NormalizeNewlines().InsertTextAt("new", 1, 1);

            Assert.Equal(exp, output);
        }

        [Fact]
        public void String_NormalizeNewlines()
        {
            var inp = "\r\n  text\n";
            var exp = Environment.NewLine + "  text" + Environment.NewLine;
            var output = inp.NormalizeNewlines();

            Assert.Equal(exp, output);
        }

        [Fact]
        public void String_ReplaceToken()
        {
            var inp = Environment.NewLine + Environment.NewLine + " token " + Environment.NewLine;
            var exp = Environment.NewLine + Environment.NewLine + "  " + Environment.NewLine;
            LinePosition pos;
            var output = inp.ReplaceToken("token", string.Empty, out pos);

            Assert.Equal(new LinePosition(2, 1), pos);
            Assert.Equal(exp, output);
        }
    }
}

Fix string test for ubuntu

Fix string test for ubuntu


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Foundatio.Extensions;
using Foundatio.Utility;

namespace Foundatio.Messaging {
    public abstract class MessageBusBase : IMessagePublisher, IDisposable {
        private readonly CancellationTokenSource _queueDisposedCancellationTokenSource;
        private readonly List<DelayedMessage> _delayedMessages = new List<DelayedMessage>();

        public MessageBusBase() {
            _queueDisposedCancellationTokenSource = new CancellationTokenSource();
            TaskHelper.RunPeriodic(DoMaintenance, TimeSpan.FromMilliseconds(500), _queueDisposedCancellationTokenSource.Token, TimeSpan.FromMilliseconds(100));
        }

        private Task DoMaintenance() {
            Trace.WriteLine("Doing maintenance...");
            foreach (var message in _delayedMessages.Where(m => m.SendTime <= DateTime.Now).ToList()) {
                _delayedMessages.Remove(message);
                Publish(message.MessageType, message.Message);
            }

            return TaskHelper.Completed();
        }

        public abstract void Publish(Type messageType, object message, TimeSpan? delay = null);

        protected void AddDelayedMessage(Type messageType, object message, TimeSpan delay) {
            if (message == null)
                throw new ArgumentNullException("message");

            _delayedMessages.Add(new DelayedMessage { Message = message, MessageType = messageType, SendTime = DateTime.Now.Add(delay) });
        }

        protected class DelayedMessage {
            public DateTime SendTime { get; set; }
            public Type MessageType { get; set; }
            public object Message { get; set; }
        }

        public virtual void Dispose() {
            _queueDisposedCancellationTokenSource.Cancel();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Foundatio.Extensions;
using Foundatio.Utility;

namespace Foundatio.Messaging {
    public abstract class MessageBusBase : IMessagePublisher, IDisposable {
        private readonly CancellationTokenSource _queueDisposedCancellationTokenSource;
        private readonly List<DelayedMessage> _delayedMessages = new List<DelayedMessage>();

        public MessageBusBase() {
            _queueDisposedCancellationTokenSource = new CancellationTokenSource();
            //TaskHelper.RunPeriodic(DoMaintenance, TimeSpan.FromMilliseconds(500), _queueDisposedCancellationTokenSource.Token, TimeSpan.FromMilliseconds(100));
        }

        private Task DoMaintenance() {
            Trace.WriteLine("Doing maintenance...");
            foreach (var message in _delayedMessages.Where(m => m.SendTime <= DateTime.Now).ToList()) {
                _delayedMessages.Remove(message);
                Publish(message.MessageType, message.Message);
            }

            return TaskHelper.Completed();
        }

        public abstract void Publish(Type messageType, object message, TimeSpan? delay = null);

        protected void AddDelayedMessage(Type messageType, object message, TimeSpan delay) {
            if (message == null)
                throw new ArgumentNullException("message");

            _delayedMessages.Add(new DelayedMessage { Message = message, MessageType = messageType, SendTime = DateTime.Now.Add(delay) });
        }

        protected class DelayedMessage {
            public DateTime SendTime { get; set; }
            public Type MessageType { get; set; }
            public object Message { get; set; }
        }

        public virtual void Dispose() {
            _queueDisposedCancellationTokenSource.Cancel();
        }
    }
}

Disable delayed messages to see what effect it has on tests.


using System;
using Shouldly;
using Xunit;

namespace Cake.Figlet.Tests
{
    public class FigletTests
    {
        [Fact]
        public void Figlet_can_render()
        {
            const string expected = @"
 _   _        _  _            __        __              _      _
| | | |  ___ | || |  ___      \ \      / /  ___   _ __ | |  __| |
| |_| | / _ \| || | / _ \      \ \ /\ / /  / _ \ | '__|| | / _` |
|  _  ||  __/| || || (_) | _    \ V  V /  | (_) || |   | || (_| |
|_| |_| \___||_||_| \___/ ( )    \_/\_/    \___/ |_|   |_| \__,_|
                          |/
";
            FigletAliases.Figlet(null, "Hello, World").ShouldBeWithLeadingLineBreak(expected);
        }
    }

    public static class ShouldlyAsciiExtensions
    {
        /// <summary>
        /// Helper to allow the expected ASCII art to be on it's own line when declaring
        /// the expected value in the source code
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="expected">The expected.</param>
        public static void ShouldBeWithLeadingLineBreak(this string input, string expected)
        {
            (Environment.NewLine + input).ShouldBe(expected, StringCompareShould.IgnoreLineEndings);
        }
    }
}

using System;
using Shouldly;
using Xunit;

namespace Cake.Figlet.Tests
{
    public class FigletTests
    {
        [Fact]
        public void Figlet_can_render()
        {
            const string expected = @"
 _   _        _  _            __        __              _      _
| | | |  ___ | || |  ___      \ \      / /  ___   _ __ | |  __| |
| |_| | / _ \| || | / _ \      \ \ /\ / /  / _ \ | '__|| | / _` |
|  _  ||  __/| || || (_) | _    \ V  V /  | (_) || |   | || (_| |
|_| |_| \___||_||_| \___/ ( )    \_/\_/    \___/ |_|   |_| \__,_|
                          |/
";
            FigletAliases.Figlet(null, "Hello, World").ShouldBeWithLeadingLineBreak(expected);
        }
    }

    public static class ShouldlyAsciiExtensions
    {
        /// <summary>
        /// Helper to allow the expected ASCII art to be on it's own line when declaring
        /// the expected value in the source code
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="expected">The expected.</param>
        public static void ShouldBeWithLeadingLineBreak(this string input, string expected)
        {
            (Environment.NewLine + input).ShouldBe(expected);
        }
    }
}

Revert "(GH-36) Fix broken test"

Revert "(GH-36) Fix broken test"

This reverts commit e8c0d4bc3a9fcb459096b05b189fd83f5883f1e2.


namespace System.Collections.Async
{
    /// <summary>
    /// This exception is thrown when you call <see cref="AsyncEnumerable{T}.Break"/>.
    /// </summary>
    public sealed class ForEachAsyncCanceledException : OperationCanceledException { }
}

namespace System.Collections.Async
{
    /// <summary>
    /// This exception is thrown when you call <see cref="ForEachAsyncExtensions.Break"/>.
    /// </summary>
    public sealed class ForEachAsyncCanceledException : OperationCanceledException { }
}

Fix xml comment cref compiler warning

Fix xml comment cref compiler warning


using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.Text;

namespace MotleyFlash.AspNetCore.MessageProviders
{
    public class SessionMessageProvider : IMessageProvider
    {
        public SessionMessageProvider(ISession session)
        {
            this.session = session;
        }

        private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
        {
            TypeNameHandling = TypeNameHandling.All
        };

        private readonly ISession session;
        private const string sessionKey = "motleyflash-session-message-provider";

        public object Get()
        {
            byte[] value;
            object messages = null;

            if (session.TryGetValue(sessionKey, out value))
            {
                if (value != null)
                {
                    messages =
                        JsonConvert.DeserializeObject(
                            Encoding.UTF8.GetString(value, 0, value.Length),
                            jsonSerializerSettings);
                }
            }

            return messages;
        }

        public void Set(object messages)
        {
            session.Set(
                sessionKey,
                Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(
                    messages,
                    jsonSerializerSettings)));

            session.CommitAsync();
        }
    }
}

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.Text;

namespace MotleyFlash.AspNetCore.MessageProviders
{
    public class SessionMessageProvider : IMessageProvider
    {
        public SessionMessageProvider(ISession session)
        {
            this.session = session;
        }

        private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
        {
            TypeNameHandling = TypeNameHandling.All
        };

        private readonly ISession session;
        private const string sessionKey = "motleyflash-session-message-provider";

        public object Get()
        {
            byte[] value;
            object messages = null;

            if (session.TryGetValue(sessionKey, out value))
            {
                if (value != null)
                {
                    messages =
                        JsonConvert.DeserializeObject(
                            Encoding.UTF8.GetString(value, 0, value.Length),
                            jsonSerializerSettings);
                }
            }

            return messages;
        }

        public void Set(object messages)
        {
            session.Set(
                sessionKey,
                Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(
                    messages,
                    jsonSerializerSettings)));
        }
    }
}

Remove session-commit statement that is not needed and already handled by middleware

Ref. https://github.com/aspnet/Session/blob/dabd28a5d9ac7837afbfce7c8dfa2805a9559857/src/Microsoft.AspNetCore.Session/SessionMiddleware.cs\#L116.


using System;
using Csla.Server;

namespace  Csla.Testing.Business.DataPortal
{
  /// <summary>
  /// Basically this test class exposes protected DataPortal constructor overloads to the
  /// Unit Testing System, allowing for a more fine-grained Unit Tests
  /// </summary>
  public class TestableDataPortal : Csla.Server.DataPortal
  {
    public TestableDataPortal() : base(){}

    public TestableDataPortal(string cslaAuthorizationProviderAppSettingName):
      base(cslaAuthorizationProviderAppSettingName)
    {
    }

    public TestableDataPortal(Type authProviderType):base(authProviderType) { }

    public static void Setup()
    {
      _authorizer = null;
    }

    public Type AuthProviderType
    {
      get { return _authorizer.GetType(); }
    }

    public IAuthorizeDataPortal AuthProvider
    {
      get { return _authorizer; }
    }

    public bool NullAuthorizerUsed
    {
      get
      {
        return AuthProviderType == typeof (NullAuthorizer);
      }
    }

  }
}

using System;
using Csla.Server;

namespace  Csla.Testing.Business.DataPortal
{
  /// <summary>
  /// Basically this test class exposes protected DataPortal constructor overloads to the
  /// Unit Testing System, allowing for a more fine-grained Unit Tests
  /// </summary>
  public class TestableDataPortal : Csla.Server.DataPortal
  {
    public TestableDataPortal() : base(){}

    public TestableDataPortal(string cslaAuthorizationProviderAppSettingName):
      base(cslaAuthorizationProviderAppSettingName)
    {
    }

    public TestableDataPortal(Type authProviderType):base(authProviderType) { }

    public static void Setup()
    {
      Authorizer = null;
    }

    public Type AuthProviderType
    {
      get { return Authorizer.GetType(); }
    }

    public IAuthorizeDataPortal AuthProvider
    {
      get { return Authorizer; }
    }

    public bool NullAuthorizerUsed
    {
      get
      {
        return AuthProviderType == typeof (NullAuthorizer);
      }
    }

  }
}

Update to use property, not field. bugid: 146


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using ReactiveUI.Routing.Presentation;
using Splat;

namespace ReactiveUI.Routing.UWP
{
    public class PagePresenter : Presenter<PagePresenterRequest>
    {
        private readonly Frame host;
        private readonly IViewLocator locator;

        public PagePresenter(Frame host, IViewLocator locator = null)
        {
            this.host = host ?? throw new ArgumentNullException(nameof(host));
            this.locator = locator ?? Locator.Current.GetService<IViewLocator>();
        }

        protected override IObservable<PresenterResponse> PresentCore(PagePresenterRequest request)
        {
            return Observable.Create<PresenterResponse>(o =>
            {
                try
                {
                    var view = locator.ResolveView(request.ViewModel);
                    view.ViewModel = request.ViewModel;
                    host.Navigate(view.GetType());

                    o.OnNext(new PresenterResponse(view));
                    o.OnCompleted();

                }
                catch (Exception ex)
                {
                    o.OnError(ex);
                }
                return new CompositeDisposable();
            });
        }

        public static IDisposable RegisterHost(Frame control)
        {
            var resolver = Locator.Current.GetService<IMutablePresenterResolver>();
            return resolver.Register(new PagePresenter(control));
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using ReactiveUI.Routing.Presentation;
using Splat;

namespace ReactiveUI.Routing.UWP
{
    public class PagePresenter : Presenter<PagePresenterRequest>
    {
        private readonly ContentControl host;
        private readonly IViewLocator locator;

        public PagePresenter(ContentControl host, IViewLocator locator = null)
        {
            this.host = host ?? throw new ArgumentNullException(nameof(host));
            this.locator = locator ?? Locator.Current.GetService<IViewLocator>();
        }

        protected override IObservable<PresenterResponse> PresentCore(PagePresenterRequest request)
        {
            return Observable.Create<PresenterResponse>(o =>
            {
                try
                {
                    var view = locator.ResolveView(request.ViewModel);

                    var disposable = view.WhenActivated(d =>
                    {
                        o.OnNext(new PresenterResponse(view));
                        o.OnCompleted();
                    });

                    view.ViewModel = request.ViewModel;
                    host.Content = view;

                    return disposable;
                }
                catch (Exception ex)
                {
                    o.OnError(ex);
                    throw;
                }
            });
        }

        public static IDisposable RegisterHost(ContentControl control)
        {
            var resolver = Locator.Current.GetService<IMutablePresenterResolver>();
            return resolver.Register(new PagePresenter(control));
        }
    }
}

Make the UWP page presenter us a common content control


using System;
using System.Runtime.InteropServices;
using System.Security;
using LibGit2Sharp.Core;

namespace LibGit2Sharp
{
    /// <summary>
    /// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access.
    /// </summary>
    public sealed class SecureUsernamePasswordCredentials : Credentials
    {
        /// <summary>
        /// Callback to acquire a credential object.
        /// </summary>
        /// <param name="cred">The newly created credential object.</param>
        /// <returns>0 for success, < 0 to indicate an error, > 0 to indicate no credential was acquired.</returns>
        protected internal override int GitCredentialHandler(out IntPtr cred)
        {
            if (Username == null || Password == null)
            {
                throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password.");
            }

            IntPtr passwordPtr = IntPtr.Zero;

            try
            {
                passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password);

                return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Marshal.PtrToStringUni(passwordPtr));
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
            }

        }

        /// <summary>
        /// Username for username/password authentication (as in HTTP basic auth).
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// Password for username/password authentication (as in HTTP basic auth).
        /// </summary>
        public SecureString Password { get; set; }
    }
}

using System;
using System.Runtime.InteropServices;
using System.Security;
using LibGit2Sharp.Core;

namespace LibGit2Sharp
{
    /// <summary>
    /// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access.
    /// </summary>
    public sealed class SecureUsernamePasswordCredentials : Credentials
    {
        /// <summary>
        /// Callback to acquire a credential object.
        /// </summary>
        /// <param name="cred">The newly created credential object.</param>
        /// <returns>0 for success, < 0 to indicate an error, > 0 to indicate no credential was acquired.</returns>
        protected internal override int GitCredentialHandler(out IntPtr cred)
        {
            if (Username == null || Password == null)
            {
                throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password.");
            }

            IntPtr passwordPtr = IntPtr.Zero;

            try
            {
#if NET40
                passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password);
#else
                passwordPtr = SecureStringMarshal.SecureStringToCoTaskMemUnicode(Password);
#endif

                return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Marshal.PtrToStringUni(passwordPtr));
            }
            finally
            {
#if NET40
                Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
#else
                SecureStringMarshal.ZeroFreeCoTaskMemUnicode(passwordPtr);
#endif
            }

        }

        /// <summary>
        /// Username for username/password authentication (as in HTTP basic auth).
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// Password for username/password authentication (as in HTTP basic auth).
        /// </summary>
        public SecureString Password { get; set; }
    }
}

Fix compile error around exporting SecureString


//-----------------------------------------------------------------------
// <copyright company="TheNucleus">
// Copyright (c) TheNucleus. All rights reserved.
// Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using Nuclei.Build;

[assembly: AssemblyCulture("")]

// Resources
[assembly: NeutralResourcesLanguage("en-US")]

// 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: AssemblyTrademark("")]

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

// Indicate that the assembly is CLS compliant.
[assembly: CLSCompliant(true)]

// The time the assembly was build
[assembly: AssemblyBuildTime(buildTime: "1900-01-01T00:00:00.0000000+00:00")]

// The version from which the assembly was build
[module: SuppressMessage(
    "Microsoft.Usage",
    "CA2243:AttributeStringLiteralsShouldParseCorrectly",
    Justification = "It's a VCS revision, not a version")]
[assembly: AssemblyBuildInformation(buildNumber: 0, versionControlInformation: "1234567890123456789012345678901234567890")]

Remove the build attributes because they'll be generated with a full namespace

references #7


using System;
using System.Text.RegularExpressions;

namespace Floobits.Common
{
    public class Constants {
        static public string baseDir = FilenameUtils.concat(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "floobits");
        static public string shareDir = FilenameUtils.concat(baseDir, "share");
        static public string version = "0.11";
        static public string pluginVersion = "0.01";
        static public string OUTBOUND_FILTER_PROXY_HOST = "proxy.floobits.com";
        static public int OUTBOUND_FILTER_PROXY_PORT = 443;
        static public string floobitsDomain = "floobits.com";
        static public string defaultHost = "floobits.com";
        static public int defaultPort = 3448;
        static public Regex NEW_LINE = new Regex("\\r\\n?", RegexOptions.Compiled);
        static public int TOO_MANY_BIG_DIRS = 50;
    }
}

using System;
using System.Text.RegularExpressions;

namespace Floobits.Common
{
    public class Constants {
        static public string baseDir = baseDirInit();
        static public string shareDir = FilenameUtils.concat(baseDir, "share");
        static public string version = "0.11";
        static public string pluginVersion = "0.01";
        static public string OUTBOUND_FILTER_PROXY_HOST = "proxy.floobits.com";
        static public int OUTBOUND_FILTER_PROXY_PORT = 443;
        static public string floobitsDomain = "floobits.com";
        static public string defaultHost = "floobits.com";
        static public int defaultPort = 3448;
        static public Regex NEW_LINE = new Regex("\\r\\n?", RegexOptions.Compiled);
        static public int TOO_MANY_BIG_DIRS = 50;

        static public string baseDirInit()
        {
            return FilenameUtils.concat(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "floobits");
        }
    }
}

Use the same folder as the JAVA implementation


using System;
using BmpListener.Bmp;
using BmpListener.JSON;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace BmpListener.ConsoleExample
{
    internal class Program
    {
        private static void Main()
        {
            JsonConvert.DefaultSettings = () =>
            {
                var settings = new JsonSerializerSettings();
                settings.Converters.Add(new IPAddressConverter());
                settings.Converters.Add(new StringEnumConverter());
                return settings;
            };

            var bmpListener = new BmpListener();
            bmpListener.Start(WriteJson).Wait();
        }

        private static void WriteJson(BmpMessage msg)
        {
            var json = JsonConvert.SerializeObject(msg);
            Console.WriteLine(json);
        }
    }
}

using System;
using BmpListener.Bmp;
using BmpListener.JSON;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

namespace BmpListener.ConsoleExample
{
    internal class Program
    {
        private static void Main()
        {
            JsonConvert.DefaultSettings = () =>
            {
                var settings = new JsonSerializerSettings();
                settings.Converters.Add(new IPAddressConverter());
                settings.Converters.Add(new StringEnumConverter());
                settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                return settings;
            };

            var bmpListener = new BmpListener();
            bmpListener.Start(WriteJson).Wait();
        }

        private static void WriteJson(BmpMessage msg)
        {
            var json = JsonConvert.SerializeObject(msg);
            Console.WriteLine(json);
        }
    }
}

Change default JSON serialization to CamelCase


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

namespace DataGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            var gen = new Fare.Xeger(ConfigurationSettings.AppSettings["pattern"]);

            for (int i = 0; i < 25; i++)
            {
                Console.WriteLine(gen.Generate());
            }

            Console.ReadLine();
        }
    }
}

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

namespace DataGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            var data = new Fare.Xeger(ConfigurationSettings.AppSettings["pattern"]);

            var tick = TimeSpan.Parse(ConfigurationSettings.AppSettings["timespan"]);

            Observable
                .Timer(TimeSpan.Zero, tick)
                .Subscribe(
                    t => { Console.WriteLine(data.Generate()); }
                );

            Console.ReadLine();
        }
    }
}

Use Timer based Observable to generate data


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

namespace Promact.Trappist.Repository.Questions
{
    public class QuestionRepository : IQuestionRespository
    {
        private readonly TrappistDbContext _dbContext;
        public QuestionRepository(TrappistDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// Get all questions
        /// </summary>
        /// <returns>Question list</returns>
        public List<SingleMultipleAnswerQuestion> GetAllQuestions()
        {
            var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
            return question;
        }
        /// <summary>
        /// Add single multiple answer question into model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <param name="singleMultipleAnswerQuestionOption"></param>
        public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
        {
            _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
            foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
            {
                singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
                _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
            }
            _dbContext.SaveChanges();
        }
    }
}

Update server side API for single multiple answer question


namespace Mappy.Models
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Windows.Forms;

    using Mappy.Data;
    using Mappy.Database;

    public interface IMapViewSettingsModel
    {
        IObservable<bool> GridVisible { get; }

        IObservable<Color> GridColor { get; }

        IObservable<Size> GridSize { get; }

        IObservable<bool> HeightmapVisible { get; }

        IObservable<bool> FeaturesVisible { get; }

        IObservable<IFeatureDatabase> FeatureRecords { get; }

        IObservable<IMainModel> Map { get; }

        IObservable<int> ViewportWidth { get; set; }

        IObservable<int> ViewportHeight { get; set; }

        void SetViewportSize(Size size);

        void SetViewportLocation(Point pos);

        void OpenFromDragDrop(string filename);

        void DragDropData(IDataObject data, Point loc);
    }
}

namespace Mappy.Models
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Windows.Forms;

    using Mappy.Data;
    using Mappy.Database;

    public interface IMapViewSettingsModel
    {
        IObservable<bool> GridVisible { get; }

        IObservable<Color> GridColor { get; }

        IObservable<Size> GridSize { get; }

        IObservable<bool> HeightmapVisible { get; }

        IObservable<bool> FeaturesVisible { get; }

        IObservable<IFeatureDatabase> FeatureRecords { get; }

        IObservable<IMainModel> Map { get; }

        IObservable<int> ViewportWidth { get; }

        IObservable<int> ViewportHeight { get; }

        void SetViewportSize(Size size);

        void SetViewportLocation(Point pos);

        void OpenFromDragDrop(string filename);

        void DragDropData(IDataObject data, Point loc);
    }
}

Remove setters from IObservable properties


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

namespace OpeningsMoeWpfClient
{
    class FfmpegMovieConverter : IMovieConverter
    {
        private string ffmpegPath;

        public Task<string> ConvertMovie(string sourcePath, string targetPath)
        {
            var tcs = new TaskCompletionSource<string>();

            var process = new Process
            {
                StartInfo =
                {
                    UseShellExecute = false,
                    FileName = ffmpegPath,
                    Arguments = $@"-i ""{sourcePath}"" -vcodec msmpeg4v2 -acodec libmp3lame -strict -2 ""{targetPath}""",
                    CreateNoWindow = true
                },
                EnableRaisingEvents = true
            };

            process.Exited += (sender, args) =>
            {
                if(process.ExitCode == 0)
                    tcs.SetResult(targetPath);
                else
                    tcs.SetException(new InvalidOperationException("SOMETHING WENT WRONG"));
                process.Dispose();
            };

            process.Start();
            process.PriorityClass = ProcessPriorityClass.BelowNormal;

            return tcs.Task;
        }

        public FfmpegMovieConverter(string ffmpegPath)
        {
            this.ffmpegPath = ffmpegPath;
        }
    }
}

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

namespace OpeningsMoeWpfClient
{
    class FfmpegMovieConverter : IMovieConverter
    {
        private string ffmpegPath;

        private Task<int> LaunchProcess(Func<Process> factory, Action<Process> postLaunchConfiguration)
        {
            var tcs = new TaskCompletionSource<int>();

            var process = factory();

            process.Exited += (sender, args) =>
            {
                tcs.SetResult(process.ExitCode);
                process.Dispose();
            };

            process.Start();
            postLaunchConfiguration(process);

            return tcs.Task;
        }

        public async Task<string> ConvertMovie(string sourcePath, string targetPath)
        {
            int exitCode = await LaunchProcess(() => new Process
            {
                StartInfo =
                {
                    UseShellExecute = false,
                    FileName = ffmpegPath,
                    Arguments =
                        $@"-i ""{sourcePath}"" -vcodec msmpeg4v2 -acodec libmp3lame -strict -2 ""{targetPath}""",
                    CreateNoWindow = true
                },
                EnableRaisingEvents = true
            }, process =>
            {
                process.PriorityClass = ProcessPriorityClass.BelowNormal;
            });

            if(exitCode == 0)
                return targetPath;
            throw new InvalidOperationException("SOMETHING WENT WRONG");
        }

        public FfmpegMovieConverter(string ffmpegPath)
        {
            this.ffmpegPath = ffmpegPath;
        }
    }
}

Split responsibility of ConvertMovie() method


using System.Linq;
using JetBrains.Annotations;
using JetBrains.ReSharper.Feature.Services.Lookup;
using JetBrains.ReSharper.PostfixTemplates.LookupItems;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;

namespace JetBrains.ReSharper.PostfixTemplates.Templates
{
  // todo: (Bar) foo.par - available in auto?

  [PostfixTemplate(
    templateName: "par",
    description: "Parenthesizes current expression",
    example: "(expr)")]
  public class ParenthesizedExpressionTemplate : IPostfixTemplate
  {
    public ILookupItem CreateItem(PostfixTemplateContext context)
    {
      if (context.IsAutoCompletion) return null;

      PrefixExpressionContext bestContext = null;
      foreach (var expressionContext in context.Expressions.Reverse())
      {
        if (CommonUtils.IsNiceExpression(expressionContext.Expression))
        {
          bestContext = expressionContext;
          break;
        }
      }

      return new ParenthesesItem(bestContext ?? context.OuterExpression);
    }

    private sealed class ParenthesesItem : ExpressionPostfixLookupItem<ICSharpExpression>
    {
      public ParenthesesItem([NotNull] PrefixExpressionContext context) : base("par", context) { }

      protected override ICSharpExpression CreateExpression(CSharpElementFactory factory,
                                                            ICSharpExpression expression)
      {
        return factory.CreateExpression("($0)", expression);
      }
    }
  }
}

using System.Linq;
using JetBrains.Annotations;
using JetBrains.ReSharper.Feature.Services.Lookup;
using JetBrains.ReSharper.PostfixTemplates.LookupItems;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;

namespace JetBrains.ReSharper.PostfixTemplates.Templates
{
  [PostfixTemplate(
    templateName: "par",
    description: "Parenthesizes current expression",
    example: "(expr)")]
  public class ParenthesizedExpressionTemplate : IPostfixTemplate
  {
    public ILookupItem CreateItem(PostfixTemplateContext context)
    {
      PrefixExpressionContext bestContext = null;
      foreach (var expressionContext in context.Expressions.Reverse())
      {
        if (CommonUtils.IsNiceExpression(expressionContext.Expression))
        {
          bestContext = expressionContext;
          break;
        }
      }

      // available in auto over cast expressions
      var targetContext = bestContext ?? context.OuterExpression;
      var insideCastExpression = CastExpressionNavigator.GetByOp(targetContext.Expression) != null;

      if (!insideCastExpression && context.IsAutoCompletion) return null;

      return new ParenthesesItem(targetContext);
    }

    private sealed class ParenthesesItem : ExpressionPostfixLookupItem<ICSharpExpression>
    {
      public ParenthesesItem([NotNull] PrefixExpressionContext context) : base("par", context) { }

      protected override ICSharpExpression CreateExpression(CSharpElementFactory factory,
                                                            ICSharpExpression expression)
      {
        return factory.CreateExpression("($0)", expression);
      }
    }
  }
}

Allow .par in auto in case of '(T) expr.par'


@using So.ImageResizer.Helpers

@{
    Style.Include("slimbox2.css");
    Script.Require("jQuery").AtFoot();
    Script.Include("slimbox2.js").AtFoot();
}
@if (!string.IsNullOrEmpty(Model.ContentField.FileNames))
{

        @foreach (var fileName in Model.ContentField.FileNames.Split(';'))
        {

                @{ var alternateText = string.IsNullOrEmpty(Model.ContentField.AlternateText) ? Path.GetFileNameWithoutExtension(fileName) : Model.ContentField.AlternateText; }

        }

}

Fix AgileUploader (remove SO image resizer)


using System;

namespace CmnTools.Suice
{
    /// <summary>
    /// @author DisTurBinG
    /// </summary>
	public class SingletonProvider : AbstractProvider
	{
		internal object Instance;

		public SingletonProvider (Type providedType)
			: base(providedType)
		{

		}

        internal virtual void CreateSingletonInstance()
        {
            SetInstance(Activator.CreateInstance(ProvidedType, ConstructorDependencies));
        }

        internal void SetInstance (object instance)
        {
            DependencyProxy dependencyProxy = Instance as DependencyProxy;

            if (dependencyProxy == null)
            {
                Instance = instance;
            }
            else
            {
                dependencyProxy.SetInstance(instance);
            }
        }

		protected override object ProvideObject()
		{
            return Instance ?? (Instance = new DependencyProxy (ProvidedType));
		}
	}
}

using System;

namespace CmnTools.Suice
{
    /// <summary>
    /// @author DisTurBinG
    /// </summary>
	public class SingletonProvider : AbstractProvider
	{
		internal object Instance;

		public SingletonProvider (Type providedType)
			: base(providedType)
		{

		}

        internal virtual void CreateSingletonInstance()
        {
            if (Instance == null)
            {
                SetInstance(Activator.CreateInstance(ProvidedType, ConstructorDependencies));
            }
        }

        internal void SetInstance (object instance)
        {
            DependencyProxy dependencyProxy = Instance as DependencyProxy;

            if (dependencyProxy == null)
            {
                Instance = instance;
            }
            else
            {
                dependencyProxy.SetInstance(instance);
            }
        }

		protected override object ProvideObject()
		{
            return Instance ?? (Instance = new DependencyProxy (ProvidedType));
		}
	}
}

Fix for Binding singleton to instance.

Fix for Binding singleton to instance.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Xml.Linq;

namespace Twilio.TwiML.Mvc
{
	public class TwiMLResult : ActionResult
	{
		XDocument data;

		public TwiMLResult()
		{
		}

		public TwiMLResult(string twiml)
		{
			data = XDocument.Parse(twiml);
		}

		public TwiMLResult(XDocument twiml)
		{
			data = twiml;
		}

		public TwiMLResult(TwilioResponse response)
		{
			data = response.ToXDocument();
		}

		public override void ExecuteResult(ControllerContext controllerContext)
		{
			var context = controllerContext.RequestContext.HttpContext;
			context.Response.ContentType = "application/xml";

			if (data == null)
			{
				data = new XDocument(new XElement("Response"));
			}

			data.Save(context.Response.Output);
		}
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Xml.Linq;

namespace Twilio.TwiML.Mvc
{
	public class TwiMLResult : ActionResult
	{
		XDocument data;

		public TwiMLResult()
		{
		}

		public TwiMLResult(string twiml)
		{
			data = XDocument.Parse(twiml);
		}

		public TwiMLResult(XDocument twiml)
		{
			data = twiml;
		}

		public TwiMLResult(TwilioResponse response)
		{
			if (response != null)
				data = response.ToXDocument();
		}

		public override void ExecuteResult(ControllerContext controllerContext)
		{
			var context = controllerContext.RequestContext.HttpContext;
			context.Response.ContentType = "application/xml";

			if (data == null)
			{
				data = new XDocument(new XElement("Response"));
			}

			data.Save(context.Response.Output);
		}
	}
}

Fix NullReference when using T4MVC

Fix NullReference when using T4MVC

T4MVC tries using the TwilioResponse constructor for the TwiMLResult object when generating the URL using URL.Action which causes a Runtime Exception.

More details can be found at https://t4mvc.codeplex.com/workitem/22


using System.Linq;
using System.Text.RegularExpressions;

namespace Inscribe.Text
{
    public static class TweetTextCounter
    {
        public static int Count(string input)
        {
            // URL is MAX 19 Chars.
            int prevIndex = 0;
            int totalCount = 0;
            foreach (var m in RegularExpressions.UrlRegex.Matches(input).OfType<Match>())
            {
                totalCount += m.Index - prevIndex;
                prevIndex = m.Index + m.Groups[0].Value.Length;
                if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength)
                    totalCount += m.Groups[0].Value.Length;
                else
                    totalCount += TwitterDefine.UrlMaxLength;
            }
            totalCount += input.Length - prevIndex;
            return totalCount;
        }
    }
}

using System.Linq;
using System.Text.RegularExpressions;

namespace Inscribe.Text
{
    public static class TweetTextCounter
    {
        public static int Count(string input)
        {
            // URL is MAX 20 Chars (if URL has HTTPS scheme, URL is MAX 21 Chars)
            int prevIndex = 0;
            int totalCount = 0;
            foreach (var m in RegularExpressions.UrlRegex.Matches(input).OfType<Match>())
            {
                totalCount += m.Index - prevIndex;
                prevIndex = m.Index + m.Groups[0].Value.Length;

                bool isHasHttpsScheme = m.Groups[0].Value.Contains("https");

                if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0))
                    totalCount += m.Groups[0].Value.Length;
                else
                    totalCount += TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0);
            }
            totalCount += input.Length - prevIndex;
            return totalCount;
        }
    }
}

Fix a bug of wrong counting characters with HTTPS URL

refs karno/Mystique#38


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using ExcelDna.Integration;

namespace RtdArrayTest
{
    public static class TestFunctions
    {
        public static object RtdArrayTest(string prefix)
        {
            object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, prefix);

            var resultString = rtdValue as string;
            if (resultString == null)
                return rtdValue;

            // We have a string value, parse and return as an 2x1 array
            var parts = resultString.Split(';');
            Debug.Assert(parts.Length == 2);
            var result = new object[2, 1];
            result[0, 0] = parts[0];
            result[1, 0] = parts[1];
            return result;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using ExcelDna.Integration;

namespace RtdArrayTest
{
    public static class TestFunctions
    {
        public static object RtdArrayTest(string prefix)
        {
            object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, prefix);

            var resultString = rtdValue as string;
            if (resultString == null)
                return rtdValue;

            // We have a string value, parse and return as an 2x1 array
            var parts = resultString.Split(';');
            Debug.Assert(parts.Length == 2);
            var result = new object[2, 1];
            result[0, 0] = parts[0];
            result[1, 0] = parts[1];
            return result;
        }

        // NOTE: This is that problem case discussed in https://groups.google.com/d/topic/exceldna/62cgmRMVtfQ/discussion
        // It seems that the DisconnectData will not be called on updates triggered by parameters from the sheet
        // for RTD functions that are marked IsMacroType=true.
        [ExcelFunction(IsMacroType=true)]
        public static object RtdArrayTestMT(string prefix)
        {
            object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, "X" + prefix);

            var resultString = rtdValue as string;
            if (resultString == null)
                return rtdValue;

            // We have a string value, parse and return as an 2x1 array
            var parts = resultString.Split(';');
            Debug.Assert(parts.Length == 2);
            var result = new object[2, 1];
            result[0, 0] = parts[0];
            result[1, 0] = parts[1];
            return result;
        }
    }
}

Add problem function (with IsMacroType=true)


// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)

using UnityEngine;
using System.Collections;

public class PortraitFlipTest : MonoBehaviour {

	void Update ()
	{
		Transform t = gameObject.transform.FindChild("Canvas/JohnCharacter");

		if (t == null)
		{
			return;
		}

		if (t.transform.localScale.x != -1f)
		{
			IntegrationTest.Fail("Character object not flipped horizontally");
		}
	}
}

// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)

using UnityEngine;
using System.Collections;

public class PortraitFlipTest : MonoBehaviour {

	void Update ()
	{
		Transform t = gameObject.transform.Find("Canvas/JohnCharacter");

		if (t == null)
		{
			return;
		}

		if (t.transform.localScale.x != -1f)
		{
			IntegrationTest.Fail("Character object not flipped horizontally");
		}
	}
}

Use transform.Find instead of deprecated transform.FindChild


using NUnit.Framework;

namespace FullSerializer.Tests.InitialInstance {
    public class SimpleModel {
        public int A;
    }

    public class InitialInstanceTests {
        [Test]
        public void TestInitialInstance() {
            SimpleModel model1 = new SimpleModel { A = 3 };

            fsData data;

            var serializer = new fsSerializer();
            Assert.IsTrue(serializer.TrySerialize(model1, out data).Succeeded);

            model1.A = 1;
            SimpleModel model2 = model1;
            Assert.IsTrue(serializer.TryDeserialize(data, ref model2).Succeeded);

            Assert.AreEqual(model1.A, 3);
            Assert.AreEqual(model2.A, 3);
            Assert.IsTrue(ReferenceEquals(model1, model2));
        }
    }
}

using NUnit.Framework;

namespace FullSerializer.Tests.InitialInstance {
    public class SimpleModel {
        public int A;
    }

    public class InitialInstanceTests {
        [Test]
        public void TestPopulateObject() {
            // This test verifies that when we pass in an existing object
            // instance that same instance is used to deserialize into, ie,
            // we can do the equivalent of Json.NET's PopulateObject

            SimpleModel model1 = new SimpleModel { A = 3 };

            fsData data;

            var serializer = new fsSerializer();
            Assert.IsTrue(serializer.TrySerialize(model1, out data).Succeeded);

            model1.A = 1;
            SimpleModel model2 = model1;
            Assert.AreEqual(1, model1.A);
            Assert.AreEqual(1, model2.A);

            Assert.IsTrue(serializer.TryDeserialize(data, ref model2).Succeeded);

            Assert.AreEqual(3, model1.A);
            Assert.AreEqual(3, model2.A);
            Assert.IsTrue(ReferenceEquals(model1, model2));
        }
    }
}

Add test description and fix param order in Assert call


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Zermelo.API")]
[assembly: AssemblyDescription("Connect to Zermelo from your .NET app")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Zermelo.API")]
[assembly: AssemblyCopyright("Copyright 2016 Arthur Rump")]
[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("2.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

// Make internal classes and functions available for testing
[assembly: InternalsVisibleTo("Zermelo.API.Tests")]

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Zermelo.API")]
[assembly: AssemblyDescription("Connect to Zermelo from your .NET app")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Zermelo.API")]
[assembly: AssemblyCopyright("Copyright 2016 Arthur Rump")]
[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("2.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]

// Make internal classes and functions available for testing
[assembly: InternalsVisibleTo("Zermelo.API.Tests")]

Change assembly version from 2.0.0.0 to 2.0.*


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

namespace JiebaNet.Analyser
{
    public abstract class KeywordExtractor
    {
        protected static readonly List<string> DefaultStopWords = new List<string>()
        {
            "the", "of", "is", "and", "to", "in", "that", "we", "for", "an", "are",
            "by", "be", "as", "on", "with", "can", "if", "from", "which", "you", "it",
            "this", "then", "at", "have", "all", "not", "one", "has", "or", "that"
        };

        protected virtual ISet<string> StopWords { get; set; }

        public void SetStopWords(string stopWordsFile)
        {
            var path = Path.GetFullPath(stopWordsFile);
            if (File.Exists(path))
            {
                var lines = File.ReadAllLines(path);
                StopWords = new HashSet<string>();
                foreach (var line in lines)
                {
                    StopWords.Add(line.Trim());
                }
            }
        }

        public abstract IEnumerable<string> ExtractTags(string text, int count = 20, IEnumerable<string> allowPos = null);
        public abstract IEnumerable<WordWeightPair> ExtractTagsWithWeight(string text, int count = 20, IEnumerable<string> allowPos = null);
    }
}

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

namespace JiebaNet.Analyser
{
    public abstract class KeywordExtractor
    {
        protected static readonly List<string> DefaultStopWords = new List<string>()
        {
            "the", "of", "is", "and", "to", "in", "that", "we", "for", "an", "are",
            "by", "be", "as", "on", "with", "can", "if", "from", "which", "you", "it",
            "this", "then", "at", "have", "all", "not", "one", "has", "or", "that"
        };

        protected virtual ISet<string> StopWords { get; set; }

        public void SetStopWords(string stopWordsFile)
        {
            StopWords = new HashSet<string>();

            var path = Path.GetFullPath(stopWordsFile);
            if (File.Exists(path))
            {
                var lines = File.ReadAllLines(path);
                foreach (var line in lines)
                {
                    StopWords.Add(line.Trim());
                }
            }
        }

        public abstract IEnumerable<string> ExtractTags(string text, int count = 20, IEnumerable<string> allowPos = null);
        public abstract IEnumerable<WordWeightPair> ExtractTagsWithWeight(string text, int count = 20, IEnumerable<string> allowPos = null);
    }
}

Use empty stopwords set when the default stopwords file is missing.


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

[assembly: AssemblyVersion(SolutionInfo.Version + ".0")]
[assembly: AssemblyInformationalVersion(SolutionInfo.Version)]
[assembly: AssemblyFileVersion(SolutionInfo.Version + ".0")]

[assembly: ComVisible(false)]

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("GitHub")]
[assembly: AssemblyProduct("Octokit")]
[assembly: AssemblyCopyright("Copyright  GitHub 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("Octokit.Tests")]
[assembly: InternalsVisibleTo("OctokitRT.Tests")]
[assembly: CLSCompliant(false)]

class SolutionInfo
{
    public const string Version = "0.1.0";
}

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

[assembly: AssemblyVersion(SolutionInfo.Version + ".0")]
[assembly: AssemblyInformationalVersion(SolutionInfo.Version)]
[assembly: AssemblyFileVersion(SolutionInfo.Version + ".0")]

[assembly: ComVisible(false)]

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("GitHub")]
[assembly: AssemblyProduct("Octokit")]
[assembly: AssemblyCopyright("Copyright  GitHub 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("Octokit.Tests")]
[assembly: InternalsVisibleTo("Octokit.Tests-NetCore45")]
[assembly: CLSCompliant(false)]

class SolutionInfo
{
    public const string Version = "0.1.0";
}

Fix up InternalsVisibleTo to new name

Fix up InternalsVisibleTo to new name


// 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 EOLib;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using XNAControls;

namespace EndlessClient.UIControls
{
    public class PictureBox : XNAControl
    {
        protected Texture2D _displayPicture;

        public Optional<Rectangle> SourceRectangle { get; set; }

        public PictureBox(Texture2D displayPicture, XNAControl parent = null)
            : base(null, null, parent)
        {
            SetNewPicture(displayPicture);
            if (parent == null)
                Game.Components.Add(this);

            SourceRectangle = new Optional<Rectangle>();
        }

        public void SetNewPicture(Texture2D displayPicture)
        {
            _displayPicture = displayPicture;
            _setSize(displayPicture.Width, displayPicture.Height);
        }

        public override void Draw(GameTime gameTime)
        {
            SpriteBatch.Begin();
            SpriteBatch.Draw(
                _displayPicture,
                DrawAreaWithOffset,
                SourceRectangle.HasValue ? SourceRectangle : null,
                Color.White);
            SpriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

// 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 EOLib;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using XNAControls;

namespace EndlessClient.UIControls
{
    public class PictureBox : XNAControl
    {
        protected Texture2D _displayPicture;

        public Optional<Rectangle?> SourceRectangle { get; set; }

        public PictureBox(Texture2D displayPicture, XNAControl parent = null)
            : base(null, null, parent)
        {
            SetNewPicture(displayPicture);
            if (parent == null)
                Game.Components.Add(this);

            SourceRectangle = new Optional<Rectangle?>();
        }

        public void SetNewPicture(Texture2D displayPicture)
        {
            _displayPicture = displayPicture;
            _setSize(displayPicture.Width, displayPicture.Height);
        }

        public override void Draw(GameTime gameTime)
        {
            SpriteBatch.Begin();
            SpriteBatch.Draw(
                _displayPicture,
                DrawAreaWithOffset,
                SourceRectangle.HasValue ? SourceRectangle.Value : null,
                Color.White);
            SpriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

Make SourceRectangle nullable so it doesn't crash.


using System;
using Newtonsoft.Json;

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

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

            writer.WriteValue (model.RemoteId);
        }

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

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

            return model;
        }

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

using System;
using Newtonsoft.Json;

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

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

            writer.WriteValue (model.RemoteId);
        }

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

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

                return model;
            }
        }

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

Make foreign key converter thread-safe.

Make foreign key converter thread-safe.


using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using OutlookMatters.Core.Http;
using OutlookMatters.Core.Mattermost.v4.Interface;

namespace OutlookMatters.Core.Mattermost.v4
{
    public class RestService : IRestService
    {
        private readonly IHttpClient _httpClient;

        public RestService(IHttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public void Login(Uri baseUri, Login login, out string token)
        {
            var loginUrl = new Uri(baseUri, "api/v4/users/login");
            using (var response = _httpClient.Request(loginUrl)
                .WithContentType("text/json")
                .Post(JsonConvert.SerializeObject(login)))
            {
                token = response.GetHeaderValue("Token");
            }
        }

        public IEnumerable<Team> GetTeams(Uri baseUri, string token)
        {
            throw new NotImplementedException();
        }
    }
}

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using OutlookMatters.Core.Http;
using OutlookMatters.Core.Mattermost.v4.Interface;

namespace OutlookMatters.Core.Mattermost.v4
{
    public class RestService : IRestService
    {
        private readonly IHttpClient _httpClient;

        public RestService(IHttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public void Login(Uri baseUri, Login login, out string token)
        {
            var loginUrl = new Uri(baseUri, "api/v4/users/login");
            using (var response = _httpClient.Request(loginUrl)
                .WithContentType("application/json")
                .Post(JsonConvert.SerializeObject(login)))
            {
                token = response.GetHeaderValue("Token");
            }
        }

        public IEnumerable<Team> GetTeams(Uri baseUri, string token)
        {
            var teamsUrl = new Uri(baseUri, "api/v4/teams");
            using (var response = _httpClient.Request(teamsUrl)
                .WithHeader("Authorization", "Bearer " + token)
                .Get())
            {
                var payload = response.GetPayload();
                return JsonConvert.DeserializeObject<IEnumerable<Team>>(payload);
            }
        }
    }
}

Implement rest call to get teams.

Implement rest call to get teams.


using System;
using System.Collections.Generic;
using Demo.Endpoints;
using Distributor;

namespace Demo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var distributables = new List<DistributableFile>
            {
                new DistributableFile
                {
                    Id = Guid.NewGuid(),
                    ProfileName = "TestProfile",
                    Name = "test.pdf",
                    Contents = null
                }
            };

            //Configure the distributor
            var distributor = new Distributor<DistributableFile>();
            distributor.EndpointDeliveryServices.Add(new SharepointDeliveryService());
            distributor.EndpointDeliveryServices.Add(new FileSystemDeliveryService());

            //Run the Distributor
            distributor.Distribute(distributables);

            Console.ReadLine();
        }
    }
}

using System;
using System.Collections.Generic;
using Demo.Endpoints.FileSystem;
using Demo.Endpoints.Sharepoint;
using Distributor;

namespace Demo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var distributables = new List<DistributableFile>
            {
                new DistributableFile
                {
                    Id = Guid.NewGuid(),
                    ProfileName = "TestProfile",
                    Name = "test.pdf",
                    Contents = null
                }
            };

            //Configure the distributor
            var distributor = new Distributor<DistributableFile>();
            distributor.EndpointDeliveryServices.Add(new SharepointDeliveryService());
            distributor.EndpointDeliveryServices.Add(new FileSystemDeliveryService());

            //Run the Distributor
            distributor.Distribute(distributables);

            Console.ReadLine();
        }
    }
}

Fix import error in demo.

Fix import error in demo.


using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;

public class UserInput : MonoBehaviour, IPointerClickHandler {

//	void Start(){}
//	void Update(){}

	// Mutually exclusive for now, priority is in the following order:
	// Left click for human,
	// Right for zombie,
	// Middle for corpse
	public void OnPointerClick(PointerEventData e)
	{
		if(e.button == PointerEventData.InputButton.Left)
		{
			FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.HUMAN, Camera.main.ScreenToWorldPoint(e.position));
		}
		else if(e.button == PointerEventData.InputButton.Right)
		{
			FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.ZOMBIE, Camera.main.ScreenToWorldPoint(e.position));
		}
		else if(e.button == PointerEventData.InputButton.Middle)
		{
			FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.CORPSE, Camera.main.ScreenToWorldPoint(e.position));
		}
	}
}

using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;

public class UserInput : MonoBehaviour, IPointerClickHandler {

//	void Start(){}
//	void Update(){}

	// Mutually exclusive for now, priority is in the following order:
	// Left click for human,
	// Right for zombie,
	// Middle for corpse
	public void OnPointerClick(PointerEventData e)
	{
		if(e.button == PointerEventData.InputButton.Left)
		{
			FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.ZOMBIE, Camera.main.ScreenToWorldPoint(e.position));
		}
		else if(e.button == PointerEventData.InputButton.Right)
		{
			FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.HUMAN, Camera.main.ScreenToWorldPoint(e.position));
		}
		else if(e.button == PointerEventData.InputButton.Middle)
		{
			FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.CORPSE, Camera.main.ScreenToWorldPoint(e.position));
		}
	}
}

Swap human/zombie spawn input so you can spawn zombies on touch screens


namespace Mappy.UI.Drawables
{
    using System;
    using System.Drawing;

    public class DrawableBandbox : IDrawable, IDisposable
    {
        private readonly Brush fillBrush;

        private readonly Pen borderPen;

        public DrawableBandbox(Brush fillBrush, Pen borderPen, Size size)
        {
            this.fillBrush = fillBrush;
            this.borderPen = borderPen;
            this.Size = size;
        }

        public Size Size { get; private set; }

        public int Width
        {
            get
            {
                return this.Size.Width;
            }
        }

        public int Height
        {
            get
            {
                return this.Size.Height;
            }
        }

        public static DrawableBandbox CreateSimple(
            Size size,
            Color color,
            Color borderColor,
            int borderWidth = 1)
        {
            return new DrawableBandbox(
                new SolidBrush(color),
                new Pen(borderColor, borderWidth),
                size);
        }

        public void Draw(Graphics graphics, Rectangle clipRectangle)
        {
            graphics.FillRectangle(this.fillBrush, 0, 0, this.Width - 1, this.Height - 1);
            graphics.DrawRectangle(this.borderPen, 0, 0, this.Width - 1, this.Height - 1);
        }

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

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.fillBrush.Dispose();
                this.borderPen.Dispose();
            }
        }
    }
}

namespace Mappy.UI.Drawables
{
    using System;
    using System.Drawing;

    public class DrawableBandbox : IDrawable, IDisposable
    {
        private readonly Brush fillBrush;

        private readonly Pen borderPen;

        public DrawableBandbox(Brush fillBrush, Pen borderPen, Size size)
        {
            this.fillBrush = fillBrush;
            this.borderPen = borderPen;
            this.Size = size;
        }

        public Size Size { get; private set; }

        public int Width
        {
            get
            {
                return this.Size.Width;
            }
        }

        public int Height
        {
            get
            {
                return this.Size.Height;
            }
        }

        public static DrawableBandbox CreateSimple(Size size, Color color, Color borderColor)
        {
            return CreateSimple(size, color, borderColor, 1);
        }

        public static DrawableBandbox CreateSimple(
            Size size,
            Color color,
            Color borderColor,
            int borderWidth)
        {
            return new DrawableBandbox(
                new SolidBrush(color),
                new Pen(borderColor, borderWidth),
                size);
        }

        public void Draw(Graphics graphics, Rectangle clipRectangle)
        {
            graphics.FillRectangle(this.fillBrush, 0, 0, this.Width - 1, this.Height - 1);
            graphics.DrawRectangle(this.borderPen, 0, 0, this.Width - 1, this.Height - 1);
        }

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

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.fillBrush.Dispose();
                this.borderPen.Dispose();
            }
        }
    }
}

Replace default parameter with overload

Replace default parameter with overload