using System.Collections.Generic;
using StockportContentApi.ContentfulModels;
using StockportContentApi.Model;

namespace StockportContentApi.ContentfulFactories
{
    public class CommsContentfulFactory : IContentfulFactory<ContentfulCommsHomepage, CommsHomepage>
    {
        private readonly IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> _callToActionFactory;
        private readonly IContentfulFactory<ContentfulEvent, Event> _eventFactory;
        private readonly IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> _basicLinkFactory;

        public CommsContentfulFactory(
            IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> callToActionFactory,
            IContentfulFactory<ContentfulEvent, Event> eventFactory,
            IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> basicLinkFactory)
        {
            _callToActionFactory = callToActionFactory;
            _eventFactory = eventFactory;
            _basicLinkFactory = basicLinkFactory;
        }

        public CommsHomepage ToModel(ContentfulCommsHomepage model)
        {

            var callToActionBanner = _callToActionFactory.ToModel(model.CallToActionBanner);
            var displayEvent = _eventFactory.ToModel(model.WhatsOnInStockportEvent);
            var basicLinks = _basicLinkFactory.ToModel(model.UsefullLinks);

            return new CommsHomepage(
                model.Title,
                model.LatestNewsHeader,
                model.TwitterFeedHeader,
                model.InstagramFeedTitle,
                model.InstagramLink,
                model.FacebookFeedTitle,
                basicLinks,
                displayEvent,
                callToActionBanner
                );
        }
    }
}

using System.Collections.Generic;
using StockportContentApi.ContentfulModels;
using StockportContentApi.Model;

namespace StockportContentApi.ContentfulFactories
{
    public class CommsContentfulFactory : IContentfulFactory<ContentfulCommsHomepage, CommsHomepage>
    {
        private readonly IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> _callToActionFactory;
        private readonly IContentfulFactory<ContentfulEvent, Event> _eventFactory;
        private readonly IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> _basicLinkFactory;

        public CommsContentfulFactory(
            IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> callToActionFactory,
            IContentfulFactory<ContentfulEvent, Event> eventFactory,
            IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> basicLinkFactory)
        {
            _callToActionFactory = callToActionFactory;
            _eventFactory = eventFactory;
            _basicLinkFactory = basicLinkFactory;
        }

        public CommsHomepage ToModel(ContentfulCommsHomepage model)
        {

            var callToActionBanner = model.CallToActionBanner != null
                ? _callToActionFactory.ToModel(model.CallToActionBanner)
                : null;
            var displayEvent = _eventFactory.ToModel(model.WhatsOnInStockportEvent);
            var basicLinks = _basicLinkFactory.ToModel(model.UsefullLinks);

            return new CommsHomepage(
                model.Title,
                model.LatestNewsHeader,
                model.TwitterFeedHeader,
                model.InstagramFeedTitle,
                model.InstagramLink,
                model.FacebookFeedTitle,
                basicLinks,
                displayEvent,
                callToActionBanner
                );
        }
    }
}

fix(Comms): Allow call to action banner to be optional


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

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

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

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

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

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

Update assembly version to 2.0.0

Update assembly version to 2.0.0


using System;
using System.Collections.Immutable;
using System.IO;
using Microsoft.Extensions.Logging;
using OmniSharp.Utilities;

namespace OmniSharp.MSBuild.Discovery.Providers
{
    internal class MonoInstanceProvider : MSBuildInstanceProvider
    {
        public MonoInstanceProvider(ILoggerFactory loggerFactory)
            : base(loggerFactory)
        {
        }

        public override ImmutableArray<MSBuildInstance> GetInstances()
        {
            if (!PlatformHelper.IsMono)
            {
                return ImmutableArray<MSBuildInstance>.Empty;
            }

            var path = PlatformHelper.GetMonoMSBuildDirPath();
            if (path == null)
            {
                return ImmutableArray<MSBuildInstance>.Empty;
            }

            var toolsPath = Path.Combine(path, "15.0", "bin");
            if (!Directory.Exists(toolsPath))
            {
                return ImmutableArray<MSBuildInstance>.Empty;
            }

            var propertyOverrides = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.OrdinalIgnoreCase);

            var localMSBuildPath = FindLocalMSBuildDirectory();
            if (localMSBuildPath != null)
            {
                var localRoslynPath = Path.Combine(localMSBuildPath, "Roslyn");
                propertyOverrides.Add("CscToolPath", localRoslynPath);
                propertyOverrides.Add("CscToolExe", "csc.exe");
            }

            return ImmutableArray.Create(
                new MSBuildInstance(
                    "Mono",
                    toolsPath,
                    new Version(15, 0),
                    DiscoveryType.Mono,
                    propertyOverrides.ToImmutable()));
        }
    }
}

using System;
using System.Collections.Immutable;
using System.IO;
using Microsoft.Extensions.Logging;
using OmniSharp.Utilities;

namespace OmniSharp.MSBuild.Discovery.Providers
{
    internal class MonoInstanceProvider : MSBuildInstanceProvider
    {
        public MonoInstanceProvider(ILoggerFactory loggerFactory)
            : base(loggerFactory)
        {
        }

        public override ImmutableArray<MSBuildInstance> GetInstances()
        {
            if (!PlatformHelper.IsMono)
            {
                return ImmutableArray<MSBuildInstance>.Empty;
            }

            var path = PlatformHelper.GetMonoMSBuildDirPath();
            if (path == null)
            {
                return ImmutableArray<MSBuildInstance>.Empty;
            }

            var toolsPath = Path.Combine(path, "15.0", "bin");
            if (!Directory.Exists(toolsPath))
            {
                return ImmutableArray<MSBuildInstance>.Empty;
            }

            var propertyOverrides = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.OrdinalIgnoreCase);

            var localMSBuildPath = FindLocalMSBuildDirectory();
            if (localMSBuildPath != null)
            {
                var localRoslynPath = Path.Combine(localMSBuildPath, "15.0", "Bin", "Roslyn");
                propertyOverrides.Add("CscToolPath", localRoslynPath);
                propertyOverrides.Add("CscToolExe", "csc.exe");
            }

            return ImmutableArray.Create(
                new MSBuildInstance(
                    "Mono",
                    toolsPath,
                    new Version(15, 0),
                    DiscoveryType.Mono,
                    propertyOverrides.ToImmutable()));
        }
    }
}

Use correct path to MSBuild Roslyn folder on Mono


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

namespace NTwitch
{
    public interface ITwitchClient
    {
        ConnectionState ConnectionState { get; }

        Task<IChannel> GetChannelAsync(ulong id);
        Task<IEnumerable<ITopGame>> GetTopGames(TwitchPageOptions options = null);
        Task<IEnumerable<IIngest>> GetIngestsAsync();
        Task<IEnumerable<IChannel>> FindChannelsAsync(string query, TwitchPageOptions options = null);
        Task<IEnumerable<IGame>> FindGamesAsync(string query, bool islive = true);
        Task<IStream> GetStreamAsync(ulong id, StreamType type = StreamType.All);
        Task<IEnumerable<IStream>> FindStreamsAsync(string query, bool hls = true, TwitchPageOptions options = null);
        Task<IEnumerable<IStream>> GetStreamsAsync(string game = null, ulong[] channelids = null, string language = null, StreamType type = StreamType.All, TwitchPageOptions options = null);
        Task<IEnumerable<IFeaturedStream>> GetFeaturedStreamsAsync(TwitchPageOptions options = null);
        Task<IEnumerable<IStreamSummary>> GetStreamSummaryAsync(string game);
        Task<IEnumerable<ITeamInfo>> GetTeamsAsync(TwitchPageOptions options = null);
        Task<IEnumerable<ITeam>> GetTeamAsync(string name);
        Task<IUser> GetUserAsync(ulong id);
    }
}

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

namespace NTwitch
{
    public interface ITwitchClient
    {
        ConnectionState ConnectionState { get; }

        Task<IChannel> GetChannelAsync(ulong id);
        Task<IEnumerable<ITopGame>> GetTopGamesAsync(TwitchPageOptions options = null);
        Task<IEnumerable<IIngest>> GetIngestsAsync();
        Task<IEnumerable<IChannel>> FindChannelsAsync(string query, TwitchPageOptions options = null);
        Task<IEnumerable<IGame>> FindGamesAsync(string query, bool islive = true);
        Task<IStream> GetStreamAsync(ulong id, StreamType type = StreamType.All);
        Task<IEnumerable<IStream>> FindStreamsAsync(string query, bool hls = true, TwitchPageOptions options = null);
        Task<IEnumerable<IStream>> GetStreamsAsync(string game = null, ulong[] channelids = null, string language = null, StreamType type = StreamType.All, TwitchPageOptions options = null);
        Task<IEnumerable<IFeaturedStream>> GetFeaturedStreamsAsync(TwitchPageOptions options = null);
        Task<IEnumerable<IStreamSummary>> GetStreamSummaryAsync(string game);
        Task<IEnumerable<ITeamInfo>> GetTeamsAsync(TwitchPageOptions options = null);
        Task<IEnumerable<ITeam>> GetTeamAsync(string name);
        Task<IUser> GetUserAsync(ulong id);
    }
}

Add missing Async name to GetTopGames

Add missing Async name to GetTopGames


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

using System;
using System.Diagnostics;

namespace Microsoft.Its.Domain
{
    /// <summary>
    /// Provides access to system time.
    /// </summary>
    [DebuggerStepThrough]
    public class SystemClock : IClock
    {
        public static readonly SystemClock Instance = new SystemClock();

        private SystemClock()
        {
        }

        /// <summary>
        /// Gets the current time via <see cref="DateTimeOffset.Now" />.
        /// </summary>
        public DateTimeOffset Now()
        {
            return DateTimeOffset.Now;
        }

        public override string ToString()
        {
            return GetType() + ": " + Now().ToString("O");
        }
    }
}

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

using System;
using System.Diagnostics;

namespace Microsoft.Its.Domain
{
    /// <summary>
    /// Provides access to system time.
    /// </summary>
    [DebuggerStepThrough]
    public class SystemClock : IClock
    {
        public static readonly SystemClock Instance = new SystemClock();

        private SystemClock()
        {
        }

        /// <summary>
        /// Gets the current time via <see cref="DateTimeOffset.Now" />.
        /// </summary>
        public DateTimeOffset Now()
        {
            return DateTimeOffset.UtcNow;
        }

        public override string ToString()
        {
            return GetType() + ": " + Now().ToString("O");
        }
    }
}

Update the systemclock to use UtcNow. This is because some of code use Month, Year properties of DateTimeOffset


@model string
@{
    ViewData["Title"] = "Thank you";
    ViewData["og:title"] = "Thank you";

    Layout = "../Shared/_Layout.cshtml";
}

Thank you for contacting us

We will aim to respond to your enquiry within 10 working days.

                    <stock-button href="@Model">Return to previous page</stock-button>

@model string
@{
    ViewData["Title"] = "Thank you";
    ViewData["og:title"] = "Thank you";

    Layout = "../Shared/_Layout.cshtml";
}

Thank you for contacting us

We will endeavour to respond to your enquiry within 10 working days.

                    <stock-button href="@Model">Return To Previous Page</stock-button>

Revert "Gary changed wording per content request"

This reverts commit 6236a41d67d021860f6073aa5a1ad72cccd52bc9.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using SendGrid;
using TapBoxCommon.Models;
using Microsoft.Azure;

namespace TapBoxWebjob
{
    class MailSender
    {
        public static void SendMailToOwner(Device NotifierDevice, int SensorValue)
        {

            SendGridMessage myMessage = new SendGridMessage();
            myMessage.AddTo(NotifierDevice.OwnerMailAddress);
            myMessage.From = new MailAddress("sjost@hsr.ch", "Samuel Jost");
            myMessage.Subject = "Notification from your Tapbox";

            Console.WriteLine($"Device: {NotifierDevice.DeviceName} - Sensor Value: {SensorValue}");
            if (SensorValue < 20)
            {
                Console.WriteLine("Your Mailbox is Empty");
                return;
            }
            else if (SensorValue < 300)
            {
                Console.WriteLine("You have some Mail");
                myMessage.Text = "You have some Mail in your device "+NotifierDevice.DeviceName;
            }
            else if (SensorValue > 300)
            {
                Console.WriteLine("You have A Lot of Mail");
                myMessage.Text = "You have a lot of Mail in your device " + NotifierDevice.DeviceName;
            }

            var apiKey = CloudConfigurationManager.GetSetting("SendGrid.API_Key");
            var transportWeb = new Web(apiKey);

            // Send the email, which returns an awaitable task.
            transportWeb.DeliverAsync(myMessage);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using SendGrid;
using TapBoxCommon.Models;
using Microsoft.Azure;

namespace TapBoxWebjob
{
    class MailSender
    {
        public static void SendMailToOwner(Device NotifierDevice, int SensorValue)
        {

            SendGridMessage myMessage = new SendGridMessage();
            myMessage.AddTo(NotifierDevice.OwnerMailAddress);
            myMessage.From = new MailAddress("sjost@hsr.ch", "Samuel Jost");
            myMessage.Subject = "Notification from your Tapbox";

            Console.WriteLine($"Device: {NotifierDevice.DeviceName} - Sensor Value: {SensorValue}");
            if (SensorValue < 100)
            {
                Console.WriteLine("Your Mailbox is Empty");
                return;
            }
            else if (SensorValue < 300)
            {
                Console.WriteLine("You have some Mail");
                myMessage.Text = "You have some Mail in your device "+NotifierDevice.DeviceName;
            }
            else if (SensorValue > 300)
            {
                Console.WriteLine("You have A Lot of Mail");
                myMessage.Text = "You have a lot of Mail in your device " + NotifierDevice.DeviceName;
            }

            var apiKey = CloudConfigurationManager.GetSetting("SendGrid.API_Key");
            var transportWeb = new Web(apiKey);

            // Send the email, which returns an awaitable task.
            transportWeb.DeliverAsync(myMessage);
        }
    }
}

Change Sensor level to 100

Change Sensor level to 100


//-----------------------------------------------------------------------
// <copyright file="PortedAttributes.cs" company="Marimer LLC">
//     Copyright (c) Marimer LLC. All rights reserved.
//     Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Dummy implementations of .NET attributes missing in WP7.</summary>
//-----------------------------------------------------------------------
using System;

namespace Csla
{
  internal class BrowsableAttribute : Attribute
  {
    public BrowsableAttribute(bool flag)
    { }
  }

  internal class DisplayAttribute : Attribute
  {
    public string Name { get; set; }
    public bool AutoGenerateField { get; set; }
    public DisplayAttribute(bool AutoGenerateField = false, string Name = "")
    {
      this.AutoGenerateField = AutoGenerateField;
      this.Name = Name;
    }
  }
}

Add missing comment block. bugid: 812

Add missing comment block.
bugid: 812


using System;
using FeatureSwitcher.AwsConfiguration.Behaviours;

namespace FeatureSwitcher.AwsConfiguration.Models
{
    internal class BehaviourCacheItem
    {
        public IBehaviour Behaviour { get; }
        public DateTime CacheTimeout { get; }

        public bool IsExpired => this.CacheTimeout < DateTime.UtcNow;

        public BehaviourCacheItem(IBehaviour behaviour, TimeSpan cacheTime)
        {
            Behaviour = behaviour;
            CacheTimeout = DateTime.UtcNow.Add(cacheTime);
        }

        public void ExtendCache()
        {
            CacheTimeout.Add(TimeSpan.FromMinutes(1));
        }
    }
}

using System;
using FeatureSwitcher.AwsConfiguration.Behaviours;

namespace FeatureSwitcher.AwsConfiguration.Models
{
    internal class BehaviourCacheItem
    {
        public IBehaviour Behaviour { get; }
        public DateTime CacheTimeout { get; private set; }

        public bool IsExpired => this.CacheTimeout < DateTime.UtcNow;

        public BehaviourCacheItem(IBehaviour behaviour, TimeSpan cacheTime)
        {
            Behaviour = behaviour;
            CacheTimeout = DateTime.UtcNow.Add(cacheTime);
        }

        public void ExtendCache()
        {
            CacheTimeout = CacheTimeout.Add(TimeSpan.FromMinutes(1));
        }
    }
}

Fix bug: Ensure CacheTimeout is actually set when extending cache.


using TruckRouter.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseHttpsRedirection();
    app.UseAuthorization();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

using TruckRouter.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseHttpsRedirection();
    app.UseAuthorization();
}

app.MapControllers();

app.Run();

Remove code that unconditionally enable https redirects and authorization


using NLog;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace SyncTrayzor.Syncthing.ApiClient
{
    public class SyncthingHttpClientHandler : WebRequestHandler
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();

        public SyncthingHttpClientHandler()
        {
            // We expect Syncthing to return invalid certs
            this.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);
            if (response.IsSuccessStatusCode)
                logger.Trace(() => response.Content.ReadAsStringAsync().Result.Trim());
            else
                logger.Warn("Non-successful status code. {0} {1}", response, (await response.Content.ReadAsStringAsync()).Trim());

            return response;
        }
    }
}

using NLog;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace SyncTrayzor.Syncthing.ApiClient
{
    public class SyncthingHttpClientHandler : WebRequestHandler
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();

        public SyncthingHttpClientHandler()
        {
            // We expect Syncthing to return invalid certs
            this.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);

            // We're getting null bodies from somewhere: try and figure out where
            var responseString = await response.Content.ReadAsStringAsync();
            if (responseString == null)
                logger.Warn($"Null response received from {request.RequestUri}. {response}. Content (again): {response.Content.ReadAsStringAsync()}");

            if (response.IsSuccessStatusCode)
                logger.Trace(() => response.Content.ReadAsStringAsync().Result.Trim());
            else
                logger.Warn("Non-successful status code. {0} {1}", response, (await response.Content.ReadAsStringAsync()).Trim());

            return response;
        }
    }
}

Add logging in case of null response from Syncthing


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

using System;
using System.Reflection;
using Microsoft.Common.Core;
using Microsoft.R.Host.Protocol;

namespace Microsoft.R.Host.Client {
    public static class AboutHostExtensions {
        private static Version _localVersion;

        static AboutHostExtensions() {
            _localVersion = typeof(AboutHost).GetTypeInfo().Assembly.GetName().Version;
        }

        public static string IsHostVersionCompatible(this AboutHost aboutHost) {
            if (_localVersion.Major != 0 || _localVersion.Minor != 0) { // Filter out debug builds
                var serverVersion = new Version(aboutHost.Version.Major, aboutHost.Version.Minor);
                var clientVersion = new Version(_localVersion.Major, _localVersion.Minor);
                if (serverVersion > clientVersion) {
                    return Resources.Error_RemoteVersionHigher.FormatInvariant(aboutHost.Version, _localVersion);
                }

                if (serverVersion < clientVersion) {
                    return Resources.Error_RemoteVersionLower.FormatInvariant(aboutHost.Version, _localVersion);
                }
            }

            return null;
        }
    }
}

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

using System;
using System.Reflection;
using Microsoft.Common.Core;
using Microsoft.R.Host.Protocol;

namespace Microsoft.R.Host.Client {
    public static class AboutHostExtensions {
        private static Version _localVersion;

        static AboutHostExtensions() {
            _localVersion = typeof(AboutHost).GetTypeInfo().Assembly.GetName().Version;
        }

        public static string IsHostVersionCompatible(this AboutHost aboutHost) {
#if !DEBUG
            if (_localVersion.Major != 0 || _localVersion.Minor != 0) { // Filter out debug builds
                var serverVersion = new Version(aboutHost.Version.Major, aboutHost.Version.Minor);
                var clientVersion = new Version(_localVersion.Major, _localVersion.Minor);
                if (serverVersion > clientVersion) {
                    return Resources.Error_RemoteVersionHigher.FormatInvariant(aboutHost.Version, _localVersion);
                }

                if (serverVersion < clientVersion) {
                    return Resources.Error_RemoteVersionLower.FormatInvariant(aboutHost.Version, _localVersion);
                }
            }
#endif

            return null;
        }
    }
}

Allow debug mode to connect to any version of remote.


using System.Runtime.Remoting.Channels;

namespace RedGate.AppHost.Remoting
{
    internal class ClientChannelSinkProviderForParticularServer : IClientChannelSinkProvider
    {
        private readonly IClientChannelSinkProvider m_Upstream;
        private readonly string m_Url;

        internal ClientChannelSinkProviderForParticularServer(IClientChannelSinkProvider upstream, string id)
        {
            if (upstream == null)
                throw new ArgumentNullException("upstream");

            if (String.IsNullOrEmpty(id))
                throw new ArgumentNullException("id");

            m_Upstream = upstream;
            m_Url = string.Format("ipc://{0}", id);
        }

        public IClientChannelSinkProvider Next
        {
            get { return m_Upstream.Next; }
            set { m_Upstream.Next = value; }
        }

        public IClientChannelSink CreateSink(IChannelSender channel, string url, object remoteChannelData)
        {
            return url == m_Url ? m_Upstream.CreateSink(channel, url, remoteChannelData) : null;
        }
    }
}

using System;
using System.Runtime.Remoting.Channels;

namespace RedGate.AppHost.Remoting
{
    internal class ClientChannelSinkProviderForParticularServer : IClientChannelSinkProvider
    {
        private readonly IClientChannelSinkProvider m_Upstream;
        private readonly string m_Url;

        internal ClientChannelSinkProviderForParticularServer(IClientChannelSinkProvider upstream, string id)
        {
            if (upstream == null)
                throw new ArgumentNullException("upstream");

            if (String.IsNullOrEmpty(id))
                throw new ArgumentNullException("id");

            m_Upstream = upstream;
            m_Url = string.Format("ipc://{0}", id);
        }

        public IClientChannelSinkProvider Next
        {
            get { return m_Upstream.Next; }
            set { m_Upstream.Next = value; }
        }

        public IClientChannelSink CreateSink(IChannelSender channel, string url, object remoteChannelData)
        {
            //Returning null indicates that the sink cannot be created as per Microsoft documentation
            return url == m_Url ? m_Upstream.CreateSink(channel, url, remoteChannelData) : null;
        }
    }
}

Document why null is ok here

Document why null is ok here


using System.ComponentModel.DataAnnotations;

namespace BatteryCommander.Common.Models
{
    public enum Rank
    {
        [Display(Name = "PVT")]
        E1 = 1,

        [Display(Name = "PV2")]
        E2 = 2,

        [Display(Name = "PFC")]
        E3 = 3,

        [Display(Name = "SPC")]
        E4 = 4,

        [Display(Name = "SGT")]
        E5 = 5,

        [Display(Name = "SSG")]
        E6 = 6,

        [Display(Name = "SFC")]
        E7 = 7,

        [Display(Name = "1SG")]
        E8 = 8,

        Cadet = 9,

        [Display(Name = "2LT")]
        O1 = 10,

        [Display(Name = "1LT")]
        O2 = 11,

        [Display(Name = "CPT")]
        O3 = 12,

        [Display(Name = "MAJ")]
        O4 = 13,

        [Display(Name = "LTC")]
        O5 = 14,

        [Display(Name = "COL")]
        O6 = 15
    }
}

using System.ComponentModel.DataAnnotations;

namespace BatteryCommander.Common.Models
{
    public enum Rank
    {
        [Display(Name = "PVT")]
        E1 = 1,

        [Display(Name = "PV2")]
        E2 = 2,

        [Display(Name = "PFC")]
        E3 = 3,

        [Display(Name = "SPC")]
        E4 = 4,

        [Display(Name = "SGT")]
        E5 = 5,

        [Display(Name = "SSG")]
        E6 = 6,

        [Display(Name = "SFC")]
        E7 = 7,

        [Display(Name = "1SG")]
        E8 = 8,

        [Display(Name = "CDT")]
        Cadet = 9,

        [Display(Name = "2LT")]
        O1 = 10,

        [Display(Name = "1LT")]
        O2 = 11,

        [Display(Name = "CPT")]
        O3 = 12,

        [Display(Name = "MAJ")]
        O4 = 13,

        [Display(Name = "LTC")]
        O5 = 14,

        [Display(Name = "COL")]
        O6 = 15
    }
}

Add a display property for cadet rank

Add a display property for cadet rank


using System.Reflection;

[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("NuProj")]
[assembly: AssemblyCopyright("Copyright © Immo Landwerth")]
[assembly: AssemblyTrademark("")]

[assembly : AssemblyMetadata("PreRelease", "Beta")]
[assembly : AssemblyMetadata("ProjectUrl", "http://nuproj.codeplex.com")]
[assembly : AssemblyMetadata("LicenseUrl", "http://nuproj.codeplex.com/license")]

[assembly: AssemblyVersion("0.9.2.0")]
[assembly: AssemblyFileVersion("0.9.2.0")]

using System.Reflection;

[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("NuProj")]
[assembly: AssemblyCopyright("Copyright © Immo Landwerth")]
[assembly: AssemblyTrademark("")]

[assembly : AssemblyMetadata("PreRelease", "Beta")]
[assembly : AssemblyMetadata("ProjectUrl", "http://github.com/terrajobst/nuproj")]
[assembly : AssemblyMetadata("LicenseUrl", "https://raw.githubusercontent.com/terrajobst/nuproj/master/LICENSE")]

[assembly: AssemblyVersion("0.9.2.0")]
[assembly: AssemblyFileVersion("0.9.2.0")]

Update project and license URLs

Update project and license URLs


using System.Reflection;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace AppHarbor
{
	public class AppHarborInstaller : IWindsorInstaller
	{
		public void Install(IWindsorContainer container, IConfigurationStore store)
		{
			container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));

			container.Register(AllTypes.FromThisAssembly()
				.BasedOn<ICommand>());

			container.Register(Component
				.For<IAccessTokenConfiguration>()
				.ImplementedBy<AccessTokenConfiguration>());

			container.Register(Component
				.For<AppHarborClient>()
				.UsingFactoryMethod(x =>
				{
					var accessTokenConfiguration = container.Resolve<AccessTokenConfiguration>();
					return new AppHarborClient(accessTokenConfiguration.GetAccessToken());
				}));

			container.Register(Component
				.For<CommandDispatcher>()
				.UsingFactoryMethod(x =>
				{
					return new CommandDispatcher(Assembly.GetExecutingAssembly().GetExportedTypes(), container.Kernel);
				}));

			container.Register(Component
				.For<IFileSystem>()
				.ImplementedBy<PhysicalFileSystem>()
				.LifeStyle.Transient);
		}
	}
}

using System.Reflection;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace AppHarbor
{
	public class AppHarborInstaller : IWindsorInstaller
	{
		public void Install(IWindsorContainer container, IConfigurationStore store)
		{
			container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));

			container.Register(AllTypes.FromThisAssembly()
				.BasedOn<ICommand>());

			container.Register(Component
				.For<IAccessTokenConfiguration>()
				.ImplementedBy<AccessTokenConfiguration>());

			container.Register(Component
				.For<IAppHarborClient>()
				.UsingFactoryMethod(x =>
				{
					return new AppHarborClient(accessTokenConfiguration.GetAccessToken());
				}));

			container.Register(Component
				.For<CommandDispatcher>()
				.UsingFactoryMethod(x =>
				{
					return new CommandDispatcher(Assembly.GetExecutingAssembly().GetExportedTypes(), container.Kernel);
				}));

			container.Register(Component
				.For<IFileSystem>()
				.ImplementedBy<PhysicalFileSystem>()
				.LifeStyle.Transient);
		}
	}
}

Make sure to register interface rather than implementation


using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using Umbraco.Core;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.WebApi.Filters;

namespace Umbraco.Web.Trees
{
    [CoreTree(TreeGroup =Constants.Trees.Groups.Settings)]
    [UmbracoTreeAuthorize(Constants.Trees.MemberTypes)]
    [Tree(Constants.Applications.Settings, Constants.Trees.MemberTypes, null, sortOrder: 2)]
    public class MemberTypeTreeController : MemberTypeAndGroupTreeControllerBase
    {
        protected override IEnumerable<TreeNode> GetTreeNodesFromService(string id, FormDataCollection queryStrings)
        {
            return Services.MemberTypeService.GetAll()
                .OrderBy(x => x.Name)
                .Select(dt => CreateTreeNode(dt, Constants.ObjectTypes.MemberType, id, queryStrings, "icon-item-arrangement", false));
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using Umbraco.Core;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.WebApi.Filters;

namespace Umbraco.Web.Trees
{
    [CoreTree(TreeGroup = Constants.Trees.Groups.Settings)]
    [UmbracoTreeAuthorize(Constants.Trees.MemberTypes)]
    [Tree(Constants.Applications.Settings, Constants.Trees.MemberTypes, null, sortOrder: 2)]
    public class MemberTypeTreeController : MemberTypeAndGroupTreeControllerBase
    {
        protected override TreeNode CreateRootNode(FormDataCollection queryStrings)
        {
            var root = base.CreateRootNode(queryStrings);
            //check if there are any member types
            root.HasChildren = Services.MemberTypeService.GetAll().Any();
            return root;
        }
        protected override IEnumerable<TreeNode> GetTreeNodesFromService(string id, FormDataCollection queryStrings)
        {
            return Services.MemberTypeService.GetAll()
                .OrderBy(x => x.Name)
                .Select(dt => CreateTreeNode(dt, Constants.ObjectTypes.MemberType, id, queryStrings, "icon-item-arrangement", false));
        }
    }
}

Fix for chekcing the children belonging to MemberType tree.


using CupCake.Command;
using CupCake.Command.Source;
using CupCake.Permissions;
using CupCake.Players;

namespace CupCake.DefaultCommands.Commands.User
{
    public sealed class KickCommand : UserCommandBase
    {
        [MinGroup(Group.Trusted)]
        [Label("kick", "kickplayer")]
        [CorrectUsage("[player] [reason]")]
        protected override void Run(IInvokeSource source, ParsedCommand message)
        {
            this.RequireOwner();
            Player player = this.GetPlayerOrSelf(source, message);
            this.RequireSameRank(source, player);

            this.Chatter.Kick(player.Username, message.GetTrail(1));
        }
    }
}

using System.Runtime.InteropServices;
using CupCake.Command;
using CupCake.Command.Source;
using CupCake.Permissions;
using CupCake.Players;

namespace CupCake.DefaultCommands.Commands.User
{
    public sealed class KickCommand : UserCommandBase
    {
        [MinGroup(Group.Trusted)]
        [Label("kick", "kickplayer")]
        [CorrectUsage("[player] [reason]")]
        protected override void Run(IInvokeSource source, ParsedCommand message)
        {
            this.RequireOwner();
            Player player = this.GetPlayerOrSelf(source, message);
            this.RequireSameRank(source, player);

            this.Chatter.ChatService.Kick(source.Name, player.Username, (message.Count > 1 ? message.GetTrail(1) : "Tsk tsk tsk"));
        }
    }
}

Add default kick message, inform who the kicker was


using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;

namespace IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext
{
    [Coalesce]
    public class TestDbContext : DbContext
    {
        public DbSet<Person> People { get; set; }
        public DbSet<Case> Cases { get; set; }
        public DbSet<Company> Companies { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<CaseProduct> CaseProducts { get; set; }

        public DbSet<ComplexModel> ComplexModels { get; set; }
        public DbSet<Test> Tests { get; set; }

        public TestDbContext() : this(Guid.NewGuid().ToString()) { }

        public TestDbContext(string memoryDatabaseName)
            : base(new DbContextOptionsBuilder<TestDbContext>().UseInMemoryDatabase(memoryDatabaseName).Options)
        { }

        public TestDbContext(DbContextOptions<TestDbContext> options)
            : base(options)
        { }
    }
}

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using System;
using System.Collections.Generic;
using System.Text;

namespace IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext
{
    [Coalesce]
    public class TestDbContext : DbContext
    {
        public DbSet<Person> People { get; set; }
        public DbSet<Case> Cases { get; set; }
        public DbSet<Company> Companies { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<CaseProduct> CaseProducts { get; set; }

        public DbSet<ComplexModel> ComplexModels { get; set; }
        public DbSet<Test> Tests { get; set; }

        public TestDbContext() : this(Guid.NewGuid().ToString()) { }

        public TestDbContext(string memoryDatabaseName)
            : base(new DbContextOptionsBuilder<TestDbContext>().UseInMemoryDatabase(memoryDatabaseName).ConfigureWarnings(w =>
            {
#if NET5_0_OR_GREATER
            w.Ignore(CoreEventId.NavigationBaseIncludeIgnored);
#endif
            }).Options)
        { }

        public TestDbContext(DbContextOptions<TestDbContext> options)
            : base(options)
        { }
    }
}

Fix tests - apparently CoreEventId.NavigationBaseIncludeIgnored now defaults to Error in EF Core 6.


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

using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using Microsoft.VisualStudio.R.Package.Commands;
using Microsoft.VisualStudio.R.Packages.R;

namespace Microsoft.VisualStudio.R.Package.Options.R.Tools {
    public sealed class SetupRemoteCommand : MenuCommand {
        private const string _remoteSetupPage = "http://aka.ms/rtvs-remote";

        public SetupRemoteCommand() :
            base(OnCommand, new CommandID(RGuidList.RCmdSetGuid, RPackageCommandId.icmdSetupRemote)) {
        }

        public static void OnCommand(object sender, EventArgs args) {
            Process.Start(_remoteSetupPage);
        }
    }
}

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

using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using Microsoft.VisualStudio.R.Package.Commands;
using Microsoft.VisualStudio.R.Packages.R;

namespace Microsoft.VisualStudio.R.Package.Options.R.Tools {
    public sealed class SetupRemoteCommand : MenuCommand {
        private const string _remoteSetupPage = "https://aka.ms/rtvs-remote-setup-instructions";

        public SetupRemoteCommand() :
            base(OnCommand, new CommandID(RGuidList.RCmdSetGuid, RPackageCommandId.icmdSetupRemote)) {
        }

        public static void OnCommand(object sender, EventArgs args) {
            Process.Start(_remoteSetupPage);
        }
    }
}

Fix link to remote R setup

Fix link to remote R setup


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

namespace Pequot
{
    [XmlRoot("settings")]
    public class SerializableSettings
        : Dictionary<string, string>, IXmlSerializable
    {

        #region IXmlSerializable Members
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            bool wasEmpty = reader.IsEmptyElement;
            reader.Read();

            if (wasEmpty)
                return;

            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                string key = XmlConvert.DecodeName(reader.Name);
                string value = reader.ReadString();

                this.Add(key, value);

                reader.Read();
            }
            reader.ReadEndElement();
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            foreach (String key in this.Keys)
            {
                writer.WriteStartElement(XmlConvert.EncodeName(key));
                writer.WriteString(this[key]);
                writer.WriteEndElement();
            }
        }
        #endregion
    }
}

using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;

namespace Pequot
{
    [XmlRoot("settings")]
    public class SerializableSettings
        : Dictionary<string, string>, IXmlSerializable
    {

        #region IXmlSerializable Members
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            bool wasEmpty = reader.IsEmptyElement;
            reader.Read();

            if (wasEmpty)
                return;

            while (reader.NodeType != XmlNodeType.EndElement)
            {
                // Convert from human-readable element names (see below)
                string key = XmlConvert.DecodeName(reader.Name.Replace("___", "_x0020_").Replace("__x005F__", "___"));
                string value = reader.ReadString();

                if(key!=null)
                {
                    if(ContainsKey(key))
                        // update if already exists
                        this[key] = value;
                    else
                        Add(key, value);
                }

                reader.Read();
            }
            reader.ReadEndElement();
        }

        public void WriteXml(XmlWriter writer)
        {
            foreach (String key in Keys)
            {
                // Convert to human-readable element names by substituting three underscores for an encoded space (2nd Replace)
                // and making sure existing triple-underscores will not cause confusion by substituting with partial encoding
                string encoded = XmlConvert.EncodeName(key);
                if (encoded == null) continue;
                writer.WriteStartElement(encoded.Replace("___", "__x005F__").Replace("_x0020_", "___"));
                writer.WriteString(this[key]);
                writer.WriteEndElement();
            }
        }
        #endregion
    }
}

Make saved settings more readable

Make saved settings more readable

Still to do: make converter for old format


namespace Nine.Application.WindowsStore.Test
{
    using System;
    using System.Reflection;
    using Windows.UI.Xaml.Controls;
    using Xunit;
    using Xunit.Abstractions;

    public sealed partial class MainPage : Page, IMessageSink
    {
        public MainPage()
        {
            InitializeComponent();

            Loaded += async (a, b) =>
            {
                await new PortableTestExecutor().RunAll(this, typeof(AppUITest).GetTypeInfo().Assembly);
            };
        }

        public bool OnMessage(IMessageSinkMessage message)
        {
            Output.Text = message.ToString();
            return true;
        }
    }
}

namespace Nine.Application.WindowsStore.Test
{
    using System;
    using System.Reflection;
    using Windows.UI.Xaml.Controls;
    using Xunit;
    using Xunit.Abstractions;

    public sealed partial class MainPage : Page, IMessageSink
    {
        public MainPage()
        {
            InitializeComponent();
        }

        public bool OnMessage(IMessageSinkMessage message)
        {
            Output.Text = message.ToString();
            return true;
        }
    }
}

Remove windows store test runner

Remove windows store test runner


using Xunit;
using System.Globalization;
using System.Threading;

namespace CronExpressionDescriptor.Test.Support
{
    public abstract class BaseTestFormats
    {
        protected virtual string GetLocale()
        {
            return "en-US";
        }

        protected string GetDescription(string expression)
        {
            return GetDescription(expression, new Options());
        }

        protected string GetDescription(string expression, Options options)
        {
            options.Locale = this.GetLocale();
            return ExpressionDescriptor.GetDescription(expression, options);
        }
    }
}

using Xunit;
using System.Globalization;
using System.Threading;

namespace CronExpressionDescriptor.Test.Support
{
    public abstract class BaseTestFormats
    {
        protected virtual string GetLocale()
        {
            return "en-US";
        }

        protected string GetDescription(string expression, bool verbose = false)
        {
            return GetDescription(expression, new Options() { Verbose = verbose });
        }

        protected string GetDescription(string expression, Options options)
        {
            options.Locale = this.GetLocale();
            return ExpressionDescriptor.GetDescription(expression, options);
        }
    }
}

Add verbose option for tests

Add verbose option for tests


using UnityEngine;
using System.Collections;

public class Trampoline : MonoBehaviour {

	public float velocityX;
	public float velocityY;
	public Input button;

	void OnTriggerStay2D(Collider2D other) {
		if (other.gameObject.tag == "Player") {
			if(button){
				other.rigidbody2D.AddForce(new Vector2(velocityX,velocityY));
				//other.rigidbody2D.velocity+=new Vector2(velocityX,velocityY);
			}

		}
	}
}

using UnityEngine;
using System.Collections;

public class Trampoline : MonoBehaviour {

	public float velocityX;
	public float velocityY;

	void OnTriggerStay2D(Collider2D other) {
		if (other.gameObject.tag == "Player") {
			other.rigidbody2D.AddForce(new Vector2(velocityX,velocityY));
			//other.rigidbody2D.velocity+=new Vector2(velocityX,velocityY);
		}
	}
}

Revert "Tried to Figure Out Button: Failed"

This reverts commit 22e4c8b1b383f6ef364cbf8209c1026530bc9414.


using System;
using Microsoft.SPOT;
using MicroTweet;
using System.Net;
using System.Threading;

namespace SampleApplication
{
    public class Program
    {
        public static void Main()
        {
            // Wait for DHCP
            while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any)
                Thread.Sleep(50);

            // Update the current time (since Twitter OAuth API requests require a valid timestamp)
            DateTime utcTime = Sntp.GetCurrentUtcTime();
            Microsoft.SPOT.Hardware.Utility.SetLocalTime(utcTime);

            // Set up application and user credentials
            // Visit https://apps.twitter.com/ to create a new Twitter application and get API keys/user access tokens
            var appCredentials = new OAuthApplicationCredentials()
            {
                ConsumerKey = "YOUR_CONSUMER_KEY_HERE",
                ConsumerSecret = "YOUR_CONSUMER_SECRET_HERE",
            };
            var userCredentials = new OAuthUserCredentials()
            {
                AccessToken = "YOUR_ACCESS_TOKEN",
                AccessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET",
            };

            // Create new Twitter client with these credentials
            var twitter = new TwitterClient(appCredentials, userCredentials);

            // Send a tweet
            twitter.SendTweet("Trying out MicroTweet!");
        }
    }
}

using System;
using Microsoft.SPOT;
using MicroTweet;
using System.Net;
using System.Threading;

namespace SampleApplication
{
    public class Program
    {
        public static void Main()
        {
            // Wait for DHCP
            while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any)
                Thread.Sleep(50);

            // Update the current time (since Twitter OAuth API requests require a valid timestamp)
            DateTime utcTime = Sntp.GetCurrentUtcTime();
            Microsoft.SPOT.Hardware.Utility.SetLocalTime(utcTime);

            // Set up application and user credentials
            // Visit https://apps.twitter.com/ to create a new Twitter application and get API keys/user access tokens
            var appCredentials = new OAuthApplicationCredentials()
            {
                ConsumerKey = "YOUR_CONSUMER_KEY_HERE",
                ConsumerSecret = "YOUR_CONSUMER_SECRET_HERE",
            };
            var userCredentials = new OAuthUserCredentials()
            {
                AccessToken = "YOUR_ACCESS_TOKEN",
                AccessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET",
            };

            // Create new Twitter client with these credentials
            var twitter = new TwitterClient(appCredentials, userCredentials);

            // Send a tweet
            var tweet = twitter.SendTweet("Trying out MicroTweet!");

            if (tweet != null)
                Debug.Print("Posted tweet with ID: " + tweet.ID);
            else
                Debug.Print("Could not send tweet.");
        }
    }
}

Modify sample application to show details about the posted tweet


using System;
using System.ComponentModel;
using Ooui.Forms.Extensions;
using Xamarin.Forms;

namespace Ooui.Forms.Renderers
{
    public class ScrollViewRenderer : ViewRenderer<ScrollView, Div>
    {
        protected override void OnElementChanged (ElementChangedEventArgs<ScrollView> e)
        {
            base.OnElementChanged (e);

            this.Style.Overflow = "scroll";
        }

        protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged (sender, e);
        }
    }
}

using System;
using System.ComponentModel;
using Ooui.Forms.Extensions;
using Xamarin.Forms;

namespace Ooui.Forms.Renderers
{
    public class ScrollViewRenderer : VisualElementRenderer<ScrollView>
    {
        bool disposed = false;

        protected override void OnElementChanged (ElementChangedEventArgs<ScrollView> e)
        {
            if (e.OldElement != null) {
                e.OldElement.ScrollToRequested -= Element_ScrollToRequested;
            }

            if (e.NewElement != null) {
                Style.Overflow = "scroll";

                e.NewElement.ScrollToRequested += Element_ScrollToRequested;
            }

            base.OnElementChanged (e);
        }

        protected override void Dispose (bool disposing)
        {
            base.Dispose (disposing);

            if (disposing && !disposed) {
                if (Element != null) {
                    Element.ScrollToRequested -= Element_ScrollToRequested;
                }
                disposed = true;
            }
        }

        void Element_ScrollToRequested (object sender, ScrollToRequestedEventArgs e)
        {
            var oe = (ITemplatedItemsListScrollToRequestedEventArgs)e;
            var item = oe.Item;
            var group = oe.Group;
            if (e.Mode == ScrollToMode.Position) {
                Send (Ooui.Message.Set (Id, "scrollTop", e.ScrollY));
                Send (Ooui.Message.Set (Id, "scrollLeft", e.ScrollX));
            }
            else {
                switch (e.Position) {
                    case ScrollToPosition.Start:
                        Send (Ooui.Message.Set (Id, "scrollTop", 0));
                        break;
                    case ScrollToPosition.End:
                        Send (Ooui.Message.Set (Id, "scrollTop", new Ooui.Message.PropertyReference { TargetId = Id, Key = "scrollHeight" }));
                        break;
                }
            }
        }
    }
}

Add ScrollTo support to ScrollView

Add ScrollTo support to ScrollView


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

[assembly: AssemblyTitle("Autofac.Extras.Multitenant")]
[assembly: AssemblyDescription("Autofac multitenancy support library.")]
[assembly: ComVisible(false)]

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

[assembly: AssemblyTitle("Autofac.Extras.Multitenant")]
[assembly: ComVisible(false)]

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


using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using WebAPI.API.ModelBindings.Providers;

namespace WebAPI.API
{
    public class ModelBindingConfig
    {
        public static void RegisterModelBindings(ServicesContainer services)
        {
            services.Add(typeof (ModelBinderProvider), new GeocodeOptionsModelBindingProvider());
            services.Add(typeof (ModelBinderProvider), new RouteMilepostOptionsModelBindingProvider());
            services.Add(typeof (ModelBinderProvider), new SearchOptionsModelBindingProvider());
            services.Add(typeof (ModelBinderProvider), new ReverseMilepostOptionsModelBindingProvider());
        }
    }
}

using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using WebAPI.API.ModelBindings.Providers;

namespace WebAPI.API
{
    public class ModelBindingConfig
    {
        public static void RegisterModelBindings(ServicesContainer services)
        {
            services.Add(typeof (ModelBinderProvider), new GeocodeOptionsModelBindingProvider());
            services.Add(typeof (ModelBinderProvider), new ArcGisOnlineOptionsModelBindingProvide());
            services.Add(typeof (ModelBinderProvider), new RouteMilepostOptionsModelBindingProvider());
            services.Add(typeof (ModelBinderProvider), new SearchOptionsModelBindingProvider());
            services.Add(typeof (ModelBinderProvider), new ReverseMilepostOptionsModelBindingProvider());
        }
    }
}

Add model binder to binding config

Add model binder to binding config


// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Utilities
{
    internal static class IVsEditorAdaptersFactoryServiceExtensions
    {
        public static IOleUndoManager TryGetUndoManager(
            this IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
            Workspace workspace,
            DocumentId contextDocumentId,
            CancellationToken cancellationToken)
        {
            var document = workspace.CurrentSolution.GetDocument(contextDocumentId);
            var text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var textSnapshot = text.FindCorrespondingEditorTextSnapshot();
            var textBuffer = textSnapshot?.TextBuffer;
            return editorAdaptersFactoryService.TryGetUndoManager(textBuffer);
        }

        public static IOleUndoManager TryGetUndoManager(
            this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextBuffer subjectBuffer)
        {
            if (subjectBuffer != null)
            {
                var adapter = editorAdaptersFactoryService.GetBufferAdapter(subjectBuffer);
                if (adapter != null)
                {
                    if (ErrorHandler.Succeeded(adapter.GetUndoManager(out var manager)))
                    {
                        return manager;
                    }
                }
            }

            return null;
        }
    }
}

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Utilities
{
    internal static class IVsEditorAdaptersFactoryServiceExtensions
    {
        public static IOleUndoManager TryGetUndoManager(
            this IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
            Workspace workspace,
            DocumentId contextDocumentId,
            CancellationToken cancellationToken)
        {
            var document = workspace.CurrentSolution.GetDocument(contextDocumentId);
            var text = document?.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var textSnapshot = text.FindCorrespondingEditorTextSnapshot();
            var textBuffer = textSnapshot?.TextBuffer;
            return editorAdaptersFactoryService.TryGetUndoManager(textBuffer);
        }

        public static IOleUndoManager TryGetUndoManager(
            this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextBuffer subjectBuffer)
        {
            if (subjectBuffer != null)
            {
                var adapter = editorAdaptersFactoryService?.GetBufferAdapter(subjectBuffer);
                if (adapter != null)
                {
                    if (ErrorHandler.Succeeded(adapter.GetUndoManager(out var manager)))
                    {
                        return manager;
                    }
                }
            }

            return null;
        }
    }
}

Address null ref when we can't get an Undo manager.


// 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.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Rulesets.Mania.Skinning.Default;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Mania.Skinning.Argon
{
    public class ArgonHitTarget : CompositeDrawable
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            RelativeSizeAxes = Axes.X;
            Height = DefaultNotePiece.NOTE_HEIGHT;

            InternalChildren = new[]
            {
                new Box
                {
                    RelativeSizeAxes = Axes.Both,
                    Alpha = 0.3f,
                    Blending = BlendingParameters.Additive,
                    Colour = Color4.White
                },
            };
        }
    }
}

// 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.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Rulesets.Mania.Skinning.Default;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Mania.Skinning.Argon
{
    public class ArgonHitTarget : CompositeDrawable
    {
        private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>();

        [BackgroundDependencyLoader]
        private void load(IScrollingInfo scrollingInfo)
        {
            RelativeSizeAxes = Axes.X;
            Height = DefaultNotePiece.NOTE_HEIGHT;

            InternalChildren = new[]
            {
                new Box
                {
                    RelativeSizeAxes = Axes.Both,
                    Alpha = 0.3f,
                    Blending = BlendingParameters.Additive,
                    Colour = Color4.White
                },
            };

            direction.BindTo(scrollingInfo.Direction);
            direction.BindValueChanged(onDirectionChanged, true);
        }

        private void onDirectionChanged(ValueChangedEvent<ScrollingDirection> direction)
        {
            Anchor = Origin = direction.NewValue == ScrollingDirection.Up ? Anchor.TopLeft : Anchor.BottomLeft;
        }
    }
}

Fix argon hit target area not being aligned correctly


using System;
using System.Collections.Generic;

namespace Fixie
{
    public class ClassExecution
    {
        public ClassExecution(ExecutionPlan executionPlan, Type testClass, CaseExecution[] caseExecutions)
        {
            ExecutionPlan = executionPlan;
            TestClass = testClass;
            CaseExecutions = caseExecutions;
        }

        public ExecutionPlan ExecutionPlan { get; private set; }
        public Type TestClass { get; private set; }
        public IReadOnlyList<CaseExecution> CaseExecutions { get; private set; }

        public void FailCases(Exception exception)
        {
            foreach (var caseExecution in CaseExecutions)
                caseExecution.Fail(exception);
        }
    }
}

using System;
using System.Collections.Generic;

namespace Fixie
{
    public class ClassExecution
    {
        public ClassExecution(ExecutionPlan executionPlan, Type testClass, IReadOnlyList<CaseExecution> caseExecutions)
        {
            ExecutionPlan = executionPlan;
            TestClass = testClass;
            CaseExecutions = caseExecutions;
        }

        public ExecutionPlan ExecutionPlan { get; private set; }
        public Type TestClass { get; private set; }
        public IReadOnlyList<CaseExecution> CaseExecutions { get; private set; }

        public void FailCases(Exception exception)
        {
            foreach (var caseExecution in CaseExecutions)
                caseExecution.Fail(exception);
        }
    }
}

Declare array parameter as an IReadOnlyList<T> since the array need not be used as mutable.


using System;
using RSB;
using RSB.Diagnostics;
using RSB.Transports.RabbitMQ;

namespace SampleDiscoverableModule
{
    class Program
    {
        static void Main(string[] args)
        {
            var bus = new Bus(RabbitMqTransport.FromConfigurationFile());

            var diagnostics = new BusDiagnostics(bus,"SampleDiscoverableModule");

            diagnostics.RegisterSubsystemHealthChecker("sampleSubsystem1", () => true);

            Console.ReadLine();
        }
    }
}

using System;
using System.Threading;
using RSB;
using RSB.Diagnostics;
using RSB.Transports.RabbitMQ;

namespace SampleDiscoverableModule
{
    class Program
    {
        static void Main(string[] args)
        {
            var bus = new Bus(RabbitMqTransport.FromConfigurationFile());

            bus.UseBusDiagnostics("SampleDiscoverableModule", diagnostics =>
            {
                diagnostics.RegisterSubsystemHealthChecker("sampleSubsystem1", () =>
                {
                    Thread.Sleep(6000);

                    return true;
                });
            });

            Console.ReadLine();
        }
    }
}

Refactor to use UseBusDiagnostics extension


using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Input;
using AudioSharp.Utils;
using Newtonsoft.Json;

namespace AudioSharp.Config
{
    public class ConfigHandler
    {
        public static void SaveConfig(Configuration config)
        {
            string json = JsonConvert.SerializeObject(config);
            File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json);
        }

        public static Configuration ReadConfig()
        {
            string path = Path.Combine(FileUtils.AppDataFolder, "settings.json");
            if (File.Exists(path))
            {
                string json = File.ReadAllText(path);
                return JsonConvert.DeserializeObject<Configuration>(json);
            }

            return new Configuration()
            {
                RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
                RecordingPrefix = "Recording",
                NextRecordingNumber = 1,
                AutoIncrementRecordingNumber = true,
                OutputFormat = "wav",
                ShowTrayIcon = true,
                GlobalHotkeys = new Dictionary<HotkeyUtils.HotkeyType, Tuple<Key, ModifierKeys>>(),
                RecordingSettingsPanelVisible = true,
                RecordingOutputPanelVisible = true
            };
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Input;
using AudioSharp.Utils;
using Newtonsoft.Json;

namespace AudioSharp.Config
{
    public class ConfigHandler
    {
        public static void SaveConfig(Configuration config)
        {
            string json = JsonConvert.SerializeObject(config);
            File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json);
        }

        public static Configuration ReadConfig()
        {
            string path = Path.Combine(FileUtils.AppDataFolder, "settings.json");
            if (File.Exists(path))
            {
                string json = File.ReadAllText(path);
                return JsonConvert.DeserializeObject<Configuration>(json);
            }

            return new Configuration()
            {
                RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
                RecordingPrefix = "Recording{n}",
                NextRecordingNumber = 1,
                AutoIncrementRecordingNumber = true,
                OutputFormat = "wav",
                ShowTrayIcon = true,
                GlobalHotkeys = new Dictionary<HotkeyUtils.HotkeyType, Tuple<Key, ModifierKeys>>(),
                RecordingSettingsPanelVisible = true,
                RecordingOutputPanelVisible = true
            };
        }
    }
}

Include the recording number in the default format


using JoinRpg.Domain;
using JoinRpg.Services.Interfaces;
using JoinRpg.TestHelpers;
using JoinRpg.Web.Models;
using Xunit;

namespace JoinRpg.Web.Test
{

    public class EnumTests
    {
        [Fact]
        public void ProblemEnum()
        {
            EnumerationTestHelper.CheckEnums<UserExtensions.AccessReason, AccessReason>();
            EnumerationTestHelper.CheckEnums<ProjectFieldViewType, DataModel.ProjectFieldType>();
            EnumerationTestHelper.CheckEnums<ClaimStatusView, DataModel.Claim.Status>();
            EnumerationTestHelper.CheckEnums<FinanceOperationActionView, FinanceOperationAction>();
        }
    }
}

using JoinRpg.Domain;
using JoinRpg.Services.Interfaces;
using JoinRpg.TestHelpers;
using JoinRpg.Web.Models;
using Xunit;

namespace JoinRpg.Web.Test
{

    public class EnumTests
    {
        [Fact]
        public void AccessReason() => EnumerationTestHelper.CheckEnums<UserExtensions.AccessReason, AccessReason>();

        [Fact]
        public void ProjectFieldType() => EnumerationTestHelper.CheckEnums<ProjectFieldViewType, DataModel.ProjectFieldType>();

        [Fact]
        public void ClaimStatus() => EnumerationTestHelper.CheckEnums<ClaimStatusView, DataModel.Claim.Status>();

        [Fact]
        public void FinanceOperation() => EnumerationTestHelper.CheckEnums<FinanceOperationActionView, FinanceOperationAction>();
    }
}

Split enum test to 4 separate

Split enum test to 4 separate


using System;
using System.Net;

namespace BmpListener.Bgp
{
    public class IPAddrPrefix
    {
        public IPAddrPrefix(byte[] data, int offset, AddressFamily afi = AddressFamily.IP)
        {
            DecodeFromBytes(data, offset, afi);
        }

        internal int ByteLength { get { return 1 + (Length + 7) / 8; } }
        public int Length { get; private set; }
        public IPAddress Prefix { get; private set; }

        public override string ToString()
        {
            return ($"{Prefix}/{Length}");
        }

        public void DecodeFromBytes(byte[] data, int offset, AddressFamily afi = AddressFamily.IP)
        {
            Length = data[offset];
            var byteLength = (Length + 7) / 8;
            var ipBytes = afi == AddressFamily.IP
                ? new byte[4]
                : new byte[16];
            Array.Copy(data, offset + 1, ipBytes, 0, byteLength);
            Prefix = new IPAddress(ipBytes);
        }
    }
}

using System;
using System.Linq;
using System.Net;

namespace BmpListener.Bgp
{
    public class IPAddrPrefix
    {
        // RFC 4721 4.3
        // The Type field indicates the length in bits of the IP address prefix.
        public int Length { get; private set; }
        public IPAddress Prefix { get; private set; }

        public override string ToString()
        {
            return ($"{Prefix}/{Length}");
        }

        public static (IPAddrPrefix prefix, int byteLength) Decode(byte[] data, int offset, AddressFamily afi)
        {
            var bitLength = data[offset];
            var byteLength = (bitLength + 7) / 8;
            var ipBytes = afi == AddressFamily.IP
                ? new byte[4]
                : new byte[16];
            Array.Copy(data, offset + 1, ipBytes, 0, byteLength);
            var prefix = new IPAddress(ipBytes);
            var ipAddrPrefix = new IPAddrPrefix { Length = bitLength, Prefix = prefix };
            return (ipAddrPrefix, byteLength + 1);
        }

        public static (IPAddrPrefix prefix, int byteLength) Decode(ArraySegment<byte> data, int offset, AddressFamily afi)
        {
            byte bitLength = data.First();
            var ipBytes = afi == AddressFamily.IP
                ? new byte[4]
                : new byte[16];
            offset += data.Offset;
            return Decode(data.Array, data.Offset, afi);
        }
    }
}

Return prefix and byte length

Return prefix and byte length


@{
    ViewData["Title"] = "Data sources";
}

@ViewData["Title"]

@ViewData["Message"]

http://www.oxfordmartin.ox.ac.uk/downloads/academic/The_Future_of_Employment.pdf

Add FutureEmployment to data sources.

Add FutureEmployment to data sources.


@{
    Layout = null;
    @using ISWebTest.ExtensionMethods;
    @using ISWebTest.Controllers;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title></title>

    <a href="@{Url.Action<HomeController>(nameof(HomeController.Analyze))}">TEST

@using ISWebTest.ExtensionMethods;
@using ISWebTest.Controllers;

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title></title>

    <a href="@(Url.Action<HomeController>(nameof(HomeController.Analyze)))">TEST

Clean up syntax of index page

Clean up syntax of index page


using IFVM.Core;

namespace IFVM.Execution
{
    public partial class Interpreter
    {
        public static uint Execute(Function function)
        {
            return 0;
        }
    }
}

using System;
using IFVM.Ast;
using IFVM.Collections;
using IFVM.Core;
using IFVM.FlowAnalysis;

namespace IFVM.Execution
{
    public partial class Interpreter
    {
        public static uint Execute(Function function, Machine machine)
        {
            var cfg = ControlFlowGraph.Compute(function.Body);
            var block = cfg.GetBlock(cfg.EntryBlock.Successors[0]);
            var result = 0u;

            while (!block.IsExit)
            {
                var nextBlockId = block.ID.GetNext();

                foreach (var statement in block.Statements)
                {
                    var jump = false;

                    void HandleReturnStatement(AstReturnStatement returnStatement)
                    {
                        result = Execute(returnStatement.Expression, machine);
                        nextBlockId = BlockId.Exit;
                        jump = true;
                    }

                    void HandleJumpStatement(AstJumpStatement jumpStatement)
                    {
                        nextBlockId = new BlockId(jumpStatement.Label.Index);
                        jump = true;
                    }

                    // Handle control flow
                    switch (statement.Kind)
                    {
                        case AstNodeKind.ReturnStatement:
                            HandleReturnStatement((AstReturnStatement)statement);
                            break;

                        case AstNodeKind.JumpStatement:
                            HandleJumpStatement((AstJumpStatement)statement);
                            break;

                        case AstNodeKind.BranchStatement:
                            {
                                var branchStatement = (AstBranchStatement)statement;
                                var condition = Execute(branchStatement.Condition, machine);
                                if (condition == 1)
                                {
                                    switch (branchStatement.Statement.Kind)
                                    {
                                        case AstNodeKind.ReturnStatement:
                                            HandleReturnStatement((AstReturnStatement)branchStatement.Statement);
                                            break;

                                        case AstNodeKind.JumpStatement:
                                            HandleJumpStatement((AstJumpStatement)branchStatement.Statement);
                                            break;

                                        default:
                                            throw new InvalidOperationException($"Invalid statement kind for branch: {branchStatement.Statement.Kind}");
                                    }
                                }

                                continue;
                            }
                    }

                    if (jump)
                    {
                        break;
                    }

                    Execute(statement, machine);
                }

                block = cfg.GetBlock(nextBlockId);
            }

            return result;
        }

        private static uint Execute(AstExpression expression, Machine machine)
        {
            switch (expression.Kind)
            {
                default:
                    throw new InvalidOperationException($"Invalid expression kind: {expression.Kind}");
            }
        }

        private static void Execute(AstStatement statement, Machine machine)
        {
            switch (statement.Kind)
            {
                case AstNodeKind.LabelStatement:
                    break;

                default:
                    throw new InvalidOperationException($"Invalid statement kind: {statement.Kind}");
            }
        }
    }
}

Add interpreter with skeleton game loop

Add interpreter with skeleton game loop


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

using System;
using System.Collections.Generic;
using Microsoft.AspNet.Http;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.OptionsModel;
using Xunit;

namespace Microsoft.AspNet.Routing.Tests
{
    public class RouteOptionsTests
    {
        [Fact]
        public void ConstraintMap_SettingNullValue_Throws()
        {
            // Arrange
            var options = new RouteOptions();

            // Act & Assert
            var ex = Assert.Throws<ArgumentNullException>(() => options.ConstraintMap = null);
            Assert.Equal("The 'ConstraintMap' property of 'Microsoft.AspNet.Routing.RouteOptions' must not be null." +
                         Environment.NewLine + "Parameter name: value", ex.Message);
        }

        [Fact]
        public void ConfigureRouting_ConfiguresOptionsProperly()
        {
            // Arrange
            var services = new ServiceCollection().AddOptions();

            // Act
            services.ConfigureRouting(options => options.ConstraintMap.Add("foo", typeof(TestRouteConstraint)));
            var serviceProvider = services.BuildServiceProvider();

            // Assert
            var accessor = serviceProvider.GetRequiredService<IOptions<RouteOptions>>();
            Assert.Equal("TestRouteConstraint", accessor.Options.ConstraintMap["foo"].Name);
        }

        private class TestRouteConstraint : IRouteConstraint
        {
            public TestRouteConstraint(string pattern)
            {
                Pattern = pattern;
            }

            public string Pattern { get; private set; }
            public bool Match(HttpContext httpContext,
                              IRouter route,
                              string routeKey,
                              IDictionary<string, object> values,
                              RouteDirection routeDirection)
            {
                throw new NotImplementedException();
            }
        }
    }
}

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

using System;
using System.Collections.Generic;
using Microsoft.AspNet.Http;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.OptionsModel;
using Xunit;

namespace Microsoft.AspNet.Routing.Tests
{
    public class RouteOptionsTests
    {
        [Fact]
        public void ConfigureRouting_ConfiguresOptionsProperly()
        {
            // Arrange
            var services = new ServiceCollection().AddOptions();

            // Act
            services.ConfigureRouting(options => options.ConstraintMap.Add("foo", typeof(TestRouteConstraint)));
            var serviceProvider = services.BuildServiceProvider();

            // Assert
            var accessor = serviceProvider.GetRequiredService<IOptions<RouteOptions>>();
            Assert.Equal("TestRouteConstraint", accessor.Options.ConstraintMap["foo"].Name);
        }

        private class TestRouteConstraint : IRouteConstraint
        {
            public TestRouteConstraint(string pattern)
            {
                Pattern = pattern;
            }

            public string Pattern { get; private set; }
            public bool Match(HttpContext httpContext,
                              IRouter route,
                              string routeKey,
                              IDictionary<string, object> values,
                              RouteDirection routeDirection)
            {
                throw new NotImplementedException();
            }
        }
    }
}

Remove test the `[NotNull]` move makes irrelevant


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

namespace Dbot.Utility {
  public static class Settings {
    public const int MessageLogSize = 200; // aka context size
    public static readonly TimeSpan UserCommandInterval = TimeSpan.FromSeconds(10);

    public const int SelfSpamSimilarity = 75;
    public const int LongSpamSimilarity = 75;

    public const int SelfSpamContextLength = 15;
    public const int LongSpamContextLength = 26;

    public const int LongSpamMinimumLength = 40;
    public const int LongSpamLongerBanMultiplier = 3;

    public const double NukeStringDelta = 0.7;
    public const int NukeLoopWait = 2000;
    public const int AegisLoopWait = 250;
    public const int NukeDefaultDuration = 30;

    public static bool IsMono;
    public static string Timezone;
  }
}

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

namespace Dbot.Utility {
  public static class Settings {
    public const int MessageLogSize = 200; // aka context size
    public static readonly TimeSpan UserCommandInterval = TimeSpan.FromSeconds(10);

    public const int SelfSpamSimilarity = 75;
    public const int LongSpamSimilarity = 75;

    public const int SelfSpamContextLength = 15;
    public const int LongSpamContextLength = 26;

    public const int LongSpamMinimumLength = 40;
    public const int LongSpamLongerBanMultiplier = 3;

    public const double NukeStringDelta = 0.7;
    public const int NukeLoopWait = 0;
    public const int AegisLoopWait = 0;
    public const int NukeDefaultDuration = 30;

    public static bool IsMono;
    public static string Timezone;
  }
}

Set NukeLoopWait and AegisLoopWait to 0 as per sztanpet.


// 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.Screens;
using osu.Game.Overlays.FirstRunSetup;

namespace osu.Game.Tests.Visual.UserInterface
{
    public class TestSceneFirstRunScreenUIScale : OsuManualInputManagerTestScene
    {
        public TestSceneFirstRunScreenUIScale()
        {
            AddStep("load screen", () =>
            {
                Child = new ScreenStack(new ScreenUIScale());
            });
        }
    }
}

// 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.Allocation;
using osu.Framework.Screens;
using osu.Game.Overlays;
using osu.Game.Overlays.FirstRunSetup;

namespace osu.Game.Tests.Visual.UserInterface
{
    public class TestSceneFirstRunScreenUIScale : OsuManualInputManagerTestScene
    {
        [Cached]
        private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple);

        public TestSceneFirstRunScreenUIScale()
        {
            AddStep("load screen", () =>
            {
                Child = new ScreenStack(new ScreenUIScale());
            });
        }
    }
}

Add missing `OverlayColourProvider` in test scene


using Xunit;

namespace Farity.Tests
{
    public class AlwaysTests
    {
        [Fact]
        public void AlwaysReturnsAFunctionThatReturnsTheSameValueAlways()
        {
            var answerToLifeUniverseAndEverything = F.Always(42);
            var answer = answerToLifeUniverseAndEverything();
            Assert.Equal(answer, answerToLifeUniverseAndEverything());
            Assert.Equal(answer, answerToLifeUniverseAndEverything(1));
            Assert.Equal(answer, answerToLifeUniverseAndEverything("string", null));
            Assert.Equal(answer, answerToLifeUniverseAndEverything(null, "str", 3));
            Assert.Equal(answer, answerToLifeUniverseAndEverything(null, null, null, null));
        }
    }
}

using Xunit;

namespace Farity.Tests
{
    public class AlwaysTests
    {
        [Fact]
        public void AlwaysReturnsAFunctionThatReturnsTheSameValueAlways()
        {
            const int expected = 42;
            var answerToLifeUniverseAndEverything = F.Always(expected);
            Assert.Equal(expected, answerToLifeUniverseAndEverything());
            Assert.Equal(expected, answerToLifeUniverseAndEverything(1));
            Assert.Equal(expected, answerToLifeUniverseAndEverything("string", null));
            Assert.Equal(expected, answerToLifeUniverseAndEverything(null, "str", 3));
            Assert.Equal(expected, answerToLifeUniverseAndEverything(null, null, null, null));
        }
    }
}

Use expected in tests for F.Always

Use expected in tests for F.Always


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;

namespace osu.Game.Tournament.Tests
{
    public class TestCaseBeatmapPanel : OsuTestCase
    {
        [Resolved]
        private APIAccess api { get; set; } = null;

        [Resolved]
        private RulesetStore rulesets { get; set; } = null;

        [BackgroundDependencyLoader]
        private void load()
        {
            var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = 1091460 });
            req.Success += success;
            api.Queue(req);
        }

        private void success(APIBeatmap apiBeatmap)
        {
            var beatmap = apiBeatmap.ToBeatmap(rulesets);
            Add(new TournamentBeatmapPanel(beatmap)
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre
            });
        }
    }
}

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

using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;

namespace osu.Game.Tournament.Tests
{
    public class TestCaseBeatmapPanel : OsuTestCase
    {
        [Resolved]
        private APIAccess api { get; set; } = null;

        [Resolved]
        private RulesetStore rulesets { get; set; } = null;

        public override IReadOnlyList<Type> RequiredTypes => new[]
        {
            typeof(TournamentBeatmapPanel),
        };

        [BackgroundDependencyLoader]
        private void load()
        {
            var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = 1091460 });
            req.Success += success;
            api.Queue(req);
        }

        private void success(APIBeatmap apiBeatmap)
        {
            var beatmap = apiBeatmap.ToBeatmap(rulesets);
            Add(new TournamentBeatmapPanel(beatmap)
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre
            });
        }
    }
}

Allow dynamic recompilation of beatmap panel testcase


#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License

// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence

#endregion

using System;
using System.IO;
using Lokad.Cqrs.Core.Outbox;

namespace Lokad.Cqrs.Feature.FilePartition
{
    public sealed class FileQueueWriter : IQueueWriter
    {
        readonly DirectoryInfo _folder;
        readonly IEnvelopeStreamer _streamer;

        public string Name { get; private set; }

        public FileQueueWriter(DirectoryInfo folder, string name, IEnvelopeStreamer streamer)
        {
            _folder = folder;
            _streamer = streamer;
            Name = name;
        }

        public void PutMessage(ImmutableEnvelope envelope)
        {
            var fileName = string.Format("{0:yyyy-MM-dd-HH-mm-ss-ffff}-{1}", envelope.CreatedOnUtc, Guid.NewGuid());
            var full = Path.Combine(_folder.FullName, fileName);
            var data = _streamer.SaveEnvelopeData(envelope);
            File.WriteAllBytes(full, data);
        }
    }
}

#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License

// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence

#endregion

using System;
using System.IO;
using System.Threading;
using Lokad.Cqrs.Core.Outbox;

namespace Lokad.Cqrs.Feature.FilePartition
{
    public sealed class FileQueueWriter : IQueueWriter
    {
        readonly DirectoryInfo _folder;
        readonly IEnvelopeStreamer _streamer;

        public string Name { get; private set; }
        public readonly string Suffix ;

        public FileQueueWriter(DirectoryInfo folder, string name, IEnvelopeStreamer streamer)
        {
            _folder = folder;
            _streamer = streamer;
            Name = name;
            Suffix = Guid.NewGuid().ToString().Substring(0, 4);
        }

        static long UniversalCounter;

        public void PutMessage(ImmutableEnvelope envelope)
        {
            var id = Interlocked.Increment(ref UniversalCounter);
            var fileName = string.Format("{0:yyyy-MM-dd-HH-mm-ss}-{1:00000000}-{2}", envelope.CreatedOnUtc, id, Suffix);
            var full = Path.Combine(_folder.FullName, fileName);
            var data = _streamer.SaveEnvelopeData(envelope);
            File.WriteAllBytes(full, data);
        }
    }
}

Fix order of high-frequency messages on file queues


using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Glimpse.Agent
{
    public class RemoteHttpMessagePublisher : IMessagePublisher, IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly HttpClientHandler _httpHandler;

        public RemoteHttpMessagePublisher()
        {
            _httpHandler = new HttpClientHandler();
            _httpClient = new HttpClient(_httpHandler);
        }

        public void PublishMessage(IMessage message)
        {
            var content = new StringContent("Hello");

            // TODO: Try shifting to async and await
            // TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync

            _httpClient.PostAsJsonAsync("http://localhost:15999/Glimpse/Agent", message)
                .ContinueWith(requestTask =>
                    {
                        // Get HTTP response from completed task.
                        HttpResponseMessage response = requestTask.Result;

                        // Check that response was successful or throw exception
                        response.EnsureSuccessStatusCode();

                        // Read response asynchronously as JsonValue and write out top facts for each country
                        var result = response.Content.ReadAsStringAsync().Result;
                    });
        }

        public void Dispose()
        {
            _httpClient.Dispose();
            _httpHandler.Dispose();
        }
    }
}

using System;
using System.Net.Http;

namespace Glimpse.Agent
{
    public class RemoteHttpMessagePublisher : IMessagePublisher, IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly HttpClientHandler _httpHandler;

        public RemoteHttpMessagePublisher()
        {
            _httpHandler = new HttpClientHandler();
            _httpClient = new HttpClient(_httpHandler);
        }

        public void PublishMessage(IMessage message)
        {
            var content = new StringContent("Hello");

            // TODO: Try shifting to async and await
            // TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync

            _httpClient.PostAsJsonAsync("http://localhost:15999/Glimpse/Agent", message)
                .ContinueWith(requestTask =>
                    {
                        // Get HTTP response from completed task.
                        HttpResponseMessage response = requestTask.Result;

                        // Check that response was successful or throw exception
                        response.EnsureSuccessStatusCode();

                        // Read response asynchronously as JsonValue and write out top facts for each country
                        var result = response.Content.ReadAsStringAsync().Result;
                    });
        }

        public void Dispose()
        {
            _httpClient.Dispose();
            _httpHandler.Dispose();
        }
    }
}

Remove not used using statements

Remove not used using statements


using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.IO;

namespace AntlrGrammarEditor
{
    public class Grammar
    {
        public const string AntlrDotExt = ".g4";
        public const string ProjectDotExt = ".age";
        public const string LexerPostfix = "Lexer";
        public const string ParserPostfix = "Parser";

        public string Name { get; set; }

        public string Root { get; set; }

        public string FileExtension { get; set; } = "txt";

        public HashSet<Runtime> Runtimes = new HashSet<Runtime>();

        public bool SeparatedLexerAndParser { get; set; }

        public bool CaseInsensitive { get; set; }

        public bool Preprocessor { get; set; }

        public bool PreprocessorCaseInsensitive { get; set; }

        public string PreprocessorRoot { get; set; }

        public bool PreprocessorSeparatedLexerAndParser { get; set; }

        public List<string> Files { get; set; } = new List<string>();

        public List<string> TextFiles { get; set; } = new List<string>();

        public string Directory { get; set; } = "";
    }
}

using System.Collections.Generic;

namespace AntlrGrammarEditor
{
    public enum CaseInsensitiveType
    {
        None,
        lower,
        UPPER
    }

    public class Grammar
    {
        public const string AntlrDotExt = ".g4";
        public const string LexerPostfix = "Lexer";
        public const string ParserPostfix = "Parser";

        public string Name { get; set; }

        public string Root { get; set; }

        public string FileExtension { get; set; } = "txt";

        public HashSet<Runtime> Runtimes = new HashSet<Runtime>();

        public bool SeparatedLexerAndParser { get; set; }

        public CaseInsensitiveType CaseInsensitiveType { get; set; }

        public bool Preprocessor { get; set; }

        public bool PreprocessorCaseInsensitive { get; set; }

        public string PreprocessorRoot { get; set; }

        public bool PreprocessorSeparatedLexerAndParser { get; set; }

        public List<string> Files { get; set; } = new List<string>();

        public List<string> TextFiles { get; set; } = new List<string>();

        public string Directory { get; set; } = "";
    }
}

Add CaseInsensitiveType (None, lower, UPPER)