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

namespace CompetitionPlatform.Models
{
    public class AuthenticateModel
    {
        public string FullName { get; set; }
        public string Password { get; set; }
    }

    public class CompetitionPlatformUser
    {
        public string Email { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string GetFullName()
        {
            return FirstName + " " + LastName;
        }
    }
}

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

namespace CompetitionPlatform.Models
{
    public class AuthenticateModel
    {
        public string FullName { get; set; }
        public string Password { get; set; }
    }

    public class CompetitionPlatformUser
    {
        public string Email { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Documents { get; set; }

        public string GetFullName()
        {
            return FirstName + " " + LastName;
        }
    }
}

Add Documents property to the user model.


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

namespace VimeoDotNet.Tests.Settings
{
    internal class SettingsLoader
    {
        private const string SETTINGS_FILE = "vimeoSettings.json";

        public static VimeoApiTestSettings LoadSettings()
        {
            if (!File.Exists(SETTINGS_FILE))
            {
                // File was not found so create a new one with blanks
                SaveSettings(new VimeoApiTestSettings());

                throw new Exception(string.Format("The file {0} was not found. A file was created, please fill in the information", SETTINGS_FILE));
            }

            var json = File.ReadAllText(SETTINGS_FILE);
            return JsonConvert.DeserializeObject<VimeoApiTestSettings>(json);
        }

        public static void SaveSettings(VimeoApiTestSettings settings)
        {
            var json = JsonConvert.SerializeObject(settings, Formatting.Indented);
            System.IO.File.WriteAllText(SETTINGS_FILE, json);
        }
    }
}

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

namespace VimeoDotNet.Tests.Settings
{
    internal class SettingsLoader
    {
        private const string SETTINGS_FILE = "vimeoSettings.json";

        public static VimeoApiTestSettings LoadSettings()
        {
            if (!File.Exists(SETTINGS_FILE))
            {
                // File was not found so create a new one with blanks
                SaveSettings(new VimeoApiTestSettings());

                throw new Exception(string.Format("The file {0} was not found. A file was created, please fill in the information", SETTINGS_FILE));
            }
            var fromEnv = GetSettingsFromEnvVars();
            if (fromEnv.UserId != 0)
                return fromEnv;
            var json = File.ReadAllText(SETTINGS_FILE);
            return JsonConvert.DeserializeObject<VimeoApiTestSettings>(json);
        }

        private static VimeoApiTestSettings GetSettingsFromEnvVars()
        {
            long userId;
            long.TryParse(Environment.GetEnvironmentVariable("UserId"), out userId);
            long albumId;
            long.TryParse(Environment.GetEnvironmentVariable("AlbumId"), out albumId);
            long channelId;
            long.TryParse(Environment.GetEnvironmentVariable("ChannelId"), out channelId);
            long videoId;
            long.TryParse(Environment.GetEnvironmentVariable("VideoId"), out videoId);
            return new VimeoApiTestSettings()
            {
                ClientId = Environment.GetEnvironmentVariable("ClientId"),
                ClientSecret = Environment.GetEnvironmentVariable("ClientSecret"),
                AccessToken = Environment.GetEnvironmentVariable("AccessToken"),
                UserId = userId,
                AlbumId = albumId,
                ChannelId = channelId,
                VideoId = videoId,
            };
        }

        public static void SaveSettings(VimeoApiTestSettings settings)
        {
            var json = JsonConvert.SerializeObject(settings, Formatting.Indented);
            System.IO.File.WriteAllText(SETTINGS_FILE, json);
        }
    }
}

Add test settings loading from enviroment for appVeyor.


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Octet.cs" company="Steven Liekens">
//   The MIT License (MIT)
// </copyright>
// <summary>
//
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using JetBrains.Annotations;
using Txt.Core;

namespace Txt.ABNF.Core.OCTET
{
    public class Octet : Element
    {
        /// <summary>Initializes a new instance of the <see cref="Element" /> class with a given element to copy.</summary>
        /// <param name="element">The element to copy.</param>
        /// <exception cref="ArgumentNullException">The value of <paramref name="element" /> is a null reference.</exception>
        public Octet([NotNull] Element element)
            : base(element)
        {
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="Element" /> class with a given string of terminal values and its
        ///     context.
        /// </summary>
        /// <param name="terminals">The terminal values.</param>
        /// <param name="context">An object that describes the current element's context.</param>
        /// <exception cref="ArgumentNullException">
        ///     The value of  <paramref name="terminals" /> or <paramref name="context" /> is a
        ///     null reference.
        /// </exception>
        public Octet(int value, [NotNull] ITextContext context)
            : base("?", context)
        {
            Value = value;
        }

        public int Value { get; }
    }
}

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Octet.cs" company="Steven Liekens">
//   The MIT License (MIT)
// </copyright>
// <summary>
//
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using JetBrains.Annotations;
using Txt.Core;

namespace Txt.ABNF.Core.OCTET
{
    public class Octet : Element
    {
        /// <summary>Initializes a new instance of the <see cref="Element" /> class with a given element to copy.</summary>
        /// <param name="element">The element to copy.</param>
        /// <exception cref="ArgumentNullException">The value of <paramref name="element" /> is a null reference.</exception>
        public Octet([NotNull] Element element)
            : base(element)
        {
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="Element" /> class with a given string of terminal values and its
        ///     context.
        /// </summary>
        /// <param name="terminals">The terminal values.</param>
        /// <param name="context">An object that describes the current element's context.</param>
        /// <exception cref="ArgumentNullException">
        ///     The value of  <paramref name="terminals" /> or <paramref name="context" /> is a
        ///     null reference.
        /// </exception>
        public Octet(int value, [NotNull] ITextContext context)
            : base("\uFFFD", context)
        {
            Value = value;
        }

        public int Value { get; }
    }
}

Use Substitution character instead of question mark


using LiveSplit.Options;
using System;
using System.Linq;

namespace LiveSplit.Model.Comparisons
{
    public class LastCompletedRunComparisonGenerator : IComparisonGenerator
    {
        public IRun Run { get; set; }
        public const string ComparisonName = "Last Completed Run";
        public const string ShortComparisonName = "Last Completed Run";
        public string Name => ComparisonName;

        public LastCompletedRunComparisonGenerator(IRun run)
        {
            Run = run;
        }

        public void Generate(TimingMethod method)
        {
            Attempt? mostRecentCompleted = null;
            foreach (var attempt in Run.AttemptHistory)
            {
                if (
                    attempt.Time[method] != null &&
                    ( mostRecentCompleted == null || ( mostRecentCompleted.Value.Ended - attempt.Ended ).Value.Seconds < 0 )
                    )
                {
                    mostRecentCompleted = attempt;
                }
            }
            TimeSpan? totalTime = TimeSpan.Zero;
            for (var ind = 0; ind < Run.Count; ind++)
            {
                TimeSpan? segmentTime;
                if (mostRecentCompleted != null)
                    segmentTime = Run[ind].SegmentHistory[mostRecentCompleted.Value.Index][method];
                else
                    segmentTime = null;
                var time = new Time(Run[ind].Comparisons[Name]);
                if (totalTime != null && segmentTime != null)
                {
                    totalTime += segmentTime;
                    time[method] = totalTime;
                }
                else
                    time[method] = null;
                Run[ind].Comparisons[Name] = time;
            }
        }

        public void Generate(ISettings settings)
        {
             Generate(TimingMethod.RealTime);
            Generate(TimingMethod.GameTime);
        }
    }
}

using LiveSplit.Options;
using System;
using System.Linq;

namespace LiveSplit.Model.Comparisons
{
    public class LastCompletedRunComparisonGenerator : IComparisonGenerator
    {
        public IRun Run { get; set; }
        public const string ComparisonName = "Last Completed Run";
        public const string ShortComparisonName = "Last Run";
        public string Name => ComparisonName;

        public LastCompletedRunComparisonGenerator(IRun run)
        {
            Run = run;
        }

        public void Generate(TimingMethod method)
        {
            Attempt? mostRecentCompleted = null;
            foreach (var attempt in Run.AttemptHistory.Reverse())
            {
                if (attempt.Time[method] != null)
                {
                    mostRecentCompleted = attempt;
                    break;
                }
            }

            TimeSpan? totalTime = TimeSpan.Zero;
            for (var ind = 0; ind < Run.Count; ind++)
            {
                TimeSpan? segmentTime;
                if (mostRecentCompleted != null)
                    segmentTime = Run[ind].SegmentHistory[mostRecentCompleted.Value.Index][method];
                else
                    segmentTime = null;
                var time = new Time(Run[ind].Comparisons[Name]);
                if (totalTime != null && segmentTime != null)
                {
                    totalTime += segmentTime;
                    time[method] = totalTime;
                }
                else
                    time[method] = null;
                Run[ind].Comparisons[Name] = time;
            }
        }

        public void Generate(ISettings settings)
        {
            Generate(TimingMethod.RealTime);
            Generate(TimingMethod.GameTime);
        }
    }
}

Simplify finding the last completed attempt


using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
    internal class ProductInformation
    {
        public const string Author = "amay077";
        public const string Name = "Xamarin.Forms.GoogleMaps";
        public const string Copyright = "Copyright © amay077. 2016 - 2018";
        public const string Trademark = "";
        public const string Version = "3.0.1.0";
    }
}

using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
    internal class ProductInformation
    {
        public const string Author = "amay077";
        public const string Name = "Xamarin.Forms.GoogleMaps";
        public const string Copyright = "Copyright © amay077. 2016 - 2018";
        public const string Trademark = "";
        public const string Version = "3.0.2.0";
    }
}

Update file ver to 3.0.2.0

Update file ver to 3.0.2.0


using System.Web.Mvc;
using Orchard.DevTools.Models;
using Orchard.Localization;
using Orchard.Mvc.ViewModels;
using Orchard.Themes;
using Orchard.UI.Notify;

namespace Orchard.DevTools.Controllers {
    [Themed]
    public class HomeController : Controller {
        private readonly INotifier _notifier;

        public HomeController(INotifier notifier) {
            _notifier = notifier;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public ActionResult Index() {
            return View(new BaseViewModel());
        }

        public ActionResult NotAuthorized() {
            _notifier.Warning(T("Simulated error goes here."));
            return new HttpUnauthorizedResult();
        }

        public ActionResult Simple() {
            return View(new Simple { Title = "This is a simple text", Quantity = 5 });
        }

        public ActionResult _RenderableAction() {
            return PartialView("_RenderableAction", "This is render action");
        }

        public ActionResult SimpleMessage() {
            _notifier.Information(T("Notifier works without BaseViewModel"));
            return RedirectToAction("Simple");
        }

        [Themed(false)]
        public ActionResult SimpleNoTheme() {
            return View("Simple", new Simple { Title = "This is not themed", Quantity = 5 });
        }
    }
}

using System.Web.Mvc;
using Orchard.DevTools.Models;
using Orchard.Localization;
using Orchard.Mvc.ViewModels;
using Orchard.Themes;
using Orchard.UI.Notify;
using Orchard.UI.Admin;

namespace Orchard.DevTools.Controllers {
    [Themed]
    [Admin]
    public class HomeController : Controller {
        private readonly INotifier _notifier;

        public HomeController(INotifier notifier) {
            _notifier = notifier;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public ActionResult Index() {
            return View(new BaseViewModel());
        }

        public ActionResult NotAuthorized() {
            _notifier.Warning(T("Simulated error goes here."));
            return new HttpUnauthorizedResult();
        }

        public ActionResult Simple() {
            return View(new Simple { Title = "This is a simple text", Quantity = 5 });
        }

        public ActionResult _RenderableAction() {
            return PartialView("_RenderableAction", "This is render action");
        }

        public ActionResult SimpleMessage() {
            _notifier.Information(T("Notifier works without BaseViewModel"));
            return RedirectToAction("Simple");
        }

        [Themed(false)]
        public ActionResult SimpleNoTheme() {
            return View("Simple", new Simple { Title = "This is not themed", Quantity = 5 });
        }
    }
}

Make the devtools controller Admin

Make the devtools controller Admin

--HG--
branch : dev


using System.Windows;

namespace CefSharp.MinimalExample.Wpf
{
    public partial class App : Application
    {
        public App()
        {
            //Perform dependency check to make sure all relevant resources are in our output directory.
            Cef.Initialize(new CefSettings(), shutdownOnProcessExit: true, performDependencyCheck: true);
        }
    }
}

using System.Windows;

namespace CefSharp.MinimalExample.Wpf
{
    public partial class App : Application
    {
        public App()
        {
            //Perform dependency check to make sure all relevant resources are in our output directory.
            var settings = new CefSettings();
            settings.EnableInternalPdfViewerOffScreen();
            Cef.Initialize(settings, shutdownOnProcessExit: true, performDependencyCheck: true);
        }
    }
}

Enable internal PDF viewer in WPF project


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

namespace System.Data.SqlClient.Tests
{
    public class SqlConnectionBasicTests
    {

        [Fact]
        public void ConnectionTest()
        {
            using (TestTdsServer server = TestTdsServer.StartTestServer())
            {
                using (SqlConnection connection = new SqlConnection(server.ConnectionString))
                {
                    connection.Open();
                }
            }
        }

        [Fact]
        [PlatformSpecific(TestPlatforms.Windows)]  // Integ auth on Test server is supported on Windows right now
        public void IntegratedAuthConnectionTest()
        {
            using (TestTdsServer server = TestTdsServer.StartTestServer())
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(server.ConnectionString);
                builder.IntegratedSecurity = true;
                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                {
                    connection.Open();
                }
            }
        }
    }

}

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

namespace System.Data.SqlClient.Tests
{
    public class SqlConnectionBasicTests
    {

        [Fact]
        public void ConnectionTest()
        {
            using (TestTdsServer server = TestTdsServer.StartTestServer())
            {
                using (SqlConnection connection = new SqlConnection(server.ConnectionString))
                {
                    connection.Open();
                }
            }
        }

        [PlatformSpecific(TestPlatforms.Windows)]  // Integ auth on Test server is supported on Windows right now
        [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))] // https://github.com/dotnet/corefx/issues/19218
        public void IntegratedAuthConnectionTest()
        {
            using (TestTdsServer server = TestTdsServer.StartTestServer())
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(server.ConnectionString);
                builder.IntegratedSecurity = true;
                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                {
                    connection.Open();
                }
            }
        }
    }

}

Disable SQL test for nano

Disable SQL test for nano


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Input;

namespace MouseRx2Wpf
{
    public class EventsExtension<TElement> where TElement : UIElement
    {
        public TElement Target { get; }
        public IObservable<IObservable<Vector>> MouseDrag { get; }

        public EventsExtension(TElement target)
        {
            Target = target;

            // Replaces events with IObservable objects.
            var mouseDown = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseDown)).Select(e => e.EventArgs);
            var mouseMove = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseMove)).Select(e => e.EventArgs);
            var mouseUp = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseUp)).Select(e => e.EventArgs);
            var mouseLeave = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseLeave)).Select(e => e.EventArgs);
            var mouseDownEnd = mouseUp.Merge(mouseLeave);

            MouseDrag = mouseDown
                .Select(e => e.GetPosition(Target))
                .Select(p0 => mouseMove
                    .TakeUntil(mouseDownEnd)
                    .Select(e => e.GetPosition(Target) - p0));
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Input;

namespace MouseRx2Wpf
{
    public class EventsExtension<TElement> where TElement : UIElement
    {
        public TElement Target { get; }

        public IObservable<IObservable<Vector>> MouseDrag { get; }

        Point MouseDragLastPoint;
        public IObservable<Vector> MouseDragDelta { get; }

        public EventsExtension(TElement target)
        {
            Target = target;

            // Replaces events with IObservable objects.
            var mouseDown = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseDown)).Select(e => e.EventArgs);
            var mouseMove = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseMove)).Select(e => e.EventArgs);
            var mouseUp = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseUp)).Select(e => e.EventArgs);
            var mouseLeave = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseLeave)).Select(e => e.EventArgs);
            var mouseDownEnd = mouseUp.Merge(mouseLeave);

            MouseDrag = mouseDown
                .Select(e => e.GetPosition(Target))
                .Select(p0 => mouseMove
                    .TakeUntil(mouseDownEnd)
                    .Select(e => e.GetPosition(Target) - p0));

            // Reports a change vector from the previous position.
            MouseDragDelta = mouseDown
                .Select(e => e.GetPosition(Target))
                .Do(p => MouseDragLastPoint = p)
                .SelectMany(p0 => mouseMove
                    .TakeUntil(mouseDownEnd)
                    .Select(e => new { p1 = MouseDragLastPoint, p2 = e.GetPosition(Target) })
                    .Do(_ => MouseDragLastPoint = _.p2)
                    .Select(_ => _.p2 - _.p1));
        }
    }
}

Add property to report deltas

Add property to report deltas


namespace DotNetRu.Clients.UI.Pages
{
    using System;

    using DotNetRu.Clients.Portable.Interfaces;
    using DotNetRu.Clients.Portable.Model;

    using Xamarin.Forms;

    public abstract class BasePage : ContentPage, IProvidePageInfo
    {
        private DateTime appeared;

        public abstract AppPage PageType { get; }

        protected string ItemId { get; set; }

        protected override void OnAppearing()
        {
            this.appeared = DateTime.UtcNow;
            App.Logger.TrackPage(this.PageType.ToString(), this.ItemId);

            base.OnAppearing();
        }

        protected override void OnDisappearing()
        {
            App.Logger.TrackTimeSpent(this.PageType.ToString(), this.ItemId, DateTime.UtcNow - this.appeared);
            base.OnDisappearing();
        }
    }
}

using System.Diagnostics;

namespace DotNetRu.Clients.UI.Pages
{
    using System;

    using DotNetRu.Clients.Portable.Interfaces;
    using DotNetRu.Clients.Portable.Model;

    using Xamarin.Forms;

    public abstract class BasePage : ContentPage, IProvidePageInfo
    {
        private Stopwatch appeared;

        public abstract AppPage PageType { get; }

        protected string ItemId { get; set; }

        protected override void OnAppearing()
        {
            this.appeared = Stopwatch.StartNew();
            App.Logger.TrackPage(this.PageType.ToString(), this.ItemId);

            base.OnAppearing();
        }

        protected override void OnDisappearing()
        {
            App.Logger.TrackTimeSpent(this.PageType.ToString(), this.ItemId, TimeSpan.FromTicks(DateTime.UtcNow.Ticks).Subtract(this.appeared.Elapsed));
            base.OnDisappearing();
        }
    }
}

Add fix: use StopWatch instead of DateTime


using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Storage;
using Audiotica.Core.Extensions;
using Audiotica.Core.Windows.Helpers;
using Audiotica.Database.Services.Interfaces;
using Audiotica.Windows.Services.Interfaces;
using Autofac;

namespace Audiotica.Windows.AppEngine.Bootstrppers
{
    public class LibraryBootstrapper : AppBootStrapper
    {
        public override void OnStart(IComponentContext context)
        {
            var service = context.Resolve<ILibraryService>();
            var insights = context.Resolve<IInsightsService>();

            using (var timer = insights.TrackTimeEvent("LibraryLoaded"))
            {
                service.Load();
                timer.AddProperty("Track count", service.Tracks.Count.ToString());
            }

            var matchingService = context.Resolve<ILibraryMatchingService>();
            matchingService.OnStartup();

            CleanupFiles(service);
        }

        private void CleanupFiles(ILibraryService service)
        {
            CleanupFiles(s => !service.Tracks.Any(p => p.ArtistArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Artists/");
            CleanupFiles(s => !service.Tracks.Any(p => p.ArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Albums/");
        }

        private async void CleanupFiles(Func<string, bool> shouldDelete, string folderPath)
        {
            var folder = await StorageHelper.GetFolderAsync(folderPath);
            var files = await folder.GetFilesAsync();
            foreach (var file in files.Where(file => shouldDelete(file.Name)))
            {
                await file.DeleteAsync();
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Storage;
using Audiotica.Core.Extensions;
using Audiotica.Core.Windows.Helpers;
using Audiotica.Database.Services.Interfaces;
using Audiotica.Windows.Services.Interfaces;
using Autofac;

namespace Audiotica.Windows.AppEngine.Bootstrppers
{
    public class LibraryBootstrapper : AppBootStrapper
    {
        public override void OnStart(IComponentContext context)
        {
            var service = context.Resolve<ILibraryService>();
            var insights = context.Resolve<IInsightsService>();

            using (var timer = insights.TrackTimeEvent("LibraryLoaded"))
            {
                service.Load();
                timer.AddProperty("Track count", service.Tracks.Count.ToString());
            }

            var matchingService = context.Resolve<ILibraryMatchingService>();
            matchingService.OnStartup();

            CleanupFiles(s => !service.Tracks.Any(p => p.ArtistArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Artists/");
            CleanupFiles(s => !service.Tracks.Any(p => p.ArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Albums/");
        }

        private static async void CleanupFiles(Func<string, bool> shouldDelete, string folderPath)
        {
            var folder = await StorageHelper.GetFolderAsync(folderPath);
            var files = await folder.GetFilesAsync();
            foreach (var file in files.Where(file => shouldDelete(file.Name)))
            {
                await file.DeleteAsync();
            }
        }
    }
}

Refactor artwork clean up code

Refactor artwork clean up 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.Allocation;
using osu.Game.Screens.Menu;
using osu.Game.Users;

namespace osu.Game.Tests.Visual.Menus
{
    public class TestSceneDisclaimer : ScreenTestScene
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            AddStep("load disclaimer", () => LoadScreen(new Disclaimer()));

            AddStep("toggle support", () =>
            {
                API.LocalUser.Value = new User
                {
                    Username = API.LocalUser.Value.Username,
                    Id = API.LocalUser.Value.Id,
                    IsSupporter = !API.LocalUser.Value.IsSupporter,
                };
            });
        }
    }
}

// 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.Game.Screens.Menu;
using osu.Game.Users;

namespace osu.Game.Tests.Visual.Menus
{
    public class TestSceneDisclaimer : ScreenTestScene
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            AddStep("load disclaimer", () => LoadScreen(new Disclaimer()));

            AddStep("toggle support", () =>
            {
                API.LocalUser.Value = new User
                {
                    Username = API.LocalUser.Value.Username,
                    Id = API.LocalUser.Value.Id + 1,
                    IsSupporter = !API.LocalUser.Value.IsSupporter,
                };
            });
        }
    }
}

Fix disclaimer test scene supporter toggle


using System.Web.Mvc;
using System.Web.Routing;

namespace RestfulRouting
{
	public abstract class Mapper
	{
		private readonly IRouteHandler _routeHandler;

		protected Mapper()
		{
			_routeHandler = new MvcRouteHandler();
		}

		protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods)
		{
			return new Route(path,
				new RouteValueDictionary(new { controller, action }),
				new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }),
				new MvcRouteHandler());
		}
	}
}

using System.Web.Mvc;
using System.Web.Routing;

namespace RestfulRouting
{
	public abstract class Mapper
	{
		private readonly IRouteHandler _routeHandler;

		protected Mapper()
		{
			_routeHandler = new MvcRouteHandler();
		}

		protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods)
		{
			return new Route(path,
				new RouteValueDictionary(new { controller, action }),
				new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }),
				_routeHandler);
		}
	}
}

Use route handler defined for instance

Use route handler defined for instance


using Should;
using Xunit;

namespace Cassette.Less
{
    public class LessCompiler_Compile
    {
        [Fact]
        public void Compile_converts_LESS_into_CSS()
        {
            var compiler = new LessCompiler(_ => @"@color: #4d926f; #header { color: @color; }");
            var css = compiler.CompileFile("");
            css.ShouldEqual("#header {\n  color: #4d926f;\n}\n");
        }

        [Fact]
        public void Compile_invalid_LESS_throws_exception()
        {
            var compiler = new LessCompiler(_ => "#unclosed_rule {");
            var exception = Assert.Throws<LessCompileException>(delegate
            {
                compiler.CompileFile("");
            });
            exception.Message.ShouldEqual("Missing closing `}`");
        }

        [Fact]
        public void Compile_LESS_that_fails_parsing_throws_LessCompileException()
        {
            var compiler = new LessCompiler(_ => "#fail { - }");
            var exception = Assert.Throws<LessCompileException>(delegate
            {
                compiler.CompileFile("");
            });
            exception.Message.ShouldEqual("Syntax Error on line 1");
        }
    }
}

using Should;
using Xunit;

namespace Cassette.Less
{
    public class LessCompiler_Compile
    {
        [Fact]
        public void Compile_converts_LESS_into_CSS()
        {
            var compiler = new LessCompiler(_ => @"@color: #4d926f; #header { color: @color; }");
            var css = compiler.CompileFile("test.less");
            css.ShouldEqual("#header {\n  color: #4d926f;\n}\n");
        }

        [Fact]
        public void Compile_invalid_LESS_throws_exception()
        {
            var compiler = new LessCompiler(_ => "#unclosed_rule {");
            var exception = Assert.Throws<LessCompileException>(delegate
            {
                compiler.CompileFile("test.less");
            });
            exception.Message.ShouldEqual("Less compile error in test.less:\r\nMissing closing `}`");
        }

        [Fact]
        public void Compile_LESS_that_fails_parsing_throws_LessCompileException()
        {
            var compiler = new LessCompiler(_ => "#fail { - }");
            var exception = Assert.Throws<LessCompileException>(delegate
            {
                compiler.CompileFile("test.less");
            });
            exception.Message.ShouldEqual("Less compile error in test.less:\r\nSyntax Error on line 1");
        }
    }
}

Fix Less compiler unit tests to expect filename in error messages.


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

namespace NBi.Core.Transformation.Transformer.Native
{
    class UtcToLocal : INativeTransformation
    {
        public string TimeZoneLabel { get; }

        public UtcToLocal(string timeZoneLabel)
        {
            TimeZoneLabel = timeZoneLabel;
        }

        public object Evaluate(object value)
        {
            if (value == null)
                return null;
            else if (value is DateTime)
                return EvaluateDateTime((DateTime)value);
            else
                throw new NotImplementedException();
        }

        protected virtual object EvaluateDateTime(DateTime value) =>
            TimeZoneInfo.ConvertTimeFromUtc(value, InstantiateTimeZoneInfo(TimeZoneLabel));

        protected TimeZoneInfo InstantiateTimeZoneInfo(string label)
        {
            var zones = TimeZoneInfo.GetSystemTimeZones();
            var zone = zones.SingleOrDefault(z => z.Id == label)
                ?? zones.SingleOrDefault(z => Tokenize(z.DisplayName).Contains(label.Replace(" ", "")));

            return zone ?? throw new ArgumentOutOfRangeException($"TimeZone '{label}' is not existing on this computer.");
        }

        private string[] Tokenize(string label) =>
            label.Replace("(", ",")
            .Replace(")", ",")
            .Replace(":", ",")
            .Replace(" ", "")
            .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

    }
}

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

namespace NBi.Core.Transformation.Transformer.Native
{
    class UtcToLocal : INativeTransformation
    {
        public string TimeZoneLabel { get; }

        public UtcToLocal(string timeZoneLabel)
        {
            TimeZoneLabel = timeZoneLabel;
        }

        public object Evaluate(object value)
        {
            if (value == null)
                return null;
            else if (value is DateTime)
                return EvaluateDateTime((DateTime)value);
            else
                throw new NotImplementedException($"The evaluation of the function utc-to-local is not possible for the value '{value}' of  type '{value.GetType()}'. Only DateTime and null are supported, you must specify the type of the expression");
        }

        protected virtual object EvaluateDateTime(DateTime value) =>
            TimeZoneInfo.ConvertTimeFromUtc(value, InstantiateTimeZoneInfo(TimeZoneLabel));

        protected TimeZoneInfo InstantiateTimeZoneInfo(string label)
        {
            var zones = TimeZoneInfo.GetSystemTimeZones();
            var zone = zones.SingleOrDefault(z => z.Id == label)
                ?? zones.SingleOrDefault(z => Tokenize(z.DisplayName).Contains(label.Replace(" ", "")));

            return zone ?? throw new ArgumentOutOfRangeException($"TimeZone '{label}' is not existing on this computer.");
        }

        private string[] Tokenize(string label) =>
            label.Replace("(", ",")
            .Replace(")", ",")
            .Replace(":", ",")
            .Replace(" ", "")
            .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

    }
}

Improve error message when utc-to-local doesn't receive a dateTime


using Microsoft.Win32;

namespace EarTrumpet.Services
{
    public static class UserSystemPreferencesService
    {
        public static bool IsTransparencyEnabled
        {
            get
            {
                using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64))
                {
                    return (int)baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").GetValue("EnableTransparency", 0) > 0;
                }
            }
        }

        public static bool UseAccentColor
        {
            get
            {
                using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64))
                {
                    return (int)baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").GetValue("ColorPrevalence", 0) > 0;
                }
            }
        }
    }
}

using Microsoft.Win32;

namespace EarTrumpet.Services
{
    public static class UserSystemPreferencesService
    {
        public static bool IsTransparencyEnabled
        {
            get
            {
                using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64))
                {
                    return (int)baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").GetValue("EnableTransparency", 0) > 0;
                }
            }
        }

        public static bool UseAccentColor
        {
            get
            {
                using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64))
                {
                    return (int)baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").GetValue("ColorPrevalence", 0) > 0;
                }
            }
        }

        public static bool IsLightTheme
        {
            get
            {
                using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64))
                {
                    return (int)baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").GetValue("AppsUseLightTheme", 0) > 0;
                }
            }
        }
    }
}

Add light theme setting support

Add light theme setting support


using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

public static class PackageExporter
{
    [MenuItem("Tools/Export Unitypackage")]
    public static void Export()
    {
        // configure
        var root = "Scripts/MagicOnion";
        var exportPath = "./MagicOnion.Client.Unity.unitypackage";

        var path = Path.Combine(Application.dataPath, root);
        var assets = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)
            .Where(x => Path.GetExtension(x) == ".cs" || Path.GetExtension(x) == ".asmdef" || Path.GetExtension(x) == ".json" || Path.GetExtension(x) == ".meta")
            .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/"))
            .ToArray();

        var netStandardsAsset = Directory.EnumerateFiles(Path.Combine(Application.dataPath, "Plugins/System.Threading.Tasks.Extensions"), "*", SearchOption.AllDirectories)
            .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/"))
            .ToArray();

        assets = assets.Concat(netStandardsAsset).ToArray();

        UnityEngine.Debug.Log("Export below files" + Environment.NewLine + string.Join(Environment.NewLine, assets));

        AssetDatabase.ExportPackage(
            assets,
            exportPath,
            ExportPackageOptions.Default);

        UnityEngine.Debug.Log("Export complete: " + Path.GetFullPath(exportPath));
    }
}

using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

public static class PackageExporter
{
    [MenuItem("Tools/Export Unitypackage")]
    public static void Export()
    {
        // configure
        var root = "Scripts/MagicOnion";
        var exportPath = "./MagicOnion.Client.Unity.unitypackage";

        var path = Path.Combine(Application.dataPath, root);
        var assets = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)
            .Where(x => Path.GetExtension(x) == ".cs" || Path.GetExtension(x) == ".asmdef" || Path.GetExtension(x) == ".json" || Path.GetExtension(x) == ".meta")
            .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/"))
            .ToArray();

        var netStandardsAsset = Directory.EnumerateFiles(Path.Combine(Application.dataPath, "Plugins"), "System.*", SearchOption.AllDirectories)
            .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/"))
            .ToArray();

        assets = assets.Concat(netStandardsAsset).ToArray();

        UnityEngine.Debug.Log("Export below files" + Environment.NewLine + string.Join(Environment.NewLine, assets));

        AssetDatabase.ExportPackage(
            assets,
            exportPath,
            ExportPackageOptions.Default);

        UnityEngine.Debug.Log("Export complete: " + Path.GetFullPath(exportPath));
    }
}

Fix .NET Standard assembly assets path.

Fix .NET Standard assembly assets path.


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

namespace Nest
{
	[JsonObject(MemberSerialization.OptIn)]
	[JsonConverter(typeof(ReadAsTypeJsonConverter<RolloverConditions>))]
	public interface IRolloverConditions
	{
		[JsonProperty("max_age")]
		Time MaxAge { get; set; }

		[JsonProperty("max_docs")]
		int MaxDocs { get; set; }
	}

	public class RolloverConditions : IRolloverConditions
	{
		public Time MaxAge { get; set; }

		public int MaxDocs { get; set; }
	}

	public class RolloverConditionsDescriptor
		: DescriptorBase<RolloverConditionsDescriptor, IRolloverConditions>, IRolloverConditions
	{
		Time IRolloverConditions.MaxAge { get; set; }

		int IRolloverConditions.MaxDocs { get; set; }

		public RolloverConditionsDescriptor MaxAge(Time maxAge) => Assign(a => a.MaxAge = maxAge);

		public RolloverConditionsDescriptor MaxDocs(int maxDocs) => Assign(a => a.MaxDocs = maxDocs);
	}
}

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

namespace Nest
{
	[JsonObject(MemberSerialization.OptIn)]
	[JsonConverter(typeof(ReadAsTypeJsonConverter<RolloverConditions>))]
	public interface IRolloverConditions
	{
		[JsonProperty("max_age")]
		Time MaxAge { get; set; }

		[JsonProperty("max_docs")]
		long MaxDocs { get; set; }
	}

	public class RolloverConditions : IRolloverConditions
	{
		public Time MaxAge { get; set; }

		public long MaxDocs { get; set; }
	}

	public class RolloverConditionsDescriptor
		: DescriptorBase<RolloverConditionsDescriptor, IRolloverConditions>, IRolloverConditions
	{
		Time IRolloverConditions.MaxAge { get; set; }

		long IRolloverConditions.MaxDocs { get; set; }

		public RolloverConditionsDescriptor MaxAge(Time maxAge) => Assign(a => a.MaxAge = maxAge);

		public RolloverConditionsDescriptor MaxDocs(int maxDocs) => Assign(a => a.MaxDocs = maxDocs);
	}
}

Change MaxDocs from int to long

Change MaxDocs from int to long


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

namespace osu.Game.Beatmaps
{
    public static class BeatSyncProviderExtensions
    {
        /// <summary>
        /// Check whether beat sync is currently available.
        /// </summary>
        public static bool CheckBeatSyncAvailable(this IBeatSyncProvider provider) => provider.Clock != null;

        /// <summary>
        /// Whether the beat sync provider is currently in a kiai section. Should make everything more epic.
        /// </summary>
        public static bool CheckIsKiaiTime(this IBeatSyncProvider provider) => provider.Clock != null && (provider.ControlPoints?.EffectPointAt(provider.Clock.CurrentTime).KiaiMode ?? false);
    }
}

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

namespace osu.Game.Beatmaps
{
    public static class BeatSyncProviderExtensions
    {
        /// <summary>
        /// Check whether beat sync is currently available.
        /// </summary>
        public static bool CheckBeatSyncAvailable(this IBeatSyncProvider provider) => provider.Clock != null;

        /// <summary>
        /// Whether the beat sync provider is currently in a kiai section. Should make everything more epic.
        /// </summary>
        public static bool CheckIsKiaiTime(this IBeatSyncProvider provider) => provider.Clock != null && provider.ControlPoints?.EffectPointAt(provider.Clock.CurrentTime).KiaiMode == true;
    }
}

Replace parantheses with nullable-bool equality operation


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

using osu.Game.Online.API.Requests;
using osu.Game.Overlays.Profile.Sections.Beatmaps;

namespace osu.Game.Overlays.Profile.Sections
{
    public class BeatmapsSection : ProfileSection
    {
        public override string Title => "Beatmaps";

        public override string Identifier => "beatmaps";

        public BeatmapsSection()
        {
            Children = new[]
            {
                new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, "Favourite Beatmaps", "None... yet."),
            };
        }
    }
}

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

using osu.Game.Online.API.Requests;
using osu.Game.Overlays.Profile.Sections.Beatmaps;

namespace osu.Game.Overlays.Profile.Sections
{
    public class BeatmapsSection : ProfileSection
    {
        public override string Title => "Beatmaps";

        public override string Identifier => "beatmaps";

        public BeatmapsSection()
        {
            Children = new[]
            {
                new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, "Favourite Beatmaps", "None... yet."),
                new PaginatedBeatmapContainer(BeatmapSetType.Ranked_And_Approved, User, "Ranked & Approved Beatmaps", "None... yet."),
            };
        }
    }
}

Add "Ranked & Approved Beatmaps" section


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Training.CSharpWorkshop.Tests
{
    [TestClass]
    public class ProgramTests
    {
        [Ignore]
        [TestMethod]
        public void IgnoreTest()
        {
            Assert.Fail();
        }

        [TestMethod()]
        public void GetRoleMessageForAdminTest()
        {
            // Arrange
            var userName = "Andrew";
            var expected = "Role: Admin.";

            // Act
            var actual = Program.GetRoleMessage(userName);

            // Assert
            Assert.AreEqual(expected, actual);
        }

        [TestMethod()]
        public void GetRoleMessageForGuestTest()
        {
            // Arrange
            var userName = "Dave";
            var expected = "Role: Guest.";

            // Act
            var actual = Program.GetRoleMessage(userName);

            // Assert
            Assert.AreEqual(expected, actual);
        }
    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Training.CSharpWorkshop.Tests
{
    [TestClass]
    public class ProgramTests
    {
        [Ignore]
        [TestMethod]
        public void IgnoreTest()
        {
            Assert.Fail();
        }

        [TestMethod()]
        public void GetRoleMessageForAdminTest()
        {
            // Arrange
            var userName = "Andrew";
            var expected = "Role: Admin.";

            // Act
            var actual = Program.GetRoleMessage(userName);

            // Assert
            Assert.AreEqual(expected, actual);
        }

        [TestMethod()]
        public void GetRoleMessageForGuestTest()
        {
            // Arrange
            var userName = "Dave";
            var expected = "Role: Guest.";

            // Act
            var actual = Program.GetRoleMessage(userName);

            // Assert
            Assert.AreEqual(expected, actual);
        }

        [TestMethod]
        public void GetRoleMessageForNoneTest()
        {
            // Arrange
            var userName = "Don";
            var expected = "Role: None.";

            // Act
            var actual = Program.GetRoleMessage(userName);

            // Assert
            Assert.AreEqual(expected, actual);
        }
    }
}

Update Console Program with the Repository call - Add the GetRoleMessageForNoneTest test method to test the None case


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

namespace Totem.Runtime.Json
{
	/// <summary>
	/// Settings used when serializing and deserializing objects in the Totem runtime
	/// </summary>
	public class TotemSerializerSettings : JsonSerializerSettings
	{
		public TotemSerializerSettings()
		{
			Formatting = Formatting.Indented;

			TypeNameHandling = TypeNameHandling.Auto;

			ContractResolver = new TotemContractResolver();

			Binder = new TotemSerializationBinder();

			Converters.Add(new StringEnumConverter());
			Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffZ" });
		}

		public bool CamelCaseProperties
		{
			get
			{
				var knownResolver = ContractResolver as TotemContractResolver;

				return knownResolver != null && knownResolver.CamelCaseProperties;
			}
			set
			{
				var knownResolver = ContractResolver as TotemContractResolver;

				if(knownResolver != null)
				{
					knownResolver.CamelCaseProperties = value;
				}
			}
		}

		public JsonSerializer CreateSerializer()
		{
			return JsonSerializer.Create(this);
		}
	}
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Totem.Runtime.Json
{
	/// <summary>
	/// Settings used when serializing and deserializing objects in the Totem runtime
	/// </summary>
	public class TotemSerializerSettings : JsonSerializerSettings
	{
		public TotemSerializerSettings()
		{
			Formatting = Formatting.Indented;

			TypeNameHandling = TypeNameHandling.Auto;

			ContractResolver = new TotemContractResolver();

			Binder = new TotemSerializationBinder();

			Converters.AddRange(
				new StringEnumConverter(),
				new IsoDateTimeConverter
				{
					DateTimeStyles = DateTimeStyles.AssumeUniversal,
					DateTimeFormat = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern
				});

			DateTimeZoneHandling = DateTimeZoneHandling.Utc;
			DateFormatHandling = DateFormatHandling.IsoDateFormat;
		}

		public bool CamelCaseProperties
		{
			get
			{
				var knownResolver = ContractResolver as TotemContractResolver;

				return knownResolver != null && knownResolver.CamelCaseProperties;
			}
			set
			{
				var knownResolver = ContractResolver as TotemContractResolver;

				if(knownResolver != null)
				{
					knownResolver.CamelCaseProperties = value;
				}
			}
		}

		public JsonSerializer CreateSerializer()
		{
			return JsonSerializer.Create(this);
		}
	}
}

Standardize JSON date/time values on UTC


// 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.Input.StateChanges.Events;

namespace osu.Framework.Input.StateChanges
{
    public interface ISourcedFromTouch
    {
        TouchStateChangeEvent TouchEvent { get; set; }
    }
}

// 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.Input.StateChanges.Events;

namespace osu.Framework.Input.StateChanges
{
    /// <summary>
    /// Denotes an input which was sourced from a touch event.
    /// Generally used to mark when an alternate input was triggered from a touch source (ie. touch being emulated as a mouse).
    /// </summary>
    public interface ISourcedFromTouch
    {
        /// <summary>
        /// The source touch event.
        /// </summary>
        TouchStateChangeEvent TouchEvent { get; set; }
    }
}

Add missing xmldoc to interface class

Add missing xmldoc to interface class


using System.Reflection;

namespace NHibernate.Mapping.ByCode.Impl.CustomizersImpl
{
	public class ComposedIdCustomizer<TEntity> : PropertyContainerCustomizer<TEntity>, IComposedIdMapper<TEntity> where TEntity : class
	{
		public ComposedIdCustomizer(IModelExplicitDeclarationsHolder explicitDeclarationsHolder, ICustomizersHolder customizersHolder)
			: base(explicitDeclarationsHolder, customizersHolder, null) {}

		protected override void RegisterPropertyMapping<TProperty>(System.Linq.Expressions.Expression<System.Func<TEntity, TProperty>> property, System.Action<IPropertyMapper> mapping)
		{
			MemberInfo member = TypeExtensions.DecodeMemberAccessExpression(property);
			ExplicitDeclarationsHolder.AddAsPartOfComposedId(member);
			base.RegisterPropertyMapping(property, mapping);
		}

		protected override void RegisterManyToOneMapping<TProperty>(System.Linq.Expressions.Expression<System.Func<TEntity, TProperty>> property, System.Action<IManyToOneMapper> mapping)
		{
			MemberInfo member = TypeExtensions.DecodeMemberAccessExpression(property);
			ExplicitDeclarationsHolder.AddAsPartOfComposedId(member);
			base.RegisterManyToOneMapping(property, mapping);
		}
	}
}

using System.Reflection;

namespace NHibernate.Mapping.ByCode.Impl.CustomizersImpl
{
	public class ComposedIdCustomizer<TEntity> : PropertyContainerCustomizer<TEntity>, IComposedIdMapper<TEntity> where TEntity : class
	{
		public ComposedIdCustomizer(IModelExplicitDeclarationsHolder explicitDeclarationsHolder, ICustomizersHolder customizersHolder)
			: base(explicitDeclarationsHolder, customizersHolder, null) {}

		protected override void RegisterPropertyMapping<TProperty>(System.Linq.Expressions.Expression<System.Func<TEntity, TProperty>> property, System.Action<IPropertyMapper> mapping)
		{
			MemberInfo member = TypeExtensions.DecodeMemberAccessExpressionOf(property);
			ExplicitDeclarationsHolder.AddAsPartOfComposedId(member);
			base.RegisterPropertyMapping(property, mapping);
		}

		protected override void RegisterManyToOneMapping<TProperty>(System.Linq.Expressions.Expression<System.Func<TEntity, TProperty>> property, System.Action<IManyToOneMapper> mapping)
		{
			MemberInfo member = TypeExtensions.DecodeMemberAccessExpressionOf(property);
			ExplicitDeclarationsHolder.AddAsPartOfComposedId(member);
			base.RegisterManyToOneMapping(property, mapping);
		}
	}
}

Fix for superclass properties (NH-3318)

Fix for superclass properties (NH-3318)

When obtained straight from a lambda expression, MemberInfo for a
superclass property has both DeclaringType and ReflectedType set to
Superclass. This causes problems when ModelMapper goes through
properties - their ReflectedType is Subclass. Turns out there was an
alternative, more thorough way of getting to that in NH codebase
already.


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

namespace NLogger
{
    public class CustomLogFactory<T> where T : NLoggerSection
    {
        private readonly List<ILogWriterRegistration<T>> _logWriterTypes;

        public CustomLogFactory()
        {
            _logWriterTypes= new List<ILogWriterRegistration<T>>();
        }

        public void RegisterLogWriterType(ILogWriterRegistration<T> registration)
        {
            _logWriterTypes.Add(registration);
        }

        /// <summary>
        /// Create a logger using App.config or Web.config settings
        /// </summary>
        /// <returns></returns>
        public ILogger CreateLogger(string sectionName)
        {
            var config = (T)ConfigurationManager.GetSection(sectionName);

            var writer = GetLogWriter(config);

            return writer != null
                ? new Logger(writer, config.LogLevel)
                : LoggerFactory.CreateLogger();
        }

        private ILogWriter GetLogWriter(T config)
        {
            var type = _logWriterTypes.FirstOrDefault(t => t.HasSection(config));

            return type != null
                ? type.GetWriter(config)
                : null;
        }
    }
}

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

namespace NLogger
{
    public class CustomLogFactory<T> where T : NLoggerSection
    {
        private readonly List<ILogWriterRegistration<T>> _logWriterTypes;

        public CustomLogFactory()
        {
            _logWriterTypes= new List<ILogWriterRegistration<T>>();
        }

        public void RegisterLogWriterType(ILogWriterRegistration<T> registration)
        {
            _logWriterTypes.Add(registration);
        }

        /// <summary>
        /// Create a logger using App.config or Web.config settings
        /// </summary>
        /// <returns></returns>
        public ILogger CreateLogger(string sectionName)
        {
            var config = (T) ConfigurationManager.GetSection(sectionName);

            if (config != null)
            {
                var writer = GetLogWriter(config);

                if (writer != null)
                {
                    return new Logger(writer, config.LogLevel);
                }
            }

            return LoggerFactory.CreateLogger();
        }

        private ILogWriter GetLogWriter(T config)
        {
            var type = _logWriterTypes.FirstOrDefault(t => t.HasSection(config));

            return type != null
                ? type.GetWriter(config)
                : null;
        }
    }
}

Deal with null config in custom log factory


using System.Reflection;

[assembly: AssemblyCompany("Picoe Software Solutions Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
[assembly: AssemblyInformationalVersion("1.3.0")]

using System.Reflection;

[assembly: AssemblyCompany("Picoe Software Solutions Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: AssemblyVersion("1.99.0.0")]
[assembly: AssemblyFileVersion("1.99.0.0")]
[assembly: AssemblyInformationalVersion("1.99.0")]

Update assembly version to v1.99 to prepare for v2.0 release


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

namespace AutoReservation.Ui.ViewModels
{
    public class AsyncRelayCommand : ICommand
    {
        protected readonly Predicate<object> _canExecute;
        protected Func<object, Task> _asyncExecute;

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public AsyncRelayCommand(Func<object, Task> execute)
            : this(execute, null)
        {
        }

        public AsyncRelayCommand(Func<object, Task> asyncExecute,
                       Predicate<object> canExecute)
        {
            _asyncExecute = asyncExecute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }

            return _canExecute(parameter);
        }

        public async void Execute(object parameter)
        {
            await ExecuteAsync(parameter);
        }

        protected virtual async Task ExecuteAsync(object parameter)
        {
            await _asyncExecute(parameter);
        }
    }
}

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

namespace AutoReservation.Ui.ViewModels
{
    /**
     * From: http://blog.mycupof.net/2012/08/23/mvvm-asyncdelegatecommand-what-asyncawait-can-do-for-uidevelopment/
     */
    public class AsyncRelayCommand : ICommand
    {
        protected readonly Predicate<object> _canExecute;
        protected Func<object, Task> _asyncExecute;

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public AsyncRelayCommand(Func<object, Task> execute)
            : this(execute, null)
        {
        }

        public AsyncRelayCommand(Func<object, Task> asyncExecute,
                       Predicate<object> canExecute)
        {
            _asyncExecute = asyncExecute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }

            return _canExecute(parameter);
        }

        public async void Execute(object parameter)
        {
            await ExecuteAsync(parameter);
        }

        protected virtual async Task ExecuteAsync(object parameter)
        {
            await _asyncExecute(parameter);
        }
    }
}

Add link to where the async relay command is from


using System;
using System.Web;

namespace WebServer
{
    public class StatusCode : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string statusCodeString = context.Request.QueryString["statuscode"];
            string statusDescription = context.Request.QueryString["statusdescription"];
            try
            {
                int statusCode = int.Parse(statusCodeString);
                context.Response.StatusCode = statusCode;
                if (!string.IsNullOrEmpty(statusDescription))
                {
                    context.Response.StatusDescription = statusDescription;
                }
            }
            catch (Exception)
            {
                context.Response.StatusCode = 500;
                context.Response.StatusDescription = "Error parsing statuscode: " + statusCodeString;
            }
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}

using System;
using System.Web;

namespace WebServer
{
    public class StatusCode : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string statusCodeString = context.Request.QueryString["statuscode"];
            string statusDescription = context.Request.QueryString["statusdescription"];
            try
            {
                int statusCode = int.Parse(statusCodeString);
                context.Response.StatusCode = statusCode;
                if (statusDescription != null)
                {
                    context.Response.StatusDescription = statusDescription;
                }
            }
            catch (Exception)
            {
                context.Response.StatusCode = 500;
                context.Response.StatusDescription = "Error parsing statuscode: " + statusCodeString;
            }
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}

Allow for blank status description

Allow for blank status description


//We are given numbers N and M and the following operations:
//  * `N = N+1`
//  * `N = N+2`
//  * `N = N*2`

//  - Write a program that finds the shortest sequence of operations from the list above that starts from `N` and finishes in `M`.
//  - _Hint_: use a queue.
//  - Example: `N = 5`, `M = 16`
//  - Sequence: 5 → 7 → 8 → 16

namespace SequenceOfOperations
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    internal class Program
    {
        public static void Main()
        {
            int start = 5;
            int end = 26;

            var sequence = GetShortestSequence(start, end);

            Console.WriteLine(string.Join(" -> ", sequence));
        }

        private static IEnumerable<int> GetShortestSequence(int start, int end)
        {
            var sequence = new Queue<int>();

            while (start <= end)
            {
                sequence.Enqueue(end);

                if (end / 2 >= start)
                {
                    if (end % 2 == 0)
                    {
                        end /= 2;
                    }
                    else
                    {
                        end--;
                    }
                }
                else
                {
                    if (end - 2 >= start)
                    {
                        end -= 2;
                    }
                    else
                    {
                        end--;
                    }
                }
            }
            return sequence.Reverse();
        }
    }
}

//We are given numbers N and M and the following operations:
//  * `N = N+1`
//  * `N = N+2`
//  * `N = N*2`

//  - Write a program that finds the shortest sequence of operations from the list above that starts from `N` and finishes in `M`.
//  - _Hint_: use a queue.
//  - Example: `N = 5`, `M = 16`
//  - Sequence: 5 → 7 → 8 → 16

namespace SequenceOfOperations
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    internal class Program
    {
        public static void Main()
        {
            int start = 5;
            int end = 26;

            var sequence = GetShortestSequence(start, end);

            Console.WriteLine(string.Join(" -> ", sequence));
        }

        private static IEnumerable<int> GetShortestSequence(int start, int end)
        {
            var sequence = new Queue<int>();

            while (start <= end)
            {
                sequence.Enqueue(end);

                if (end / 2 > start)
                {
                    if (end % 2 == 0)
                    {
                        end /= 2;
                    }
                    else
                    {
                        end--;
                    }
                }
                else
                {
                    if (end - 2 >= start)
                    {
                        end -= 2;
                    }
                    else
                    {
                        end--;
                    }
                }
            }

            return sequence.Reverse();
        }
    }
}

Fix bug from 1 to 3

Fix bug from 1 to 3


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18033
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

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

[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18033
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

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

[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]

Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.


using Xunit;
using Unity.SolrNetCloudIntegration;
using Unity;

namespace SolrNet.Cloud.Tests
{
    public class UnityTests
    {
        private IUnityContainer Setup() {
            return new SolrNetContainerConfiguration().ConfigureContainer(
                new FakeProvider(),
                new UnityContainer());
        }

        [Fact]
        public void ShouldResolveBasicOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrBasicOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveOperationsFromStartupContainer() {
            Assert.NotNull(
                Setup().Resolve<ISolrOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveReadOnlyOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveIOperations ()
        {
            using (var container = new UnityContainer())
            {
                var cont = new Unity.SolrNetCloudIntegration.SolrNetContainerConfiguration().ConfigureContainer(new FakeProvider(), container);
                var obj = cont.Resolve<ISolrOperations<Camera>>();

            }
        }

        public class Camera
        {
            [Attributes.SolrField("Name")]
            public string Name { get; set; }

            [Attributes.SolrField("UID")]
            public int UID { get; set; }

            [Attributes.SolrField("id")]
            public string Id { get; set; }
        }
    }
}

using Xunit;
using Unity.SolrNetCloudIntegration;
using Unity;

namespace SolrNet.Cloud.Tests
{
    public class UnityTests
    {
        private IUnityContainer Setup() {
            return new SolrNetContainerConfiguration().ConfigureContainer(
                new FakeProvider(),
                new UnityContainer());
        }

        [Fact]
        public void ShouldResolveBasicOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrBasicOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveOperationsFromStartupContainer() {
            Assert.NotNull(
                Setup().Resolve<ISolrOperations<FakeEntity>>());
        }

        [Fact]
        public void ShouldResolveReadOnlyOperationsFromStartupContainer()
        {
            Assert.NotNull(
                Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>());
        }
    }
}

Revert "Add test trying to recreate the issue"

This reverts commit 90fdb46611e69f97f0e72690ab5749d353da3828.


using System;
using Cake.Core;
using Cake.Core.Diagnostics;
using Cake.Module.Shared;
using CakeBuildLog = Cake.Core.Diagnostics.CakeBuildLog;

namespace Cake.TeamCity.Module
{
    public class TeamCityLog : ICakeLog
    {
        public TeamCityLog(IConsole console, Verbosity verbosity = Verbosity.Normal)
        {
            _cakeLogImplementation = new CakeBuildLog(console, verbosity);
        }
        private readonly ICakeLog _cakeLogImplementation;

        public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args)
        {
            if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("TF_BUILD")))
            {
                switch (level)
                {
                    case LogLevel.Fatal:
                    case LogLevel.Error:
                        _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information,
                            "##teamcity[buildProblem description='{0}']", string.Format(format, args));
                        break;
                    case LogLevel.Warning:
                        _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information,
                            "##teamcity[message text='{0}' status='WARNING']", string.Format(format, args));
                        break;
                    case LogLevel.Information:
                    case LogLevel.Verbose:
                    case LogLevel.Debug:
                        break;
                    default:
                        throw new ArgumentOutOfRangeException(nameof(level), level, null);
                }
            }
            _cakeLogImplementation.Write(verbosity, level, format, args);
        }

        public Verbosity Verbosity
        {
            get { return _cakeLogImplementation.Verbosity; }
            set { _cakeLogImplementation.Verbosity = value; }
        }
    }
}

using System;
using Cake.Core;
using Cake.Core.Diagnostics;
using Cake.Module.Shared;
using CakeBuildLog = Cake.Core.Diagnostics.CakeBuildLog;

namespace Cake.TeamCity.Module
{
    public class TeamCityLog : ICakeLog
    {
        public TeamCityLog(IConsole console, Verbosity verbosity = Verbosity.Normal)
        {
            _cakeLogImplementation = new CakeBuildLog(console, verbosity);
        }
        private readonly ICakeLog _cakeLogImplementation;

        public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args)
        {
            if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("TEAMCITY_VERSION")))
            {
                switch (level)
                {
                    case LogLevel.Fatal:
                    case LogLevel.Error:
                        _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information,
                            "##teamcity[buildProblem description='{0}']", string.Format(format, args));
                        break;
                    case LogLevel.Warning:
                        _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information,
                            "##teamcity[message text='{0}' status='WARNING']", string.Format(format, args));
                        break;
                    case LogLevel.Information:
                    case LogLevel.Verbose:
                    case LogLevel.Debug:
                        break;
                    default:
                        throw new ArgumentOutOfRangeException(nameof(level), level, null);
                }
            }
            _cakeLogImplementation.Write(verbosity, level, format, args);
        }

        public Verbosity Verbosity
        {
            get { return _cakeLogImplementation.Verbosity; }
            set { _cakeLogImplementation.Verbosity = value; }
        }
    }
}

Fix Environment Variable check for TeamCity Log

Was previously look for TF_BUILD which is for TFS/VSTS Environments.


using System;
using System.Threading.Tasks;
using Messages_Stateless;
using NServiceBus;

namespace Back_Stateless
{
    public class SubmitOrderHandler : IHandleMessages<SubmitOrder>
    {
        private OrderContext orderContext;

        public SubmitOrderHandler(OrderContext orderContext)
        {
            this.orderContext = orderContext;
        }

        public async Task Handle(SubmitOrder message, IMessageHandlerContext context)
        {
            var order = new Order
            {
                ConfirmationId = message.ConfirmationId,
                SubmittedOn = message.SubmittedOn,
                ProcessedOn = DateTime.UtcNow
            };

            orderContext.Orders.Add(order);

            await orderContext.SaveChangesAsync();

            ServiceEventSource.Current.Write(nameof(SubmitOrder), message);
        }
    }
}

using System;
using System.Threading.Tasks;
using Messages_Stateless;
using NServiceBus;

namespace Back_Stateless
{
    public class SubmitOrderHandler : IHandleMessages<SubmitOrder>
    {
        private OrderContext orderContext;

        public SubmitOrderHandler(OrderContext orderContext)
        {
            this.orderContext = orderContext;
        }

        public async Task Handle(SubmitOrder message, IMessageHandlerContext context)
        {
            var order = new Order
            {
                ConfirmationId = message.ConfirmationId,
                SubmittedOn = message.SubmittedOn,
                ProcessedOn = DateTime.UtcNow
            };

            orderContext.Orders.Add(order);

            await orderContext.SaveChangesAsync();
        }
    }
}

Remove service event source for now

Remove service event source for now


#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"

public class ContextInfo
{
    public string NugetVersion { get; set; }
    public string AssemblyVersion { get; set; }
    public GitVersion Git { get; set; }

    public string BuildVersion
    {
        get { return NugetVersion + "-" + Git.Sha; }
    }
}

ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
    get
    {
        if(_versionContext == null)
            throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");

        return _versionContext;
    }
}

public ContextInfo ReadContext(FilePath filepath)
{
    _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
    _versionContext.Git = GitVersion();
    return _versionContext;
}

public void UpdateAppVeyorBuildVersionNumber()
{
    var increment = 0;
    while(increment < 10)
    {
        try
        {
            var version = VersionContext.BuildVersion;
            if(increment > 0)
                version += "-" + increment;

            AppVeyor.UpdateBuildVersion(version);
            break;
        }
        catch
        {
            increment++;
        }
    }
}

#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"

public class ContextInfo
{
    public string NugetVersion { get; set; }
    public string AssemblyVersion { get; set; }
    public GitVersion Git { get; set; }

    public string BuildVersion
    {
        get { return NugetVersion + "-" + Git.Sha; }
    }
}

ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
    get
    {
        if(_versionContext == null)
            throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");

        return _versionContext;
    }
}

public ContextInfo ReadContext(FilePath filepath)
{
    _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
    try
    {
        _versionContext.Git = GitVersion();
    }
    catch
    {
        _versionContext.Git = new Cake.Common.Tools.GitVersion.GitVersion();
    }
    return _versionContext;
}

public void UpdateAppVeyorBuildVersionNumber()
{
    var increment = 0;
    while(increment < 10)
    {
        try
        {
            var version = VersionContext.BuildVersion;
            if(increment > 0)
                version += "-" + increment;

            AppVeyor.UpdateBuildVersion(version);
            break;
        }
        catch
        {
            increment++;
        }
    }
}

Allow to run build even if git repo informations are not available


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RazorEngine;
using NUnit.Framework;

namespace Test.RazorEngine
{
    /// <summary>
    /// Various general tests.
    /// </summary>
    [TestFixture]
    public class VariousTestsFixture
    {
        /// <summary>
        /// Test if we can call GetTypes on the RazorEngine assembly.
        /// This will make sure all SecurityCritical attributes are valid.
        /// </summary>
        [Test]
        public void AssemblyIsScannable()
        {
            typeof(Engine).Assembly.GetTypes();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RazorEngine;
using NUnit.Framework;

namespace Test.RazorEngine
{
    /// <summary>
    /// Various general tests.
    /// </summary>
    [TestFixture]
    public class VariousTestsFixture
    {
        /// <summary>
        /// Test if we can call GetTypes on the RazorEngine assembly.
        /// This will make sure all SecurityCritical attributes are valid.
        /// </summary>
        [Test]
        public void AssemblyIsScannable()
        {
            typeof(Engine).Assembly.GetTypes();
        }
        /*
        /// <summary>
        /// Check that Contracts are enabled and work on this build machine.
        /// </summary>
        [Test]
        [ExpectedException(typeof(ArgumentException))]
        public void ConstractsWork()
        {
            System.Diagnostics.Contracts.Contract.Requires<ArgumentException>(false);
        }

        [Test]
        //[ExpectedException(typeof(Exception))]
        public void ConstractsWork_2()
        {
            System.Diagnostics.Contracts.Contract.Requires(false);
        }*/
    }
}

Add tests to check if contracts are working (currently disabled)


// 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.Runtime.CompilerServices;

namespace System.Collections.Generic
{
    /// <summary>
    /// These public methods are required by RegexWriter.
    /// </summary>
    internal ref partial struct ValueListBuilder<T>
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public T Pop()
        {
            _pos--;
            return _span[_pos];
        }
    }
}

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

#nullable enable
using System.Runtime.CompilerServices;

namespace System.Collections.Generic
{
    /// <summary>
    /// These public methods are required by RegexWriter.
    /// </summary>
    internal ref partial struct ValueListBuilder<T>
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public T Pop()
        {
            _pos--;
            return _span[_pos];
        }
    }
}

Fix nullability mismatch on partial declarations


using System;
using System.IO;
using System.Text;

namespace ValveResourceFormat.ResourceTypes
{
    public class Panorama : Blocks.ResourceData
    {
        public byte[] Data { get; private set; }
        public uint Crc32 { get; private set; }

        public override void Read(BinaryReader reader, Resource resource)
        {
            reader.BaseStream.Position = this.Offset;

            Crc32 = reader.ReadUInt32();

            var size = reader.ReadUInt16();
            int headerSize = 4 + 2;

            for (var i = 0; i < size; i++)
            {
                var name = reader.ReadNullTermString(Encoding.UTF8);

                reader.ReadBytes(4); // TODO: ????

                headerSize += name.Length + 1 + 4; // string length + null byte + 4 bytes
            }

            Data = reader.ReadBytes((int)this.Size - headerSize);
            if (ValveResourceFormat.Crc32.Compute(Data) != Crc32)
            {
                throw new InvalidDataException("CRC32 mismatch for read data.");
            }
        }

        public override string ToString()
        {
            return Encoding.UTF8.GetString(Data);
        }
    }
}

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

namespace ValveResourceFormat.ResourceTypes
{
    public class Panorama : Blocks.ResourceData
    {
        public class NameEntry
        {
            public string Name { get; set; }
            public uint CRC32 { get; set; } // TODO: unconfirmed
        }

        public List<NameEntry> Names;

        public byte[] Data { get; private set; }
        public uint CRC32 { get; private set; }

        public Panorama()
        {
            Names = new List<NameEntry>();
        }

        public override void Read(BinaryReader reader, Resource resource)
        {
            reader.BaseStream.Position = this.Offset;

            CRC32 = reader.ReadUInt32();

            var size = reader.ReadUInt16();
            int headerSize = 4 + 2;

            for (var i = 0; i < size; i++)
            {
                var entry = new NameEntry
                {
                    Name = reader.ReadNullTermString(Encoding.UTF8),
                    CRC32 = reader.ReadUInt32(),
                };

                Names.Add(entry);

                headerSize += entry.Name.Length + 1 + 4; // string length + null byte + 4 bytes
            }

            Data = reader.ReadBytes((int)this.Size - headerSize);

            if (Crc32.Compute(Data) != CRC32)
            {
                throw new InvalidDataException("CRC32 mismatch for read data.");
            }
        }

        public override string ToString()
        {
            return Encoding.UTF8.GetString(Data);
        }
    }
}

Read panorama name entries into a list

Read panorama name entries into a list


// Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.
//
// 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 Hazelcast.Util;

namespace Hazelcast.Client.Protocol.Codec
{
    internal static class StackTraceElementCodec
    {
        public static StackTraceElement Decode(IClientMessage clientMessage)
        {
            var declaringClass = clientMessage.GetStringUtf8();
            var methodName = clientMessage.GetStringUtf8();
            var fileName_notNull = clientMessage.GetBoolean();
            string fileName = null;
            if (fileName_notNull)
            {
                fileName = clientMessage.GetStringUtf8();
            }
            var lineNumber = clientMessage.GetInt();
            return new StackTraceElement(declaringClass, methodName, fileName, lineNumber);
        }
    }
}

// Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.
//
// 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 Hazelcast.Util;

namespace Hazelcast.Client.Protocol.Codec
{
    internal static class StackTraceElementCodec
    {
        public static StackTraceElement Decode(IClientMessage clientMessage)
        {
            var declaringClass = clientMessage.GetStringUtf8();
            var methodName = clientMessage.GetStringUtf8();
            var filename_Null = clientMessage.GetBoolean();
            string fileName = null;
            if (!filename_Null)
            {
                fileName = clientMessage.GetStringUtf8();
            }
            var lineNumber = clientMessage.GetInt();
            return new StackTraceElement(declaringClass, methodName, fileName, lineNumber);
        }
    }
}

Update stack trace decoding to match Java


using Umbraco.Core;
using Archetype.Umbraco.Models;

namespace Archetype.Umbraco.Extensions
{
    public static class Extensions
    {
        //lifted from the core as it is marked 'internal'
        public static bool DetectIsJson(this string input)
        {
            input = input.Trim();
            return input.StartsWith("{") && input.EndsWith("}")
                   || input.StartsWith("[") && input.EndsWith("]");
        }

        public static bool IsArchetype(this Property prop)
        {
            return prop.PropertyEditorAlias.InvariantEquals(Constants.PropertyEditorAlias);
        }
    }
}

using System;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Umbraco.Core;
using Umbraco.Web;
using Archetype.Umbraco.Models;

namespace Archetype.Umbraco.Extensions
{
    public static class Extensions
    {
        //lifted from the core as it is marked 'internal'
        public static bool DetectIsJson(this string input)
        {
            input = input.Trim();
            return input.StartsWith("{") && input.EndsWith("}")
                   || input.StartsWith("[") && input.EndsWith("]");
        }

        public static bool IsArchetype(this Property prop)
        {
            return prop.PropertyEditorAlias.InvariantEquals(Constants.PropertyEditorAlias);
        }

        public static HtmlString ParseMacros(this string input, UmbracoHelper umbHelper)
        {
            var regex = new Regex("(<div class=\".*umb-macro-holder.*\".*macroAlias=\"(\\w*)\"(.*)\\/>.*\\/div>)");
            var match = regex.Match(input);

            while (match.Success)
            {
                var parms = match.Groups[3].ToString().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                var dictionary = new Dictionary<string, object>();
                foreach (var parm in parms)
                {
                    var thisParm = parm.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                    dictionary.Add(thisParm[0], thisParm[1].Substring(1, thisParm[1].Length - 2));
                }

                input = input.Replace(match.Groups[0].ToString(), umbHelper.RenderMacro(match.Groups[2].ToString(), dictionary).ToHtmlString());
                match = regex.Match(input);
            }

            return new HtmlString(input);
        }
    }
}

Use an extension to parse the RTE macros into rendered macros


using System;
using System.Linq;
using Android.OS;
using Android.Views;
using Android.Widget;
using Toggl.Joey.UI.Adapters;
using ListFragment = Android.Support.V4.App.ListFragment;

namespace Toggl.Joey.UI.Fragments
{
    public class RecentTimeEntriesListFragment : ListFragment
    {
        public override void OnViewCreated (View view, Bundle savedInstanceState)
        {
            base.OnViewCreated (view, savedInstanceState);
            var headerView = new View (Activity);
            headerView.SetMinimumHeight (6);
            ListView.AddHeaderView (headerView);
            ListAdapter = new RecentTimeEntriesAdapter ();
        }

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

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

            model.Continue ();
        }
    }
}

using System;
using System.Linq;
using Android.OS;
using Android.Views;
using Android.Widget;
using Toggl.Joey.UI.Adapters;
using ListFragment = Android.Support.V4.App.ListFragment;

namespace Toggl.Joey.UI.Fragments
{
    public class RecentTimeEntriesListFragment : ListFragment
    {
        public override void OnViewCreated (View view, Bundle savedInstanceState)
        {
            base.OnViewCreated (view, savedInstanceState);
            var headerView = new View (Activity);
            headerView.SetMinimumHeight (6);
            ListView.AddHeaderView (headerView);
            ListAdapter = new RecentTimeEntriesAdapter ();
        }

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

            if (adapter == null)
                return;

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

            model.Continue ();
        }
    }
}

Fix click on item event after adding header wrapper


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

#nullable enable

using System;
using Newtonsoft.Json;
using osu.Game.Users;

namespace osu.Game.Online.Multiplayer
{
    [Serializable]
    public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser>
    {
        public readonly int UserID;

        public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle;

        public User? User { get; set; }

        [JsonConstructor]
        public MultiplayerRoomUser(in int userId)
        {
            UserID = userId;
        }

        public bool Equals(MultiplayerRoomUser other)
        {
            if (ReferenceEquals(this, other)) return true;

            return UserID == other.UserID;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != GetType()) return false;

            return Equals((MultiplayerRoomUser)obj);
        }

        public override int GetHashCode() => UserID.GetHashCode();
    }
}

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

#nullable enable

using System;
using Newtonsoft.Json;
using osu.Game.Online.Rooms;
using osu.Game.Users;

namespace osu.Game.Online.Multiplayer
{
    [Serializable]
    public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser>
    {
        public readonly int UserID;

        public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle;

        /// <summary>
        /// The availability state of the beatmap, set to <see cref="DownloadState.LocallyAvailable"/> by default.
        /// </summary>
        public BeatmapAvailability BeatmapAvailability { get; set; } = new BeatmapAvailability(DownloadState.LocallyAvailable);

        public User? User { get; set; }

        [JsonConstructor]
        public MultiplayerRoomUser(in int userId)
        {
            UserID = userId;
        }

        public bool Equals(MultiplayerRoomUser other)
        {
            if (ReferenceEquals(this, other)) return true;

            return UserID == other.UserID;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != GetType()) return false;

            return Equals((MultiplayerRoomUser)obj);
        }

        public override int GetHashCode() => UserID.GetHashCode();
    }
}

Add user beatmap availability property

Add user beatmap availability property


using System.Collections.Generic;
using System.Linq;
using FastMember;
using Newtonsoft.Json;

namespace MyAccounts.Business.Extensions
{
    public static class ObjectExtensions
    {
        public static IDictionary<string, string> ToRawMembersDictionary(this object obj)
        {
            var accessor = TypeAccessor.Create(obj.GetType());
            var members = accessor.GetMembers();
            var keyvalues = members.ToDictionary(m => m.Name, m => JsonConvert.ToString(accessor[obj, m.Name]));
            return keyvalues;
        }

        public static void SetFromRawMembersDictionary(this object obj, IDictionary<string, string> keyvalues)
        {
            var typeAccessor = TypeAccessor.Create(obj.GetType());

            foreach (var member in typeAccessor.GetMembers())
            {
                if (keyvalues.ContainsKey(member.Name))
                {
                    var @override = keyvalues[member.Name];

                    typeAccessor[obj, member.Name] = JsonConvert.DeserializeObject(@override, member.Type);
                }
            }
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using FastMember;
using Newtonsoft.Json;

namespace MyAccounts.Business.Extensions
{
    public static class ObjectExtensions
    {
        public static IDictionary<string, string> ToRawMembersDictionary(this object obj)
        {
            var accessor = TypeAccessor.Create(obj.GetType());
            var members = accessor.GetMembers();
            var keyvalues = members.ToDictionary(m => m.Name, m => accessor[obj, m.Name]?.ToString());
            return keyvalues;
        }

        public static void SetFromRawMembersDictionary(this object obj, IDictionary<string, string> keyvalues)
        {
            var typeAccessor = TypeAccessor.Create(obj.GetType());

            foreach (var member in typeAccessor.GetMembers())
            {
                if (keyvalues.ContainsKey(member.Name))
                {
                    var @override = keyvalues[member.Name];

                    typeAccessor[obj, member.Name] = JsonConvert.DeserializeObject(@override, member.Type);
                }
            }
        }
    }
}

Fix regression (unit tests were failing because of this)