using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;

namespace Syndll2
{
    public class SynelServer : IDisposable
    {
        private readonly IConnection _connection;
        private bool _disposed;

        private SynelServer(IConnection connection)
        {
            _connection = connection;
        }

        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
                _connection.Dispose();

            _disposed = true;
        }

        public static SynelServer Listen(Action<PushNotification> action)
        {
            return Listen(3734, action);
        }

        public static SynelServer Listen(int port, Action<PushNotification> action)
        {
            var connection = NetworkConnection.Listen(port, (stream, socket) =>
                {
                    var history = new List<string>();

                    var receiver = new Receiver(stream);
                    var signal = new SemaphoreSlim(1);

                    receiver.MessageHandler += message =>
                        {
                            if (!history.Contains(message.RawResponse))
                            {
                                history.Add(message.RawResponse);

                                Util.Log(string.Format("Received: {0}", message.RawResponse));
                                if (message.Response != null)
                                {
                                    var notification = new PushNotification(stream, message.Response, (IPEndPoint) socket.RemoteEndPoint);
                                    action(notification);
                                }
                            }
                            signal.Release();
                        };
                    receiver.WatchStream();
                    while (stream.CanRead)
                        signal.Wait();
                });
            return new SynelServer(connection);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;

namespace Syndll2
{
    public class SynelServer : IDisposable
    {
        private readonly IConnection _connection;
        private bool _disposed;

        private SynelServer(IConnection connection)
        {
            _connection = connection;
        }

        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
                _connection.Dispose();

            _disposed = true;
        }

        public static SynelServer Listen(Action<PushNotification> action)
        {
            return Listen(3734, action);
        }

        public static SynelServer Listen(int port, Action<PushNotification> action)
        {
            var connection = NetworkConnection.Listen(port, (stream, socket) =>
                {
                    var history = new List<string>();

                    var receiver = new Receiver(stream);
                    var signal = new ManualResetEvent(false);

                    receiver.MessageHandler = message =>
                        {
                            if (!history.Contains(message.RawResponse))
                            {
                                history.Add(message.RawResponse);

                                Util.Log(string.Format("Received: {0}", message.RawResponse));
                                if (message.Response != null)
                                {
                                    var notification = new PushNotification(stream, message.Response, (IPEndPoint) socket.RemoteEndPoint);
                                    action(notification);
                                }
                            }
                            signal.Set();
                        };

                    receiver.WatchStream();

                    // Wait until a message is received
                    while (stream.CanRead && socket.Connected)
                        if (signal.WaitOne(100))
                            break;
                });
            return new SynelServer(connection);
        }
    }
}

Improve server wait and disconnect after each msg


namespace ForecastPCL.Test
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using ForecastIOPortable;

    using NUnit.Framework;

    [TestFixture]
    public class LanguageTests
    {
        [Test]
        public void AllLanguagesHaveValues()
        {
            foreach (Language language in Enum.GetValues(typeof(Language)))
            {
                Assert.That(() => language.ToValue(), Throws.Nothing);
            }
        }
    }
}

namespace ForecastPCL.Test
{
    using System;
    using System.Configuration;

    using ForecastIOPortable;

    using NUnit.Framework;

    [TestFixture]
    public class LanguageTests
    {
        // These coordinates came from the Forecast API documentation,
        // and should return forecasts with all blocks.
        private const double AlcatrazLatitude = 37.8267;
        private const double AlcatrazLongitude = -122.423;

        private const double MumbaiLatitude = 18.975;
        private const double MumbaiLongitude = 72.825833;

        /// <summary>
        /// API key to be used for testing. This should be specified in the
        /// test project's app.config file.
        /// </summary>
        private string apiKey;

        /// <summary>
        /// Sets up all tests by retrieving the API key from app.config.
        /// </summary>
        [TestFixtureSetUp]
        public void SetUp()
        {
            this.apiKey = ConfigurationManager.AppSettings["ApiKey"];
        }

        [Test]
        public void AllLanguagesHaveValues()
        {
            foreach (Language language in Enum.GetValues(typeof(Language)))
            {
                Assert.That(() => language.ToValue(), Throws.Nothing);
            }
        }

        [Test]
        public async void UnicodeLanguageIsSupported()
        {
            var client = new ForecastApi(this.apiKey);
            var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese);
            Assert.That(result, Is.Not.Null);
        }
    }
}

Add test to check that Unicode languages work (testing Chinese).


using System;
using System.Diagnostics;
using Basics.Algorithms.Sorts;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Basics.Algorithms.Tests
{
    [TestClass]
    public class SortingPerformanceTests
    {
        private const int size = 10000;

        private class SortInfo
        {
            public string Name { get; set; }
            public Action<int[]> Act { get; set; }
        }

        [TestMethod]
        public void SortingPerformanceTest()
        {
            var stopwatch = new Stopwatch();
            var sortedArray = new int[size];
            for (int i = 0; i < size; i++)
            {
                sortedArray[i] = i;
            }
            var sorts = new SortInfo[]
            {
                new SortInfo { Name = "Selection Sort", Act = array => Selection.Sort(array) },
                new SortInfo { Name = "Insertion Sort", Act = array => Insertion.Sort(array) },
                new SortInfo { Name = "Shell Sort", Act = array => Shell.Sort(array) },
                new SortInfo { Name = "Mergesort", Act = array => Merge.Sort(array) },
                new SortInfo { Name = "Quicksort", Act = array => Quick.Sort(array) }
            };

            foreach (var sort in sorts)
            {
                sortedArray.Shuffle();
                stopwatch.Restart();
                sort.Act(sortedArray);
                stopwatch.Stop();
                Console.WriteLine("{0}:\t{1}", sort.Name, stopwatch.ElapsedTicks);
            }
        }
    }
}

using System;
using System.Diagnostics;
using System.Linq;
using Basics.Algorithms.Sorts;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Basics.Algorithms.Tests
{
    [TestClass]
    public class SortingPerformanceTests
    {
        private const int size = 1000000;

        private class SortInfo
        {
            public string Name { get; set; }
            public Action<int[]> Act { get; set; }
            public bool Enabled { get; set; }
        }

        [TestMethod]
        public void SortingPerformanceTest()
        {
            var stopwatch = new Stopwatch();
            var sortedArray = new int[size];
            for (int i = 0; i < size; i++)
            {
                sortedArray[i] = i;
            }
            var sorts = new SortInfo[]
            {
                new SortInfo { Name = "Selection Sort", Act = array => Selection.Sort(array), Enabled = false },
                new SortInfo { Name = "Insertion Sort", Act = array => Insertion.Sort(array), Enabled = false },
                new SortInfo { Name = "Shell Sort", Act = array => Shell.Sort(array), Enabled = false },
                new SortInfo { Name = "Mergesort", Act = array => Merge.Sort(array), Enabled = true },
                new SortInfo { Name = "Quicksort", Act = array => Quick.Sort(array), Enabled = true }
            };

            foreach (var sort in sorts.Where(s => s.Enabled))
            {
                sortedArray.Shuffle();
                stopwatch.Restart();
                sort.Act(sortedArray);
                stopwatch.Stop();
                Console.WriteLine("{0}:\t{1}", sort.Name, stopwatch.ElapsedTicks);
            }
        }
    }
}

Implement Enabled flag to be able to run sorts separately


using System;
using System.Linq;
using Android.App;
using Android.OS;
using Android.Views;
using Toggl.Joey.UI.Adapters;

namespace Toggl.Joey.UI.Fragments
{
    public class RecentTimeEntriesListFragment : ListFragment
    {
        public override void OnViewCreated (View view, Bundle savedInstanceState)
        {
            base.OnViewCreated (view, savedInstanceState);

            ListAdapter = new RecentTimeEntriesAdapter ();
        }
    }
}

using System;
using System.Linq;
using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using Toggl.Joey.UI.Adapters;

namespace Toggl.Joey.UI.Fragments
{
    public class RecentTimeEntriesListFragment : ListFragment
    {
        public override void OnViewCreated (View view, Bundle savedInstanceState)
        {
            base.OnViewCreated (view, savedInstanceState);

            ListAdapter = new RecentTimeEntriesAdapter ();
        }

        public override void OnListItemClick (ListView l, View v, int position, long id)
        {
            var adapter = l.Adapter as RecentTimeEntriesAdapter;
            if (adapter == null)
                return;

            var model = adapter.GetModel (position);
            if (model == null)
                return;

            model.Continue ();
        }
    }
}

Add continue time entry on recent list view click.


using System;
using System.Collections.Generic;

namespace PrepareLanding.Filters
{
    public enum FilterHeaviness
    {
        Light = 0,
        Medium = 1,
        Heavy = 2
    }

    public interface ITileFilter
    {
        string SubjectThingDef { get; }

        string RunningDescription { get; }

        string AttachedProperty { get; }

        Action<PrepareLandingUserData, List<int>> FilterAction { get; }

        FilterHeaviness Heaviness { get; }

        List<int> FilteredTiles { get; }

        void Filter(PrepareLandingUserData userData, List<int> inputList);
    }
}

using System;
using System.Collections.Generic;

namespace PrepareLanding.Filters
{
    public enum FilterHeaviness
    {
        Light = 0,
        Medium = 1,
        Heavy = 2
    }

    public interface ITileFilter
    {
        string SubjectThingDef { get; }

        string RunningDescription { get; }

        string AttachedProperty { get; }

        Action<List<int>> FilterAction { get; }

        FilterHeaviness Heaviness { get; }

        List<int> FilteredTiles { get; }

        void Filter(List<int> inputList);

        bool IsFilterActive { get; }
    }
}

Add IsFilterActive; remove unneeded parameters to filter (pass it on ctor)


using Microsoft.ServiceFabric.Actors;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SoCreate.ServiceFabric.PubSub.Events;
using SoCreate.ServiceFabric.PubSub.State;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SoCreate.ServiceFabric.PubSub.Tests
{
    [TestClass]
    public class GivenDefaultBrokerEventsManager
    {
        [TestMethod]
        public async Task WhenInsertingConcurrently_ThenAllCallbacksAreMadeCorrectly()
        {
            int callCount = 0;
            var manager = new DefaultBrokerEventsManager();
            manager.Subscribed += (s, e, t) =>
            {
                lock (manager)
                {
                    callCount++;
                }

                return Task.CompletedTask;

            };
            const int attempts = 20;
            var tasks = new List<Task>(attempts);

            for (int i = 0; i < attempts; i++)
            {
                var actorReference = new ActorReference{ ActorId =  ActorId.CreateRandom() };
                tasks.Add(manager.OnSubscribedAsync("Key", new ActorReferenceWrapper(actorReference), "MessageType"));
            }

            await Task.WhenAll(tasks);

            Assert.AreEqual(attempts, callCount);
        }
    }
}

using Microsoft.ServiceFabric.Actors;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SoCreate.ServiceFabric.PubSub.Events;
using SoCreate.ServiceFabric.PubSub.State;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace SoCreate.ServiceFabric.PubSub.Tests
{
    [TestClass]
    public class GivenDefaultBrokerEventsManager
    {
        [TestMethod]
        public void WhenInsertingConcurrently_ThenAllCallbacksAreMadeCorrectly()
        {
            bool hasCrashed = false;
            var manager = new DefaultBrokerEventsManager();
            ManualResetEvent mr = new ManualResetEvent(false);
            ManualResetEvent mr2 = new ManualResetEvent(false);

            manager.Subscribed += (s, e, t) =>
            {
                mr.WaitOne();
                return Task.CompletedTask;
            };

            const int attempts = 2000;

            for (int i = 0; i < attempts; i++)
            {
                ThreadPool.QueueUserWorkItem(async j =>
                {
                    var actorReference = new ActorReference { ActorId = ActorId.CreateRandom() };
                    try
                    {
                        await manager.OnSubscribedAsync("Key" + (int) j % 5, new ActorReferenceWrapper(actorReference),
                            "MessageType");
                    }
                    catch (NullReferenceException)
                    {
                        hasCrashed = true;
                    }
                    catch (IndexOutOfRangeException)
                    {
                        hasCrashed = true;
                    }
                    finally
                    {
                        if ((int)j == attempts - 1)
                        {
                            mr2.Set();
                        }
                    }
                }, i);

            }

            mr.Set();

            Assert.IsTrue(mr2.WaitOne(TimeSpan.FromSeconds(10)), "Failed to run within time limits.");
            Assert.IsFalse(hasCrashed, "Should not crash.");
        }
    }
}

Change test code to repro issue in old code and prove new code doesn't crash


using System;
using System.Collections;
using NHibernate.Type;

namespace NHibernate.Cfg
{
	[Serializable]
	internal class EmptyInterceptor : IInterceptor
	{

		public EmptyInterceptor()
		{
		}

		public void OnDelete( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
		{
		}

		public bool OnFlushDirty( object entity, object id, object[ ] currentState, object[ ] previousState, string[ ] propertyNames, IType[ ] types )
		{
			return false;
		}

		public bool OnLoad( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
		{
			return false;
		}

		public bool OnSave( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
		{
			return false;
		}

		public void OnPostFlush( object entity, object id, object[ ] currentState, string[ ] propertyNames, IType[ ] types )
		{
		}

		public void PostFlush( ICollection entities )
		{
		}

		public void PreFlush( ICollection entitites )
		{
		}

		public object IsUnsaved( object entity )
		{
			return null;
		}

		public object Instantiate( System.Type clazz, object id )
		{
			return null;
		}

		public int[ ] FindDirty( object entity, object id, object[ ] currentState, object[ ] previousState, string[ ] propertyNames, IType[ ] types )
		{
			return null;
		}
	}

}

using System;
using System.Collections;
using NHibernate.Type;

namespace NHibernate.Cfg
{
	[Serializable]
	public class EmptyInterceptor : IInterceptor
	{
		public virtual void OnDelete( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
		{
		}

		public virtual bool OnFlushDirty( object entity, object id, object[ ] currentState, object[ ] previousState, string[ ] propertyNames, IType[ ] types )
		{
			return false;
		}

		public virtual bool OnLoad( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
		{
			return false;
		}

		public virtual bool OnSave( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
		{
			return false;
		}

		public virtual void PostFlush( ICollection entities )
		{
		}

		public virtual void PreFlush( ICollection entitites )
		{
		}

		public virtual object IsUnsaved( object entity )
		{
			return null;
		}

		public virtual object Instantiate( System.Type clazz, object id )
		{
			return null;
		}

		public virtual int[] FindDirty( object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types )
		{
			return null;
		}
	}

}

Make class public and all methods virtual so that it can be used as a base class for interceptors.

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@2077


            Thank you for registering!

            You should receive an Email confirmation shortly.

            If not, ensure you check any spam filters you may have running.

            <button class="centered active-btn" ng-click="resendConfirmation()">Resend Confirmation Email"</button>

            Thank you for registering!

            You should receive an Email confirmation shortly.

            If not, ensure you check any spam filters you may have running.

            <button class="centered active-btn" ng-click="resendConfirmation()">Resend Confirmation Email</button>

Fix for resend confirmation button

Fix for resend confirmation button


namespace Glimpse.Agent.AspNet.Mvc.Messages
{
    public class BeforeActionMessage : IActionRouteFoundMessage
    {
        public string ActionId { get; set; }

        public string DisplayName { get; set; }

        public RouteData RouteData { get; set; }

        public string ActionName { get; set; }

        public string ControllerName { get; set; }
    }
}

namespace Glimpse.Agent.AspNet.Mvc.Messages
{
    public class BeforeActionMessage : IActionRouteFoundMessage
    {
        public string ActionId { get; set; }

        public string DisplayName { get; set; }

        public string ActionName { get; set; }

        public string ControllerName { get; set; }

        public RouteData RouteData { get; set; }
    }
}

Move ordering if types around

Move ordering if types around


Counter

Current count: <MessageComponent Message=@currentCount.ToString() />

<button @onclick(IncrementCount)>Click me</button>

@functions {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
    }
}

Counter

Current count: <MessageComponent message=@currentCount.ToString() />

<button @onclick(IncrementCount)>Click me</button>

@functions {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
    }
}

Cover case-insensitive child component parameter names in E2E test


using Moq;
using SFA.DAS.EAS.TestCommon.DbCleanup;
using SFA.DAS.EAS.TestCommon.DependencyResolution;
using SFA.DAS.EAS.Web;
using SFA.DAS.EAS.Web.Authentication;
using SFA.DAS.Messaging;
using StructureMap;
using TechTalk.SpecFlow;

namespace SFA.DAS.EAS.Transactions.AcceptanceTests.Steps.CommonSteps
{
    [Binding]
    public static class GlobalTestSteps
    {
        private static Mock<IMessagePublisher> _messagePublisher;
        private static Mock<IOwinWrapper> _owinWrapper;
        private static Container _container;
        private static Mock<ICookieService> _cookieService;

        [AfterTestRun()]
        public static void Arrange()
        {
            _messagePublisher = new Mock<IMessagePublisher>();
            _owinWrapper = new Mock<IOwinWrapper>();
            _cookieService = new Mock<ICookieService>();

            _container = IoC.CreateContainer(_messagePublisher, _owinWrapper, _cookieService);

            var cleanDownDb = _container.GetInstance<ICleanDatabase>();
            cleanDownDb.Execute().Wait();
        }
    }
}

using Moq;
using SFA.DAS.EAS.TestCommon.DbCleanup;
using SFA.DAS.EAS.TestCommon.DependencyResolution;
using SFA.DAS.EAS.Web;
using SFA.DAS.EAS.Web.Authentication;
using SFA.DAS.Messaging;
using StructureMap;
using TechTalk.SpecFlow;

namespace SFA.DAS.EAS.Transactions.AcceptanceTests.Steps.CommonSteps
{
    [Binding]
    public static class GlobalTestSteps
    {
        private static Mock<IMessagePublisher> _messagePublisher;
        private static Mock<IOwinWrapper> _owinWrapper;
        private static Container _container;
        private static Mock<ICookieService> _cookieService;

        [AfterTestRun()]
        public static void Arrange()
        {
            _messagePublisher = new Mock<IMessagePublisher>();
            _owinWrapper = new Mock<IOwinWrapper>();
            _cookieService = new Mock<ICookieService>();

            _container = IoC.CreateContainer(_messagePublisher, _owinWrapper, _cookieService);

            var cleanDownDb = _container.GetInstance<ICleanDatabase>();
            cleanDownDb.Execute().Wait();

            var cleanDownTransactionDb = _container.GetInstance<ICleanTransactionsDatabase>();
            cleanDownTransactionDb.Execute().Wait();
        }
    }
}

Add cleandatabase call in global steps

Add cleandatabase call in global steps

Added call to clean the levy database after running the tests for
transactions.


namespace SEEK.AdPostingApi.Client.Models
{
    public enum AdditionalPropertyType
    {
        ResidentsOnly = 1
    }
}

namespace SEEK.AdPostingApi.Client.Models
{
    public enum AdditionalPropertyType
    {
        ResidentsOnly = 1,
        Graduate
    }
}

FLAPI-216: Add graduate flag as additional property


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

[assembly: AssemblyTitle("Autofac.Integration.Mef")]
[assembly: AssemblyDescription("Autofac MEF Integration")]
[assembly: InternalsVisibleTo("Autofac.Tests.Integration.Mef, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]

Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.


using Template10.Mvvm;
using Template10.Services.SettingsService;

namespace Zermelo.App.UWP.Services
{
    public class SettingsService : BindableBase, ISettingsService
    {
        ISettingsHelper _helper;

        public SettingsService(ISettingsHelper settingsHelper)
        {
            _helper = settingsHelper;
        }

        private T Read<T>(string key, T otherwise = default(T))
            => _helper.Read<T>(key, otherwise, SettingsStrategies.Roam);

        private void Write<T>(string key, T value) => _helper.Write(key, value, SettingsStrategies.Roam);

        //Account
        public string School
        {
            get => Read<string>("Host");
            set
            {
                Write("Host", value);
                RaisePropertyChanged();
            }
        }

        public string Token
        {
            get => Read<string>("Token");
            set
            {
                Write("Token", value);
                RaisePropertyChanged();
            }
        }
    }
}

using Template10.Mvvm;
using Template10.Services.SettingsService;
using Windows.Storage;

namespace Zermelo.App.UWP.Services
{
    public class SettingsService : BindableBase, ISettingsService
    {
        ApplicationDataContainer _settings;

        public SettingsService()
        {
            _settings = ApplicationData.Current.RoamingSettings;
        }

        private T Read<T>(string key)
            => (T)_settings.Values[key];

        private void Write<T>(string key, T value)
            => _settings.Values[key] = value;

        //Account
        public string School
        {
            get => Read<string>("Host");
            set
            {
                Write("Host", value);
                RaisePropertyChanged();
            }
        }

        public string Token
        {
            get => Read<string>("Token");
            set
            {
                Write("Token", value);
                RaisePropertyChanged();
            }
        }
    }
}

Store settings as plain strings, without SettingsHelper

Fix #23


// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

namespace ServiceStack.IntroSpec.Services
{
    using System.Linq;
    using DTO;

    public class ApiSpecMetadataService : IService
    {
        private readonly IApiDocumentationProvider documentationProvider;

        public ApiSpecMetadataService(IApiDocumentationProvider documentationProvider)
        {
            documentationProvider.ThrowIfNull(nameof(documentationProvider));
            this.documentationProvider = documentationProvider;
        }

        public object Get(SpecMetadataRequest request)
        {
            var documentation = documentationProvider.GetApiDocumentation();

            return SpecMetadataResponse.Create(
                documentation.Resources.Select(r => r.TypeName).Distinct().ToArray(),
                documentation.Resources.Select(r => r.Category).Distinct().ToArray(),
                documentation.Resources.SelectMany(r => r.Tags).Distinct().ToArray()
                );
        }
    }
}

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

namespace ServiceStack.IntroSpec.Services
{
    using System.Linq;
    using DTO;

    public class ApiSpecMetadataService : IService
    {
        private readonly IApiDocumentationProvider documentationProvider;

        public ApiSpecMetadataService(IApiDocumentationProvider documentationProvider)
        {
            documentationProvider.ThrowIfNull(nameof(documentationProvider));
            this.documentationProvider = documentationProvider;
        }

        public object Get(SpecMetadataRequest request)
        {
            var documentation = documentationProvider.GetApiDocumentation();

            return SpecMetadataResponse.Create(
                documentation.Resources.Select(r => r.TypeName).Distinct().ToArray(),
                documentation.Resources.Select(r => r.Category).Where(c => !string.IsNullOrEmpty(c)).Distinct().ToArray(),
                documentation.Resources.SelectMany(r => r.Tags ?? new string[0]).Distinct().ToArray()
                );
        }
    }
}

Handle null/missing category and tags

Handle null/missing category and tags


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

namespace StrangerData.Utils
{
    internal static class RandomValues
    {
        public static object ForColumn(TableColumnInfo columnInfo)
        {
            switch (columnInfo.ColumnType)
            {
                case ColumnType.String:
                    // generates a random string
                    return Any.String(columnInfo.MaxLength);
                case ColumnType.Int:
                    // generates a random integer
                    long maxValue = 10 ^ columnInfo.Precision - 1;
                    if (maxValue > int.MaxValue)
                    {
                        return Any.Long(1, columnInfo.Precision - 1);
                    }
                    return Any.Int(1, 10 ^ columnInfo.Precision - 1);
                case ColumnType.Decimal:
                    // generates a random decimal
                    return Any.Double(columnInfo.Precision, columnInfo.Scale);
                case ColumnType.Double:
                    // generates a random double
                    return Any.Double(columnInfo.Precision, columnInfo.Scale);
                case ColumnType.Long:
                    // generates a random long
                    return Any.Long(1, 10 ^ columnInfo.Precision - 1);
                case ColumnType.Boolean:
                    // generates a random boolean
                    return Any.Boolean();
                case ColumnType.Guid:
                    // generates a random guid
                    return Guid.NewGuid();
                case ColumnType.Date:
                    // generates a random date
                    return Any.DateTime().Date;
                case ColumnType.Datetime:
                    // generates a random DateTime
                    return Any.DateTime();
                default:
                    return null;
            }
        }
    }
}

using System;

namespace StrangerData.Utils
{
    internal static class RandomValues
    {
        public static object ForColumn(TableColumnInfo columnInfo)
        {
            switch (columnInfo.ColumnType)
            {
                case ColumnType.String:
                    // generates a random string
                    return Any.String(columnInfo.MaxLength);
                case ColumnType.Int:
                    // generates a random integer
                    long maxValue = (int)Math.Pow(10, columnInfo.Precision - 1);
                    if (maxValue > int.MaxValue)
                    {
                        return Any.Long(1, maxValue);
                    }
                    return Any.Int(1, (int)maxValue);
                case ColumnType.Decimal:
                    // generates a random decimal
                    return Any.Double(columnInfo.Precision, columnInfo.Scale);
                case ColumnType.Double:
                    // generates a random double
                    return Any.Double(columnInfo.Precision, columnInfo.Scale);
                case ColumnType.Long:
                    // generates a random long
                    return Any.Long(1, (int)Math.Pow(10, columnInfo.Precision - 1));
                case ColumnType.Boolean:
                    // generates a random boolean
                    return Any.Boolean();
                case ColumnType.Guid:
                    // generates a random guid
                    return Guid.NewGuid();
                case ColumnType.Date:
                    // generates a random date
                    return Any.DateTime().Date;
                case ColumnType.Datetime:
                    // generates a random DateTime
                    return Any.DateTime();
                default:
                    return null;
            }
        }
    }
}

:bug: Fix evaluation of max values for random int and long

Use Math.Pow instead of logical XOR to evaluate max values


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using NDesk.Options;

namespace LessMsi.Cli
{
	internal class OpenGuiCommand : LessMsiCommand
	{
		public override void Run(List<string> args)
		{
			if (args.Count < 2)
				throw new OptionException("You must specify the name of the msi file to open when using the o command.", "o");

			ShowGui(args);
		}

		public static void ShowGui(List<string> args)
		{
			var guiExe = Path.Combine(AppPath, "lessmsi-gui.exe");
			if (File.Exists(guiExe))
			{
				//should we wait for exit?
				if (args.Count > 0)
					Process.Start(guiExe, args[1]);
				else
					Process.Start(guiExe);
			}
		}

		private static string AppPath
		{
			get
			{
				var codeBase = new Uri(typeof(OpenGuiCommand).Assembly.CodeBase);
				var local = Path.GetDirectoryName(codeBase.LocalPath);
				return local;
			}
		}
	}
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using NDesk.Options;

namespace LessMsi.Cli
{
	internal class OpenGuiCommand : LessMsiCommand
	{
		public override void Run(List<string> args)
		{
			if (args.Count < 2)
				throw new OptionException("You must specify the name of the msi file to open when using the o command.", "o");

			ShowGui(args);
		}

		public static void ShowGui(List<string> args)
		{
			var guiExe = Path.Combine(AppPath, "lessmsi-gui.exe");
			if (File.Exists(guiExe))
			{
			    var p = new Process();
			    p.StartInfo.FileName = guiExe;

			    if (args.Count > 0)
			    {
                    // We add double quotes to support paths with spaces, for ex: "E:\Downloads and Sofware\potato.msi".
                    p.StartInfo.Arguments = string.Format("\"{0}\"", args[1]);
			        p.Start();
			    }
			    else
			        p.Start();
			}
		}

		private static string AppPath
		{
			get
			{
				var codeBase = new Uri(typeof(OpenGuiCommand).Assembly.CodeBase);
				var local = Path.GetDirectoryName(codeBase.LocalPath);
				return local;
			}
		}
	}
}

Make CLI work with paths containing spaces.


// Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Collections.Generic;
using System.Linq;
using Nuke.Common.IO;

namespace Nuke.Common.Execution
{
    [AttributeUsage(AttributeTargets.Class)]
    internal class HandleShellCompletionAttribute : Attribute, IOnBeforeLogo
    {
        public void OnBeforeLogo(
            NukeBuild build,
            IReadOnlyCollection<ExecutableTarget> executableTargets)
        {
            var completionItems = new SortedDictionary<string, string[]>();

            var targetNames = build.ExecutableTargets.Select(x => x.Name).OrderBy(x => x).ToList();
            completionItems[Constants.InvokedTargetsParameterName] = targetNames.ToArray();
            completionItems[Constants.SkippedTargetsParameterName] = targetNames.ToArray();

            var parameters = InjectionUtility.GetParameterMembers(build.GetType(), includeUnlisted: false);
            foreach (var parameter in parameters)
            {
                var parameterName = ParameterService.GetParameterMemberName(parameter);
                if (completionItems.ContainsKey(parameterName))
                    continue;

                var subItems = ParameterService.GetParameterValueSet(parameter, build)?.Select(x => x.Text);
                completionItems[parameterName] = subItems?.ToArray();
            }

            SerializationTasks.YamlSerializeToFile(completionItems, Constants.GetCompletionFile(NukeBuild.RootDirectory));

            if (EnvironmentInfo.GetParameter<bool>(Constants.CompletionParameterName))
                Environment.Exit(exitCode: 0);
        }
    }
}

// Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Collections.Generic;
using System.Linq;
using Nuke.Common.IO;
using static Nuke.Common.Constants;

namespace Nuke.Common.Execution
{
    [AttributeUsage(AttributeTargets.Class)]
    internal class HandleShellCompletionAttribute : Attribute, IOnBeforeLogo
    {
        public void OnBeforeLogo(
            NukeBuild build,
            IReadOnlyCollection<ExecutableTarget> executableTargets)
        {
            var completionItems = new SortedDictionary<string, string[]>();

            var targets = build.ExecutableTargets.OrderBy(x => x.Name).ToList();
            completionItems[InvokedTargetsParameterName] = targets.Where(x => x.Listed).Select(x => x.Name).ToArray();
            completionItems[SkippedTargetsParameterName] = targets.Select(x => x.Name).ToArray();

            var parameters = InjectionUtility.GetParameterMembers(build.GetType(), includeUnlisted: false);
            foreach (var parameter in parameters)
            {
                var parameterName = ParameterService.GetParameterMemberName(parameter);
                if (completionItems.ContainsKey(parameterName))
                    continue;

                var subItems = ParameterService.GetParameterValueSet(parameter, build)?.Select(x => x.Text);
                completionItems[parameterName] = subItems?.ToArray();
            }

            SerializationTasks.YamlSerializeToFile(completionItems, GetCompletionFile(NukeBuild.RootDirectory));

            if (EnvironmentInfo.GetParameter<bool>(CompletionParameterName))
                Environment.Exit(exitCode: 0);
        }
    }
}

Fix shell-completion.yml to exclude unlisted targets for invocation


using NUnit.Framework;
using Shouldly.DifferenceHighlighting2;
using System;

namespace Shouldly.Tests.InternalTests
{
    [TestFixture]
    public static class StringDiffHighlighterTests
    {
        private static IStringDifferenceHighlighter _sut;
        [SetUp]
        public static void Setup()
        {
            _sut = new StringDifferenceHighlighter(null, 0);
        }

        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public static void Should_throw_exception_when_expected_arg_is_null()
        {
            _sut.HighlightDifferences("not null", null);
        }
        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public static void Should_throw_exception_when_actual_arg_is_null()
        {
            _sut.HighlightDifferences(null, "not null");
        }
    }
}

using NUnit.Framework;
using Shouldly.DifferenceHighlighting2;
using System;

namespace Shouldly.Tests.InternalTests
{
    [TestFixture]
    public static class StringDiffHighlighterTests
    {
        private static IStringDifferenceHighlighter _sut;
        [SetUp]
        public static void Setup()
        {
            _sut = new StringDifferenceHighlighter(null, 0);
        }

        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public static void Should_throw_exception_when_expected_arg_is_null()
        {
            _sut.HighlightDifferences(null, "not null");
        }
        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public static void Should_throw_exception_when_actual_arg_is_null()
        {
            _sut.HighlightDifferences("not null", null);
        }
    }
}

Correct order of params in diff highlighter tests


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tracer;
namespace Tester
{
    class SingleThreadTest : ITest
    {
        private ITracer tracer = new Tracer.Tracer();
        public void Run()
        {
            tracer.StartTrace();

            RunCycle(204800000);

            tracer.StopTrace();

            TraceResult result = tracer.GetTraceResult();
            result.PrintToConsole();
        }

        private void RunCycle(int repeatAmount)
        {
            ITracer tracer = new Tracer.Tracer();
            tracer.StartTrace();

            for (int i = 0; i < repeatAmount; i++)
            {
                int a = 1;
                a += i;
            }

            tracer.StopTrace();

            TraceResult result = tracer.GetTraceResult();
            result.PrintToConsole();
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tracer;
using System.Threading;
namespace Tester
{
    class SingleThreadTest : ITest
    {
        private ITracer tracer = new Tracer.Tracer();
        public void Run()
        {
            tracer.StartTrace();

            Thread.Sleep(500);
            RunCycle(500);

            tracer.StopTrace();

            PrintTestResults();
        }

        private void RunCycle(int sleepTime)
        {
            tracer.StartTrace();

            Thread.Sleep(sleepTime);

            tracer.StopTrace();
        }

        private void PrintTestResults()
        {
            var traceResult = tracer.GetTraceResult();
            foreach (TraceResultItem analyzedItem in traceResult)
            {
                analyzedItem.PrintToConsole();
            }
        }

    }
}

Update Tester class implementation due to the recent changes in Tester implementation


using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Taxjar.Tests
{
    public class TaxjarFixture
    {
        public static string GetJSON(string fixturePath)
        {
            using (StreamReader file = File.OpenText(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "../../../", "Fixtures", fixturePath)))
            using (JsonTextReader reader = new JsonTextReader(file))
            {
                JObject response = (JObject)JToken.ReadFrom(reader);
                var resString = response.ToString(Formatting.None).Replace(@"\", "");
                return response.ToString(Formatting.None).Replace(@"\", "");
            }
        }
    }
}

using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Taxjar.Tests
{
    public class TaxjarFixture
    {
        public static string GetJSON(string fixturePath)
        {
            using (StreamReader file = File.OpenText(Path.Combine("../../../", "Fixtures", fixturePath)))
            using (JsonTextReader reader = new JsonTextReader(file))
            {
                JObject response = (JObject)JToken.ReadFrom(reader);
                var resString = response.ToString(Formatting.None).Replace(@"\", "");
                return response.ToString(Formatting.None).Replace(@"\", "");
            }
        }
    }
}

Update fixture path for specs

Update fixture path for specs


using System.Threading.Tasks;

namespace ForecastPCL.Test
{
    using System;
    using System.Configuration;

    using ForecastIOPortable;

    using NUnit.Framework;

    [TestFixture]
    public class LanguageTests
    {
        // These coordinates came from the Forecast API documentation,
        // and should return forecasts with all blocks.
        private const double AlcatrazLatitude = 37.8267;
        private const double AlcatrazLongitude = -122.423;

        private const double MumbaiLatitude = 18.975;
        private const double MumbaiLongitude = 72.825833;

        /// <summary>
        /// API key to be used for testing. This should be specified in the
        /// test project's app.config file.
        /// </summary>
        private string apiKey;

        /// <summary>
        /// Sets up all tests by retrieving the API key from app.config.
        /// </summary>
        [TestFixtureSetUp]
        public void SetUp()
        {
            this.apiKey = ConfigurationManager.AppSettings["ApiKey"];
        }

        [Test]
        public void AllLanguagesHaveValues()
        {
            foreach (Language language in Enum.GetValues(typeof(Language)))
            {
                Assert.That(() => language.ToValue(), Throws.Nothing);
            }
        }

        [Test]
        public async Task UnicodeLanguageIsSupported()
        {
            var client = new ForecastApi(this.apiKey);
            var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese);
            Assert.That(result, Is.Not.Null);
        }
    }
}

using System.Threading.Tasks;

namespace ForecastPCL.Test
{
    using System;
    using System.Configuration;

    using ForecastIOPortable;

    using NUnit.Framework;

    [TestFixture]
    public class LanguageTests
    {
        // These coordinates came from the Forecast API documentation,
        // and should return forecasts with all blocks.
        private const double AlcatrazLatitude = 37.8267;
        private const double AlcatrazLongitude = -122.423;

        /// <summary>
        /// API key to be used for testing. This should be specified in the
        /// test project's app.config file.
        /// </summary>
        private string apiKey;

        /// <summary>
        /// Sets up all tests by retrieving the API key from app.config.
        /// </summary>
        [TestFixtureSetUp]
        public void SetUp()
        {
            this.apiKey = ConfigurationManager.AppSettings["ApiKey"];
        }

        [Test]
        public void AllLanguagesHaveValues()
        {
            foreach (Language language in Enum.GetValues(typeof(Language)))
            {
                Assert.That(() => language.ToValue(), Throws.Nothing);
            }
        }

        [Test]
        public async Task UnicodeLanguageIsSupported()
        {
            var client = new ForecastApi(this.apiKey);
            var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese);
            Assert.That(result, Is.Not.Null);
        }
    }
}

Clean up unused lat/long coordinates in language tests.


using Microsoft.Extensions.DependencyInjection;

using ISTS.Application.Rooms;
using ISTS.Application.Studios;
using ISTS.Domain.Rooms;
using ISTS.Domain.Studios;
using ISTS.Infrastructure.Repository;

namespace ISTS.Api
{
    public static class DependencyInjectionConfiguration
    {
        public static void Configure(IServiceCollection services)
        {
            services.AddSingleton<IStudioRepository, StudioRepository>();
            services.AddSingleton<IRoomRepository, RoomRepository>();

            services.AddSingleton<IStudioService, StudioService>();
            services.AddSingleton<IRoomService, RoomService>();
        }
    }
}

using Microsoft.Extensions.DependencyInjection;

using ISTS.Application.Rooms;
using ISTS.Application.Schedules;
using ISTS.Application.Studios;
using ISTS.Domain.Rooms;
using ISTS.Domain.Schedules;
using ISTS.Domain.Studios;
using ISTS.Infrastructure.Repository;

namespace ISTS.Api
{
    public static class DependencyInjectionConfiguration
    {
        public static void Configure(IServiceCollection services)
        {
            services.AddSingleton<ISessionScheduleValidator, SessionScheduleValidator>();

            services.AddSingleton<IStudioRepository, StudioRepository>();
            services.AddSingleton<IRoomRepository, RoomRepository>();

            services.AddSingleton<IStudioService, StudioService>();
            services.AddSingleton<IRoomService, RoomService>();
        }
    }
}

Fix stackoverflow error caused by navigation property in Session model


using UnityEditor;
using UnityEngine;

namespace Alensia.Core.UI
{
    public static class ComponentFactory
    {
        [MenuItem("GameObject/UI/Alensia/Button", false, 10)]
        public static Button CreateButton(MenuCommand command)
        {
            var button = Button.CreateInstance();

            GameObjectUtility.SetParentAndAlign(button.gameObject, command.context as GameObject);

            Undo.RegisterCreatedObjectUndo(button, "Create " + button.name);

            Selection.activeObject = button;

            return button;
        }

        [MenuItem("GameObject/UI/Alensia/Label", false, 10)]
        public static Label CreateLabel(MenuCommand command)
        {
            var label = Label.CreateInstance();

            GameObjectUtility.SetParentAndAlign(label.gameObject, command.context as GameObject);

            Undo.RegisterCreatedObjectUndo(label, "Create " + label.name);

            Selection.activeObject = label;

            return label;
        }

        [MenuItem("GameObject/UI/Alensia/Panel", false, 10)]
        public static Panel CreatePanel(MenuCommand command)
        {
            var panel = Panel.CreateInstance();

            GameObjectUtility.SetParentAndAlign(panel.gameObject, command.context as GameObject);

            Undo.RegisterCreatedObjectUndo(panel, "Create " + panel.name);

            Selection.activeObject = panel;

            return panel;
        }
    }
}

using System;
using UnityEditor;
using UnityEngine;

namespace Alensia.Core.UI
{
    public static class ComponentFactory
    {
        [MenuItem("GameObject/UI/Alensia/Button", false, 10)]
        public static Button CreateButton(MenuCommand command) => CreateComponent(command, Button.CreateInstance);

        [MenuItem("GameObject/UI/Alensia/Label", false, 10)]
        public static Label CreateLabel(MenuCommand command) => CreateComponent(command, Label.CreateInstance);

        [MenuItem("GameObject/UI/Alensia/Panel", false, 10)]
        public static Panel CreatePanel(MenuCommand command) => CreateComponent(command, Panel.CreateInstance);

        private static T CreateComponent<T>(
            MenuCommand command, Func<T> factory) where T : UIComponent
        {
            var component = factory.Invoke();

            GameObjectUtility.SetParentAndAlign(
                component.gameObject, command.context as GameObject);

            Undo.RegisterCreatedObjectUndo(component, "Create " + component.name);

            Selection.activeObject = component;

            return component;
        }
    }
}

Simplify component factory with generics


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("ENode")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ENode")]
[assembly: AssemblyCopyright("Copyright ©  2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bdf470ac-90a3-47cf-9032-a3f7a298a688")]

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

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("ENode")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ENode")]
[assembly: AssemblyCopyright("Copyright ©  2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bdf470ac-90a3-47cf-9032-a3f7a298a688")]

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

Modify the enode project assembly.cs file


Welcome!

We are Sweet Water Revolver. This is our website. Please look around and check out our...

... showtimes.

Welcome!

We are Sweet Water Revolver. This is our website. Please look around.

Remove the non-active button from the jumbotron.


// Copyright 2016 Google Inc. All Rights Reserved.
// Licensed under the Apache License Version 2.0.

using Google.Apis.Dns.v1;
using Google.PowerShell.Common;

namespace Google.PowerShell.Dns
{
    /// <summary>
    /// Base class for Google DNS-based cmdlets.
    /// </summary>
    public abstract class GcdCmdlet : GCloudCmdlet
    {
        // The Service for the Google DNS API
        public DnsService Service { get; }

        protected GcdCmdlet() : this(null)
        {
        }

        protected GcdCmdlet(DnsService service)
        {
            Service = service ?? new DnsService(GetBaseClientServiceInitializer());
        }
    }
}

Revert "Newline at end of file missing, added."

This reverts commit 4a444ccadc24dc37a2255a33f0dc1f762f13079b.
Undo newline.


// Copyright 2015-2017 Directive Games Limited - All Rights Reserved

using UnrealBuildTool;

public class RapidJson : ModuleRules
{
    public RapidJson(TargetInfo Target)
    {
        bFasterWithoutUnity = true;
        PCHUsage = PCHUsageMode.NoSharedPCHs;

        PublicIncludePaths.AddRange(
            new string[] {
                // ... add public include paths required here ...
            }
            );

        PrivateIncludePaths.AddRange(
            new string[] {
                // ... add other private include paths required here ...
            }
            );

        PublicDependencyModuleNames.AddRange(
            new string[]
            {
                // ... add other public dependencies that you statically link with here ...
                "Core",
                "HTTP",
            }
            );

        PrivateDependencyModuleNames.AddRange(
            new string[]
            {
                // ... add private dependencies that you statically link with here ...
            }
            );

    }
}

// Copyright 2015-2017 Directive Games Limited - All Rights Reserved

using UnrealBuildTool;

public class RapidJson : ModuleRules
{
    public RapidJson(TargetInfo Target)
    {
        bFasterWithoutUnity = true;
        PCHUsage = PCHUsageMode.NoSharedPCHs;

        PublicIncludePaths.AddRange(
            new string[] {
                // ... add public include paths required here ...
            }
            );

        PrivateIncludePaths.AddRange(
            new string[] {
                // ... add other private include paths required here ...
            }
            );

        PublicDependencyModuleNames.AddRange(
            new string[]
            {
                // ... add other public dependencies that you statically link with here ...
                "Core",
                "HTTP",
            }
            );

        PrivateDependencyModuleNames.AddRange(
            new string[]
            {
                // ... add private dependencies that you statically link with here ...
            }
            );

        if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.PS4))
        {
            Definitions.Add("RAPIDJSON_HAS_CXX11_RVALUE_REFS=1");
        }
    }
}

Fix build error in VS2015

Fix build error in VS2015


using KeePassLib;
using System;
using System.Linq;

namespace HaveIBeenPwned
{
    public static class PwEntryExtension
    {
        public static DateTime GetPasswordLastModified(this PwEntry entry)
        {
            if(entry.History != null && entry.History.Any())
            {
                var sortedEntries = entry.History.OrderByDescending(h => h.LastModificationTime);
                foreach(var historyEntry in sortedEntries)
                {
                    if(entry.Strings.GetSafe(PwDefs.PasswordField).ReadString() != historyEntry.Strings.GetSafe(PwDefs.PasswordField).ReadString())
                    {
                        return historyEntry.LastModificationTime;
                    }
                }
                return sortedEntries.Last().LastModificationTime;
            }

            return entry.LastModificationTime;
        }
    }
}

using KeePass.Plugins;
using KeePassLib;
using System;
using System.Linq;

namespace HaveIBeenPwned
{
    public static class PwEntryExtension
    {
        public static DateTime GetPasswordLastModified(this PwEntry entry)
        {
            if(entry.History != null && entry.History.Any())
            {
                var sortedEntries = entry.History.OrderByDescending(h => h.LastModificationTime);
                foreach(var historyEntry in sortedEntries)
                {
                    if(entry.Strings.GetSafe(PwDefs.PasswordField).ReadString() != historyEntry.Strings.GetSafe(PwDefs.PasswordField).ReadString())
                    {
                        return historyEntry.LastModificationTime;
                    }
                }
                return sortedEntries.Last().LastModificationTime;
            }

            return entry.LastModificationTime;
        }

        public static bool IsDeleted(this PwEntry entry, IPluginHost pluginHost)
        {
            return entry.ParentGroup.Uuid.CompareTo(pluginHost.Database.RecycleBinUuid) == 0;
        }
    }
}

Add extension method for working out if an entry is deleted or not.


using System;
using System.IO;
using System.Reflection;
using NServiceBus;
using NServiceBus.Settings;

static class ScriptLocation
{
    public static string FindScriptDirectory(ReadOnlySettings settings)
    {
        var currentDirectory = GetCurrentDirectory(settings);
        return Path.Combine(currentDirectory, "NServiceBus.Persistence.Sql", settings.GetSqlDialect().Name);
    }

    static string GetCurrentDirectory(ReadOnlySettings settings)
    {
        if (settings.TryGet("SqlPersistence.ScriptDirectory", out string scriptDirectory))
        {
            return scriptDirectory;
        }
        var entryAssembly = Assembly.GetEntryAssembly();
        if (entryAssembly == null)
        {
            return AppDomain.CurrentDomain.BaseDirectory;
        }
        var codeBase = entryAssembly.CodeBase;
        return Directory.GetParent(new Uri(codeBase).LocalPath).FullName;
    }

    public static void ValidateScriptExists(string createScript)
    {
        if (!File.Exists(createScript))
        {
            throw new Exception($"Expected '{createScript}' to exist. It is possible it was not deployed with the endpoint or NServiceBus.Persistence.Sql.MsBuild nuget was not included in the project.");
        }
    }
}

using System;
using System.IO;
using System.Reflection;
using NServiceBus;
using NServiceBus.Settings;

static class ScriptLocation
{
    const string ScriptFolder = "NServiceBus.Persistence.Sql";

    public static string FindScriptDirectory(ReadOnlySettings settings)
    {
        var currentDirectory = GetCurrentDirectory(settings);
        return Path.Combine(currentDirectory, ScriptFolder, settings.GetSqlDialect().Name);
    }

    static string GetCurrentDirectory(ReadOnlySettings settings)
    {
        if (settings.TryGet("SqlPersistence.ScriptDirectory", out string scriptDirectory))
        {
            return scriptDirectory;
        }
        var entryAssembly = Assembly.GetEntryAssembly();
        if (entryAssembly == null)
        {
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var scriptDir = Path.Combine(baseDir, ScriptFolder);
            //if the app domain base dir contains the scripts folder, return it. Otherwise add "bin" to the base dir so that web apps work correctly
            if (Directory.Exists(scriptDir))
            {
                return baseDir;
            }
            return Path.Combine(baseDir, "bin");
        }
        var codeBase = entryAssembly.CodeBase;
        return Directory.GetParent(new Uri(codeBase).LocalPath).FullName;
    }

    public static void ValidateScriptExists(string createScript)
    {
        if (!File.Exists(createScript))
        {
            throw new Exception($"Expected '{createScript}' to exist. It is possible it was not deployed with the endpoint or NServiceBus.Persistence.Sql.MsBuild nuget was not included in the project.");
        }
    }
}

Fix script location via AppDomain base dir for web applications


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

namespace Rhaeo.Mvvm
{
    public class ObservableObject
    {
    }
}

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ObservableObject.cs" company="Rhaeo">
//   Licenced under the MIT licence.
// </copyright>
// <summary>
//   Defines the ObservableObject type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Linq.Expressions;

namespace Rhaeo.Mvvm
{
  /// <summary>
  /// Serves as a back class for object instances obserable through the <see cref="INotifyPropertyChanged"/> interface.
  /// </summary>
  public class ObservableObject
    : INotifyPropertyChanged
  {
    #region Events

    /// <summary>
    /// Occurs when a property value changes.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    #region Methods

    /// <summary>
    /// Raises the <see cref="PropertyChanged"/> event with a property name extracted from the property expression.
    /// </summary>
    /// <typeparam name="TViewModel">
    /// The view model type.
    /// </typeparam>
    /// <typeparam name="TValue">
    /// The property value type.
    /// </typeparam>
    /// <param name="propertyExpression">
    /// The property expression.
    /// </param>
    protected void RaisePropertyChanged<TViewModel, TValue>(Expression<Func<TViewModel, TValue>> propertyExpression) where TViewModel : ObservableObject
    {
      var propertyName = (propertyExpression.Body as MemberExpression).Member.Name;

      var propertyChangedHandler = this.PropertyChanged;
      if (propertyChangedHandler != null)
      {
        propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));
      }
    }

    #endregion
  }
}

Implement extracting the property name

Implement extracting the property name


// https://www.reddit.com/r/dailyprogrammer/comments/3n55f3/20150930_challenge_234_intermediate_red_squiggles/
//
// Your challenge today is to implement a real time spell checker and indicate where you would throw the red squiggle. For your dictionary use /usr/share/dict/words
//

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

class Trie
{
    private class Node
    {
        internal Dictionary<char, Node> Next = new Dictionary<char, Node>();
        bool IsWord = false;
    }
}

class Program
{
    static void Main()
    {
        Trie trie = new Trie();
        using (StreamReader reader = new StreamReader("/usr/share/dict/words"))
        {
            String line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

// https://www.reddit.com/r/dailyprogrammer/comments/3n55f3/20150930_challenge_234_intermediate_red_squiggles/
//
// Your challenge today is to implement a real time spell checker and indicate where you would throw the red squiggle. For your dictionary use /usr/share/dict/words
//

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

class Trie
{
    private class Node
    {
        internal Dictionary<char, Node> Next = new Dictionary<char, Node>();
        internal bool IsWord = false;

        public override String ToString()
        {
            return String.Format("[Node.IsWord:{0} {1}]",
                                 IsWord,
                                 String.Join(", ", Next.Select(x =>
                                                               String.Format("{0} => {1}", x.Key, x.Value.ToString()))));
        }
    }

    private readonly Node Root = new Node();

    public void Add(String s)
    {
        Node current = Root;
        for (int i = 0; i < s.Length; i++)
        {
            Node next;
            if (!current.Next.TryGetValue(s[i], out next))
            {
                next = new Node();
                current.Next[s[i]] = next;
            }

            next.IsWord = i == s.Length - 1;
            current = next;
        }
    }

    public override String ToString()
    {
        return Root.ToString();
    }
}

class Program
{
    static void Main()
    {
        Trie trie = new Trie();
        using (StreamReader reader = new StreamReader("/usr/share/dict/words"))
        {
            String line;
            while ((line = reader.ReadLine()) != null)
            {
                trie.Add(line);
            }
        }

        Console.WriteLine(trie);
    }
}

Build and print the trie

Build and print the trie


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

using Android.App;
using Android.OS;
using Android.Content.PM;
using Android.Views;

namespace SampleGame.Android
{
    [Activity(Label = "SampleGame", MainLauncher = true, ScreenOrientation = ScreenOrientation.Landscape, Theme = "@android:style/Theme.NoTitleBar")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Window.AddFlags(WindowManagerFlags.Fullscreen);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);
            SetContentView(new SampleGameView(this));
        }
    }
}

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

using Android.App;
using Android.OS;
using Android.Content.PM;
using Android.Views;
using System;
using Android.Runtime;
using Android.Content.Res;

namespace SampleGame.Android
{
    [Activity(Label = "SampleGame", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")]
    public class MainActivity : Activity
    {
        private SampleGameView sampleGameView;

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

            Window.AddFlags(WindowManagerFlags.Fullscreen);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            SetContentView(sampleGameView = new SampleGameView(this));
        }
    }
}

Allow rotating the screen without crashing by overriding the Configuration changes.

Restarting the activity is not a choice on orientation changes.


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("PinWin")]
[assembly: AssemblyDescription("Allows user to make desktop windows top most")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PinWin")]
[assembly: AssemblyCopyright("Copyright © Victor Zakharov 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7ae6966c-0686-4ac4-afbb-9ffd7bf7b81c")]

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

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("PinWin")]
[assembly: AssemblyDescription("Allows user to make desktop windows top most")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PinWin")]
[assembly: AssemblyCopyright("Copyright © Victor Zakharov 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7ae6966c-0686-4ac4-afbb-9ffd7bf7b81c")]

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

Increment version before creating release (0.2.5).


// Copyright (c) 2016-2017 Nicolas Musset. All rights reserved.
// This file is licensed under the MIT license.
// See the LICENSE.md file in the project root for more information.

using System;
using System.Windows.Documents;
using Markdig.Annotations;
using Markdig.Syntax.Inlines;
using Markdig.Wpf;

namespace Markdig.Renderers.Wpf.Inlines
{
    /// <summary>
    /// A WPF renderer for a <see cref="AutolinkInline"/>.
    /// </summary>
    /// <seealso cref="Markdig.Renderers.Wpf.WpfObjectRenderer{Markdig.Syntax.Inlines.AutolinkInline}" />
    public class AutolinkInlineRenderer : WpfObjectRenderer<AutolinkInline>
    {
        /// <inheritdoc/>
        protected override void Write([NotNull] WpfRenderer renderer, [NotNull] AutolinkInline link)
        {
            var url = link.Url;

            if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
            {
                url = "#";
            }

            var hyperlink = new Hyperlink
            {
                Command = Commands.Hyperlink,
                CommandParameter = url,
                NavigateUri = new Uri(url, UriKind.RelativeOrAbsolute),
                ToolTip = url,
            };

            renderer.WriteInline(hyperlink);
        }
    }
}

// Copyright (c) 2016-2017 Nicolas Musset. All rights reserved.
// This file is licensed under the MIT license.
// See the LICENSE.md file in the project root for more information.

using System;
using System.Windows.Documents;
using Markdig.Annotations;
using Markdig.Syntax.Inlines;
using Markdig.Wpf;

namespace Markdig.Renderers.Wpf.Inlines
{
    /// <summary>
    /// A WPF renderer for a <see cref="AutolinkInline"/>.
    /// </summary>
    /// <seealso cref="Markdig.Renderers.Wpf.WpfObjectRenderer{Markdig.Syntax.Inlines.AutolinkInline}" />
    public class AutolinkInlineRenderer : WpfObjectRenderer<AutolinkInline>
    {
        /// <inheritdoc/>
        protected override void Write([NotNull] WpfRenderer renderer, [NotNull] AutolinkInline link)
        {
            var url = link.Url;

            if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
            {
                url = "#";
            }

            var hyperlink = new Hyperlink
            {
                Command = Commands.Hyperlink,
                CommandParameter = url,
                NavigateUri = new Uri(url, UriKind.RelativeOrAbsolute),
                ToolTip = url,
            };

            renderer.Push(hyperlink);
            renderer.WriteText(link.Url);
            renderer.Pop();
        }
    }
}

Write the autolink's URL so we can see the autolink.


using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Swashbuckle.Swagger.Application
{
    public class SwaggerSerializerFactory
    {
        internal static JsonSerializer Create(IOptions<MvcJsonOptions> mvcJsonOptions)
        {
            // TODO: Should this handle case where mvcJsonOptions.Value == null?
            return new JsonSerializer
            {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver = new SwaggerContractResolver(mvcJsonOptions.Value.SerializerSettings)
            };
        }
    }
}

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Swashbuckle.Swagger.Application
{
    public class SwaggerSerializerFactory
    {
        internal static JsonSerializer Create(IOptions<MvcJsonOptions> mvcJsonOptions)
        {
            // TODO: Should this handle case where mvcJsonOptions.Value == null?
            return new JsonSerializer
            {
                NullValueHandling = NullValueHandling.Ignore,
                Formatting = mvcJsonOptions.Value.SerializerSettings.Formatting,
                ContractResolver = new SwaggerContractResolver(mvcJsonOptions.Value.SerializerSettings)
            };
        }
    }
}

Use MvcJsonOptions json serializer formatting when generating swagger.json


using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;

using Raven.Client;
using Raven.Client.Embedded;

namespace CGO.Web.NinjectModules
{
    public class RavenModule : NinjectModule
    {
        public override void Load()
        {
            Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope();
            Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope();
        }

        private static IDocumentStore InitialiseDocumentStore()
        {
            var documentStore = new EmbeddableDocumentStore
            {
                DataDirectory = "CGO.raven",
                UseEmbeddedHttpServer = true,
                Configuration = { Port = 28645 }
            };

            documentStore.Initialize();
            documentStore.InitializeProfiling();

            return documentStore;
        }
    }
}

using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;

using Raven.Client;
using Raven.Client.Embedded;

namespace CGO.Web.NinjectModules
{
    public class RavenModule : NinjectModule
    {
        public override void Load()
        {
            Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope();
            Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope();
        }

        private static IDocumentStore InitialiseDocumentStore()
        {
            var documentStore = new EmbeddableDocumentStore
            {
                DataDirectory = "CGO.raven",
                Configuration = { Port = 28645 }
            };

            documentStore.Initialize();
            documentStore.InitializeProfiling();

            return documentStore;
        }
    }
}

Disable Raven's Embedded HTTP server

Disable Raven's Embedded HTTP server

I'm not really making use of this, and it's preventing successful
deployment in Azure.


using Conventional.Conventions;

namespace Pirac.Conventions
{
    internal class ViewConvention : Convention
    {
        public ViewConvention()
        {
            Must.HaveNameEndWith("View").BeAClass();

            Should.BeAConcreteClass();

            BaseName = t => t.Name.Substring(0, t.Name.Length - 4);

            Variants.HaveBaseNameAndEndWith("View");
        }
    }
}

using System;
using Conventional.Conventions;

namespace Pirac.Conventions
{
    internal class ViewConvention : Convention
    {
        public ViewConvention()
        {
            Must.Pass(t => t.IsClass && (t.Name.EndsWith("View") || t.Name == "MainWindow"), "Name ends with View or is named MainWindow");

            Should.BeAConcreteClass();

            BaseName = t => t.Name == "MainWindow" ? t.Name : t.Name.Substring(0, t.Name.Length - 4);

            Variants.Add(new DelegateBaseFilter((t, b) =>
            {
                if (t.Name == "MainWindow" && b == "MainWindow")
                    return true;

                return t.Name == b + "View";
            }));
        }

        class DelegateBaseFilter : IBaseFilter
        {
            private readonly Func<Type, string, bool> predicate;

            public DelegateBaseFilter(Func<Type, string, bool> predicate)
            {
                this.predicate = predicate;
            }

            public bool Matches(Type t, string baseName)
            {
                return predicate(t, baseName);
            }
        }
    }
}

Update View convention to recognize MainWindow


using System;
using System.Collections.Generic;
using System.IO;
using Cake.Core;
using Cake.Core.Configuration;
using Cake.Frosting;
using Cake.NuGet;

public class Program : IFrostingStartup
{
    public static int Main(string[] args)
    {
        // Create the host.
        var host = new CakeHostBuilder()
            .WithArguments(args)
            .UseStartup<Program>()
            .Build();

        // Run the host.
        return host.Run();
    }

    public void Configure(ICakeServices services)
    {
        services.UseContext<Context>();
        services.UseLifetime<Lifetime>();
        services.UseWorkingDirectory("..");

        // from https://github.com/cake-build/cake/discussions/2931
        var module = new NuGetModule(new CakeConfiguration(new Dictionary<string, string>()));
        module.Register(services);

        services.UseTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1"));
        services.UseTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0"));
        services.UseTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0"));
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using Cake.Core;
using Cake.Core.Configuration;
using Cake.Frosting;
using Cake.NuGet;

public class Program : IFrostingStartup
{
    public static int Main(string[] args)
    {
        // Create the host.
        var host = new CakeHostBuilder()
            .WithArguments(args)
            .UseStartup<Program>()
            .Build();

        // Run the host.
        return host.Run();
    }

    public void Configure(ICakeServices services)
    {
        services.UseContext<Context>();
        services.UseLifetime<Lifetime>();
        services.UseWorkingDirectory("..");

        // from https://github.com/cake-build/cake/discussions/2931
        var module = new NuGetModule(new CakeConfiguration(new Dictionary<string, string>()));
        module.Register(services);

        services.UseTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1"));
        services.UseTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0"));
        services.UseTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0"));
        services.UseTool(new Uri("nuget:?package=NuGet.CommandLine&version=5.8.0"));
    }
}

Install NuGet as a tool

Install NuGet as a tool


/*
 * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
 * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

using QuantConnect.Configuration;

namespace QuantConnect
{
    /// <summary>
    /// Provides application level constant values
    /// </summary>
    public static class Constants
    {
        /// <summary>
        /// The root directory of the data folder for this application
        /// </summary>
        public static string DataFolder
        {
            get { return Config.Get("data-folder", @"../../../Data/"); }
        }

        /// <summary>
        /// The directory used for storing downloaded remote files
        /// </summary>
        public const string Cache = "./cache/data";

        /// <summary>
        /// The version of lean
        /// </summary>
        public static readonly string Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
    }
}

/*
 * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
 * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

using QuantConnect.Configuration;

namespace QuantConnect
{
    /// <summary>
    /// Provides application level constant values
    /// </summary>
    public static class Constants
    {
        private static readonly string DataFolderPath = Config.Get("data-folder", @"../../../Data/");

        /// <summary>
        /// The root directory of the data folder for this application
        /// </summary>
        public static string DataFolder
        {
            get { return DataFolderPath; }
        }

        /// <summary>
        /// The directory used for storing downloaded remote files
        /// </summary>
        public const string Cache = "./cache/data";

        /// <summary>
        /// The version of lean
        /// </summary>
        public static readonly string Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
    }
}

Move DataFolder config get to static member initializer


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

namespace Kyru.Core
{
    class Config
    {
        internal readonly string storeDirectory;

        internal Config() {
            storeDirectory = Path.Combine(System.Windows.Forms.Application.UserAppDataPath);
        }
    }
}

using System;
using System.IO;

namespace Kyru.Core
{
	internal sealed class Config
	{
		internal string storeDirectory;

		internal Config()
		{
			storeDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Kyru", "objects");
		}
	}
}

Use a path for storage that doesn't include version and company name


using System;
using System.IO;

using Mango;

//
//  This the default StaticContentModule that comes with all Mango apps
//  if you do not wish to serve any static content with Mango you can
//  remove its route handler from <YourApp>.cs's constructor and delete
//  this file.
//
//  All Content placed on the Content/ folder should be handled by this
//  module.
//

namespace $APPNAME {

	public class StaticContentModule : MangoModule {

		public StaticContentModule ()
		{
			Get ("*", Content);

		}

		public static void Content (MangoContext ctx)
		{
			string path = ctx.Request.LocalPath;

			if (path.StartsWith ("/"))
				path = path.Substring (1);

			if (File.Exists (path)) {
				ctx.Response.SendFile (path);
			} else
				ctx.Response.StatusCode = 404;
		}
	}
}

using System;
using System.IO;

using Mango;

//
//  This the default StaticContentModule that comes with all Mango apps
//  if you do not wish to serve any static content with Mango you can
//  remove its route handler from <YourApp>.cs's constructor and delete
//  this file.
//
//  All Content placed on the Content/ folder should be handled by this
//  module.
//

namespace AppNameFoo {

	public class StaticContentModule : MangoModule {

		public StaticContentModule ()
		{
			Get ("*", Content);

		}

		public static void Content (IMangoContext ctx)
		{
			string path = ctx.Request.LocalPath;

			if (path.StartsWith ("/"))
				path = path.Substring (1);

			if (File.Exists (path)) {
				ctx.Response.SendFile (path);
			} else
				ctx.Response.StatusCode = 404;
		}
	}
}

Update the static content module to fit the new API.


using System;
using Mono.Addins;
using Mono.Addins.Description;

[assembly:Addin (
	"${ProjectName}",
	Namespace = "${ProjectName}",
	Version = "1.0"
)]

[assembly:AddinName ("${ProjectName}")]
[assembly:AddinCategory ("${ProjectName}")]
[assembly:AddinDescription ("${ProjectName}")]
[assembly:AddinAuthor ("${AuthorName}")]

using System;
using Mono.Addins;
using Mono.Addins.Description;

[assembly:Addin (
	"${ProjectName}",
	Namespace = "${ProjectName}",
	Version = "1.0"
)]

[assembly:AddinName ("${ProjectName}")]
[assembly:AddinCategory ("IDE extensions")]
[assembly:AddinDescription ("${ProjectName}")]
[assembly:AddinAuthor ("${AuthorName}")]

Fix default category for new addins

Fix default category for new addins


using Nancy;
using Owin;

namespace Bbl.KnockoutJs
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseNancy();
        }
    }

    public class IndexModule : NancyModule
    {
        public IndexModule()
        {
            Get["/"] = parameters => View["index"];
        }
    }
}

using System.IO;
using System.Linq;
using System.Web.Hosting;
using Nancy;
using Owin;

namespace Bbl.KnockoutJs
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseNancy();
        }
    }

    public class IndexModule : NancyModule
    {
        private const string UnicornsPath = "/Content/Unicorn/";

        public IndexModule()
        {
            Get["/"] = parameters => View["index"];

            Get["/api/unicorns"] = parameters =>
                {
                    var imagesDirectory = HostingEnvironment.MapPath("~" + UnicornsPath);
                    return new DirectoryInfo(imagesDirectory)
                        .EnumerateFiles()
                        .Select(ConvertToDto);
                };
        }

        private dynamic ConvertToDto(FileInfo file)
        {
            var name = Path.GetFileNameWithoutExtension(file.Name);

            return new
                   {
                       Key = name,
                       ImagePath = UnicornsPath + file.Name,
                       Name = name.Replace('_', ' '),
                       Keywords = name.Split('_'),
                       CreationDate = file.CreationTime
                   };
        }
    }
}

Add url to get unicorns

Add url to get unicorns


using System;
using System.Diagnostics;
using System.IO;

namespace dotnet_new2
{
    public class ProjectCreator
    {
        public bool CreateProject(string name, string path, Template template)
        {
            Directory.CreateDirectory(path);

            foreach (var file in template.Files)
            {
                var dest = Path.Combine(path, file.DestPath);
                File.Copy(file.SourcePath, dest);
                ProcessFile(dest, name);
            }

            Console.WriteLine();
            Console.WriteLine($"Created \"{name}\" in {path}");

            return true;
        }

        private void ProcessFile(string destPath, string name)
        {
            // TODO: Make this good
            var contents = File.ReadAllText(destPath);

            File.WriteAllText(destPath, contents.Replace("$DefaultNamespace$", name));
        }
    }
}

using System;
using System.Diagnostics;
using System.IO;

namespace dotnet_new2
{
    public class ProjectCreator
    {
        public bool CreateProject(string name, string path, Template template)
        {
            Directory.CreateDirectory(path);

            if (Directory.GetFileSystemEntries(path).Length > 0)
            {
                // Files already exist in the directory
                Console.WriteLine($"Directory {path} already contains files. Please specify a different project name.");
                return false;
            }

            foreach (var file in template.Files)
            {
                var dest = Path.Combine(path, file.DestPath);

                File.Copy(file.SourcePath, dest);
                ProcessFile(dest, name);
            }

            Console.WriteLine();
            Console.WriteLine($"Created \"{name}\" in {path}");
            Console.WriteLine();

            return true;
        }

        private void ProcessFile(string destPath, string name)
        {
            // TODO: Make this good
            var contents = File.ReadAllText(destPath);

            File.WriteAllText(destPath, contents.Replace("$DefaultNamespace$", name));
        }
    }
}

Fix case when project directory already exists


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

namespace SteamIrcBot
{
    class ServiceDispatcher
    {
        static ServiceDispatcher _instance = new ServiceDispatcher();
        public static ServiceDispatcher Instance { get { return _instance; } }

        Task dispatcher;
        CancellationTokenSource cancelToken;

        ServiceDispatcher()
        {
            cancelToken = new CancellationTokenSource();
            dispatcher = new Task( ServiceTick, cancelToken.Token, TaskCreationOptions.LongRunning );
        }

        void ServiceTick()
        {
            while ( true )
            {
                if ( cancelToken.IsCancellationRequested )
                    break;

                Steam.Instance.Tick();
                IRC.Instance.Tick();
                RSS.Instance.Tick();
            }
        }

        public void Start()
        {
            dispatcher.Start();
        }

        public void Stop()
        {
            cancelToken.Cancel();
        }

        public void Wait()
        {
            try
            {
                dispatcher.Wait();
            }
            catch ( AggregateException )
            {
                // we'll ignore any cancelled/failed tasks
            }
        }

    }
}

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

namespace SteamIrcBot
{
    class ServiceDispatcher
    {
        static ServiceDispatcher _instance = new ServiceDispatcher();
        public static ServiceDispatcher Instance { get { return _instance; } }

        Task dispatcher;
        CancellationTokenSource cancelToken;

        ServiceDispatcher()
        {
            cancelToken = new CancellationTokenSource();
            dispatcher = new Task( ServiceTick, cancelToken.Token, TaskCreationOptions.LongRunning );
        }

        void ServiceTick()
        {
            while ( true )
            {
                if ( cancelToken.IsCancellationRequested )
                    break;

                Steam.Instance.Tick();
                IRC.Instance.Tick();
                RSS.Instance.Tick();
            }
        }

        public void Start()
        {
            dispatcher.Start();
        }

        public void Stop()
        {
            cancelToken.Cancel();
        }

        public void Wait()
        {
            dispatcher.Wait();
        }

    }
}

Throw all dispatcher exceptions on the non-service build.


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

namespace Monacs.Core.Unit
{
    ///
    /// Extensions for <see cref="Result<Unit>" /> type.
    ///
    public static class Result
    {
        ///
        /// Creates successful <see cref="Result<Unit>" />.
        ///
        public static Result<Unit> Ok() =>
            Core.Result.Ok(Unit.Default);

        ///
        /// Creates failed <see cref="Result<Unit>" /> with provided error details.
        ///
        public static Result<Unit> Error(ErrorDetails error) =>
            Core.Result.Error<Unit>(error);

        ///
        /// Rejects the value of the <see cref="Result<T>" /> and returns <see cref="Result<Unit>" /> instead.
        /// If the input <see cref="Result<T>" /> is Error then the error details are preserved.
        ///
        public static Result<Unit> Ignore<T>(this Result<T> result) =>
            result.Map(_ => Unit.Default);
    }
}

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

namespace Monacs.Core.Unit
{
    ///
    /// Extensions for <see cref="Result{Unit}" /> type.
    ///
    public static class Result
    {
        ///
        /// Creates successful <see cref="Result{Unit}" />.
        ///
        public static Result<Unit> Ok() =>
            Core.Result.Ok(Unit.Default);

        ///
        /// Creates failed <see cref="Result{Unit}" /> with provided error details.
        ///
        public static Result<Unit> Error(ErrorDetails error) =>
            Core.Result.Error<Unit>(error);

        ///
        /// Rejects the value of the <see cref="Result{T}" /> and returns <see cref="Result{Unit}" /> instead.
        /// If the input <see cref="Result{T}" /> is Error then the error details are preserved.
        ///
        public static Result<Unit> Ignore<T>(this Result<T> result) =>
            result.Map(_ => Unit.Default);
    }
}

Fix the XML docs generic class references


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

[assembly: AssemblyTitle("ProviderModel")]
[assembly: AssemblyDescription("An improvment over the bundled .NET provider model")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Enrique Alejandro Allegretta")]
[assembly: AssemblyProduct("ProviderModel")]
[assembly: AssemblyCopyright("Copyright ©  2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("en-US")]
[assembly: ComVisible(false)]
[assembly: Guid("9d02304c-cda1-4d3b-afbc-725731a794b5")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]

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

[assembly: AssemblyTitle("ProviderModel")]
[assembly: AssemblyDescription("An improvment over the bundled .NET provider model")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Enrique Alejandro Allegretta")]
[assembly: AssemblyProduct("ProviderModel")]
[assembly: AssemblyCopyright("Copyright ©  2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("9d02304c-cda1-4d3b-afbc-725731a794b5")]
[assembly: AssemblyVersion("1.0.1")]
[assembly: AssemblyFileVersion("1.0.1")]
[assembly: AssemblyInformationalVersion("1.0.1")]

Set assembly culture to neutral

Set assembly culture to neutral


using SOVND.Lib;
using System.IO;

namespace SOVND.Server
{
    public class ServerMqttSettings : IMQTTSettings
    {
        public string Broker { get { return "104.131.87.42"; } }

        public int Port { get { return 8883; } }

        public string Username
        {
            get { return File.ReadAllText("username.key"); }
        }

        public string Password
        {
            get { return File.ReadAllText("password.key"); }
        }
    }
}

using SOVND.Lib;
using System.IO;

namespace SOVND.Server
{
    public class ServerMqttSettings : IMQTTSettings
    {
        public string Broker { get { return "104.131.87.42"; } }

        public int Port { get { return 2883; } }

        public string Username
        {
            get { return File.ReadAllText("username.key"); }
        }

        public string Password
        {
            get { return File.ReadAllText("password.key"); }
        }
    }
}

Change port for new RabbitMQ-MQTT server