using System;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using WebAPI.Domain.InputOptions;

namespace WebAPI.API.ModelBindings
{
    public class SearchOptionsModelBinding : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var keyValueModel = actionContext.Request.RequestUri.ParseQueryString();

            string pointJson = keyValueModel["geometry"],
                   spatialReference = keyValueModel["spatialReference"],
                   predicate = keyValueModel["predicate"],
                   attribute = keyValueModel["attributeStyle"],
                   bufferAmount = keyValueModel["buffer"];

            int wkid;
            var attributeType = AttributeStyle.Camel;

            int.TryParse(string.IsNullOrEmpty(spatialReference) ? "26912" : spatialReference, out wkid);

            try
            {
                attributeType =
                    (AttributeStyle)
                    Enum.Parse(typeof(AttributeStyle), string.IsNullOrEmpty(attribute) ? "Camel" : attribute, true);
            }
            catch (Exception)
            {
                /*ie sometimes sends display value in text box.*/
            }

            double buffer;
            double.TryParse(string.IsNullOrEmpty(bufferAmount) ? "0" : bufferAmount, out buffer);

            bindingContext.Model = new SearchOptions
                {
                    Geometry = pointJson,
                    Predicate = predicate,
                    WkId = wkid,
                    Buffer = buffer,
                    AttributeStyle = attributeType
                };

            return true;
        }
    }
}

using System;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using WebAPI.Domain.InputOptions;

namespace WebAPI.API.ModelBindings
{
    public class SearchOptionsModelBinding : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var keyValueModel = actionContext.Request.RequestUri.ParseQueryString();

            string pointJson = keyValueModel["geometry"],
                   spatialReference = keyValueModel["spatialReference"],
                   predicate = keyValueModel["predicate"],
                   attribute = keyValueModel["attributeStyle"],
                   bufferAmount = keyValueModel["buffer"];

            int wkid;
            var attributeType = AttributeStyle.Camel;

            int.TryParse(string.IsNullOrEmpty(spatialReference) ? "26912" : spatialReference, out wkid);

            try
            {
                attributeType =
                    (AttributeStyle)
                    Enum.Parse(typeof(AttributeStyle), string.IsNullOrEmpty(attribute) ? "Lower" : attribute, true);
            }
            catch (Exception)
            {
                /*ie sometimes sends display value in text box.*/
            }

            double buffer;
            double.TryParse(string.IsNullOrEmpty(bufferAmount) ? "0" : bufferAmount, out buffer);

            bindingContext.Model = new SearchOptions
                {
                    Geometry = pointJson,
                    Predicate = predicate,
                    WkId = wkid,
                    Buffer = buffer,
                    AttributeStyle = attributeType
                };

            return true;
        }
    }
}

Change default attributeStyle to lower for search


using System.IO;
using BenchmarkDotNet.Attributes;
using FreeImageAPI;
using ImageMagick;
using DS = DevILSharp;

namespace Pfim.Benchmarks
{
    public class TargaBenchmark
    {
        [Params("true-32-rle-large.tga", "true-24-large.tga", "true-24.tga", "true-32-rle.tga", "rgb24_top_left")]
        public string Payload { get; set; }

        private byte[] data;

        [GlobalSetup]
        public void SetupData()
        {
            data = File.ReadAllBytes(Payload);
            DS.Bootstrap.Init();
        }

        [Benchmark]
        public IImage Pfim() => Targa.Create(new MemoryStream(data));

        [Benchmark]
        public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data));

        [Benchmark]
        public int ImageMagick()
        {
            var settings = new MagickReadSettings {Format = MagickFormat.Tga};
            using (var image = new MagickImage(new MemoryStream(data), settings))
            {
                return image.Width;
            }
        }

        [Benchmark]
        public int DevILSharp()
        {
            using (var image = DS.Image.Load(data, DS.ImageType.Tga))
            {
                return image.Width;
            }
        }

        [Benchmark]
        public int TargaImage()
        {
            using (var image = new Paloma.TargaImage(new MemoryStream(data)))
            {
                return image.Stride;
            }
        }
    }
}

using System.IO;
using BenchmarkDotNet.Attributes;
using FreeImageAPI;
using ImageMagick;
using DS = DevILSharp;

namespace Pfim.Benchmarks
{
    public class TargaBenchmark
    {
        [Params("true-32-rle-large.tga", "true-24-large.tga", "true-24.tga", "true-32-rle.tga", "rgb24_top_left.tga")]
        public string Payload { get; set; }

        private byte[] data;

        [GlobalSetup]
        public void SetupData()
        {
            data = File.ReadAllBytes(Payload);
            DS.Bootstrap.Init();
        }

        [Benchmark]
        public IImage Pfim() => Targa.Create(new MemoryStream(data));

        [Benchmark]
        public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data));

        [Benchmark]
        public int ImageMagick()
        {
            var settings = new MagickReadSettings {Format = MagickFormat.Tga};
            using (var image = new MagickImage(new MemoryStream(data), settings))
            {
                return image.Width;
            }
        }

        [Benchmark]
        public int DevILSharp()
        {
            using (var image = DS.Image.Load(data, DS.ImageType.Tga))
            {
                return image.Width;
            }
        }

        [Benchmark]
        public int TargaImage()
        {
            using (var image = new Paloma.TargaImage(new MemoryStream(data)))
            {
                return image.Stride;
            }
        }
    }
}

Fix incorrect file path in benchmarks

Fix incorrect file path in benchmarks


@page "/about"
@inject Navigator Navigator

Money

Neptuo

    v@(typeof(About).Assembly.GetName().Version.ToString(3))

    Documentation

    Report an issue

@page "/about"
@inject Navigator Navigator

<Title Main="Money" Sub="Nepuo" />

    v@(typeof(About).Assembly.GetName().Version.ToString(3))

    Documentation

    Report an issue

Use <Title in about page.

Use <Title in about page.


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Owin;

namespace JabbR.Middleware
{
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public class RequireHttpsHandler
    {
        private readonly AppFunc _next;

        public RequireHttpsHandler(AppFunc next)
        {
            _next = next;
        }

        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new ServerRequest(env);
            var response = new Gate.Response(env);

            if (!request.Url.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                var builder = new UriBuilder(request.Url);
                builder.Scheme = "https";

                response.SetHeader("Location", builder.ToString());
                response.StatusCode = 302;

                return TaskAsyncHelper.Empty;
            }
            else
            {
                return _next(env);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Owin;

namespace JabbR.Middleware
{
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public class RequireHttpsHandler
    {
        private readonly AppFunc _next;

        public RequireHttpsHandler(AppFunc next)
        {
            _next = next;
        }

        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new ServerRequest(env);
            var response = new Gate.Response(env);

            if (!request.Url.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                var builder = new UriBuilder(request.Url);
                builder.Scheme = "https";

                if (builder.Port == 80)
                {
                    builder.Port = -1;
                }

                response.SetHeader("Location", builder.ToString());
                response.StatusCode = 302;

                return TaskAsyncHelper.Empty;
            }
            else
            {
                return _next(env);
            }
        }
    }
}

Set port to -1 if port is 80

Set port to -1 if port is 80


using Mapsui.Utilities;
using System;
using System.Collections.Generic;
using System.Text;

namespace Mapsui.Extensions
{
    public static class ViewportExtensions
    {
        /// <summary>
        /// True if Width and Height are not zero
        /// </summary>
        public static bool HasSize(this IReadOnlyViewport viewport) =>
            !viewport.Width.IsNanOrInfOrZero() && !viewport.Height.IsNanOrInfOrZero();

        /// <summary>
        /// IsRotated is true, when viewport displays map rotated
        /// </summary>
        public static bool IsRotated(this IReadOnlyViewport viewport) =>
            !double.IsNaN(viewport.Rotation) && viewport.Rotation > Constants.Epsilon
            && viewport.Rotation < 360 - Constants.Epsilon;
    }
}

using Mapsui.Utilities;
using System;
using System.Collections.Generic;
using System.Text;

namespace Mapsui.Extensions
{
    public static class ViewportExtensions
    {
        /// <summary>
        /// True if Width and Height are not zero
        /// </summary>
        public static bool HasSize(this IReadOnlyViewport viewport) =>
            !viewport.Width.IsNanOrInfOrZero() && !viewport.Height.IsNanOrInfOrZero();

        /// <summary>
        /// IsRotated is true, when viewport displays map rotated
        /// </summary>
        public static bool IsRotated(this IReadOnlyViewport viewport) =>
            !double.IsNaN(viewport.Rotation) && viewport.Rotation > Constants.Epsilon
            && viewport.Rotation < 360 - Constants.Epsilon;

        /// <summary>
        /// Calculates extent from the viewport
        /// </summary>
        /// <remarks>
        /// This MRect is horizontally and vertically aligned, even if the viewport
        /// is rotated. So this MRect perhaps contain parts, that are not visible.
        /// </remarks>
        public static MRect GetExtent(this IReadOnlyViewport viewport)
        {
            // calculate the window extent
            var halfSpanX = viewport.Width * viewport.Resolution * 0.5;
            var halfSpanY = viewport.Height * viewport.Resolution * 0.5;
            var minX = viewport.CenterX - halfSpanX;
            var minY = viewport.CenterY - halfSpanY;
            var maxX = viewport.CenterX + halfSpanX;
            var maxY = viewport.CenterY + halfSpanY;

            if (!viewport.IsRotated())
            {
                return new MRect(minX, minY, maxX, maxY);
            }
            else
            {
                var windowExtent = new MQuad
                {
                    BottomLeft = new MPoint(minX, minY),
                    TopLeft = new MPoint(minX, maxY),
                    TopRight = new MPoint(maxX, maxY),
                    BottomRight = new MPoint(maxX, minY)
                };

                // Calculate the extent that will encompass a rotated viewport (slightly larger - used for tiles).
                // Perform rotations on corner offsets and then add them to the Center point.
                return windowExtent.Rotate(-viewport.Rotation, viewport.CenterX, viewport.CenterY).ToBoundingBox();
            }
        }
    }
}

Add GetExtent to viewport extensions

Add GetExtent to viewport extensions


using Discord;
using System;

namespace MitternachtWeb.Models {
	[Flags]
	public enum BotLevelPermission {
		None                 = 0b_0000,
		ReadBotConfig        = 0b_0001,
		WriteBotConfig       = 0b_0011,
		ReadAllGuildConfigs  = 0b_0100,
		WriteAllGuildConfigs = 0b_1100,
		All                  = 0b_1111,
	}

	[Flags]
	public enum GuildLevelPermission {
		None             = 0b_0000_0000,
		ReadGuildConfig  = 0b_0000_0001,
		WriteGuildConfig = 0b_0000_0011,
	}

	public static class PagePermissionExtensions {
		public static GuildLevelPermission GetGuildPagePermissions(this GuildPermissions guildPerms) {
			var perms = GuildLevelPermission.None;

			if(guildPerms.KickMembers) {
				perms |= GuildLevelPermission.ReadGuildConfig;
			}

			if(guildPerms.Administrator) {
				perms |= GuildLevelPermission.WriteGuildConfig;
			}

			return perms;
		}
	}
}

using Discord;
using System;

namespace MitternachtWeb.Models {
	[Flags]
	public enum BotLevelPermission {
		None                 = 0b_0000,
		ReadBotConfig        = 0b_0001,
		WriteBotConfig       = 0b_0011,
		ReadAllGuildConfigs  = 0b_0100,
		WriteAllGuildConfigs = 0b_1100,
		All                  = 0b_1111,
	}

	[Flags]
	public enum GuildLevelPermission {
		None             = 0b_0000_0000,
		ReadGuildConfig  = 0b_0000_0001,
		WriteGuildConfig = 0b_0000_0011,
	}

	public static class PagePermissionExtensions {
		public static GuildLevelPermission GetGuildPagePermissions(this GuildPermissions guildPerms) {
			var perms = GuildLevelPermission.None;

			if(guildPerms.ViewAuditLog) {
				perms |= GuildLevelPermission.ReadGuildConfig;
			}

			if(guildPerms.Administrator) {
				perms |= GuildLevelPermission.WriteGuildConfig;
			}

			return perms;
		}
	}
}

Change guild permissions to have ReadGuildConfig when ViewAuditLog is true.


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

namespace MartinCostello.ProjectEuler.Puzzles
{
    using System;
    using System.Linq;

    /// <summary>
    /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
    /// </summary>
    internal sealed class Puzzle010 : Puzzle
    {
        /// <inheritdoc />
        public override string Question => "Find the sum of all the primes below the specified value.";

        /// <inheritdoc />
        protected override int MinimumArguments => 1;

        /// <inheritdoc />
        protected override int SolveCore(string[] args)
        {
            int max;

            if (!TryParseInt32(args[0], out max) || max < 2)
            {
                Console.Error.WriteLine("The specified number is invalid.");
                return -1;
            }

            Answer = Enumerable.Range(2, max - 2)
                .AsParallel()
                .Where((p) => Maths.IsPrime(p))
                .Select((p) => (long)p)
                .Sum();

            return 0;
        }
    }
}

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

namespace MartinCostello.ProjectEuler.Puzzles
{
    using System;
    using System.Linq;

    /// <summary>
    /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
    /// </summary>
    internal sealed class Puzzle010 : Puzzle
    {
        /// <inheritdoc />
        public override string Question => "Find the sum of all the primes below the specified value.";

        /// <inheritdoc />
        protected override int MinimumArguments => 1;

        /// <inheritdoc />
        protected override int SolveCore(string[] args)
        {
            int max;

            if (!TryParseInt32(args[0], out max) || max < 2)
            {
                Console.Error.WriteLine("The specified number is invalid.");
                return -1;
            }

            Answer = ParallelEnumerable.Range(2, max - 2)
                .Where((p) => Maths.IsPrime(p))
                .Select((p) => (long)p)
                .Sum();

            return 0;
        }
    }
}

Use ParallelEnumerable in puzzle 10

Use ParallelEnumerable in puzzle 10

Use ParallelEnumerable.Range() instead of Enumerable.Range() and
AsParallel().


using CommonUtil.Disk;

namespace Common
{
    public static class SourceDirectoryFinder
    {
        private static string crayonSourceDirectoryCached = null;
        public static string CrayonSourceDirectory
        {
            // Presumably running from source. Walk up to the root directory and find the Libraries directory.
            // From there use the list of folders.
            // TODO: mark this as DEBUG only
            get
            {
#if DEBUG
                if (crayonSourceDirectoryCached == null)
                {
                    string currentDirectory = Path.GetCurrentDirectory();
                    while (!string.IsNullOrEmpty(currentDirectory))
                    {
                        string librariesPath = FileUtil.JoinPath(currentDirectory, "Libraries");
                        if (FileUtil.DirectoryExists(librariesPath) &&
                            FileUtil.FileExists(FileUtil.JoinPath(currentDirectory, "Compiler", "CrayonWindows.sln"))) // quick sanity check
                        {
                            crayonSourceDirectoryCached = currentDirectory;
                            break;
                        }
                        currentDirectory = FileUtil.GetParentDirectory(currentDirectory);
                    }
                }
                return crayonSourceDirectoryCached;
#else
                return null;
#endif
            }
        }
    }
}

using CommonUtil.Disk;

namespace Common
{
    public static class SourceDirectoryFinder
    {
        private static string crayonSourceDirectoryCached = null;
        public static string CrayonSourceDirectory
        {
            // Presumably running from source. Walk up to the root directory and find the Libraries directory.
            // From there use the list of folders.
            // TODO: mark this as DEBUG only
            get
            {
#if DEBUG
                if (crayonSourceDirectoryCached == null)
                {
                    string currentDirectory = Path.GetCurrentDirectory();
                    while (!string.IsNullOrEmpty(currentDirectory))
                    {
                        string librariesPath = FileUtil.JoinPath(currentDirectory, "Libraries");
                        if (FileUtil.DirectoryExists(librariesPath) &&
                            FileUtil.FileExists(FileUtil.JoinPath(currentDirectory, "Compiler", "CrayonWindows.sln"))) // quick sanity check
                        {
                            crayonSourceDirectoryCached = currentDirectory;
                            break;
                        }
                        currentDirectory = FileUtil.GetParentDirectory(currentDirectory);
                    }
                }
#endif
                return crayonSourceDirectoryCached;
            }
        }
    }
}

Remove unused variable compiler warning when building release build.


using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Stratis.Bitcoin.Miner;
using Stratis.Bitcoin.RPC.ModelBinders;
using Stratis.Bitcoin.Wallet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Stratis.Bitcoin.RPC
{
    public static class WebHostExtensions
    {
        public static IWebHostBuilder ForFullNode(this IWebHostBuilder hostBuilder, FullNode fullNode)
        {
            hostBuilder.ConfigureServices(s =>
            {
                s.AddMvcCore(o =>
                {
                    o.ModelBinderProviders.Insert(0, new DestinationModelBinder());
                    o.ModelBinderProviders.Insert(0, new MoneyModelBinder());
                });
                s.AddSingleton(fullNode);
                s.AddSingleton(fullNode as Builder.IFullNode);
                s.AddSingleton(fullNode.Network);
                s.AddSingleton(fullNode.Settings);
                s.AddSingleton(fullNode.ConsensusLoop);
                s.AddSingleton(fullNode.ConsensusLoop?.Validator);
                s.AddSingleton(fullNode.Chain);
                s.AddSingleton(fullNode.ChainBehaviorState);
                s.AddSingleton(fullNode.BlockStoreManager);
                s.AddSingleton(fullNode.MempoolManager);
                s.AddSingleton(fullNode.ConnectionManager);
                s.AddSingleton(fullNode.Services.ServiceProvider.GetService<IWalletManager>());
                var pow = fullNode.Services.ServiceProvider.GetService<PowMining>();
                if(pow != null)
                    s.AddSingleton(pow);
            });
            return hostBuilder;
        }
    }
}

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Stratis.Bitcoin.Miner;
using Stratis.Bitcoin.RPC.ModelBinders;
using Stratis.Bitcoin.Wallet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Stratis.Bitcoin.RPC
{
    public static class WebHostExtensions
    {
        public static IWebHostBuilder ForFullNode(this IWebHostBuilder hostBuilder, FullNode fullNode)
        {
            hostBuilder.ConfigureServices(s =>
            {
                s.AddMvcCore(o =>
                {
                    o.ModelBinderProviders.Insert(0, new DestinationModelBinder());
                    o.ModelBinderProviders.Insert(0, new MoneyModelBinder());
                });
            });

            return hostBuilder;
        }
    }
}

Remove manual DI configuration for node in RPC

DI for RPC now automatically adds full node DI to its DI container.
This is done in RPCFeature on startup.


using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup(typeof(SignInCheckIn.Startup))]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
namespace SignInCheckIn
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            GlobalHost.Configuration.TransportConnectTimeout = TimeSpan.FromSeconds(15);

            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            // Branch the pipeline here for requests that start with /signalr
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);

                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the /signalr
                // path.
                map.RunSignalR();
            });
        }
    }
}

using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup(typeof(SignInCheckIn.Startup))]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
namespace SignInCheckIn
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            // Branch the pipeline here for requests that start with /signalr
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);

                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the /signalr
                // path.
                map.RunSignalR();
            });
        }
    }
}

Remove unhelpful line of code.

Remove unhelpful line of code.


using FluentScheduler;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using System;

namespace BatteryCommander.Web.Jobs
{
    internal static class JobHandler
    {
        public static void UseJobScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            var logger = loggerFactory.CreateLogger(typeof(JobHandler));

            JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name);

            JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration);

            JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name);

            JobManager.UseUtcTime();

            JobManager.JobFactory = new JobFactory(app.ApplicationServices);

            var registry = new Registry();

            registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().At(hours: 11, minutes: 0);

            registry.Schedule<EvaluationDueReminderJob>().ToRunNow();

            // registry.Schedule<EvaluationDueReminderJob>().ToRunEvery(1).Weeks().On(DayOfWeek.Friday).At(hours: 12, minutes: 0);

            JobManager.Initialize(registry);
        }

        private class JobFactory : IJobFactory
        {
            private readonly IServiceProvider serviceProvider;

            public JobFactory(IServiceProvider serviceProvider)
            {
                this.serviceProvider = serviceProvider;
            }

            public IJob GetJobInstance<T>() where T : IJob
            {
                return serviceProvider.GetService(typeof(T)) as IJob;
            }
        }
    }
}

using FluentScheduler;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using System;

namespace BatteryCommander.Web.Jobs
{
    internal static class JobHandler
    {
        public static void UseJobScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            var logger = loggerFactory.CreateLogger(typeof(JobHandler));

            JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name);

            JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration);

            JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name);

            JobManager.UseUtcTime();

            JobManager.JobFactory = new JobFactory(app.ApplicationServices);

            var registry = new Registry();

            registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().At(hours: 11, minutes: 0);

            registry.Schedule<EvaluationDueReminderJob>().ToRunEvery(1).Weeks().On(DayOfWeek.Friday).At(hours: 12, minutes: 0);

            JobManager.Initialize(registry);
        }

        private class JobFactory : IJobFactory
        {
            private readonly IServiceProvider serviceProvider;

            public JobFactory(IServiceProvider serviceProvider)
            {
                this.serviceProvider = serviceProvider;
            }

            public IJob GetJobInstance<T>() where T : IJob
            {
                return serviceProvider.GetService(typeof(T)) as IJob;
            }
        }
    }
}

Remove test fire schedule for eval due

Remove test fire schedule for eval due


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GlobalAssemblyInfo.cs" company="Helix Toolkit">
//   Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System.Reflection;

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Helix Toolkit")]
[assembly: AssemblyCompany("Helix Toolkit")]
[assembly: AssemblyCopyright("Copyright (C) Helix Toolkit 2018.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The version numbers are patched by GitVersion, see the `before_build` step in appveyor.yml
[assembly: AssemblyVersion("0.0.0.1")]
[assembly: AssemblyFileVersion("0.0.0.1")]

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GlobalAssemblyInfo.cs" company="Helix Toolkit">
//   Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System.Reflection;

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Helix Toolkit")]
[assembly: AssemblyCompany("Helix Toolkit")]
[assembly: AssemblyCopyright("Copyright (C) Helix Toolkit 2019.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The version numbers are patched by GitVersion, see the `before_build` step in appveyor.yml
[assembly: AssemblyVersion("0.0.0.1")]
[assembly: AssemblyFileVersion("0.0.0.1")]

Update assembly info - copyright date

Update assembly info - copyright date


@using Dangl.WebDocumentation
@using Dangl.WebDocumentation.Models
@using Dangl.WebDocumentation.ViewModels.Account
@using Dangl.WebDocumentation.ViewModels.Manage
@using Microsoft.AspNet.Identity
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
@inject Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration TelemetryConfiguration

@using Dangl.WebDocumentation
@using Dangl.WebDocumentation.Models
@using Dangl.WebDocumentation.ViewModels.Account
@using Dangl.WebDocumentation.ViewModels.Manage
@using Microsoft.AspNetCore.Identity
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Fix Razor tag helpers and usings

Fix Razor tag helpers and usings


namespace Glimpse.Agent.Internal.Inspectors.Mvc.Proxies
{
    public interface IViewComponentContext
    {
        IViewComponentDescriptor ViewComponentDescriptor { get; }

        object[] Arguments { get; }
    }
}

using System.Collections.Generic;

namespace Glimpse.Agent.Internal.Inspectors.Mvc.Proxies
{
    public interface IViewComponentContext
    {
        IViewComponentDescriptor ViewComponentDescriptor { get; }

        IDictionary<string, object> Arguments { get; }
    }
}

Update ViewComponentContext to respond to changed type


@model Dashboard.Models.JobSummary

@{
    ViewBag.Title = $"{Model.Name} Summary";

    var summaryValues = string.Join(
        ";",
        Model.JobDaySummaryList.Select(x => $"{x.Date.ToLocalTime().ToString("yyyy-MM-dd")},{x.Succeeded},{x.Failed},{x.Aborted}"));

    var durationDates = string.Join(
        ";",
        Model.JobDaySummaryList.Select(x => x.Date.ToLocalTime().ToString("yyyy-MM-dd")).ToArray());

    var durationTimes = string.Join(
        ";",
        Model.JobDaySummaryList.Select(x => x.AverageDuration.TotalSeconds).ToArray());
}

@Model.Name

Average Duration: @Model.AverageDuration

@section scripts {

}

@model Dashboard.Models.JobSummary

@{
    ViewBag.Title = $"{Model.Name} Summary";

    var jobs = Model.JobDaySummaryList.OrderBy(x => x.Date);
    var summaryValues = string.Join(
        ";",
        jobs.Select(x => $"{x.Date.ToLocalTime().ToString("yyyy-MM-dd")},{x.Succeeded},{x.Failed},{x.Aborted}"));

    var durationDates = string.Join(
        ";",
        jobs.Select(x => x.Date.ToLocalTime().ToString("yyyy-MM-dd")).ToArray());

    var durationTimes = string.Join(
        ";",
        jobs.Select(x => x.AverageDuration.TotalMinutes).ToArray());
}

@Model.Name

Average Duration: @Model.AverageDuration

@section scripts {

}

Convert to minutes in the duration display


using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
using Bloom.Api;
using Bloom.Book;
using Bloom.MiscUI;
using Bloom.Publish;
using Bloom.Utils;
using SIL.IO;

namespace Bloom.web.controllers
{
	public class ProgressDialogApi
	{
		private static Action _cancelHandler;
		public static void SetCancelHandler(Action cancelHandler)
		{
			_cancelHandler = cancelHandler;
		}

		public void RegisterWithApiHandler(BloomApiHandler apiHandler)
		{
			apiHandler.RegisterEndpointLegacy("progress/cancel", Cancel, false, false);
			apiHandler.RegisterEndpointHandler("progress/closed", BrowserProgressDialog.HandleProgressDialogClosed, false);
			apiHandler.RegisterEndpointHandler("progress/ready", BrowserProgressDialog.HandleProgressReady, false);
		}

		private void Cancel(ApiRequest request)
		{
			// if it's null, and that causes a throw, well... that *is* an error situation
			_cancelHandler();
			request.PostSucceeded();
		}
	}
}

using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
using Bloom.Api;
using Bloom.Book;
using Bloom.MiscUI;
using Bloom.Publish;
using Bloom.Utils;
using SIL.IO;

namespace Bloom.web.controllers
{
	public class ProgressDialogApi
	{
		private static Action _cancelHandler;
		public static void SetCancelHandler(Action cancelHandler)
		{
			_cancelHandler = cancelHandler;
		}

		public void RegisterWithApiHandler(BloomApiHandler apiHandler)
		{
			apiHandler.RegisterEndpointLegacy("progress/cancel", Cancel, false, false);
			apiHandler.RegisterEndpointHandler("progress/closed", BrowserProgressDialog.HandleProgressDialogClosed, false);
			// Doesn't need sync because all it does is set a flag, which nothing else modifies.
			// Mustn't need sync because we may be processing another request (e.g., creating a TC) when we launch the dialog
			// that we want to know is ready to receive messages.
			apiHandler.RegisterEndpointHandler("progress/ready", BrowserProgressDialog.HandleProgressReady, false, false);
		}

		private void Cancel(ApiRequest request)
		{
			// if it's null, and that causes a throw, well... that *is* an error situation
			_cancelHandler();
			request.PostSucceeded();
		}
	}
}

Allow progress dialog ready API call to proceed without sync (BL-11484)


using System;
using Microsoft.SPOT;

namespace IntervalTimer
{
    public class IntervalTimer
    {
        public TimeSpan ShortDuration { get; set; }
        public TimeSpan LongDuration { get; set; }

        public IntervalTimer(TimeSpan shortDuration, TimeSpan longDuration)
        {
            ShortDuration = shortDuration;
            LongDuration = longDuration;
        }

        public IntervalTimer(int shortSeconds, int longSeconds)
        {
            ShortDuration = new TimeSpan(0, 0, shortSeconds);
            LongDuration = new TimeSpan(0, 0, longSeconds);
        }
    }
}

using System;
using Microsoft.SPOT;

namespace IntervalTimer
{
    public delegate void IntervalEventHandler(object sender, EventArgs e);

    public class IntervalTimer
    {
        public TimeSpan ShortDuration { get; set; }
        public TimeSpan LongDuration { get; set; }

        public IntervalTimer(TimeSpan shortDuration, TimeSpan longDuration)
        {
            ShortDuration = shortDuration;
            LongDuration = longDuration;
        }

        public IntervalTimer(int shortSeconds, int longSeconds)
        {
            ShortDuration = new TimeSpan(0, 0, shortSeconds);
            LongDuration = new TimeSpan(0, 0, longSeconds);
        }

    }
}

Add (temporary) event handler delegate.

Add (temporary) event handler delegate.


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

namespace clipman.Views
{
    /// <summary>
    /// Interaction logic for ClipList.xaml
    /// </summary>
    public partial class ClipList : UserControl
    {
        public ClipList()
        {
            InitializeComponent();
        }
    }
}

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

namespace clipman.Views
{
    /// <summary>
    /// Interaction logic for ClipList.xaml
    /// </summary>
    public partial class ClipList : UserControl
    {
        public ClipList()
        {
            InitializeComponent();
        }

        private void Copy(object sender, MouseButtonEventArgs e)
        {
            Console.WriteLine("Trying to copy");
            var clip = (Models.Clip)(sender as ListBoxItem).DataContext;

            var parentWindow = Window.GetWindow(this) as MainWindow;
            if (parentWindow != null)
            {
                parentWindow.HasJustCopied = true;
            }

            clip.Copy();
        }
    }
}

Add double click to copy functionality

Add double click to copy functionality


/// <summary>
/// Action to take if the message text contains an invalid character
/// Valid characters are defined in the GSM 03.38 character set
/// </summary>
public enum InvalidCharacterAction
{
    /// <summary>
    /// Use the default setting from your account
    /// </summary>
    AccountDefault = 0,
    /// <summary>
    /// Take no action
    /// </summary>
    None = 1,
    /// <summary>
    /// Remove any Non-GSM character
    /// </summary>
    Remove = 2,
    /// <summary>
    /// Replace Non-GSM characters where possible
    /// remove any others
    /// </summary>
    Replace = 3
}

/// <summary>
/// Action to take if the message text contains an invalid character
/// Valid characters are defined in the GSM 03.38 character set
/// </summary>
public enum InvalidCharacterAction
{
    /// <summary>
    /// Use the default setting from your account
    /// </summary>
    AccountDefault = 0,
    /// <summary>
    /// Return an error if a Non-GSM character is found
    /// </summary>
    Error = 1,
    /// <summary>
    /// Remove any Non-GSM character
    /// </summary>
    Remove = 2,
    /// <summary>
    /// Replace Non-GSM characters where possible
    /// remove any others
    /// </summary>
    Replace = 3
}

Change invalid character enum to make more send (None becomes Error)


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TrayLeds")]
[assembly: AssemblyDescription("Tray Notification Leds")]
[assembly: AssemblyProduct("TrayLeds")]
[assembly: AssemblyCopyright("Copyright © Carlos Alberto Costa Beppler 2017")]

// 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("eecfb156-872b-498d-9a01-42d37066d3d4")]

// 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.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TrayLeds")]
[assembly: AssemblyDescription("Tray Notification Leds")]
[assembly: AssemblyProduct("TrayLeds")]
[assembly: AssemblyCopyright("Copyright © Carlos Alberto Costa Beppler 2017")]

// 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("eecfb156-872b-498d-9a01-42d37066d3d4")]

// 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.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]

Update version number to 0.3.0.0.

Update version number to 0.3.0.0.


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

namespace DangerousPanel_Server
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

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

namespace DangerousPanel_Server
{
    class Program
    {
        static void Log(string text, ConsoleColor color)
        {
            ConsoleColor oldColor = Console.ForegroundColor;
            Console.ForegroundColor = color;
            Console.WriteLine(text);
            Console.ForegroundColor = oldColor;
        }

        static void Main(string[] args)
        {
            Console.Title = "Dangerous Panel Server";
            Log("Dangerous Panel Server (by Mitchfizz05)", ConsoleColor.Cyan);

            Console.ReadKey();
        }
    }
}

Set title for console window.

Set title for console window.


using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;

namespace DocNuget {
    public class Startup {
        public void ConfigureServices(IServiceCollection services) {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) {
            loggerFactory.MinimumLevel = LogLevel.Debug;
            loggerFactory.AddConsole(LogLevel.Debug);

            app
                .UseErrorPage()
                .UseDefaultFiles()
                .UseStaticFiles(new StaticFileOptions {
                    ServeUnknownFileTypes = true,
                })
                .UseMvc()
                .UseSendFileFallback()
                .Use(async (context, next) => {
                    await context.Response.SendFileAsync("wwwroot/index.html");
                });
        }
    }
}

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;

namespace DocNuget {
    public class Startup {
        public void ConfigureServices(IServiceCollection services) {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) {
            loggerFactory.MinimumLevel = LogLevel.Debug;
            loggerFactory.AddConsole(LogLevel.Debug);

            app
                .UseErrorPage()
                .UseDefaultFiles()
                .UseStaticFiles(new StaticFileOptions {
                    ServeUnknownFileTypes = true,
                })
                .UseMvc()
                .Use((context, next) => {
                    context.Request.Path = new PathString("/index.html");
                    return next();
                })
                .UseStaticFiles();
        }
    }
}

Rewrite request path to serve up index instead of sending it without content type


using System;
using System.Collections.Generic;

namespace FbxSharp
{
    public class Scene : Document
    {
        public Scene(string name="")
        {
            RootNode = new Node();
            Nodes.Add(RootNode);
        }

        public List<Node> Nodes = new List<Node>();
        public Node RootNode { get; protected set; }
    }
}

using System;
using System.Collections.Generic;

namespace FbxSharp
{
    public class Scene : Document
    {
        public Scene(string name="")
        {
            RootNode = new Node();
            Nodes.Add(RootNode);
        }

        public List<Node> Nodes = new List<Node>();
        public Node RootNode { get; protected set; }

        public Node GetRootNode()
        {
            return RootNode;
        }
    }
}

Add a GetRootNode method, to match the interface of the sdk.


using System;
using System.Collections.Generic;
#if NET_45
using System.Collections.ObjectModel;
#endif

namespace Octokit
{
    /// <summary>
    /// Extra information returned as part of each api response.
    /// </summary>
    public class ApiInfo
    {
        public ApiInfo(IDictionary<string, Uri> links,
            IList<string> oauthScopes,
            IList<string> acceptedOauthScopes,
            string etag,
            RateLimit rateLimit)
        {
            Ensure.ArgumentNotNull(links, "links");
            Ensure.ArgumentNotNull(oauthScopes, "ouathScopes");

            Links = new ReadOnlyDictionary<string, Uri>(links);
            OauthScopes = new ReadOnlyCollection<string>(oauthScopes);
            AcceptedOauthScopes = new ReadOnlyCollection<string>(acceptedOauthScopes);
            Etag = etag;
            RateLimit = rateLimit;
        }

        /// <summary>
        /// Oauth scopes that were included in the token used to make the request.
        /// </summary>
        public IReadOnlyList<string> OauthScopes { get; private set; }

        /// <summary>
        /// Oauth scopes accepted for this particular call.
        /// </summary>
        public IReadOnlyList<string> AcceptedOauthScopes { get; private set; }

        /// <summary>
        /// Etag
        /// </summary>
        public string Etag { get; private set; }

        /// <summary>
        /// Links to things like next/previous pages
        /// </summary>
        public IReadOnlyDictionary<string, Uri> Links { get; private set; }

        /// <summary>
        /// Information about the API rate limit
        /// </summary>
        public RateLimit RateLimit { get; private set; }
    }
}

using System;
using System.Collections.Generic;
#if NET_45
using System.Collections.ObjectModel;
#endif

namespace Octokit
{
    /// <summary>
    /// Extra information returned as part of each api response.
    /// </summary>
    public class ApiInfo
    {
        public ApiInfo(IDictionary<string, Uri> links,
            IList<string> oauthScopes,
            IList<string> acceptedOauthScopes,
            string etag,
            RateLimit rateLimit)
        {
            Ensure.ArgumentNotNull(links, "links");
            Ensure.ArgumentNotNull(oauthScopes, "oauthScopes");

            Links = new ReadOnlyDictionary<string, Uri>(links);
            OauthScopes = new ReadOnlyCollection<string>(oauthScopes);
            AcceptedOauthScopes = new ReadOnlyCollection<string>(acceptedOauthScopes);
            Etag = etag;
            RateLimit = rateLimit;
        }

        /// <summary>
        /// Oauth scopes that were included in the token used to make the request.
        /// </summary>
        public IReadOnlyList<string> OauthScopes { get; private set; }

        /// <summary>
        /// Oauth scopes accepted for this particular call.
        /// </summary>
        public IReadOnlyList<string> AcceptedOauthScopes { get; private set; }

        /// <summary>
        /// Etag
        /// </summary>
        public string Etag { get; private set; }

        /// <summary>
        /// Links to things like next/previous pages
        /// </summary>
        public IReadOnlyDictionary<string, Uri> Links { get; private set; }

        /// <summary>
        /// Information about the API rate limit
        /// </summary>
        public RateLimit RateLimit { get; private set; }
    }
}

Fix typo: ouath -> oauth

Fix typo: ouath -> oauth


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

namespace Octokit
{
    internal static class CollectionExtensions
    {
        public static TValue SafeGet<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key)
        {
            Ensure.ArgumentNotNull(dictionary, "dictionary");

            TValue value;
            return dictionary.TryGetValue(key, out value) ? value : default(TValue);
        }

        public static IList<string> Clone(this IReadOnlyList<string> input)
        {
            List<string> output = null;
            if (input == null)
                return output;

            output = new List<string>();

            foreach (var item in input)
            {
                output.Add(new String(item.ToCharArray()));
            }

            return output;
        }

        public static IDictionary<string, Uri> Clone(this IReadOnlyDictionary<string, Uri> input)
        {
            Dictionary<string, Uri> output = null;
            if (input == null)
                return output;

            output = new Dictionary<string, Uri>();

            foreach (var item in input)
            {
                output.Add(new String(item.Key.ToCharArray()), new Uri(item.Value.ToString()));
            }

            return output;
        }
    }
}

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

namespace Octokit
{
    internal static class CollectionExtensions
    {
        public static TValue SafeGet<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key)
        {
            Ensure.ArgumentNotNull(dictionary, "dictionary");

            TValue value;
            return dictionary.TryGetValue(key, out value) ? value : default(TValue);
        }

        public static IList<string> Clone(this IReadOnlyList<string> input)
        {
            if (input == null)
                return null;

            return input.Select(item => new String(item.ToCharArray())).ToList();
        }

        public static IDictionary<string, Uri> Clone(this IReadOnlyDictionary<string, Uri> input)
        {
            if (input == null)
                return null;

            return input.ToDictionary(item => new String(item.Key.ToCharArray()), item => new Uri(item.Value.ToString()));
        }
    }
}

Use linq expression to create dictionary

Just feels nicer than mutating a dictionary.


using System.Reflection;

// 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("Basics Algorithms")]
[assembly: AssemblyCulture("")]

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

// 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("Basics Algorithms")]
[assembly: AssemblyCulture("")]

[assembly: InternalsVisibleTo("Basics.Algorithms.Tests")]

Make internals visible to test assembly

Make internals visible to test assembly


using Autofac;
using Bit.ViewModel.Contracts;
using Simple.OData.Client;
using System;
using System.Net.Http;

namespace Prism.Ioc
{
    public static class ContainerBuilderExtensions
    {
        public static ContainerBuilder RegisterODataClient(this ContainerBuilder containerBuilder)
        {
            if (containerBuilder == null)
                throw new ArgumentNullException(nameof(containerBuilder));

            Simple.OData.Client.V4Adapter.Reference();

            containerBuilder.Register(c =>
            {
                HttpMessageHandler authenticatedHttpMessageHandler = c.ResolveNamed<HttpMessageHandler>(ContractKeys.AuthenticatedHttpMessageHandler);

                IClientAppProfile clientAppProfile = c.Resolve<IClientAppProfile>();

                IODataClient odataClient = new ODataClient(new ODataClientSettings(new Uri(clientAppProfile.HostUri, clientAppProfile.ODataRoute))
                {
                    RenewHttpConnection = false,
                    OnCreateMessageHandler = () => authenticatedHttpMessageHandler
                });

                return odataClient;
            }).PreserveExistingDefaults();

            containerBuilder
                .Register(c => new ODataBatch(c.Resolve<IODataClient>(), reuseSession: true))
                .PreserveExistingDefaults();

            return containerBuilder;
        }
    }
}

using Autofac;
using Bit.ViewModel.Contracts;
using Simple.OData.Client;
using System;
using System.Net.Http;

namespace Prism.Ioc
{
    public static class ContainerBuilderExtensions
    {
        public static ContainerBuilder RegisterODataClient(this ContainerBuilder containerBuilder)
        {
            if (containerBuilder == null)
                throw new ArgumentNullException(nameof(containerBuilder));

            Simple.OData.Client.V4Adapter.Reference();

            containerBuilder.Register(c =>
            {
                IClientAppProfile clientAppProfile = c.Resolve<IClientAppProfile>();

                IODataClient odataClient = new ODataClient(new ODataClientSettings(httpClient: c.Resolve<HttpClient>(), new Uri(clientAppProfile.ODataRoute, uriKind: UriKind.Relative))
                {
                    RenewHttpConnection = false
                });

                return odataClient;
            }).PreserveExistingDefaults();

            containerBuilder
                .Register(c => new ODataBatch(c.Resolve<IODataClient>(), reuseSession: true))
                .PreserveExistingDefaults();

            return containerBuilder;
        }
    }
}

Use prepared http client to build odata client.


namespace WebServer
{
    public class Default404Servlet : HTMLServlet
    {
        protected override void OnService()
        {
            Write(
                DocType("html"),
                Tag("html", lang => "en", another => "blah")(
                    Tag("head")(
                        Tag("title")("Error 404")
                    ),
                    Tag("body")(
                        Tag("p")(
                            "The URL you requested could not be found", Ln,
                            Tag("code")(Request.RawUrl)
                        )
                    )
                )
            );
        }
    }
}

namespace WebServer
{
    public class Default404Servlet : HTMLServlet
    {
        protected override void OnService()
        {
            Response.StatusCode = 404;

            Write(
                DocType("html"),
                Tag("html", lang => "en", another => "blah")(
                    Tag("head")(
                        Tag("title")("Error 404")
                    ),
                    Tag("body")(
                        Tag("p")(
                            "The URL you requested could not be found", Ln,
                            Tag("code")(Request.RawUrl)
                        )
                    )
                )
            );
        }
    }
}

Set status code for not found servlet

Set status code for not found servlet


using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel;
using AgGateway.ADAPT.PluginManager;

namespace AgGateway.ADAPT.Visualizer
{
    public class DataProvider
    {
        private PluginFactory _pluginFactory;

        public void Initialize(string pluginsPath)
        {
            _pluginFactory = new PluginFactory(pluginsPath);
        }

        public List<string> AvailablePlugins
        {
            get { return PluginFactory.AvailablePlugins; }
        }

        public PluginFactory PluginFactory
        {
            get { return _pluginFactory; }
        }

        public ApplicationDataModel.ApplicationDataModel Import(string datacardPath, string initializeString)
        {
            foreach (var availablePlugin in AvailablePlugins)
            {
                var plugin = GetPlugin(availablePlugin);
                plugin.Initialize(initializeString);

                if (plugin.IsDataCardSupported(datacardPath))
                {
                    return plugin.Import(datacardPath);
                }
            }

            return null;
        }

        public IPlugin GetPlugin(string pluginName)
        {
            return _pluginFactory.GetPlugin(pluginName);
        }

        public static void Export(IPlugin plugin, ApplicationDataModel.ApplicationDataModel applicationDataModel, string initializeString, string exportPath)
        {
            if (string.IsNullOrEmpty(initializeString))
            {
                plugin.Initialize(initializeString);
            }

            plugin.Export(applicationDataModel, exportPath);
        }
    }
}

using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel;
using AgGateway.ADAPT.PluginManager;

namespace AgGateway.ADAPT.Visualizer
{
    public class DataProvider
    {
        private PluginFactory _pluginFactory;

        public void Initialize(string pluginsPath)
        {
            _pluginFactory = new PluginFactory(pluginsPath);
        }

        public List<string> AvailablePlugins
        {
            get { return PluginFactory.AvailablePlugins; }
        }

        public PluginFactory PluginFactory
        {
            get { return _pluginFactory; }
        }

        public ApplicationDataModel.ApplicationDataModel Import(string datacardPath, string initializeString)
        {
            foreach (var availablePlugin in AvailablePlugins)
            {
                var plugin = GetPlugin(availablePlugin);
                InitializePlugin(plugin, initializeString);

                if (plugin.IsDataCardSupported(datacardPath))
                {
                    return plugin.Import(datacardPath);
                }
            }

            return null;
        }

        public IPlugin GetPlugin(string pluginName)
        {
            return _pluginFactory.GetPlugin(pluginName);
        }

        public static void Export(IPlugin plugin, ApplicationDataModel.ApplicationDataModel applicationDataModel, string initializeString, string exportPath)
        {
            InitializePlugin(plugin, initializeString);

            plugin.Export(applicationDataModel, exportPath);
        }

        private static void InitializePlugin(IPlugin plugin, string initializeString)
        {
            if (string.IsNullOrEmpty(initializeString))
            {
                plugin.Initialize(initializeString);
            }
        }
    }
}

Visualizer: Check if initialize string is available before setting it

Signed-off-by: Tarak Reddy <83c0befc10b630ca3a0bb9b7bea0b0bf61554a65@johndeere.com>


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

namespace Core2D.Avalonia
{
    public class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
            this.AttachDevTools();
        }

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    }
}

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

namespace Core2D.Avalonia
{
    public class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
#if DEBUG
            this.AttachDevTools();
#endif
        }

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    }
}

Attach dev tools only in debug builds

Attach dev tools only in debug builds


using System;
using System.Collections.Generic;
using System.Web;
using Nancy;
using Nancy.ErrorHandling;

namespace NancyBenchmark
{
    public class Global : HttpApplication
    {
        protected void Application_Start()
        {

        }
    }
}

using System;
using System.Collections.Generic;
using System.Web;
using Nancy;
using Nancy.ErrorHandling;
using System.Threading;

namespace NancyBenchmark
{
    public class Global : HttpApplication
    {
        protected void Application_Start()
        {
            var threads = 40 * Environment.ProcessorCount;
            ThreadPool.SetMaxThreads(threads, threads);
            ThreadPool.SetMinThreads(threads, threads);
        }
    }
}

Set improved ThreadPool values for nancy


using System;
using System.Collections;
using System.Globalization;
using System.Text;
using Microsoft.WindowsAzure.Storage.Table;
using log4net.Core;

namespace log4net.Appender
{
    internal sealed class AzureLoggingEventEntity : TableEntity
    {
        public AzureLoggingEventEntity(LoggingEvent e)
        {
            Domain = e.Domain;
            Identity = e.Identity;
            Level = e.Level;
            LoggerName = e.LoggerName;
            var sb = new StringBuilder(e.Properties.Count);
            foreach (DictionaryEntry entry in e.Properties)
            {
                sb.AppendFormat("{0}:{1}", entry.Key, entry.Value);
                sb.AppendLine();
            }
            Properties = sb.ToString();
            Message = e.RenderedMessage;
            ThreadName = e.ThreadName;
            TimeStamp = e.TimeStamp;
            UserName = e.UserName;

            PartitionKey = e.LoggerName;
            RowKey = MakeRowKey(e);
        }

        private static string MakeRowKey(LoggingEvent loggingEvent)
        {
            return string.Format("{0}.{1}",
                                 loggingEvent.TimeStamp.ToString("yyyy_MM_dd_HH_mm_ss_fffffff",
                                                                 DateTimeFormatInfo.InvariantInfo),
                                 Guid.NewGuid().ToString().ToLower());
        }

        public string UserName { get; set; }

        public DateTime TimeStamp { get; set; }

        public string ThreadName { get; set; }

        public string Message { get; set; }

        public string Properties { get; set; }

        public string LoggerName { get; set; }

        public Level Level { get; set; }

        public string Identity { get; set; }

        public string Domain { get; set; }
    }
}

using System;
using System.Collections;
using System.Globalization;
using System.Text;
using Microsoft.WindowsAzure.Storage.Table;
using log4net.Core;

namespace log4net.Appender
{
    internal sealed class AzureLoggingEventEntity : TableEntity
    {
        public AzureLoggingEventEntity(LoggingEvent e)
        {
            Domain = e.Domain;
            Identity = e.Identity;
            Level = e.Level;
            LoggerName = e.LoggerName;
            var sb = new StringBuilder(e.Properties.Count);
            foreach (DictionaryEntry entry in e.Properties)
            {
                sb.AppendFormat("{0}:{1}", entry.Key, entry.Value);
                sb.AppendLine();
            }
            Properties = sb.ToString();
            Message = e.RenderedMessage;
            ThreadName = e.ThreadName;
            EventTimeStamp = e.TimeStamp;
            UserName = e.UserName;

            PartitionKey = e.LoggerName;
            RowKey = MakeRowKey(e);
        }

        private static string MakeRowKey(LoggingEvent loggingEvent)
        {
            return string.Format("{0}.{1}",
                                 loggingEvent.TimeStamp.ToString("yyyy_MM_dd_HH_mm_ss_fffffff",
                                                                 DateTimeFormatInfo.InvariantInfo),
                                 Guid.NewGuid().ToString().ToLower());
        }

        public string UserName { get; set; }

        public DateTime EventTimeStamp { get; set; }

        public string ThreadName { get; set; }

        public string Message { get; set; }

        public string Properties { get; set; }

        public string LoggerName { get; set; }

        public Level Level { get; set; }

        public string Identity { get; set; }

        public string Domain { get; set; }
    }
}

Rename TimeStamp to EventTimeStamp to avoid confusion with native Azure Table Storage "Timestamp" column


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

namespace Assent.Reporters.DiffPrograms
{
    public class VsCodeDiffProgram : DiffProgramBase
    {
        static VsCodeDiffProgram()
        {
            var paths = new List<string>();
            if (DiffReporter.IsWindows)
            {
                paths.AddRange(WindowsProgramFilePaths
                    .Select(p => $@"{p}\Microsoft VS Code\Code.exe")
                    .ToArray());
            }
            else
            {
                paths.Add("/usr/local/bin/code");
            }
            DefaultSearchPaths = paths;
        }

        public static readonly IReadOnlyList<string> DefaultSearchPaths;

        public VsCodeDiffProgram() : base(DefaultSearchPaths)
        {
        }

        public VsCodeDiffProgram(IReadOnlyList<string> searchPaths)
            : base(searchPaths)
        {
        }

        protected override string CreateProcessStartArgs(string receivedFile, string approvedFile)
        {
            return $"--diff --wait --new-window \"{receivedFile}\" \"{approvedFile}\"";
        }
    }
}

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

namespace Assent.Reporters.DiffPrograms
{
    public class VsCodeDiffProgram : DiffProgramBase
    {
        static VsCodeDiffProgram()
        {
            var paths = new List<string>();
            if (DiffReporter.IsWindows)
            {
                paths.AddRange(WindowsProgramFilePaths
                    .Select(p => $@"{p}\Microsoft VS Code\Code.exe")
                    .ToArray());
            }
            else
            {
                paths.Add("/usr/local/bin/code");
                paths.Add("/snap/bin/code");
            }
            DefaultSearchPaths = paths;
        }

        public static readonly IReadOnlyList<string> DefaultSearchPaths;

        public VsCodeDiffProgram() : base(DefaultSearchPaths)
        {
        }

        public VsCodeDiffProgram(IReadOnlyList<string> searchPaths)
            : base(searchPaths)
        {
        }

        protected override string CreateProcessStartArgs(string receivedFile, string approvedFile)
        {
            return $"--diff --wait --new-window \"{receivedFile}\" \"{approvedFile}\"";
        }
    }
}

Add support for vscode install via snap

Add support for vscode install via snap


using System.Linq;
using System.Text;

namespace ReimuPlugins.Common
{
    public static class StringExtensions
    {
        public static string ToCStr(this string str)
        {
            return str.Contains('\0') ? str : str + '\0';
        }

        public static string Convert(this string str, Encoding src, Encoding dst)
        {
            return dst.GetString(Encoding.Convert(src, dst, src.GetBytes(str)));
        }
    }
}

using System.Linq;
using System.Text;

namespace ReimuPlugins.Common
{
    public static class StringExtensions
    {
        public static string ToCStr(this string str)
        {
            return str.Contains('\0') ? str : str + '\0';
        }

        public static string Convert(this string str, Encoding src, Encoding dst)
        {
            return dst.GetString(Encoding.Convert(src, dst, src.GetBytes(str)));
        }

        public static string ToSJIS(this string str)
        {
            return str.Convert(Enc.UTF8, Enc.SJIS);
        }
    }
}

Add the extension method ToSJIS()

Add the extension method ToSJIS()


using System;

namespace Equifax
{
    /// <summary>
    /// Creates globally secure Equifax-style GUIDs.
    /// </summary>
    public static class Guid
    {
        /// <summary>
        /// Creates a new Equifax secure GUID using the current UTC time.
        /// UTC ensures global consistency and uniqueness.
        /// </summary>
        public static System.Guid NewGuid()
            => NewGuid(DateTime.UtcNow);

        /// <summary>
        /// Creates a new Equifax secure GUID from the provided time stamp,
        /// assumed to already have been secured for uniqueness.
        /// </summary>
        public static System.Guid NewGuid(DateTime secureTimestamp)
            => new System.Guid(
                "00000000-0000-0000-0000-00" +
                $"{secureTimestamp.Month:00}" +
                $"{secureTimestamp.Day:00}" +
                $"{secureTimestamp.Year % 100:00}" +
                $"{secureTimestamp.Hour:00}" +
                $"{secureTimestamp.Minute:00}");\
    }
}

using System;

namespace Equifax
{
    /// <summary>
    /// Creates globally secure Equifax-style GUIDs.
    /// </summary>
    public static class Guid
    {
        /// <summary>
        /// Creates a new Equifax secure GUID using the current UTC time.
        /// UTC ensures global consistency and uniqueness.
        /// </summary>
        public static System.Guid NewGuid()
            => NewGuid(DateTime.UtcNow);

        /// <summary>
        /// Creates a new Equifax secure GUID from the provided time stamp,
        /// assumed to already have been secured for uniqueness.
        /// </summary>
        public static System.Guid NewGuid(DateTime secureTimestamp)
            => new System.Guid(
                "00000000-0000-0000-0000-00" +
                $"{secureTimestamp.Month:00}" +
                $"{secureTimestamp.Day:00}" +
                $"{secureTimestamp.Year % 100:00}" +
                $"{secureTimestamp.Hour:00}" +
                $"{secureTimestamp.Minute:00}");
    }
}

Fix typo in build. We should add tests.

Fix typo in build. We should add tests.


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

namespace Avalonia.Rendering
{
    public class SleepLoopRenderTimer : IRenderTimer
    {
        public event Action<TimeSpan> Tick;

        public SleepLoopRenderTimer(int fps)
        {
            var timeBetweenTicks = TimeSpan.FromSeconds(1d / fps);
            new Thread(() =>
            {
                var st = Stopwatch.StartNew();
                var now = st.Elapsed;
                var lastTick = now;

                while (true)
                {
                    var timeTillNextTick = lastTick + timeBetweenTicks - now;
                    if (timeTillNextTick.TotalMilliseconds > 1)
                        Thread.Sleep(timeTillNextTick);

                    Tick?.Invoke(now);
                    now = st.Elapsed;
                }
            }) { IsBackground = true }.Start();
        }
    }
}

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

namespace Avalonia.Rendering
{
    public class SleepLoopRenderTimer : IRenderTimer
    {
        private Action<TimeSpan> _tick;
        private int _count;
        private readonly object _lock = new object();
        private bool _running;
        private readonly Stopwatch _st = Stopwatch.StartNew();
        private readonly TimeSpan _timeBetweenTicks;

        public SleepLoopRenderTimer(int fps)
        {
            _timeBetweenTicks = TimeSpan.FromSeconds(1d / fps);
        }

        public event Action<TimeSpan> Tick
        {
            add
            {
                lock (_lock)
                {
                    _tick += value;
                    _count++;
                    if (_running)
                        return;
                    _running = true;
                    new Thread(LoopProc) { IsBackground = true }.Start();
                }

            }
            remove
            {
                lock (_lock)
                {
                    _tick -= value;
                    _count--;
                }
            }
        }

        void LoopProc()
        {
            var now = _st.Elapsed;
            var lastTick = now;

            while (true)
            {
                var timeTillNextTick = lastTick + _timeBetweenTicks - now;
                if (timeTillNextTick.TotalMilliseconds > 1) Thread.Sleep(timeTillNextTick);

                lock (_lock)
                {
                    if (_count == 0)
                    {
                        _running = false;
                        return;
                    }
                }

                _tick?.Invoke(now);
                now = _st.Elapsed;
            }
        }

    }
}

Stop the loop when there are no subscribers


#if TFS2015u2
using System;
using System.Diagnostics.CodeAnalysis;

using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.VisualStudio.Services.Location;
using Microsoft.VisualStudio.Services.Location.Server;

namespace Aggregator.Core.Extensions
{
    public static class LocationServiceExtensions
    {
        [SuppressMessage("Maintainability", "S1172:Unused method parameters should be removed", Justification = "Required by original interface", Scope = "member", Target = "~M:Aggregator.Core.Extensions.LocationServiceExtensions.GetSelfReferenceUri(Microsoft.VisualStudio.Services.Location.Server.ILocationService,Microsoft.TeamFoundation.Framework.Server.IVssRequestContext,Microsoft.VisualStudio.Services.Location.AccessMapping)~System.Uri")]
        public static Uri GetSelfReferenceUri(this ILocationService self, IVssRequestContext context, AccessMapping mapping)
        {
            string url = self.GetSelfReferenceUrl(context, self.GetDefaultAccessMapping(context));
            return new Uri(url, UriKind.Absolute);
        }
    }
}
#endif

#if TFS2015u2
using System;
using System.Diagnostics.CodeAnalysis;

using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.VisualStudio.Services.Location;
using Microsoft.VisualStudio.Services.Location.Server;

namespace Aggregator.Core.Extensions
{
    public static class LocationServiceExtensions
    {
        public static Uri GetSelfReferenceUri(this ILocationService self, IVssRequestContext context, AccessMapping mapping)
        {
            string url = self.GetSelfReferenceUrl(context, mapping);
            return new Uri(url, UriKind.Absolute);
        }
    }
}
#endif

Use th esupplied access mappign instead of looking it up a second time.


using System.Data;
using NHibernate.SqlCommand;
using NHibernate.SqlTypes;

namespace NHibernate.Dialect
{
	public class Oracle9iDialect : Oracle8iDialect
	{
		public override string CurrentTimestampSelectString
		{
			get { return "select systimestamp from dual"; }
		}

		public override string CurrentTimestampSQLFunctionName
		{
			get
			{
				// the standard SQL function name is current_timestamp...
				return "current_timestamp";
			}
		}

		protected override void RegisterDateTimeTypeMappings()
		{
			RegisterColumnType(DbType.Date, "DATE");
			RegisterColumnType(DbType.DateTime, "TIMESTAMP(4)");
			RegisterColumnType(DbType.Time, "TIMESTAMP(4)");
		}
		public override string GetSelectClauseNullString(SqlType sqlType)
		{
			return GetBasicSelectClauseNullString(sqlType);
		}

		public override CaseFragment CreateCaseFragment()
		{
			// Oracle did add support for ANSI CASE statements in 9i
			return new ANSICaseFragment(this);
		}
	}
}

using System.Data;
using NHibernate.SqlCommand;
using NHibernate.SqlTypes;

namespace NHibernate.Dialect
{
	public class Oracle9iDialect : Oracle8iDialect
	{
		public override string CurrentTimestampSelectString
		{
			get { return "select systimestamp from dual"; }
		}

		public override string CurrentTimestampSQLFunctionName
		{
			get
			{
				// the standard SQL function name is current_timestamp...
				return "current_timestamp";
			}
		}

		protected override void RegisterDateTimeTypeMappings()
		{
			RegisterColumnType(DbType.Date, "DATE");
			RegisterColumnType(DbType.DateTime, "TIMESTAMP(4)");
			RegisterColumnType(DbType.Time, "TIMESTAMP(4)");
		}

		public override long TimestampResolutionInTicks
		{
			// matches precision of TIMESTAMP(4)
			get { return 1000L; }
		}

		public override string GetSelectClauseNullString(SqlType sqlType)
		{
			return GetBasicSelectClauseNullString(sqlType);
		}

		public override CaseFragment CreateCaseFragment()
		{
			// Oracle did add support for ANSI CASE statements in 9i
			return new ANSICaseFragment(this);
		}
	}
}

Fix NH-2927 - Oracle Dialect does not handle the correct resolution for timestamp version columns

Fixes the following tests on Oracle:

NHibernate.Test.Component.Basic.ComponentTest.TestComponent
NHibernate.Test.Component.Basic.ComponentTest.TestComponentStateChangeAndDirtiness
NHibernate.Test.Legacy.CriteriaTest.CriteriaLeftOuterJoin
NHibernate.Test.Legacy.CriteriaTest.CriteriaManyToOneEquals
NHibernate.Test.Legacy.MasterDetailTest.Serialization
NHibernate.Test.Stateless.StatelessSessionFixture.CreateUpdateReadDelete
NHibernate.Test.Operations.MergeFixture.PersistThenMergeInSameTxnWithTimestamp


using UnityEngine;
using System.Collections;

public class NurseryResource : CellFeature {

    public override int Amount
    {
        set
        {
            // add _amount - value to the player's resource store
            _amount = value;
            Debug.Log("child thingy");
        }
    }

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}
}

using UnityEngine;
using System.Collections;

public class NurseryResource : CellFeature {

    public override int Amount
    {
        set
        {
            _amount = value;
            FindObjectOfType<Resources>().addPlacementResource(_amount - value);
        }
    }

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}
}

Integrate cell resources with player resources code


<environment names="Development">
    <script src="~/lib/jquery-validation/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
<environment names="Staging,Production">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"
            asp-fallback-src="~/lib/jquery-validation/jquery.validate.js"
            asp-fallback-test="window.jquery && window.jquery.validator">
    </script>
    <script src="https://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"
            asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"
            asp-fallback-test="window.jquery && window.jquery.validator && window.jquery.validator.unobtrusive">
    </script>
</environment>

<environment names="Development">
    <script src="~/lib/jquery-validation/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
<environment names="Staging,Production">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"
            asp-fallback-src="~/lib/jquery-validation/jquery.validate.js"
            asp-fallback-test="window.jQuery && window.jQuery.validator">
    </script>
    <script src="https://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"
            asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"
            asp-fallback-test="window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive">
    </script>
</environment>

Fix casing of jQuery validation fallback test


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

namespace TfsHelperLib
{
    public class TfsChangeset
    {
        public int ChangesetId { get; set; }

        public string Owner { get; set; }

        public DateTime CreationDate { get; set; }

        public string Comment { get; set; }

        public string Changes_0_ServerItem { get; set; }
    }
}

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

namespace TfsHelperLib
{
    public class TfsChangeset : IComparable
    {
        public int ChangesetId { get; set; }

        public string Owner { get; set; }

        public DateTime CreationDate { get; set; }

        public string Comment { get; set; }

        public string Changes_0_ServerItem { get; set; }

        public int CompareTo(object obj)
        {
            return ChangesetId.CompareTo(((TfsChangeset)obj).ChangesetId);
        }
    }
}

Implement IComparable interface for sorting


using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using NoAdsHere.Common;
using NoAdsHere.Common.Preconditions;

namespace NoAdsHere.Commands.Master
{
    public class MasterModule : ModuleBase
    {
        [Command("Reset Guild")]
        [RequirePermission(AccessLevel.Master)]
        public async Task Reset(IGuild guild)
        {
            await Task.CompletedTask;
        }
    }
}

using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using NoAdsHere.Common;
using NoAdsHere.Common.Preconditions;

namespace NoAdsHere.Commands.Master
{
    public class MasterModule : ModuleBase
    {
        [Command("Reset Guild")]
        [RequirePermission(AccessLevel.Master)]
        public async Task Reset(ulong guildId)
        {
            await Task.CompletedTask;
        }
    }
}

Change IGuild parameter to ulong

Change IGuild parameter to ulong

Implement this at a later date


@model IEnumerable<Zk.Models.Crop>

@{
    ViewBag.Title = "Gewassen";
}

Dit zijn de gewassen in onze database:

    	Naam	Ras	Categorie	Opp. per 1
    		Opp. per zak	Prijs per zakje	Zaaimaanden	Oogstmaanden

		@foreach (var crop in Model) {

	    	@crop.Name	@crop.Race	@crop.Category	@crop.AreaPerCrop
	    		@crop.AreaPerBag	@crop.PricePerBag
	    		@crop.SowingMonths	@crop.HarvestingMonths

		}

@Html.ActionLink("Terug naar Zaaien en oogsten", "Index",  "Home",  null, null)

@model IEnumerable<Oogstplanner.Models.Crop>

@{
    ViewBag.Title = "Gewassen";
}

Dit zijn de gewassen in onze database:

    	Naam	Ras	Categorie	Opp. per 1
    		Opp. per zak	Prijs per zakje	Zaaimaanden	Oogstmaanden

		@foreach (var crop in Model) {

	    	@crop.Name	@crop.Race	@crop.Category	@crop.AreaPerCrop
	    		@crop.AreaPerBag	@crop.PricePerBag
	    		@crop.SowingMonths	@crop.HarvestingMonths

		}

@Html.ActionLink("Terug naar Zaaien en oogsten", "Index",  "Home",  null, null)

Change model reference with old namespace to new


using System;
using System.Numerics;

namespace DynamixelServo.Quadruped
{
    public class BasicQuadrupedGaitEngine : QuadrupedGaitEngine
    {
        private const int Speed = 12;

        private int _currentIndex;

        private readonly Vector3[] _positions =
        {
            new Vector3(-5, 5, 3),
            new Vector3(5, 5, -3),
            new Vector3(5, -5, 3),
            new Vector3(-5, -5, -3)
        };

        private const float LegHeight = -11f;
        private const int LegDistance = 15;

        private Vector3 _lastWrittenPosition = Vector3.Zero;

        public BasicQuadrupedGaitEngine(QuadrupedIkDriver driver) : base(driver)
        {
            Driver.Setup();
            Driver.StandUpfromGround();
            StartEngine();
        }

        protected override void EngineSpin()
        {
            if (_lastWrittenPosition.Similar(_positions[_currentIndex], 0.25f))
            {
                _currentIndex++;
                if (_currentIndex >= _positions.Length)
                {
                    _currentIndex = 0;
                }
            }
            _lastWrittenPosition =
                _lastWrittenPosition.MoveTowards(_positions[_currentIndex], Speed * 0.001f * TimeSincelastTick);
            Driver.MoveAbsoluteCenterMass(_lastWrittenPosition, LegDistance, LegHeight);
        }
    }
}

using System;
using System.Numerics;

namespace DynamixelServo.Quadruped
{
    public class BasicQuadrupedGaitEngine : QuadrupedGaitEngine
    {
        private const int Speed = 12;
        private float NextStepLength => Speed * 0.001f * TimeSincelastTick;

        private int _currentIndex;

        private readonly Vector3[] _positions =
        {
            new Vector3(-5, 5, 3),
            new Vector3(5, 5, -3),
            new Vector3(5, -5, 3),
            new Vector3(-5, -5, -3)
        };

        private const float LegHeight = -11f;
        private const int LegDistance = 15;

        private Vector3 _lastWrittenPosition = Vector3.Zero;

        public BasicQuadrupedGaitEngine(QuadrupedIkDriver driver) : base(driver)
        {
            Driver.Setup();
            Driver.StandUpfromGround();
            StartEngine();
        }

        protected override void EngineSpin()
        {
            if (_lastWrittenPosition.Similar(_positions[_currentIndex], 0.25f))
            {
                _currentIndex++;
                if (_currentIndex >= _positions.Length)
                {
                    _currentIndex = 0;
                }
            }
            _lastWrittenPosition =
                _lastWrittenPosition.MoveTowards(_positions[_currentIndex], NextStepLength);
            Driver.MoveAbsoluteCenterMass(_lastWrittenPosition, LegDistance, LegHeight);
        }
    }
}

Move next step calculation to a property


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

using AutoMapper;

using ISTS.Domain.Studios;

namespace ISTS.Application.Studios
{
    public class StudioService : IStudioService
    {
        private readonly IStudioRepository _studioRepository;
        private readonly IMapper _mapper;

        public StudioService(
            IStudioRepository studioRepository,
            IMapper mapper)
        {
            _studioRepository = studioRepository;
            _mapper = mapper;
        }

        public StudioDto Create(string name, string friendlyUrl)
        {
            var entity = _studioRepository.Create(name, friendlyUrl);

            var result = _mapper.Map<StudioDto>(entity);
            return result;
        }

        public List<StudioDto> GetAll()
        {
            var entities = _studioRepository.Get().ToList();

            var result = _mapper.Map<List<StudioDto>>(entities);
            return result;
        }

        public StudioDto Get(Guid id)
        {
            // var entity = _studioRepository.Get(id);
            var entity = _studioRepository.Create("My Studio", "mystudio");

            var result = _mapper.Map<StudioDto>(entity);
            return result;
        }

        public StudioRoomDto CreateRoom(Guid studioId, string name)
        {
            var studio = _studioRepository.Get(studioId);
            var model = studio.CreateRoom(name);

            var result = _studioRepository.CreateRoom(model.StudioId, model.Name);

            var studioRoomDto = _mapper.Map<StudioRoomDto>(result);
            return studioRoomDto;
        }
    }
}

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

using AutoMapper;

using ISTS.Domain.Studios;

namespace ISTS.Application.Studios
{
    public class StudioService : IStudioService
    {
        private readonly IStudioRepository _studioRepository;
        private readonly IMapper _mapper;

        public StudioService(
            IStudioRepository studioRepository,
            IMapper mapper)
        {
            _studioRepository = studioRepository;
            _mapper = mapper;
        }

        public StudioDto Create(string name, string friendlyUrl)
        {
            var entity = _studioRepository.Create(name, friendlyUrl);

            var result = _mapper.Map<StudioDto>(entity);
            return result;
        }

        public List<StudioDto> GetAll()
        {
            var entities = _studioRepository.Get().ToList();

            var result = _mapper.Map<List<StudioDto>>(entities);
            return result;
        }

        public StudioDto Get(Guid id)
        {
            var entity = _studioRepository.Get(id);

            var result = _mapper.Map<StudioDto>(entity);
            return result;
        }

        public StudioRoomDto CreateRoom(Guid studioId, string name)
        {
            var studio = _studioRepository.Get(studioId);
            var model = studio.CreateRoom(name);

            var result = _studioRepository.CreateRoom(model.StudioId, model.Name);

            var studioRoomDto = _mapper.Map<StudioRoomDto>(result);
            return studioRoomDto;
        }
    }
}

Remove studio repo Create call used for testing


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

using osu.Framework.Audio;
using osu.Framework.IO.Stores;
using osuTK.Graphics;

namespace osu.Game.Skinning
{
    public class DefaultLegacySkin : LegacySkin
    {
        public DefaultLegacySkin(IResourceStore<byte[]> storage, AudioManager audioManager)
            : base(Info, storage, audioManager, string.Empty)
        {
            Configuration.CustomColours["SliderBall"] = new Color4(2, 170, 255, 255);
            Configuration.ComboColours.AddRange(new[]
            {
                new Color4(255, 192, 0, 255),
                new Color4(0, 202, 0, 255),
                new Color4(18, 124, 255, 255),
                new Color4(242, 24, 57, 255),
            });
        }

        public static SkinInfo Info { get; } = new SkinInfo
        {
            ID = -1, // this is temporary until database storage is decided upon.
            Name = "osu!classic",
            Creator = "team osu!"
        };
    }
}

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

using osu.Framework.Audio;
using osu.Framework.IO.Stores;
using osuTK.Graphics;

namespace osu.Game.Skinning
{
    public class DefaultLegacySkin : LegacySkin
    {
        public DefaultLegacySkin(IResourceStore<byte[]> storage, AudioManager audioManager)
            : base(Info, storage, audioManager, string.Empty)
        {
            Configuration.CustomColours["SliderBall"] = new Color4(2, 170, 255, 255);
            Configuration.ComboColours.AddRange(new[]
            {
                new Color4(255, 192, 0, 255),
                new Color4(0, 202, 0, 255),
                new Color4(18, 124, 255, 255),
                new Color4(242, 24, 57, 255),
            });

            Configuration.LegacyVersion = 2.0;
        }

        public static SkinInfo Info { get; } = new SkinInfo
        {
            ID = -1, // this is temporary until database storage is decided upon.
            Name = "osu!classic",
            Creator = "team osu!"
        };
    }
}

Set legacy version of osu!classic skin to 2.0


//
// Urho's Object C# sugar
//
// Authors:
//   Miguel de Icaza (miguel@xamarin.com)
//
// Copyrigh 2015 Xamarin INc
//

using System;
using System.Runtime.InteropServices;

namespace Urho {

	public partial class UrhoObject : RefCounted {

		// Invoked by the subscribe methods
		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		static void ObjectCallback (IntPtr data, int stringHash, IntPtr variantMap)
		{
			GCHandle gch = GCHandle.FromIntPtr(data);
			Action<IntPtr> a = (Action<IntPtr>) gch.Target;
			a (variantMap);
		}
	}
}

//
// Urho's Object C# sugar
//
// Authors:
//   Miguel de Icaza (miguel@xamarin.com)
//
// Copyrigh 2015 Xamarin INc
//

using System;
using System.Runtime.InteropServices;

namespace Urho {

	public partial class UrhoObject : RefCounted {

		// Invoked by the subscribe methods
		static void ObjectCallback (IntPtr data, int stringHash, IntPtr variantMap)
		{
			GCHandle gch = GCHandle.FromIntPtr(data);
			Action<IntPtr> a = (Action<IntPtr>) gch.Target;
			a (variantMap);
		}
	}
}

Fix build, this is not allwoed on the method itself


// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
#if PLATFORM_DOTNET
using System.Reflection;
#endif

namespace CommandLine.Core
{
    sealed class Verb
    {
        private readonly string name;
        private readonly string helpText;

        public Verb(string name, string helpText)
        {
            if (name == null) throw new ArgumentNullException("name");
            if (helpText == null) throw new ArgumentNullException("helpText");

            this.name = name;
            this.helpText = helpText;
        }

        public string Name
        {
            get { return name; }
        }

        public string HelpText
        {
            get { return helpText; }
        }

        public static Verb FromAttribute(VerbAttribute attribute)
        {
            return new Verb(
                attribute.Name,
                attribute.HelpText
                );
        }

        public static IEnumerable<Tuple<Verb, Type>> SelectFromTypes(IEnumerable<Type> types)
        {
            return from type in types
                   let attrs = type.GetTypeInfo().GetCustomAttributes(typeof(VerbAttribute), true).ToArray()
                   where attrs.Length == 1
                   select Tuple.Create(
                       FromAttribute((VerbAttribute)attrs.Single()),
                       type);
        }
    }
}

// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
#if !NET40
using System.Reflection;
#endif

namespace CommandLine.Core
{
    sealed class Verb
    {
        private readonly string name;
        private readonly string helpText;

        public Verb(string name, string helpText)
        {
            if (name == null) throw new ArgumentNullException("name");
            if (helpText == null) throw new ArgumentNullException("helpText");

            this.name = name;
            this.helpText = helpText;
        }

        public string Name
        {
            get { return name; }
        }

        public string HelpText
        {
            get { return helpText; }
        }

        public static Verb FromAttribute(VerbAttribute attribute)
        {
            return new Verb(
                attribute.Name,
                attribute.HelpText
                );
        }

        public static IEnumerable<Tuple<Verb, Type>> SelectFromTypes(IEnumerable<Type> types)
        {
            return from type in types
                   let attrs = type.GetTypeInfo().GetCustomAttributes(typeof(VerbAttribute), true).ToArray()
                   where attrs.Length == 1
                   select Tuple.Create(
                       FromAttribute((VerbAttribute)attrs.Single()),
                       type);
        }
    }
}

Use the new reflection API on .NET 4.5 and .NET Core


using CurrencyRates.Entity;
using System;

namespace CurrencyRates
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

using System;

namespace CurrencyRates
{
    class Program
    {
        enum Actions { Fetch, Show };

        static void Main(string[] args)
        {
            try
            {
                var action = Actions.Fetch;

                if (args.Length > 0)
                {
                    action = (Actions)Enum.Parse(typeof(Actions), args[0], true);
                }

                switch (action)
                {
                    case Actions.Fetch:
                        //@todo implement Fetch action
                        break;

                    case Actions.Show:
                        //@todo implement Show action
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e) {
                Console.WriteLine("An error occured: " + e.Message);
            }
        }
    }
}

Add skeleton code to main program

Add skeleton code to main program