using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.ServiceProcess;
using System.Timers;
using NLog;

namespace ZBuildLightsUpdater
{
    public partial class ZBuildLightsUpdaterService : ServiceBase
    {
        private static readonly Logger Log = LogManager.GetCurrentClassLogger();
        private Timer _timer;
        private string _triggerUrl;

        public ZBuildLightsUpdaterService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            File.AppendAllLines(@"c:\var\ZBuildLights\_logs\servicelog.txt", new[] {"Service starting..."});
            Log.Info("ZBuildLights Updater Service Starting...");
            _timer = new Timer();
            var updateSeconds = Int32.Parse(ConfigurationManager.AppSettings["UpdateIntervalSeconds"]);
            _timer.Interval = TimeSpan.FromSeconds(updateSeconds).TotalMilliseconds;
            _timer.Elapsed += OnTimerElapsed;
            _timer.Start();

            _triggerUrl = ConfigurationManager.AppSettings["TriggerUrl"];

            Log.Info("ZBuildLights Updater Service Startup Complete.");
        }

        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            Log.Debug("Initiating status refresh...");
            var request = WebRequest.Create(_triggerUrl);
            request.GetResponse();
            Log.Debug("Status refresh complete.");
        }

        protected override void OnStop()
        {
            Log.Info("ZBuildLights Updater Service Stopping.");
        }
    }
}

using System;
using System.Configuration;
using System.Net;
using System.ServiceProcess;
using System.Timers;
using NLog;

namespace ZBuildLightsUpdater
{
    public partial class ZBuildLightsUpdaterService : ServiceBase
    {
        private static readonly Logger Log = LogManager.GetCurrentClassLogger();
        private Timer _timer;
        private string _triggerUrl;

        public ZBuildLightsUpdaterService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            Log.Info("ZBuildLights Updater Service Starting...");
            _timer = new Timer();
            var updateSeconds = Int32.Parse(ConfigurationManager.AppSettings["UpdateIntervalSeconds"]);
            _timer.Interval = TimeSpan.FromSeconds(updateSeconds).TotalMilliseconds;
            _timer.Elapsed += OnTimerElapsed;
            _timer.Start();

            _triggerUrl = ConfigurationManager.AppSettings["TriggerUrl"];

            Log.Info("ZBuildLights Updater Service Startup Complete.");
        }

        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            Log.Debug("Initiating status refresh...");
            var request = WebRequest.Create(_triggerUrl);
            request.GetResponse();
            Log.Debug("Status refresh complete.");
        }

        protected override void OnStop()
        {
            Log.Info("ZBuildLights Updater Service Stopping.");
        }
    }
}

Remove old logging line. Causes an exception if the directory doesn't exist.


using System.Linq;
using Microsoft.Bot.Connector;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.Bot.Builder.Tests
{
    [TestClass]
    public class ActivityExTests
    {
        [TestMethod]
        public void HasContent_Test()
        {
            IMessageActivity activity = DialogTestBase.MakeTestMessage();
            Assert.IsFalse(activity.HasContent());
            activity.Text = "test";
            Assert.IsTrue(activity.HasContent());

        }

        public void GetMentions_Test()
        {
            IMessageActivity activity = DialogTestBase.MakeTestMessage();
            Assert.IsFalse(activity.GetMentions().Any());
            activity.Entities.Add(new Mention() { Text = "testMention" });
            Assert.IsTrue(activity.GetMentions().Any());
            Assert.AreEqual("testMention", activity.GetMentions()[0].Text);
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using Microsoft.Bot.Connector;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;

namespace Microsoft.Bot.Builder.Tests
{
    [TestClass]
    public class ActivityExTests
    {
        [TestMethod]
        public void HasContent_Test()
        {
            IMessageActivity activity = DialogTestBase.MakeTestMessage();
            Assert.IsFalse(activity.HasContent());
            activity.Text = "test";
            Assert.IsTrue(activity.HasContent());

        }

        [TestMethod]
        public void GetMentions_Test()
        {
            IMessageActivity activity = DialogTestBase.MakeTestMessage();
            Assert.IsFalse(activity.GetMentions().Any());
            activity.Entities = new List<Entity> { new Mention() { Text = "testMention" } };
            // Cloning activity to resemble the incoming activity to bot
            var clonedActivity = JsonConvert.DeserializeObject<Activity>(JsonConvert.SerializeObject(activity));
            Assert.IsTrue(clonedActivity.GetMentions().Any());
            Assert.AreEqual("testMention", clonedActivity.GetMentions()[0].Text);
        }
    }
}

Fix getmentions tests and add missing TestMethod attribute


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

namespace ReaderHaskellDocsExample1
{
    using Bindings = IDictionary<string, int>;

    internal class Program
    {
        private static void Main()
        {
            var sampleBindings = new Dictionary<string, int>
                {
                    {"count", 3},
                    {"1", 1},
                    {"b", 2}
                };

            Console.Write("Count is correct for bindings " + FormatBindings(sampleBindings) + ": ");
            Console.WriteLine(IsCountCorrect(sampleBindings));
        }

        private static bool IsCountCorrect(Bindings bindings)
        {
            return CalcIsCountCorrect().RunReader(bindings);
        }

        private static Reader<Bindings, bool> CalcIsCountCorrect()
        {
            Func<Bindings, int> lookupVarPartiallyApplied = bindings => LookupVar("count", bindings);

            return Reader.Asks(lookupVarPartiallyApplied).Bind(
                count => Reader<Bindings>.Ask().Bind(
                    bindings => Reader<Bindings>.Return(
                        count == bindings.Count)));
        }

        private static int LookupVar(string name, Bindings bindings)
        {
            return bindings.GetValue(name).FromJust;
        }

        private static string FormatBindings(Bindings bindings)
        {
            Func<KeyValuePair<string, int>, string> formatBinding =
                kvp => string.Format("(\"{0}\",{1})", kvp.Key, kvp.Value);
            return string.Format("[{0}]", string.Join(",", bindings.Select(formatBinding)));
        }
    }
}

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

namespace ReaderHaskellDocsExample1
{
    using Bindings = IDictionary<string, int>;

    internal class Program
    {
        private static void Main()
        {
            var sampleBindings = new Dictionary<string, int>
                {
                    {"count", 3},
                    {"1", 1},
                    {"b", 2}
                };

            Console.Write("Count is correct for bindings " + FormatBindings(sampleBindings) + ": ");
            Console.WriteLine(IsCountCorrect(sampleBindings));
        }

        private static bool IsCountCorrect(Bindings bindings)
        {
            return CalcIsCountCorrect().RunReader(bindings);
        }

        private static Reader<Bindings, bool> CalcIsCountCorrect()
        {
            Func<string, Func<Bindings, int>> partiallyAppliedLookupVar = name => bindings => LookupVar(name, bindings);

            return Reader.Asks(partiallyAppliedLookupVar("count")).Bind(
                count => Reader<Bindings>.Ask().Bind(
                    bindings => Reader<Bindings>.Return(
                        count == bindings.Count)));
        }

        private static int LookupVar(string name, Bindings bindings)
        {
            return bindings.GetValue(name).FromJust;
        }

        private static string FormatBindings(Bindings bindings)
        {
            Func<KeyValuePair<string, int>, string> formatBinding =
                kvp => string.Format("(\"{0}\",{1})", kvp.Key, kvp.Value);
            return string.Format("[{0}]", string.Join(",", bindings.Select(formatBinding)));
        }
    }
}

Tweak to one of the demo programs

Tweak to one of the demo programs


using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Eto.Platform.iOS.Forms;
using Eto.Forms;

namespace Eto.Platform.iOS
{
	[MonoTouch.Foundation.Register("EtoAppDelegate")]
	public class EtoAppDelegate : UIApplicationDelegate
	{
		public EtoAppDelegate ()
		{
		}

		public override bool WillFinishLaunching (UIApplication application, NSDictionary launchOptions)
		{
			ApplicationHandler.Instance.Initialize(this);
			return true;
		}
	}
}

using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Eto.Platform.iOS.Forms;
using Eto.Forms;

namespace Eto.Platform.iOS
{
	[MonoTouch.Foundation.Register("EtoAppDelegate")]
	public class EtoAppDelegate : UIApplicationDelegate
	{
		public EtoAppDelegate ()
		{
		}

		public override bool FinishedLaunching (UIApplication application, NSDictionary launcOptions)
		{
			ApplicationHandler.Instance.Initialize(this);
			return true;
		}
	}
}

Fix running on < iOS 6.0

iOS: Fix running on < iOS 6.0


namespace NuGet.Common
{
    public class CommandLineRepositoryFactory : PackageRepositoryFactory
    {
        public static readonly string UserAgent = "NuGet Command Line";

        private readonly IConsole _console;

        public CommandLineRepositoryFactory(IConsole console)
        {
            _console = console;
        }

        public override IPackageRepository CreateRepository(string packageSource)
        {
            var repository = base.CreateRepository(packageSource);
            var httpClientEvents = repository as IHttpClientEvents;

            if (httpClientEvents != null)
            {
                httpClientEvents.SendingRequest += (sender, args) =>
                {
                    if (_console.Verbosity == Verbosity.Detailed)
                    {
                        _console.WriteLine(
                            System.ConsoleColor.Green,
                            "{0} {1}", args.Request.Method, args.Request.RequestUri);
                    }
                    string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent);
                    HttpUtility.SetUserAgent(args.Request, userAgent);
                };
            }

            return repository;
        }
    }
}

using System.Windows;

namespace NuGet.Common
{
    public class CommandLineRepositoryFactory : PackageRepositoryFactory, IWeakEventListener
    {
        public static readonly string UserAgent = "NuGet Command Line";

        private readonly IConsole _console;

        public CommandLineRepositoryFactory(IConsole console)
        {
            _console = console;
        }

        public override IPackageRepository CreateRepository(string packageSource)
        {
            var repository = base.CreateRepository(packageSource);
            var httpClientEvents = repository as IHttpClientEvents;
            if (httpClientEvents != null)
            {
                SendingRequestEventManager.AddListener(httpClientEvents, this);
            }

            return repository;
        }

        public bool ReceiveWeakEvent(System.Type managerType, object sender, System.EventArgs e)
        {
            if (managerType == typeof(SendingRequestEventManager))
            {
                var args = (WebRequestEventArgs)e;
                if (_console.Verbosity == Verbosity.Detailed)
                {
                    _console.WriteLine(
                        System.ConsoleColor.Green,
                        "{0} {1}", args.Request.Method, args.Request.RequestUri);
                }
                string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent);
                HttpUtility.SetUserAgent(args.Request, userAgent);
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

Fix the problem that the web request is displayed twice when -Verbosity is set to detailed.

The cause of the duplicate output is the change to fix issue 3801 (which
was caused by incorrect use of the weak  event handler pattern). With
that fix, the SendingRequest handler will be called twice. The fix is to
use the weak event handler pattern here too.


namespace DependencyInjection.Console
{
    internal class OddEvenPatternGenerator : IPatternGenerator
    {
        public Pattern Generate(int width, int height)
        {
            var generate = new Pattern(width, height);
            var squares = generate.Squares;

            for (var i = 0; i < squares.GetLength(0); ++i)
            {
                for (var j = 0; j < squares.GetLength(1); ++j)
                {
                    squares[i, j] = (i ^ j) % 2 == 0 ? Square.White : Square.Black;
                }
            }

            return generate;
        }
    }
}

namespace DependencyInjection.Console
{
    internal class OddEvenPatternGenerator : IPatternGenerator
    {
        public Pattern Generate(int width, int height)
        {
            var generate = new Pattern(width, height);
            var squares = generate.Squares;

            for (var i = 0; i < squares.GetLength(0); ++i)
            {
                for (var j = 0; j < squares.GetLength(1); ++j)
                {
                    squares[i, j] = ((i ^ j) & 1) == 0 ? Square.White : Square.Black;
                }
            }

            return generate;
        }
    }
}

Use bitwise operator (review by Clive)

Use bitwise operator (review by Clive)


// 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.Game.Configuration;

namespace osu.Game.Screens.Play.PlayerSettings
{
    public class InputSettings : PlayerSettingsGroup
    {
        private readonly PlayerCheckbox mouseButtonsCheckbox;

        public InputSettings()
            : base("Input Settings")
        {
            Children = new Drawable[]
            {
                mouseButtonsCheckbox = new PlayerCheckbox
                {
                    LabelText = "Disable mouse buttons"
                }
            };
        }

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config) => mouseButtonsCheckbox.Current = config.GetBindable<bool>(OsuSetting.MouseDisableButtons);
    }
}

// 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.Game.Configuration;
using osu.Game.Localisation;

namespace osu.Game.Screens.Play.PlayerSettings
{
    public class InputSettings : PlayerSettingsGroup
    {
        private readonly PlayerCheckbox mouseButtonsCheckbox;

        public InputSettings()
            : base("Input Settings")
        {
            Children = new Drawable[]
            {
                mouseButtonsCheckbox = new PlayerCheckbox
                {
                    LabelText = MouseSettingsStrings.DisableMouseButtons
                }
            };
        }

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config) => mouseButtonsCheckbox.Current = config.GetBindable<bool>(OsuSetting.MouseDisableButtons);
    }
}

Update player loader screen mouse disable text to use localised version


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

namespace SFA.DAS.Reservations.Api.Types
{
    public class ReservationAllocationStatusResult
    {
        public bool AutoReservations { get; set; }
    }
}

namespace SFA.DAS.Reservations.Api.Types
{
    public class ReservationAllocationStatusResult
    {
        public bool CanAutoCreateReservations { get; set; }
    }
}

Update automatic reservations flag to match what has been implemented


using System;
using System.Net;
using System.Net.Http;

namespace Kudu.Client
{
    public static class HttpResponseMessageExtensions
    {
        /// <summary>
        /// Determines if the HttpResponse is successful, throws otherwise.
        /// </summary>
        public static HttpResponseMessage EnsureSuccessful(this HttpResponseMessage httpResponseMessage)
        {
            if (httpResponseMessage.StatusCode == HttpStatusCode.InternalServerError)
            {
                // For 500, we serialize the exception message on the server.
                var exceptionMessage = httpResponseMessage.Content.ReadAsAsync<HttpExceptionMessage>().Result;
                exceptionMessage.StatusCode = httpResponseMessage.StatusCode;
                exceptionMessage.ReasonPhrase = httpResponseMessage.ReasonPhrase;

                throw new HttpUnsuccessfulRequestException(exceptionMessage);
            }
            return httpResponseMessage.EnsureSuccessStatusCode();
        }
    }

    public class HttpExceptionMessage
    {
        public HttpStatusCode StatusCode { get; set; }

        public string ReasonPhrase { get; set; }

        public string ExceptionMessage { get; set; }

        public string ExceptionType { get; set; }
    }

    public class HttpUnsuccessfulRequestException : HttpRequestException
    {
        public HttpUnsuccessfulRequestException()
            : this(null)
        {
        }

        public HttpUnsuccessfulRequestException(HttpExceptionMessage responseMessage)
            : base(
                responseMessage != null ?
                    String.Format("{0}: {1}\nStatus Code: {2}", responseMessage.ReasonPhrase, responseMessage.ExceptionMessage, responseMessage.StatusCode) :
                    null)
        {
            ResponseMessage = responseMessage;
        }

        public HttpExceptionMessage ResponseMessage { get; private set; }
    }
}

using System;
using System.Net;
using System.Net.Http;

namespace Kudu.Client
{
    public static class HttpResponseMessageExtensions
    {
        /// <summary>
        /// Determines if the HttpResponse is successful, throws otherwise.
        /// </summary>
        public static HttpResponseMessage EnsureSuccessful(this HttpResponseMessage httpResponseMessage)
        {
            if (httpResponseMessage.StatusCode == HttpStatusCode.InternalServerError)
            {
                // For 500, we serialize the exception message on the server.
                HttpExceptionMessage exceptionMessage;
                try
                {
                    exceptionMessage = httpResponseMessage.Content.ReadAsAsync<HttpExceptionMessage>().Result;
                }
                catch (InvalidOperationException ex)
                {
                    // This would happen if the response type is not a Json object.
                    throw new HttpRequestException(httpResponseMessage.Content.ReadAsStringAsync().Result, ex);
                }
                exceptionMessage.StatusCode = httpResponseMessage.StatusCode;
                exceptionMessage.ReasonPhrase = httpResponseMessage.ReasonPhrase;

                throw new HttpUnsuccessfulRequestException(exceptionMessage);
            }
            return httpResponseMessage.EnsureSuccessStatusCode();
        }
    }

    public class HttpExceptionMessage
    {
        public HttpStatusCode StatusCode { get; set; }

        public string ReasonPhrase { get; set; }

        public string ExceptionMessage { get; set; }

        public string ExceptionType { get; set; }
    }

    public class HttpUnsuccessfulRequestException : HttpRequestException
    {
        public HttpUnsuccessfulRequestException()
            : this(null)
        {
        }

        public HttpUnsuccessfulRequestException(HttpExceptionMessage responseMessage)
            : base(
                responseMessage != null ?
                    String.Format("{0}: {1}\nStatus Code: {2}", responseMessage.ReasonPhrase, responseMessage.ExceptionMessage, responseMessage.StatusCode) :
                    null)
        {
            ResponseMessage = responseMessage;
        }

        public HttpExceptionMessage ResponseMessage { get; private set; }
    }
}

Print out the response as a string when the exception is not JSON


using System;
using System.Diagnostics.Contracts;

namespace Cogito
{

    public static class ExceptionExtensions
    {

        /// <summary>
        /// Traces the exception to the default trace source as an error.
        /// </summary>
        /// <param name="self"></param>
        public static void Trace(this Exception self)
        {
            Contract.Requires<ArgumentNullException>(self != null);

            System.Diagnostics.Trace.TraceError("{0:HH:mm:ss.fff} {1} {2}", DateTime.Now, self.GetType().FullName, self);
        }

    }

}

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

namespace Cogito
{

    public static class ExceptionExtensions
    {

        /// <summary>
        /// Traces the exception to the default trace source as an error.
        /// </summary>
        /// <param name="self"></param>
        public static void Trace(this Exception self)
        {
            Contract.Requires<ArgumentNullException>(self != null);

            System.Diagnostics.Trace.TraceError("{0:HH:mm:ss.fff} {1} {2}", DateTime.Now, self.GetType().FullName, self);
        }

        /// <summary>
        /// Unpacks any InnerExceptions hidden by <see cref="AggregateException"/>.
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static IEnumerable<Exception> Expand(this Exception e)
        {
            var ae = e as AggregateException;
            if (ae != null)
                foreach (var aee in Expand(ae))
                    yield return aee;
            else
                yield return e;
        }

    }

}

Make sure to expand out exceptions.

Make sure to expand out exceptions.


using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;

namespace Promact.Trappist.Core.Controllers
{
    [Route("api/question")]
    public class QuestionsController : Controller
    {
        private readonly IQuestionRepository _questionsRepository;
        public QuestionsController(IQuestionRepository questionsRepository)
        {
            _questionsRepository = questionsRepository;
        }

        [HttpGet]
        /// <summary>
        /// Gets all questions
        /// </summary>
        /// <returns>Questions list</returns>
        public IActionResult GetQuestions()
        {
            var questions = _questionsRepository.GetAllQuestions();
            return Json(questions);
        }
        [HttpPost]
        /// <summary>
        ///
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
            return Ok();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
            return Ok();
        }
    }
}

using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;

namespace Promact.Trappist.Core.Controllers
{
    [Route("api/question")]
    public class QuestionsController : Controller
    {
        private readonly IQuestionRepository _questionsRepository;
        public QuestionsController(IQuestionRepository questionsRepository)
        {
            _questionsRepository = questionsRepository;
        }

        [HttpGet]
        /// <summary>
        /// Gets all questions
        /// </summary>
        /// <returns>Questions list</returns>
        public IActionResult GetQuestions()
        {
            var questions = _questionsRepository.GetAllQuestions();
            return Json(questions);
        }

        [HttpPost]
        /// <summary>
        /// Add single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
            return Ok();
        }

        /// <summary>
        /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestionOption"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
            return Ok();
        }
    }
}

Update server side API for single multiple answer question


using System;
using System.Collections.Generic;

namespace Equality {
	public struct StructEqualityComparer<T> : IEqualityComparer<T> where T : struct {
		public static StructEqualityComparer<T> Default = new StructEqualityComparer<T>();

		public Boolean Equals(T x, T y) => Struct.Equals(ref x, ref y);
		public Int32 GetHashCode(T x) => Struct.GetHashCode(ref x);

		public Boolean Equals(ref T x, ref T y) => Struct.Equals(ref x, ref y);
		public Int32 GetHashCode(ref T x) => Struct.GetHashCode(ref x);
	}
}

using System;
using System.Collections.Generic;

namespace Equality {
	public struct StructEqualityComparer<T> : IEqualityComparer<T> where T : struct {
		public static StructEqualityComparer<T> Default = new StructEqualityComparer<T>();

		public Boolean Equals(T x, T y) => Struct.Equals(ref x, ref y);
		public Int32 GetHashCode(T x) => Struct.GetHashCode(ref x);

		public static Boolean Equals(ref T x, ref T y) => Struct.Equals(ref x, ref y);
		public static Int32 GetHashCode(ref T x) => Struct.GetHashCode(ref x);
	}
}

Make the two extra ByRef value-type equality comparer methods static


// 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 System.IO;
using osu.Framework.IO.Network;

namespace osu.Game.Online.API
{
    public abstract class APIDownloadRequest : APIRequest
    {
        private string filename;

        protected override WebRequest CreateWebRequest()
        {
            var request = new FileWebRequest(filename = Path.GetTempFileName(), Uri);
            request.DownloadProgress += request_Progress;
            return request;
        }

        private void request_Progress(long current, long total) => API.Schedule(() => Progressed?.Invoke(current, total));

        protected APIDownloadRequest()
        {
            base.Success += onSuccess;
        }

        private void onSuccess()
        {
            Success?.Invoke(filename);
        }

        public event APIProgressHandler Progressed;

        public new event APISuccessHandler<string> Success;
    }
}

// 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 System.IO;
using osu.Framework.IO.Network;

namespace osu.Game.Online.API
{
    public abstract class APIDownloadRequest : APIRequest
    {
        private string filename;

        /// <summary>
        /// Sets the extension of the file outputted by this request.
        /// </summary>
        protected virtual string FileExtension { get; } = @".tmp";

        protected override WebRequest CreateWebRequest()
        {
            var file = Path.GetTempFileName();

            File.Move(file, filename = Path.ChangeExtension(file, FileExtension));

            var request = new FileWebRequest(filename, Uri);
            request.DownloadProgress += request_Progress;
            return request;
        }

        private void request_Progress(long current, long total) => API.Schedule(() => Progressed?.Invoke(current, total));

        protected APIDownloadRequest()
        {
            base.Success += onSuccess;
        }

        private void onSuccess()
        {
            Success?.Invoke(filename);
        }

        public event APIProgressHandler Progressed;

        public new event APISuccessHandler<string> Success;
    }
}

Add ability to change the flie extension of API download requests


// 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 System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;

namespace osu.Framework.Tests.Audio
{
    [TestFixture]
    public class AudioCollectionManagerTest
    {
        [Test]
        public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
        {
            var manager = new AudioCollectionManager<AdjustableAudioComponent>();

            // add a huge amount of items to the queue
            for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent());

            // in a seperate thread start processing the queue
            new Thread(() => manager.Update()).Start();

            // wait a little for beginning of the update to start
            Thread.Sleep(4);

            Assert.DoesNotThrow(() => manager.Dispose());
        }

        private class TestingAdjustableAudioComponent : AdjustableAudioComponent
        {
        }
    }
}

// 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 System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;

namespace osu.Framework.Tests.Audio
{
    [TestFixture]
    public class AudioCollectionManagerTest
    {
        [Test]
        public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
        {
            var manager = new TestAudioCollectionManager();

            var threadExecutionFinished = new ManualResetEventSlim();
            var updateLoopStarted = new ManualResetEventSlim();

            // add a huge amount of items to the queue
            for (int i = 0; i < 10000; i++)
                manager.AddItem(new TestingAdjustableAudioComponent());

            // in a separate thread start processing the queue
            var thread = new Thread(() =>
            {
                while (!manager.IsDisposed)
                {
                    manager.Update();
                    updateLoopStarted.Set();
                }

                threadExecutionFinished.Set();
            });

            thread.Start();

            Assert.IsTrue(updateLoopStarted.Wait(1000));

            Assert.DoesNotThrow(() => manager.Dispose());

            Assert.IsTrue(threadExecutionFinished.Wait(1000));
        }

        private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent>
        {
            public new bool IsDisposed => base.IsDisposed;
        }

        private class TestingAdjustableAudioComponent : AdjustableAudioComponent
        {
        }
    }
}

Improve reliability of test by using semaphores


using System;
using System.Collections.Generic;

namespace Additio.Configuration
{
    public class Node
    {
        public const string IncludeFolderPath = @"App_Config\Include";

        public string FilePath { get; set; }

        public string RelativePath => FilePath.Remove(0, FilePath.IndexOf(IncludeFolderPath, StringComparison.OrdinalIgnoreCase) + 19);

        public List<Node> Dependencies { get; } = new List<Node>();
    }
}

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

namespace Additio.Configuration
{
    [DebuggerDisplay("{RelativePath}")]
    public class Node
    {
        private string Root { get; }

        public Node(string root)
        {
            if (!root.EndsWith("\\"))
                root += "\\";
            Root = root;
        }

        public string FilePath { get; set; }

        public string RelativePath => FilePath.Replace(Root, "");

        public List<Node> Dependencies { get; } = new List<Node>();
    }
}

Make node root path variable and add debugger display


using System;
using System.IO.Ports;
using MYCroes.ATCommands;
using MYCroes.ATCommands.Forwarding;

namespace SupportManager.Control
{
    public class ATHelper : IDisposable
    {
        private readonly SerialPort serialPort;

        public ATHelper(string port)
        {
            serialPort = new SerialPort(port);
            serialPort.Open();
        }

        public void ForwardTo(string phoneNumberWithInternationalAccessCode)
        {
            var cmd = ForwardingStatus.Set(ForwardingReason.Unconditional, ForwardingMode.Registration,
                phoneNumberWithInternationalAccessCode, ForwardingPhoneNumberType.WithInternationalAccessCode,
                ForwardingClass.Voice);

            Execute(cmd);
        }

        public string GetForwardedPhoneNumber()
        {
            var cmd = ForwardingStatus.Query(ForwardingReason.Unconditional);
            var res = Execute(cmd);

            return ForwardingStatus.Parse(res[0]).Number;
        }

        private string[] Execute(ATCommand command)
        {
            var stream = serialPort.BaseStream;
            stream.ReadTimeout = 10000;
            stream.WriteTimeout = 10000;

            return command.Execute(stream);
        }

        public void Dispose()
        {
            if (serialPort.IsOpen) serialPort.Close();

            serialPort.Dispose();
        }
    }
}

using System;
using System.IO.Ports;
using MYCroes.ATCommands;
using MYCroes.ATCommands.Forwarding;

namespace SupportManager.Control
{
    public class ATHelper : IDisposable
    {
        private readonly SerialPort serialPort;

        public ATHelper(string portConnectionString)
        {
            serialPort = SerialPortFactory.CreateFromConnectionString(portConnectionString);
            serialPort.Open();
        }

        public ATHelper(SerialPort port)
        {
            serialPort = port;
            port.Open();
        }

        public void ForwardTo(string phoneNumberWithInternationalAccessCode)
        {
            var cmd = ForwardingStatus.Set(ForwardingReason.Unconditional, ForwardingMode.Registration,
                phoneNumberWithInternationalAccessCode, ForwardingPhoneNumberType.WithInternationalAccessCode,
                ForwardingClass.Voice);

            Execute(cmd);
        }

        public string GetForwardedPhoneNumber()
        {
            var cmd = ForwardingStatus.Query(ForwardingReason.Unconditional);
            var res = Execute(cmd);

            return ForwardingStatus.Parse(res[0]).Number;
        }

        private string[] Execute(ATCommand command)
        {
            var stream = serialPort.BaseStream;
            stream.ReadTimeout = 10000;
            stream.WriteTimeout = 10000;

            return command.Execute(stream);
        }

        public void Dispose()
        {
            if (serialPort.IsOpen) serialPort.Close();

            serialPort.Dispose();
        }
    }
}

Replace SerialPort construction with factory invocation

Allows properties to be set on the SerialPort while preserving backward
compatibility (i.e. "COM3" is still valid).


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EndlessAges.LauncherService.Controllers
{
	/// <summary>
	/// Emulated controller ContentManager.aspx from the Endless Ages backend.
	/// </summary>
	[Route("ContentManager.aspx")]
	public class ContentManager : Controller
	{

	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EndlessAges.LauncherService.Controllers
{
	/// <summary>
	/// Emulated controller ContentManager.aspx from the Endless Ages backend.
	/// </summary>
	[Route("ContentManager.aspx")]
	public class ContentManager : Controller
	{
		//ContentManager.aspx?installer_patcher=ENDLESS
		[HttpGet]
		public IActionResult Get([FromQuery]string installer_patcher)
		{
			//If no valid parameter was provided in the query then return an error code
			//This should only happen if someone is spoofing
			//422 (Unprocessable Entity)
			if (string.IsNullOrWhiteSpace(installer_patcher))
				return StatusCode(422);

			//TODO: What exactly should the backend return? EACentral returns a broken url
			return Content($"{@"http://game1.endlessagesonline./ENDLESSINSTALL.cab"}\n{@"ENDLESSINSTALL.cab"}");
		}
	}
}

Add installer_patcher get controller method

ContentManager.aspx?installer_patcher=ENDLESS


// 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 Markdig.Extensions.Yaml;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Game.Graphics.Containers.Markdown;

namespace osu.Game.Overlays.Wiki.Markdown
{
    public class WikiMarkdownContainer : OsuMarkdownContainer
    {
        public string CurrentPath
        {
            set => Schedule(() => DocumentUrl += $"wiki/{value}");
        }

        protected override void AddMarkdownComponent(IMarkdownObject markdownObject, FillFlowContainer container, int level)
        {
            switch (markdownObject)
            {
                case YamlFrontMatterBlock yamlFrontMatterBlock:
                    container.Add(CreateNotice(yamlFrontMatterBlock));
                    break;

                default:
                    base.AddMarkdownComponent(markdownObject, container, level);
                    break;
            }
        }

        public override MarkdownTextFlowContainer CreateTextFlow() => new WikiMarkdownTextFlowContainer();

        protected override MarkdownParagraph CreateParagraph(ParagraphBlock paragraphBlock, int level) => new WikiMarkdownParagraph(paragraphBlock);

        protected virtual FillFlowContainer CreateNotice(YamlFrontMatterBlock yamlFrontMatterBlock) => new WikiNoticeContainer(yamlFrontMatterBlock);

        private class WikiMarkdownTextFlowContainer : OsuMarkdownTextFlowContainer
        {
            protected override void AddImage(LinkInline linkInline) => AddDrawable(new WikiMarkdownImage(linkInline));
        }
    }
}

// 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 Markdig.Extensions.Yaml;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Game.Graphics.Containers.Markdown;

namespace osu.Game.Overlays.Wiki.Markdown
{
    public class WikiMarkdownContainer : OsuMarkdownContainer
    {
        public string CurrentPath
        {
            set => Schedule(() => DocumentUrl += $"wiki/{value}");
        }

        protected override void AddMarkdownComponent(IMarkdownObject markdownObject, FillFlowContainer container, int level)
        {
            switch (markdownObject)
            {
                case YamlFrontMatterBlock yamlFrontMatterBlock:
                    container.Add(CreateNotice(yamlFrontMatterBlock));
                    return;
            }

            base.AddMarkdownComponent(markdownObject, container, level);
        }

        public override MarkdownTextFlowContainer CreateTextFlow() => new WikiMarkdownTextFlowContainer();

        protected override MarkdownParagraph CreateParagraph(ParagraphBlock paragraphBlock, int level) => new WikiMarkdownParagraph(paragraphBlock);

        protected virtual FillFlowContainer CreateNotice(YamlFrontMatterBlock yamlFrontMatterBlock) => new WikiNoticeContainer(yamlFrontMatterBlock);

        private class WikiMarkdownTextFlowContainer : OsuMarkdownTextFlowContainer
        {
            protected override void AddImage(LinkInline linkInline) => AddDrawable(new WikiMarkdownImage(linkInline));
        }
    }
}

Split out `base` call from `switch` statement


using NUnit.Framework;
using System.Web.Mvc;
using System.Web.Routing;

using Zk.Helpers;

namespace Zk.Tests
{
    [TestFixture]
    public class UrlHelperExtensionTest
    {

        [Test]
        public void UrlHelper_CreatePartialViewName()
        {
            // ARRANGE
            var httpContext = MvcMockHelpers.MockHttpContext();
            var routeData = new RouteData();
            var requestContext = new RequestContext(httpContext, routeData);
            var urlHelper = new UrlHelper(requestContext);

            // ACT
            var expected = "~/Views/Controller/_PartialView.cshtml";
            var actual = urlHelper.View("_PartialView", "Controller");

            // ASSERT
            Assert.AreEqual(expected, actual,
                "The UrlpHelper View extension should return the path to the partial view.");
        }

    }
}

using NUnit.Framework;
using System.Web.Mvc;
using System.Web.Routing;

using Zk.Helpers;

namespace Zk.Tests
{
    [Ignore]
    [TestFixture]
    public class UrlHelperExtensionTest
    {

        [Test]
        public void UrlHelper_CreatePartialViewName()
        {
            // ARRANGE
            var httpContext = MvcMockHelpers.MockHttpContext();
            var routeData = new RouteData();
            var requestContext = new RequestContext(httpContext, routeData);
            var urlHelper = new UrlHelper(requestContext);

            // ACT
            var expected = "~/Views/Controller/_PartialView.cshtml";
            var actual = urlHelper.View("_PartialView", "Controller");

            // ASSERT
            Assert.AreEqual(expected, actual,
                "The UrlpHelper View extension should return the path to the partial view.");
        }

    }
}

Add ignore attribute to test which for some reason fails when it is run together with other tests


using System.Linq;
using System.Web.Http;
using System.Web.Http.OData;
using NuGet.Lucene.Web.Models;
using NuGet.Lucene.Web.Util;

namespace NuGet.Lucene.Web.Controllers
{
    /// <summary>
    /// OData provider for Lucene based NuGet package repository.
    /// </summary>
    public class PackagesODataController : ODataController
    {
        public ILucenePackageRepository Repository { get; set; }

        [Queryable]
        public IQueryable<ODataPackage> Get()
        {
            return Repository.LucenePackages.Select(p => p.AsDataServicePackage()).AsQueryable();
        }

        public object Get([FromODataUri] string id, [FromODataUri] string version)
        {
            SemanticVersion semanticVersion;
            if (!SemanticVersion.TryParse(version, out semanticVersion))
            {
                return BadRequest("Invalid version");
            }

            if (string.IsNullOrWhiteSpace(id))
            {
                return BadRequest("Invalid package id");
            }

            var package = Repository.FindPackage(id, semanticVersion);

            return package == null ? (object)NotFound() : package.AsDataServicePackage();
        }
    }
}

using System.Linq;
using System.Web.Http;
using System.Web.Http.OData;
using NuGet.Lucene.Web.Models;
using NuGet.Lucene.Web.Util;

namespace NuGet.Lucene.Web.Controllers
{
    /// <summary>
    /// OData provider for Lucene based NuGet package repository.
    /// </summary>
    public class PackagesODataController : ODataController
    {
        public ILucenePackageRepository Repository { get; set; }
        public IMirroringPackageRepository MirroringRepository { get; set; }

        [Queryable]
        public IQueryable<ODataPackage> Get()
        {
            return Repository.LucenePackages.Select(p => p.AsDataServicePackage()).AsQueryable();
        }

        public object Get([FromODataUri] string id, [FromODataUri] string version)
        {
            SemanticVersion semanticVersion;
            if (!SemanticVersion.TryParse(version, out semanticVersion))
            {
                return BadRequest("Invalid version");
            }

            if (string.IsNullOrWhiteSpace(id))
            {
                return BadRequest("Invalid package id");
            }

            var package = MirroringRepository.FindPackage(id, semanticVersion);

            return package == null ? (object)NotFound() : package.AsDataServicePackage();
        }
    }
}

Use MirroringPackageRepository to auto-mirror packages in OData lookup.


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

namespace MalApi.IntegrationTests
{
    public class GetRecentOnlineUsersTest
    {
        public void GetRecentOnlineUsers()
        {
            using (MyAnimeListApi api = new MyAnimeListApi())
            {
                RecentUsersResults results = api.GetRecentOnlineUsers();
                Assert.NotEmpty(results.RecentUsers);
            }
        }
    }
}

/*
 Copyright 2017 Greg Najda

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

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

namespace MalApi.IntegrationTests
{
    public class GetRecentOnlineUsersTest
    {
        [Fact]
        public void GetRecentOnlineUsers()
        {
            using (MyAnimeListApi api = new MyAnimeListApi())
            {
                RecentUsersResults results = api.GetRecentOnlineUsers();
                Assert.NotEmpty(results.RecentUsers);
            }
        }
    }
}

/*
 Copyright 2017 Greg Najda

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

Add [Fact] attribute to a test that was missing it, regaining coverage.


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

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

namespace Internal.StackGenerator.Dia
{
    internal static class Guids
    {
        public static readonly IEnumerable<Guid> DiaSource_CLSIDs =
            new Guid[]
            {
                new Guid("3BFCEA48-620F-4B6B-81F7-B9AF75454C7D"),  // msdia120.dll
                new Guid("761D3BCD-1304-41D5-94E8-EAC54E4AC172"),  // msdia110.dll
            };

        public static readonly Guid IID_IDiaDataSource = new Guid("79F1BB5F-B66E-48E5-B6A9-1545C323CA3D");
    }
}

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

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

namespace Internal.StackGenerator.Dia
{
    internal static class Guids
    {
        public static readonly IEnumerable<Guid> DiaSource_CLSIDs =
            new Guid[]
            {
                new Guid("E6756135-1E65-4D17-8576-610761398C3C"),  // msdia140.dll
                new Guid("3BFCEA48-620F-4B6B-81F7-B9AF75454C7D"),  // msdia120.dll
            };

        public static readonly Guid IID_IDiaDataSource = new Guid("79F1BB5F-B66E-48E5-B6A9-1545C323CA3D");
    }
}

Add support for MSDIA140 to DIA-based CoreRT/.NETNative StackTraceGenerator on Windows

Include the CLSID of MSDIA140 in the lookup for IDiaSource to enable DIA-based symbolic exception stack traces on machines with new VS installation that only include msdia140.

[tfs-changeset: 1650741]


using MultiMiner.CoinApi.Data;
using MultiMiner.Xgminer.Data;
using Newtonsoft.Json.Linq;
using System.Linq;

namespace MultiMiner.WhatMine.Extensions
{
    public static class CoinInformationExtensions
    {
        public static void PopulateFromJson(this CoinInformation coinInformation, JToken jToken)
        {
            coinInformation.Symbol = jToken.Value<string>("market_code");
            coinInformation.Name = jToken.Value<string>("name");

            string algorithm = jToken.Value<string>("algorithm");
            coinInformation.Algorithm = FixAlgorithmName(algorithm);

            coinInformation.CurrentBlocks = jToken.Value<int>("height");
            coinInformation.Difficulty = jToken.Value<double>("difficulty");
            coinInformation.Reward = jToken.Value<double>("reward");
            coinInformation.Exchange = jToken.Value<string>("exchange_name");
            coinInformation.Income = jToken.Value<double>("btc_per_day");

            if (coinInformation.Symbol.Equals("BTC", System.StringComparison.OrdinalIgnoreCase))
                coinInformation.Price = 1;
            else
                coinInformation.Price = jToken.Value<double>("exchange_rate");
        }

        private static string FixAlgorithmName(string algorithm)
        {
            string result = algorithm;
            if (algorithm.Equals(ApiContext.ScryptNFactor, System.StringComparison.OrdinalIgnoreCase))
                result = AlgorithmFullNames.ScryptN;
            else
            {
                var knownAlgorithm = KnownAlgorithms.Algorithms.Single(a => a.Name.Equals(algorithm, System.StringComparison.OrdinalIgnoreCase));
                result = knownAlgorithm.FullName;
            }
            return result;
        }
    }
}

using MultiMiner.CoinApi.Data;
using MultiMiner.Xgminer.Data;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;

namespace MultiMiner.WhatMine.Extensions
{
    public static class CoinInformationExtensions
    {
        public static void PopulateFromJson(this CoinInformation coinInformation, JToken jToken)
        {
            coinInformation.Symbol = jToken.Value<string>("market_code");
            coinInformation.Name = jToken.Value<string>("name");

            string algorithm = jToken.Value<string>("algorithm");
            coinInformation.Algorithm = FixAlgorithmName(algorithm);

            coinInformation.CurrentBlocks = jToken.Value<int>("height");
            coinInformation.Difficulty = jToken.Value<double>("difficulty");
            coinInformation.Reward = jToken.Value<double>("reward");
            coinInformation.Exchange = jToken.Value<string>("exchange_name");
            coinInformation.Income = jToken.Value<double>("btc_per_day");

            if (coinInformation.Symbol.Equals("BTC", System.StringComparison.OrdinalIgnoreCase))
                coinInformation.Price = 1;
            else
                coinInformation.Price = jToken.Value<double>("exchange_rate");
        }

        private static string FixAlgorithmName(string algorithm)
        {
            string result = algorithm;
            if (algorithm.Equals(ApiContext.ScryptNFactor, StringComparison.OrdinalIgnoreCase))
                result = AlgorithmFullNames.ScryptN;
            else
            {
                KnownAlgorithm knownAlgorithm = KnownAlgorithms.Algorithms.SingleOrDefault(a => a.Name.Equals(algorithm, StringComparison.OrdinalIgnoreCase));
                if (knownAlgorithm != null) result = knownAlgorithm.FullName;
            }
            return result;
        }
    }
}

Use SingleOrDefault as we may not know all WhatMine.com algorithms


using System.Windows.Forms;
using TweetDuck.Core.Controls;
using TweetDuck.Plugins;
using TweetDuck.Resources;

namespace TweetDuck.Core.Notification.Example{
    sealed class FormNotificationExample : FormNotificationMain{
        public override bool RequiresResize => true;
        protected override bool CanDragWindow => Program.UserConfig.NotificationPosition == TweetNotification.Position.Custom;

        protected override FormBorderStyle NotificationBorderStyle{
            get{
                if (Program.UserConfig.NotificationSize == TweetNotification.Size.Custom){
                    switch(base.NotificationBorderStyle){
                        case FormBorderStyle.FixedSingle: return FormBorderStyle.Sizable;
                        case FormBorderStyle.FixedToolWindow: return FormBorderStyle.SizableToolWindow;
                    }
                }

                return base.NotificationBorderStyle;
            }
        }

        private readonly TweetNotification exampleNotification;

        public FormNotificationExample(FormBrowser owner, PluginManager pluginManager) : base(owner, pluginManager, false){
            string exampleTweetHTML = ScriptLoader.LoadResource("pages/example.html", true).Replace("{avatar}", TweetNotification.AppLogoLink);

            #if DEBUG
            exampleTweetHTML = exampleTweetHTML.Replace("
", @"

Scrollbar test padding...
");
            #endif

            exampleNotification = TweetNotification.Example(exampleTweetHTML, 176);
        }

        public override void HideNotification(){
            Location = ControlExtensions.InvisibleLocation;
        }

        public void ShowExampleNotification(bool reset){
            if (reset){
                LoadTweet(exampleNotification);
            }
            else{
                PrepareAndDisplayWindow();
            }

            UpdateTitle();
        }
    }
}

using System.Windows.Forms;
using TweetDuck.Core.Controls;
using TweetDuck.Plugins;
using TweetDuck.Resources;

namespace TweetDuck.Core.Notification.Example{
    sealed class FormNotificationExample : FormNotificationMain{
        public override bool RequiresResize => true;
        protected override bool CanDragWindow => Program.UserConfig.NotificationPosition == TweetNotification.Position.Custom;

        protected override FormBorderStyle NotificationBorderStyle{
            get{
                if (Program.UserConfig.NotificationSize == TweetNotification.Size.Custom){
                    switch(base.NotificationBorderStyle){
                        case FormBorderStyle.FixedSingle: return FormBorderStyle.Sizable;
                        case FormBorderStyle.FixedToolWindow: return FormBorderStyle.SizableToolWindow;
                    }
                }

                return base.NotificationBorderStyle;
            }
        }

        private readonly TweetNotification exampleNotification;

        public FormNotificationExample(FormBrowser owner, PluginManager pluginManager) : base(owner, pluginManager, false){
            string exampleTweetHTML = ScriptLoader.LoadResource("pages/example.html", true).Replace("{avatar}", TweetNotification.AppLogoLink);

            #if DEBUG
            exampleTweetHTML = exampleTweetHTML.Replace("
", @"

Scrollbar test padding...
");
            #endif

            exampleNotification = TweetNotification.Example(exampleTweetHTML, 176);
        }

        public override void HideNotification(){
            Location = ControlExtensions.InvisibleLocation;
        }

        public override void FinishCurrentNotification(){}

        public void ShowExampleNotification(bool reset){
            if (reset){
                LoadTweet(exampleNotification);
            }
            else{
                PrepareAndDisplayWindow();
            }

            UpdateTitle();
        }
    }
}

Fix example notification timer breaking on skip (forward mouse button or Enter)


using System;
using EPiServer.Framework.Localization;
using EPiServer.ServiceLocation;
using EPiServer.Web;

namespace AlloyDemoKit.Business.Channels
{
    /// <summary>
    /// Base class for all resolution definitions
    /// </summary>
    public abstract class DisplayResolutionBase : IDisplayResolution
    {
        private Injected<LocalizationService> LocalizationService { get; set; }
        private static object syncLock = new Object();

        protected DisplayResolutionBase(string name, int width, int height)
        {
            Id = GetType().FullName;
            Name = Translate(name);
            Width = width;
            Height = height;
        }

        /// <summary>
        /// Gets the unique ID for this resolution
        /// </summary>
        public string Id { get; protected set; }

        /// <summary>
        /// Gets the name of resolution
        /// </summary>
        public string Name { get; protected set; }

        /// <summary>
        /// Gets the resolution width in pixels
        /// </summary>
        public int Width { get; protected set; }

        /// <summary>
        /// Gets the resolution height in pixels
        /// </summary>
        public int Height { get; protected set; }

        private string Translate(string resurceKey)
        {
            string value;

            lock (syncLock)
            {
                if (!LocalizationService.Service.TryGetString(resurceKey, out value))
                {
                    value = resurceKey;
                }
            }

            return value;
        }
    }
}

using EPiServer.Framework.Localization;
using EPiServer.ServiceLocation;
using EPiServer.Web;

namespace AlloyDemoKit.Business.Channels
{
    /// <summary>
    /// Base class for all resolution definitions
    /// </summary>
    public abstract class DisplayResolutionBase : IDisplayResolution
    {
        private Injected<LocalizationService> LocalizationService { get; set; }

        protected DisplayResolutionBase(string name, int width, int height)
        {
            Id = GetType().FullName;
            Name = Translate(name);
            Width = width;
            Height = height;
        }

        /// <summary>
        /// Gets the unique ID for this resolution
        /// </summary>
        public string Id { get; protected set; }

        /// <summary>
        /// Gets the name of resolution
        /// </summary>
        public string Name { get; protected set; }

        /// <summary>
        /// Gets the resolution width in pixels
        /// </summary>
        public int Width { get; protected set; }

        /// <summary>
        /// Gets the resolution height in pixels
        /// </summary>
        public int Height { get; protected set; }

        private string Translate(string resurceKey)
        {
            string value;

            if(!LocalizationService.Service.TryGetString(resurceKey, out value))
            {
                value = resurceKey;
            }

            return value;
        }
    }
}

Revert "Fix threading issue on initialisation"

This reverts commit b7dc99206b36c34ddc5d10607edc315e6d7bf5f8.


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Xunit;

namespace System.Collections.Tests
{
    public class InternalHashCodeTests
    {
        /// <summary>
        /// Given a byte array, copies it to the string, without messing with any encoding.  This issue was hit on a x64 machine
        /// </summary>
        private static string GetString(byte[] bytes)
        {
            var chars = new char[bytes.Length / sizeof(char)];
            Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }

        [Fact]
        public static void OutOfBoundsRegression()
        {
            var dictionary = new Dictionary<string, string>();

            foreach (var item in TestData.GetData())
            {
                var operation = item.Item1;
                var keyBase64 = item.Item2;

                var key = keyBase64.Length > 0 ? GetString(Convert.FromBase64String(keyBase64)) : string.Empty;

                if (operation == InputAction.Add)
                    dictionary[key] = key;
                else if (operation == InputAction.Delete)
                    dictionary.Remove(key);
            }
        }
    }
}

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Xunit;

namespace System.Collections.Tests
{
    public class InternalHashCodeTests
    {
        /// <summary>
        /// Given a byte array, copies it to the string, without messing with any encoding.  This issue was hit on a x64 machine
        /// </summary>
        private static string GetString(byte[] bytes)
        {
            var chars = new char[bytes.Length / sizeof(char)];
            Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }

        [Fact]
        [OuterLoop("Takes over 55% of System.Collections.Tests testing time")]
        public static void OutOfBoundsRegression()
        {
            var dictionary = new Dictionary<string, string>();

            foreach (var item in TestData.GetData())
            {
                var operation = item.Item1;
                var keyBase64 = item.Item2;

                var key = keyBase64.Length > 0 ? GetString(Convert.FromBase64String(keyBase64)) : string.Empty;

                if (operation == InputAction.Add)
                    dictionary[key] = key;
                else if (operation == InputAction.Delete)
                    dictionary.Remove(key);
            }
        }
    }
}

Mark System.Collections HashCollisionScenario test as OuterLoop

Takes a long time: any changes to Dictionary's hashing algorithm are
likely to be checked very very carefully anyway, as this has the
potential to cause breaking changes


namespace TraktApiSharp.Modules
{
    using Enums;
    using Objects.Basic;
    using Requests;
    using Requests.WithoutOAuth.Search;
    using System.Threading.Tasks;

    public class TraktSearchModule : TraktBaseModule
    {
        public TraktSearchModule(TraktClient client) : base(client) { }

        public async Task<TraktPaginationListResult<TraktSearchResult>> SearchTextQueryAsync(string query, TraktSearchResultType? type = null,
                                                                                int? year = null, int? page = null, int? limit = null)
        {
            return await QueryAsync(new TraktSearchTextQueryRequest(Client)
            {
                Query = query,
                Type = type,
                Year = year,
                PaginationOptions = new TraktPaginationOptions(page, limit)
            });
        }

        public async Task<TraktPaginationListResult<TraktSearchIdLookupResult>> SearchIdLookupAsync(TraktSearchLookupIdType type, string lookupId,
                                                                                int? page = null, int? limit = null)
        {
            return await QueryAsync(new TraktSearchIdLookupRequest(Client)
            {
                Type = type,
                LookupId = lookupId,
                PaginationOptions = new TraktPaginationOptions(page, limit)
            });
        }
    }
}

namespace TraktApiSharp.Modules
{
    using Enums;
    using Objects.Basic;
    using Requests;
    using Requests.WithoutOAuth.Search;
    using System;
    using System.Threading.Tasks;

    public class TraktSearchModule : TraktBaseModule
    {
        public TraktSearchModule(TraktClient client) : base(client) { }

        public async Task<TraktPaginationListResult<TraktSearchResult>> SearchTextQueryAsync(string query, TraktSearchResultType? type = null,
                                                                                int? year = null, int? page = null, int? limit = null)
        {
            ValidateQuery(query);

            return await QueryAsync(new TraktSearchTextQueryRequest(Client)
            {
                Query = query,
                Type = type,
                Year = year,
                PaginationOptions = new TraktPaginationOptions(page, limit)
            });
        }

        public async Task<TraktPaginationListResult<TraktSearchIdLookupResult>> SearchIdLookupAsync(TraktSearchLookupIdType type, string lookupId,
                                                                                int? page = null, int? limit = null)
        {
            ValidateIdLookup(lookupId);

            return await QueryAsync(new TraktSearchIdLookupRequest(Client)
            {
                Type = type,
                LookupId = lookupId,
                PaginationOptions = new TraktPaginationOptions(page, limit)
            });
        }

        private void ValidateQuery(string query)
        {
            if (string.IsNullOrEmpty(query))
                throw new ArgumentException("search query not valid", "query");
        }

        private void ValidateIdLookup(string lookupId)
        {
            if (string.IsNullOrEmpty(lookupId))
                throw new ArgumentException("search lookup id not valid", "lookupId");
        }
    }
}

Add validation implementation in search module.


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

using System.Collections.Generic;

namespace osu.Game.Storyboards
{
    public class CommandLoop : CommandTimelineGroup
    {
        public double LoopStartTime;
        public int LoopCount;

        public override double StartTime => LoopStartTime;
        public override double EndTime => LoopStartTime + CommandsDuration * LoopCount;

        public CommandLoop(double startTime, int loopCount)
        {
            LoopStartTime = startTime;
            LoopCount = loopCount;
        }

        public override IEnumerable<CommandTimeline<T>.TypedCommand> GetCommands<T>(CommandTimelineSelector<T> timelineSelector, double offset = 0)
        {
            for (var loop = 0; loop < LoopCount; loop++)
            {
                var loopOffset = LoopStartTime + loop * CommandsDuration;
                foreach (var command in base.GetCommands(timelineSelector, offset + loopOffset))
                    yield return command;
            }
        }

        public override string ToString()
            => $"{LoopStartTime} x{LoopCount}";
    }
}

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

using System.Collections.Generic;

namespace osu.Game.Storyboards
{
    public class CommandLoop : CommandTimelineGroup
    {
        public double LoopStartTime;
        public int LoopCount;

        public override double StartTime => LoopStartTime + CommandsStartTime;
        public override double EndTime => StartTime + CommandsDuration * LoopCount;

        public CommandLoop(double startTime, int loopCount)
        {
            LoopStartTime = startTime;
            LoopCount = loopCount;
        }

        public override IEnumerable<CommandTimeline<T>.TypedCommand> GetCommands<T>(CommandTimelineSelector<T> timelineSelector, double offset = 0)
        {
            for (var loop = 0; loop < LoopCount; loop++)
            {
                var loopOffset = LoopStartTime + loop * CommandsDuration;
                foreach (var command in base.GetCommands(timelineSelector, offset + loopOffset))
                    yield return command;
            }
        }

        public override string ToString()
            => $"{LoopStartTime} x{LoopCount}";
    }
}

Fix storyboard loops start time when none of their commands start at 0.


using Windows.UI.Xaml;

namespace TestAppUWP.Samples.InterControlAnimation
{
    public sealed partial class InterControlAnimation
    {
        private static Control2 _control2;
        private static Control1 _control1;

        public InterControlAnimation()
        {
            InitializeComponent();
            ContentPresenter.Content = new Control1();
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            ContentPresenter.Content = ContentPresenter.Content is Control1 ?
                (object) GetControl2() : GetControl1();
        }

        private static Control1 GetControl1()
        {
            return _control1 ?? (_control1 = new Control1());
        }

        private static Control2 GetControl2()
        {
            return _control2 ?? (_control2 = new Control2());
        }
    }
}

using Windows.UI.Xaml;

namespace TestAppUWP.Samples.InterControlAnimation
{
    public sealed partial class InterControlAnimation
    {
        private static Control2 _control2;
        private static Control1 _control1;

        public InterControlAnimation()
        {
            InitializeComponent();
            ContentPresenter.Content = new Control1();
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var changeControlAnimation = new ChangeControlAnimation();
            ContentPresenter.Content = ContentPresenter.Content is Control1 ?
                (object) GetControl2() : GetControl1();
        }

        private static Control1 GetControl1()
        {
            return _control1 ?? (_control1 = new Control1());
        }

        private static Control2 GetControl2()
        {
            return _control2 ?? (_control2 = new Control2());
        }
    }

    public class ChangeControlAnimation
    {
    }
}

Add some empty code to InterControlAnimation


using TicTacToe.Core.Enums;

namespace TicTacToe.Web.ViewModels
{
    public class TurnResultViewModel
    {
        public string Status { get; set; }
        public string ErrorText { get; set; }
        public bool IsGameDone { get; set; }
        public PlayerCode Winner { get; set; }
        public byte OpponentMove { get; set; }
    }

    public static class RusultStatus
    {
        public static string Error = "error";
        public static string Success = "success";
    }
}

using TicTacToe.Core.Enums;

namespace TicTacToe.Web.ViewModels
{
    public class TurnResultViewModel
    {
        public string status { get; set; }
        public string errorText { get; set; }
        public bool isGameDone { get; set; }
        public PlayerCode winner { get; set; }
        public int opponentMove { get; set; }

        public TurnResultViewModel()
        {
            opponentMove = -1;
        }
    }

    public static class RusultStatus
    {
        public static string Error = "error";
        public static string Success = "success";
    }
}

Change case for capability with js code.


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

using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;

namespace osu.Game.Rulesets.Taiko.Skinning
{
    public class LegacyHitExplosion : CompositeDrawable
    {
        public LegacyHitExplosion(Drawable sprite)
        {
            InternalChild = sprite;

            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;

            AutoSizeAxes = Axes.Both;
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            const double animation_time = 120;

            this.FadeInFromZero(animation_time).Then().FadeOut(animation_time * 1.5);

            this.ScaleTo(0.6f)
                .Then().ScaleTo(1.1f, animation_time * 0.8)
                .Then().ScaleTo(0.9f, animation_time * 0.4)
                .Then().ScaleTo(1f, animation_time * 0.2);

            Expire(true);
        }
    }
}

// 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;

namespace osu.Game.Rulesets.Taiko.Skinning
{
    public class LegacyHitExplosion : CompositeDrawable
    {
        private readonly Drawable sprite;
        private readonly Drawable strongSprite;

        /// <summary>
        /// Creates a new legacy hit explosion.
        /// </summary>
        /// <remarks>
        /// Contrary to stable's, this implementation doesn't require a frame-perfect hit
        /// for the strong sprite to be displayed.
        /// </remarks>
        /// <param name="sprite">The normal legacy explosion sprite.</param>
        /// <param name="strongSprite">The strong legacy explosion sprite.</param>
        public LegacyHitExplosion(Drawable sprite, Drawable strongSprite = null)
        {
            this.sprite = sprite;
            this.strongSprite = strongSprite;
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;

            AutoSizeAxes = Axes.Both;

            AddInternal(sprite);

            if (strongSprite != null)
                AddInternal(strongSprite.With(s => s.Alpha = 0));
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            const double animation_time = 120;

            this.FadeInFromZero(animation_time).Then().FadeOut(animation_time * 1.5);

            this.ScaleTo(0.6f)
                .Then().ScaleTo(1.1f, animation_time * 0.8)
                .Then().ScaleTo(0.9f, animation_time * 0.4)
                .Then().ScaleTo(1f, animation_time * 0.2);

            Expire(true);
        }
    }
}

Allow specifying two sprites for legacy hit explosions


// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestEDITOR
{
    /// <summary>
    ///
    /// </summary>
    internal class ProjectContractResolver : DefaultContractResolver
    {
        /// <summary>
        /// Use ObservableCollection for IList contract.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public override JsonContract ResolveContract(Type type)
        {
            if (type.IsGenericType
                && type.GetGenericTypeDefinition() == typeof(IList<>))
            {
                return base
                    .ResolveContract(typeof(ObservableCollection<>)
                    .MakeGenericType(type.GenericTypeArguments[0]));
            }
            else
            {
                return base.ResolveContract(type);
            }
        }

        /// <summary>
        /// Serialize only writable properties.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="memberSerialization"></param>
        /// <returns></returns>
        protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization)
        {
            IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
            return props.Where(p => p.Writable).ToList();
        }
    }
}

// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestEDITOR
{
    /// <summary>
    ///
    /// </summary>
    internal class ProjectContractResolver : DefaultContractResolver
    {
        /// <summary>
        /// Use ImmutableArray for IList contract.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public override JsonContract ResolveContract(Type type)
        {
            if (type.IsGenericType
                && type.GetGenericTypeDefinition() == typeof(IList<>))
            {
                return base
                    .ResolveContract(typeof(ImmutableArray<>)
                    .MakeGenericType(type.GenericTypeArguments[0]));
            }
            else
            {
                return base.ResolveContract(type);
            }
        }

        /// <summary>
        /// Serialize only writable properties.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="memberSerialization"></param>
        /// <returns></returns>
        protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization)
        {
            IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
            return props.Where(p => p.Writable).ToList();
        }
    }
}

Use ImmutableArray for IList interface

Use ImmutableArray for IList interface


namespace MusicXml.Domain
{
	public class Note
	{
		internal Note()
		{
			Type = string.Empty;
			Duration = -1;
			Voice = -1;
			Staff = -1;
			IsChordTone = false;
		}

		public string Type { get; internal set; }

		public int Voice { get; internal set; }

		public int Duration { get; internal set; }

		public Lyric Lyric { get; internal set; }

		public Pitch Pitch { get; internal set; }

		public int Staff { get; internal set; }

		public bool IsChordTone { get; internal set; }
	}
}

namespace MusicXml.Domain
{
	public class Note
	{
		internal Note()
		{
			Type = string.Empty;
			Duration = -1;
			Voice = -1;
			Staff = -1;
			IsChordTone = false;
			Lyric = new Lyric();
			Pitch = new Pitch();
		}

		public string Type { get; internal set; }

		public int Voice { get; internal set; }

		public int Duration { get; internal set; }

		public Lyric Lyric { get; internal set; }

		public Pitch Pitch { get; internal set; }

		public int Staff { get; internal set; }

		public bool IsChordTone { get; internal set; }
	}
}

Add default values for lyric and pitch

Add default values for lyric and pitch


using Oxide.Core.Libraries;

namespace Oxide.Game.Rust.Libraries
{
    public class Server : Library
    {
        #region Chat and Commands

        /// <summary>
        /// Broadcasts a chat message to all players
        /// </summary>
        /// <param name="message"></param>
        /// <param name="userId"></param>
        /// <param name="prefix"></param>
        public void Broadcast(string message, string prefix = null, ulong userId = 0)
        {
            ConsoleNetwork.BroadcastToAllClients("chat.add", userId, prefix != null ? $"{prefix} {message}" : message, 1.0);
        }

        /// <summary>
        /// Broadcasts a chat message to all players
        /// </summary>
        /// <param name="message"></param>
        /// <param name="userId"></param>
        /// <param name="prefix"></param>
        /// <param name="args"></param>
        public void Broadcast(string message, string prefix = null, ulong userId = 0, params object[] args) => Broadcast(string.Format(message, args), prefix, userId);

        /// <summary>
        /// Broadcasts a chat message to all players
        /// </summary>
        /// <param name="message"></param>
        /// <param name="prefix"></param>
        /// <param name="args"></param>
        public void Broadcast(string message, string prefix = null, params object[] args) => Broadcast(string.Format(message, args), prefix);

        /// <summary>
        /// Runs the specified server command
        /// </summary>
        /// <param name="command"></param>
        /// <param name="args"></param>
        public void Command(string command, params object[] args) => ConsoleSystem.Run(ConsoleSystem.Option.Server, command, args);

        #endregion
    }
}

using Oxide.Core.Libraries;

namespace Oxide.Game.Rust.Libraries
{
    public class Server : Library
    {
        #region Chat and Commands

        /// <summary>
        /// Broadcasts a chat message to all players
        /// </summary>
        /// <param name="message"></param>
        /// <param name="userId"></param>
        /// <param name="prefix"></param>
        public void Broadcast(string message, string prefix = null, ulong userId = 0)
        {
            ConsoleNetwork.BroadcastToAllClients("chat.add", userId, prefix != null ? $"{prefix} {message}" : message, 1.0);
        }

        /// <summary>
        /// Broadcasts a chat message to all players
        /// </summary>
        /// <param name="message"></param>
        /// <param name="userId"></param>
        /// <param name="prefix"></param>
        /// <param name="args"></param>
        public void Broadcast(string message, string prefix = null, ulong userId = 0, params object[] args) => Broadcast(string.Format(message, args), prefix, userId);

        /// <summary>
        /// Runs the specified server command
        /// </summary>
        /// <param name="command"></param>
        /// <param name="args"></param>
        public void Command(string command, params object[] args) => ConsoleSystem.Run(ConsoleSystem.Option.Server, command, args);

        #endregion
    }
}

[Rust] Fix rust.BroadcastChat using wrong Broadcast method


@model CompetitionPlatform.Models.ProjectViewModels.AddResultViewModel

@*<form asp-controller="ProjectDetails" asp-action="SaveResult" enctype="multipart/form-data">

            <input asp-for="@Model.ProjectId" type="hidden"/>
            <input asp-for="@Model.ParticipantId" type="hidden"/>
            <input asp-for="@Model.Link" class="form-control inline" placeholder="Insert link for the shared file(Dropbox, googleDrive, GitHub)"/>

            <input type="submit" value="Send Result" class="btn btn-primary col-md-2 inline" />

    </form>*@

<form asp-controller="ProjectDetails" asp-action="SaveResult" enctype="multipart/form-data" class="form form--share_result">
        <input asp-for="@Model.ProjectId" type="hidden" />
        <input asp-for="@Model.ParticipantId" type="hidden" />

            <input asp-for="@Model.Link" class="form-control" type="text" placeholder="Insert link for the shared file(Dropbox, googleDrive, GitHub)" />

            <button type="submit" class="btn btn-md"> Send Result</button>

</form>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

@model CompetitionPlatform.Models.ProjectViewModels.AddResultViewModel

            <form asp-controller="ProjectDetails" asp-action="SaveResult" enctype="multipart/form-data" class="form form--share_result">
                <input asp-for="@Model.ProjectId" type="hidden" />
                <input asp-for="@Model.ParticipantId" type="hidden" />

                        <input asp-for="@Model.Link" class="form-control" type="text" placeholder="Insert link for the shared file(Dropbox, googleDrive, GitHub)" />

                        <button type="submit" class="btn btn-md"> Send Result</button>

            </form>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Fix add result form styles. Remove Comments.


// 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 System.Diagnostics.CodeAnalysis;

namespace osu.Framework.Extensions.ObjectExtensions
{
    /// <summary>
    /// Extensions that apply to all objects.
    /// </summary>
    public static class ObjectExtensions
    {
        /// <summary>
        /// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
        /// </summary>
        /// <remarks>
        /// This should only be used when an assertion or other handling is not a reasonable alternative.
        /// </remarks>
        /// <param name="obj">The nullable object.</param>
        /// <typeparam name="T">The type of the object.</typeparam>
        /// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
        public static T AsNonNull<T>(this T? obj)
            where T : class
        {
            return obj!;
        }

        /// <summary>
        /// If the given object is null.
        /// </summary>
        public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);

        /// <summary>
        /// <c>true</c> if the given object is not null, <c>false</c> otherwise.
        /// </summary>
        public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
    }
}

// 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 System.Diagnostics.CodeAnalysis;

namespace osu.Framework.Extensions.ObjectExtensions
{
    /// <summary>
    /// Extensions that apply to all objects.
    /// </summary>
    public static class ObjectExtensions
    {
        /// <summary>
        /// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
        /// </summary>
        /// <remarks>
        /// This should only be used when an assertion or other handling is not a reasonable alternative.
        /// </remarks>
        /// <param name="obj">The nullable object.</param>
        /// <typeparam name="T">The type of the object.</typeparam>
        /// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
        [return: NotNullIfNotNull("obj")]
        public static T AsNonNull<T>(this T? obj) => obj!;

        /// <summary>
        /// If the given object is null.
        /// </summary>
        public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);

        /// <summary>
        /// <c>true</c> if the given object is not null, <c>false</c> otherwise.
        /// </summary>
        public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
    }
}

Remove class constraint on AsNonNull()

Remove class constraint on AsNonNull()


using System;
using System.Reflection;

[assembly: AssemblyTitle("Autofac.Extras.CommonServiceLocator")]
[assembly: AssemblyDescription("Autofac Adapter for the Microsoft CommonServiceLocator")]

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;
using System.Collections.Generic;

namespace GitVersion.Helpers
{
    internal class OperationWithExponentialBackoff<T> where T : Exception
    {
        private IThreadSleep ThreadSleep;
        private Action Operation;
        private int MaxRetries;

        public OperationWithExponentialBackoff(IThreadSleep threadSleep, Action operation, int maxRetries = 5)
        {
            if (threadSleep == null)
                throw new ArgumentNullException("threadSleep");
            if (maxRetries < 0)
                throw new ArgumentOutOfRangeException("maxRetries");

            this.ThreadSleep = threadSleep;
            this.Operation = operation;
            this.MaxRetries = maxRetries;
        }

        public void Execute()
        {
            var exceptions = new List<Exception>();

            int tries = 0;
            int sleepMSec = 500;

            while (tries <= MaxRetries)
            {
                tries++;

                try
                {
                    Operation();
                    break;
                }
                catch (T e)
                {
                    exceptions.Add(e);
                    if (tries > MaxRetries)
                    {
                        throw new AggregateException("Operation failed after maximum number of retries were exceeded.", exceptions);
                    }
                }

                ThreadSleep.Sleep(sleepMSec);
                sleepMSec *= 2;
            }
        }
    }
}

using System;
using System.Collections.Generic;

namespace GitVersion.Helpers
{
    internal class OperationWithExponentialBackoff<T> where T : Exception
    {
        private IThreadSleep ThreadSleep;
        private Action Operation;
        private int MaxRetries;

        public OperationWithExponentialBackoff(IThreadSleep threadSleep, Action operation, int maxRetries = 5)
        {
            if (threadSleep == null)
                throw new ArgumentNullException("threadSleep");
            if (maxRetries < 0)
                throw new ArgumentOutOfRangeException("maxRetries");

            this.ThreadSleep = threadSleep;
            this.Operation = operation;
            this.MaxRetries = maxRetries;
        }

        public void Execute()
        {
            var exceptions = new List<Exception>();

            int tries = 0;
            int sleepMSec = 500;

            while (tries <= MaxRetries)
            {
                tries++;

                try
                {
                    Operation();
                    break;
                }
                catch (T e)
                {
                    exceptions.Add(e);
                    if (tries > MaxRetries)
                    {
                        throw new AggregateException("Operation failed after maximum number of retries were exceeded.", exceptions);
                    }
                }

                Logger.WriteInfo(string.Format("Operation failed, retrying in {0} milliseconds.", sleepMSec));
                ThreadSleep.Sleep(sleepMSec);
                sleepMSec *= 2;
            }
        }
    }
}

Write to log when retrying

Write to log when retrying


@model IEnumerable<Models.Person>
@{
    ViewBag.Title = "_FilterResults";
}

        Volunteer Name
        Email
        Phone
        Cluster

    @if (Model != null)
    {
        foreach (var person in Model)
        {

                @(person.LastName + ", " + person.FirstName)
                @person.Email
                @person.PhoneNumber
                @(Html.Encode(person.Cluster != null ? person.Cluster.Name : ""))

        }
    }

@model IEnumerable<Models.Person>
@{
    ViewBag.Title = "_FilterResults";
}

        Volunteer Name
        Email
        Phone
        Cluster

    @if (Model != null)
    {
        foreach (var person in Model)
        {

                @(person.LastName + ", " + person.FirstName)
                @person.Email
                @person.PhoneNumber

                    @foreach (var commitment in person.Commitments)
                    {
                        @(Html.Encode(commitment.Cluster != null ? commitment.Cluster.Name : ""))
                    }

        }
    }

Fix for the volunteer results page. Not finished.


namespace Microsoft.Framework.DependencyInjection.Test
{
    using Microsoft.ApplicationInsights.AspNetCore;
    using Microsoft.ApplicationInsights.Extensibility;
    using Xunit;

    public static class ApplicationInsightsJavaScriptTest
    {
        [Fact]
        public static void SnippetWillBeEmptyWhenInstrumentationKeyIsNotDefined()
        {
            var telemetryConfigurationWithNullKey = new TelemetryConfiguration();
            var snippet = new JavaScriptSnippet(telemetryConfigurationWithNullKey);
            Assert.Equal(string.Empty, snippet.FullScript.ToString());
        }

        [Fact]
        public static void SnippetWillBeEmptyWhenInstrumentationKeyIsEmpty()
        {
            var telemetryConfigurationWithEmptyKey = new TelemetryConfiguration { InstrumentationKey = string.Empty };
            var snippet = new JavaScriptSnippet(telemetryConfigurationWithEmptyKey);
            Assert.Equal(string.Empty, snippet.FullScript.ToString());
        }

        [Fact]
        public static void SnippetWillIncludeInstrumentationKeyAsSubstring()
        {
            string unittestkey = "unittestkey";
            var telemetryConfiguration = new TelemetryConfiguration { InstrumentationKey = unittestkey };
            var snippet = new JavaScriptSnippet(telemetryConfiguration);
            Assert.Contains("'" + unittestkey + "'", snippet.FullScript.ToString());
        }
    }
}

namespace Microsoft.Framework.DependencyInjection.Test
{
    using Microsoft.ApplicationInsights.AspNetCore;
    using Microsoft.ApplicationInsights.Extensibility;
    using Xunit;

    public static class ApplicationInsightsJavaScriptTest
    {
        [Fact]
        public static void SnippetWillBeEmptyWhenInstrumentationKeyIsNotDefined()
        {
            var telemetryConfigurationWithNullKey = new TelemetryConfiguration();
            var snippet = new JavaScriptSnippet(telemetryConfigurationWithNullKey);
            Assert.Equal(string.Empty, snippet.FullScript.ToString());
        }

        [Fact]
        public static void SnippetWillBeEmptyWhenInstrumentationKeyIsEmpty()
        {
            var telemetryConfigurationWithEmptyKey = new TelemetryConfiguration { InstrumentationKey = string.Empty };
            var snippet = new JavaScriptSnippet(telemetryConfigurationWithEmptyKey);
            Assert.Equal(string.Empty, snippet.FullScript.ToString());
        }

        [Fact]
        public static void SnippetWillIncludeInstrumentationKeyAsSubstring()
        {
            string unittestkey = "unittestkey";
            var telemetryConfiguration = new TelemetryConfiguration { InstrumentationKey = unittestkey };
            var snippet = new JavaScriptSnippet(telemetryConfiguration);
            Assert.Contains("instrumentationKey: '" + unittestkey + "'", snippet.FullScript.ToString());
        }
    }
}

Improve JS Snippet unit test

Improve JS Snippet unit test


namespace Vaskelista.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class RoomHouseholdRelation : DbMigration
    {
        public override void Up()
        {

            AddColumn("dbo.Rooms", "HouseHold_HouseholdId", c => c.Int(nullable: false));
            CreateIndex("dbo.Rooms", "HouseHold_HouseholdId");
            AddForeignKey("dbo.Rooms", "HouseHold_HouseholdId", "dbo.Households", "HouseholdId", cascadeDelete: true);
        }

        public override void Down()
        {
            DropForeignKey("dbo.Rooms", "HouseHold_HouseholdId", "dbo.Households");
            DropIndex("dbo.Rooms", new[] { "HouseHold_HouseholdId" });
            DropColumn("dbo.Rooms", "HouseHold_HouseholdId");
        }
    }
}

namespace Vaskelista.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class RoomHouseholdRelation : DbMigration
    {
        public override void Up()
        {
            Sql("TRUNCATE TABLE dbo.Rooms");
            AddColumn("dbo.Rooms", "HouseHold_HouseholdId", c => c.Int(nullable: false));
            CreateIndex("dbo.Rooms", "HouseHold_HouseholdId");
            AddForeignKey("dbo.Rooms", "HouseHold_HouseholdId", "dbo.Households", "HouseholdId", cascadeDelete: true);
        }

        public override void Down()
        {
            DropForeignKey("dbo.Rooms", "HouseHold_HouseholdId", "dbo.Households");
            DropIndex("dbo.Rooms", new[] { "HouseHold_HouseholdId" });
            DropColumn("dbo.Rooms", "HouseHold_HouseholdId");
        }
    }
}

Fix migration by truncating rooms table

Fix migration by truncating rooms table


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

namespace Alice
{
    public class BenchResult
    {
        public BenchResult(string name, List<long> ticks)
        {
            Name = name;
            _ticks = ticks;
            Mean = _ticks.Sum() / _ticks.Count;
            Median = _ticks[_ticks.Count / 2];
            Variance = Math.Sqrt(_ticks.Select(t => Math.Pow(t - Mean, 2)).Sum() / _ticks.Count);
        }

        public string Name { get; }

        public long Mean { get; }

        public long Median { get; }

        public double Variance { get; }

        private List<long> _ticks;
        public IEnumerable<long> Ticks => _ticks;

        public override string ToString() =>
            $"{Name}: {string.Join(",\t", _ticks)} (mean: {Mean}, median: {Median}, r: {Variance:0.00})";
    }
}

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

namespace Alice
{
    public class BenchResult
    {
        public BenchResult(string name, List<long> ticks)
        {
            Name = name;
            _ticks = ticks;
            _ticks.Sort();
            Mean = _ticks.Sum() / _ticks.Count;
            var idx = (_ticks.Count / 2);
            Median = _ticks.Count % 2 == 0 ? (_ticks[idx] + _ticks[idx - 1]) / 2 : _ticks[idx];
            Variance = Math.Sqrt(_ticks.Select(t => Math.Pow(t - Mean, 2)).Sum() / _ticks.Count);
        }

        public string Name { get; }

        public long Mean { get; }

        public long Median { get; }

        public double Variance { get; }

        private List<long> _ticks;
        public IEnumerable<long> Ticks => _ticks;

        public override string ToString()
        {
            var ticks = string.Join(",", _ticks.Select(t => string.Format("{0,10}", t)));
            return $"{Name,15}: {ticks} (mean: {Mean,10}, median: {Median,10}, r: {Variance:0.00})";
        }
    }
}

Fix Error in Median Calculation

Fix Error in Median Calculation

Sort the array of tick samples before calculating the median.