using System.Data;
using System.Data.SQLite;
using System.Reflection;
using FakeItEasy;
using FakeItEasy.Core;
using SimpleMigrations;
using SimpleMigrations.VersionProvider;
using Smoother.IoC.Dapper.Repository.UnitOfWork.Data;
using Smoother.IoC.Dapper.Repository.UnitOfWork.UoW;

namespace Smoother.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestClasses.Migrations
{
    public class MigrateDb
    {
        public ISession Connection { get; }
        public MigrateDb()
        {
            var migrationsAssembly = Assembly.GetExecutingAssembly();
            var versionProvider = new SqliteVersionProvider();
            var factory = A.Fake<IDbFactory>();
            Connection = new TestSession(factory, "Data Source=:memory:;Version=3;New=True;");

            A.CallTo(() => factory.CreateUnitOwWork<IUnitOfWork>(A<IDbFactory>._, A<ISession>._))
                .ReturnsLazily(CreateUnitOrWork);
            var migrator = new SimpleMigrator(migrationsAssembly, Connection, versionProvider);
            migrator.Load();
            migrator.MigrateToLatest();
        }

        private IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg)
        {
            return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory) arg.FakedObject, Connection);
        }
    }

    public class TestSession : SqliteSession<SQLiteConnection>
    {
        public TestSession(IDbFactory factory, string connectionString) : base(factory, connectionString)
        {
        }
    }

}

using System.Data;
using System.Data.SQLite;
using System.Reflection;
using FakeItEasy;
using FakeItEasy.Core;
using SimpleMigrations;
using SimpleMigrations.VersionProvider;
using Smoother.IoC.Dapper.Repository.UnitOfWork.Data;
using Smoother.IoC.Dapper.Repository.UnitOfWork.UoW;

namespace Smoother.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestClasses.Migrations
{
    public class MigrateDb
    {
        public ISession Connection { get; }
        public MigrateDb()
        {
            var migrationsAssembly = Assembly.GetExecutingAssembly();
            var versionProvider = new SqliteVersionProvider();
            var factory = A.Fake<IDbFactory>();
            Connection = new TestSession(factory, "Data Source=:memory:;Version=3;New=True;");

            A.CallTo(() => factory.CreateUnitOwWork<IUnitOfWork>(A<IDbFactory>._, A<ISession>._))
                .ReturnsLazily(CreateUnitOrWork);
            var migrator = new SimpleMigrator(migrationsAssembly, Connection, versionProvider);
            migrator.Load();
            migrator.MigrateToLatest();
        }

        private IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg)
        {
            return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory) arg.FakedObject, Connection);
        }
    }

    internal class TestSession : SqliteSession<SQLiteConnection>
    {
        public TestSession(IDbFactory factory, string connectionString) : base(factory, connectionString)
        {
        }
    }

}

Fix issue with test class

Fix issue with test class


using System;

    class Program
    {
        static void Main()
        {
            Console.WriteLine("Hello, C#!");
        }
    }

using System;

    class Program
    {
        static void Main()
        {
            Console.WriteLine(DateTime.Now);
        }
    }

Repair error in Console Writeline

Repair error in Console Writeline


using System;
using System.ComponentModel;
using GitHub.Models;

namespace GitHub.Services
{
    /// <summary>
    /// Responsible for watching the active repository in Team Explorer.
    /// </summary>
    /// <remarks>
    /// A <see cref="PropertyChanged"/> event is fired when moving to a new repository.
    /// A <see cref="StatusChanged"/> event is fired when the CurrentBranch or HeadSha changes.
    /// </remarks>
    public interface ITeamExplorerContext : INotifyPropertyChanged
    {
        /// <summary>
        /// The active Git repository in Team Explorer.
        /// This will be null if no repository is active.
        /// </summary>
        ILocalRepositoryModel ActiveRepository { get; }

        /// <summary>
        /// Fired when the CurrentBranch or HeadSha changes.
        /// </summary>
        event EventHandler StatusChanged;
    }
}

using System;
using System.ComponentModel;
using GitHub.Models;

namespace GitHub.Services
{
    /// <summary>
    /// Responsible for watching the active repository in Team Explorer.
    /// </summary>
    /// <remarks>
    /// A <see cref="PropertyChanged"/> event is fired when moving to a new repository.
    /// A <see cref="StatusChanged"/> event is fired when the CurrentBranch or HeadSha changes.
    /// </remarks>
    public interface ITeamExplorerContext : INotifyPropertyChanged
    {
        /// <summary>
        /// The active Git repository in Team Explorer.
        /// This will be null if no repository is active.
        /// </summary>
        /// <remarks>
        /// This property might be changed by a non-UI thread.
        /// </remarks>
        ILocalRepositoryModel ActiveRepository { get; }

        /// <summary>
        /// Fired when the CurrentBranch or HeadSha changes.
        /// </summary>
        /// <remarks>
        /// This event might fire on a non-UI thread.
        /// </remarks>
        event EventHandler StatusChanged;
    }
}

Add remarks about non-UI thread

Add remarks about non-UI thread


using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using twitch_tv_viewer.Repositories;

namespace twitch_tv_viewer.ViewModels
{
    internal class SettingsViewModel : ViewModelBase
    {
        private ObservableCollection<string> _items;

        private string _selected;

        private readonly ISettingsRepository _settings;

        //

        public SettingsViewModel()
        {
            _settings = new SettingsRepository();
            Items = new ObservableCollection<string> {"Source", "Low"};
            Selected = _settings.Quality;
            ApplyCommand = new RelayCommand(Apply);
            CancelCommand = new RelayCommand(Cancel);
        }

        //

        public Action Close { get; set; }

        public ObservableCollection<string> Items
        {
            get { return _items; }
            set
            {
                _items = value;
                RaisePropertyChanged();
            }
        }

        public string Selected
        {
            get { return _selected; }
            set
            {
                _selected = value;
                RaisePropertyChanged();
            }
        }

        public ICommand ApplyCommand { get; set; }

        public ICommand CancelCommand { get; set; }

        //

        private void Cancel() => Close();

        private void Apply()
        {
            _settings.Quality = Selected;
            Close();
        }
    }
}

using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using twitch_tv_viewer.Repositories;

namespace twitch_tv_viewer.ViewModels
{
    internal class SettingsViewModel : ViewModelBase
    {
        private ObservableCollection<string> _items;

        private string _selected;

        private readonly ISettingsRepository _settings;

        private bool _checked;

        //

        public SettingsViewModel()
        {
            _settings = new SettingsRepository();
            Items = new ObservableCollection<string> {"Source", "Low"};
            Selected = _settings.Quality;
            Checked = _settings.UserAlert;
            ApplyCommand = new RelayCommand(Apply);
            CancelCommand = new RelayCommand(Cancel);
        }

        //

        public Action Close { get; set; }

        public ObservableCollection<string> Items
        {
            get { return _items; }
            set
            {
                _items = value;
                RaisePropertyChanged();
            }
        }

        public string Selected
        {
            get { return _selected; }
            set
            {
                _selected = value;
                RaisePropertyChanged();
            }
        }

        public bool Checked
        {
            get { return _checked; }
            set
            {
                _checked = value;
                RaisePropertyChanged();
            }
        }

        public ICommand ApplyCommand { get; set; }

        public ICommand CancelCommand { get; set; }

        //

        private void Cancel() => Close();

        private void Apply()
        {
            _settings.UserAlert = Checked;
            _settings.Quality = Selected;
            Close();
        }
    }
}

Add bindings in settings viewmodel for user alert


// 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Screens.Ranking.Expanded;

namespace osu.Game.Tests.Visual.Ranking
{
    public class TestSceneStarRatingDisplay : OsuTestScene
    {
        [SetUp]
        public void SetUp() => Schedule(() =>
        {
            StarRatingDisplay changingStarRating;

            Child = new FillFlowContainer
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Children = new Drawable[]
                {
                    new StarRatingDisplay(new StarDifficulty(1.23, 0)),
                    new StarRatingDisplay(new StarDifficulty(2.34, 0)),
                    new StarRatingDisplay(new StarDifficulty(3.45, 0)),
                    new StarRatingDisplay(new StarDifficulty(4.56, 0)),
                    new StarRatingDisplay(new StarDifficulty(5.67, 0)),
                    new StarRatingDisplay(new StarDifficulty(6.78, 0)),
                    new StarRatingDisplay(new StarDifficulty(10.11, 0)),
                    changingStarRating = new StarRatingDisplay(),
                }
            };

            Scheduler.AddDelayed(() =>
            {
                changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next());
            }, 500, true);
        });
    }
}

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

using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Screens.Ranking.Expanded;

namespace osu.Game.Tests.Visual.Ranking
{
    public class TestSceneStarRatingDisplay : OsuTestScene
    {
        [Test]
        public void TestDisplay()
        {
            StarRatingDisplay changingStarRating = null;

            AddStep("load displays", () => Child = new FillFlowContainer
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Children = new Drawable[]
                {
                    new StarRatingDisplay(new StarDifficulty(1.23, 0)),
                    new StarRatingDisplay(new StarDifficulty(2.34, 0)),
                    new StarRatingDisplay(new StarDifficulty(3.45, 0)),
                    new StarRatingDisplay(new StarDifficulty(4.56, 0)),
                    new StarRatingDisplay(new StarDifficulty(5.67, 0)),
                    new StarRatingDisplay(new StarDifficulty(6.78, 0)),
                    new StarRatingDisplay(new StarDifficulty(10.11, 0)),
                    changingStarRating = new StarRatingDisplay(),
                }
            });

            AddRepeatStep("change bottom rating", () =>
            {
                changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next());
            }, 10);
        }
    }
}

Use regular test steps rather than one-time set up and scheduling


@using Microsoft.AspNetCore.Builder
@using Microsoft.Extensions.Options

@model IEnumerable<Category>
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var cultures = LocOptions.Value.SupportedUICultures
        .Skip(1)
        .Select(culture => new { Culture = culture.Name, Name = culture.EnglishName })
        .ToArray();
}

Global categories

            Default name
            @foreach (var culture in cultures)
            {
                @culture.Name translate
            }

        @foreach (var category in Model)
        {

                    @category.Name

                        <input type="text" value="name" class="form-control" />
                        <input type="hidden" value="#@category.Color.ToString("X6")" />

                @foreach (var culture in cultures)
                {
                    var locName = category.Localizations.SingleOrDefault(loc => loc.Culture == culture.Culture);
                    if (locName != null)
                    {
                        @locName.Name
                    }
                    else
                    {
                        @category.Name
                    }
                }

        }

@using Microsoft.AspNetCore.Builder
@using Microsoft.Extensions.Options

@model IEnumerable<Category>
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var cultures = LocOptions.Value.SupportedUICultures
        .Skip(1)
        .Select(culture => new { Culture = culture.Name, Name = culture.EnglishName })
        .ToArray();
}

Global categories

            Default name
            @foreach (var culture in cultures)
            {
                @culture.Name translate
            }

        @foreach (var category in Model)
        {

                    @category.Name

                @foreach (var culture in cultures)
                {
                    var locName = category.Localizations.SingleOrDefault(loc => loc.Culture == culture.Culture);
                    if (locName != null)
                    {
                        @locName.Name
                    }
                    else
                    {
                        @category.Name
                    }
                }

        }

Make global categories colors are display only


using FogCreek.Plugins;

[assembly: AssemblyFogCreekPluginId("FBExtendedEvents@goit.io")]
[assembly: AssemblyFogCreekMajorVersion(3)]
[assembly: AssemblyFogCreekMinorVersionMin(5)]
[assembly: AssemblyFogCreekEmailAddress("jozef.izso@gmail.com")]
[assembly: AssemblyFogCreekWebsite("https://github.com/jozefizso/FBExtendedEvents")]

using FogCreek.Plugins;

[assembly: AssemblyFogCreekPluginId("FBExtendedEvents@goit.io")]
[assembly: AssemblyFogCreekMajorVersion(3)]
[assembly: AssemblyFogCreekMinorVersionMin(5)]
[assembly: AssemblyFogCreekEmailAddress("jozef.izso@gmail.com")]
[assembly: AssemblyFogCreekWebsite("https://github.com/jozefizso/FogBugz-ExtendedEvents")]

Add new plugin repository URL

Add new plugin repository URL


using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;

namespace BatteryCommander.Web.Controllers
{
    [ApiExplorerSettings(IgnoreApi = true)]
    public class AdminController : Controller
    {
        // Admin Tasks:

        // Add/Remove Users

        // Backup SQLite Db

        // Scrub Soldier Data

        private readonly Database db;

        public AdminController(Database db)
        {
            this.db = db;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Backup()
        {
            var data = System.IO.File.ReadAllBytes("Data.db");

            var mimeType = "application/octet-stream";

            return File(data, mimeType);
        }

        public IActionResult Jobs()
        {
            return View(JobManager.AllSchedules);
        }
    }
}

using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Controllers
{
    [ApiExplorerSettings(IgnoreApi = true)]
    public class AdminController : Controller
    {
        // Admin Tasks:

        // Add/Remove Users

        // Backup SQLite Db

        // Scrub Soldier Data

        private readonly Database db;

        public AdminController(Database db)
        {
            this.db = db;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Backup()
        {
            var data = System.IO.File.ReadAllBytes("Data.db");

            var mimeType = "application/octet-stream";

            return File(data, mimeType);
        }

        public IActionResult Jobs()
        {
            return View(JobManager.AllSchedules);
        }

        public async Task<IActionResult> Users()
        {
            var soldiers_with_access =
                await db
                .Soldiers
                .Where(soldier => soldier.CanLogin)
                .Select(soldier => new
                {
                    soldier.FirstName,
                    soldier.LastName,
                    soldier.CivilianEmail
                })
                .ToListAsync();

            return Json(soldiers_with_access);
        }
    }
}

Add simple JSON endpoint for soldiers with access

Fixes #412


using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Foundation;

namespace BleLab.Services
{
    public class CharacteristicSubscriptionService
    {
        private readonly Dictionary<Guid, GattCharacteristic> _subscribedCharacteristics = new Dictionary<Guid, GattCharacteristic>();

        public event TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs> ValueChanged;

        public bool Subscribe(GattCharacteristic characteristic)
        {
            if (_subscribedCharacteristics.ContainsKey(characteristic.Uuid))
                return false;

            characteristic.ValueChanged += CharacteristicOnValueChanged;
            _subscribedCharacteristics.Add(characteristic.Uuid, characteristic);
            return true;
        }

        public bool Unsubscribe(GattCharacteristic characteristic)
        {
            if (!_subscribedCharacteristics.TryGetValue(characteristic.Uuid, out characteristic))
                return false;

            characteristic.ValueChanged -= CharacteristicOnValueChanged;
            _subscribedCharacteristics.Remove(characteristic.Uuid);
            return true;
        }

        public bool IsSubscribed(GattCharacteristic characteristic)
        {
            return _subscribedCharacteristics.ContainsKey(characteristic.Uuid);
        }

        public void DeviceDisconnected(BluetoothLEDevice device)
        {
            if (device == null)
                return;

            var deviceId = device.DeviceId;
            var characteristics = _subscribedCharacteristics.Values.Where(t => t.Service.DeviceId == deviceId).ToList();

            foreach (var characteristic in characteristics)
            {
                try
                {
                    Unsubscribe(characteristic);
                }
                catch
                {
                }
            }
        }

        private void CharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            ValueChanged?.Invoke(sender, args);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Foundation;

namespace BleLab.Services
{
    public class CharacteristicSubscriptionService
    {
        private readonly Dictionary<Guid, GattCharacteristic> _subscribedCharacteristics = new Dictionary<Guid, GattCharacteristic>();

        public event TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs> ValueChanged;

        public bool Subscribe(GattCharacteristic characteristic)
        {
            if (_subscribedCharacteristics.ContainsKey(characteristic.Uuid))
                return false;

            characteristic.ValueChanged += CharacteristicOnValueChanged;
            _subscribedCharacteristics.Add(characteristic.Uuid, characteristic);
            return true;
        }

        public bool Unsubscribe(GattCharacteristic characteristic)
        {
            if (!_subscribedCharacteristics.TryGetValue(characteristic.Uuid, out characteristic))
                return false;

            characteristic.ValueChanged -= CharacteristicOnValueChanged;
            _subscribedCharacteristics.Remove(characteristic.Uuid);
            return true;
        }

        public bool IsSubscribed(GattCharacteristic characteristic)
        {
            return _subscribedCharacteristics.ContainsKey(characteristic.Uuid);
        }

        public void DeviceDisconnected(BluetoothLEDevice device)
        {
            if (device == null)
                return;

            var deviceId = device.DeviceId;
            var characteristics = _subscribedCharacteristics.Values.Where(t => t.Service.Device.DeviceId == deviceId).ToList();

            foreach (var characteristic in characteristics)
            {
                try
                {
                    Unsubscribe(characteristic);
                }
                catch
                {
                }
            }
        }

        private void CharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            ValueChanged?.Invoke(sender, args);
        }
    }
}

Fix of not unsubscribing to characteristics on disconnect


using System;
using Bartender;
using ConsoleApplication.Domain.Personne.Create;
using ConsoleApplication.Domain.Personne.Read;
using ConsoleApplication.Registries;
using StructureMap;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var registry = new Registry();
            registry.IncludeRegistry<InfrastructureRegistry>();
            var container = new Container(registry);

            var createPersonCommandHandler = container.GetInstance<IHandler<CreatePersonCommand>>();
            createPersonCommandHandler.Handle(new CreatePersonCommand());

            var getPersonQueryHandler = container.GetInstance<IHandler<GetPersonQuery, GetPersonReadModel>>();
            var person = getPersonQueryHandler.Handle(new GetPersonQuery());

            Console.WriteLine($"Hello {person.Name} !");

            Console.ReadKey();
        }
    }
}

using System;
using Bartender;
using ConsoleApplication.Domain.Personne.Create;
using ConsoleApplication.Domain.Personne.Read;
using ConsoleApplication.Registries;
using StructureMap;

namespace ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            var registry = new Registry();
            registry.IncludeRegistry<InfrastructureRegistry>();
            var container = new Container(registry);

            var dispatcher = container.GetInstance<IDispatcher>();
            dispatcher.Dispatch(new CreatePersonCommand());

            var person = dispatcher.Dispatch<GetPersonQuery, GetPersonReadModel>(new GetPersonQuery());

            Console.WriteLine($"Hello {person.Name} !");
            Console.ReadKey();
        }
    }
}

Switch direct handling by a syncrhonous dispatching in console sample


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

namespace Common.Alogs
{
    public static class GiftExtensions
    {
        public static double DistanceTo(this Gift one, Gift two)
        {
            var phyOne = one.Latitude / 360 * Math.PI * 2;
            //var phyTwo

            return 0;
        }

        private static double ToRadiant(double degrees)
        {
            return degrees / 360 * Math.PI * 2;
        }
    }
}

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

namespace Common.Alogs
{
    public static class GiftExtensions
    {
        public static double DistanceTo(this Gift one, Gift two)
        {
            const double radius = 6371000;

            var phyOne = ToRadiant(one.Latitude);
            var phyTwo = ToRadiant(two.Latitude);

            var lambdaOne = ToRadiant(one.Longitude);
            var lambdaTwo = ToRadiant(two.Longitude);

            var underRoot =
                PowTwo(Math.Sin((phyTwo - phyOne)/2))
                + Math.Cos(phyOne)
                * Math.Cos(phyTwo)
                * PowTwo(Math.Sin((lambdaTwo - lambdaOne)/2));

            var arg = Math.Sqrt(underRoot);

            return
                2
                * radius
                * Math.Asin(arg);
        }

        private static double PowTwo(double input)
        {
            return Math.Pow(input, 2);
        }

        private static double ToRadiant(double degrees)
        {
            return degrees / 360 * Math.PI * 2;
        }
    }
}

Create algo to calculate distance between gift points


using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Glimpse.Host.Web.AspNet.Framework;

namespace Glimpse.Host.Web.AspNet
{
    public class GlimpseMiddleware
    {
        private readonly RequestDelegate _innerNext;

        public GlimpseMiddleware(RequestDelegate innerNext)
        {
            _innerNext = innerNext;
        }

        public async Task Invoke(Microsoft.AspNet.Http.HttpContext context)
        {
            var newContext = new HttpContext(context);

            await _innerNext(context);
        }
    }
}

using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Glimpse.Host.Web.AspNet.Framework;
using Glimpse.Agent.Web;

namespace Glimpse.Host.Web.AspNet
{
    public class GlimpseMiddleware
    {
        private readonly RequestDelegate _innerNext;
        private readonly WebAgentRuntime _runtime;

        public GlimpseMiddleware(RequestDelegate innerNext)
        {
            _innerNext = innerNext;
            _runtime = new WebAgentRuntime();   // TODO: This shouldn't have this direct depedency
        }

        public async Task Invoke(Microsoft.AspNet.Http.HttpContext context)
        {
            var newContext = new HttpContext(context);

            _runtime.Begin(newContext);

            await _innerNext(context);

            _runtime.End(newContext);
        }
    }
}

Add agent to the web middleware

Add agent to the web middleware


// ReSharper disable once CheckNamespace
namespace IdParser
{
    public enum Version : byte
    {
        PreStandard = 0,
        Aamva2000 = 1,
        Aamva2003 = 2,
        Aamva2005 = 3,
        Aamva2009 = 4,
        Aamva2010 = 5,
        Aamva2011 = 6,
        Aamva2012 = 7,
        Aamva2013 = 8,
        Aamva2016 = 9,
        Future = 99
    }
}

// ReSharper disable once CheckNamespace
namespace IdParser
{
    public enum Version : byte
    {
        PreStandard = 0,
        Aamva2000 = 1,
        Aamva2003 = 2,
        Aamva2005 = 3,
        Aamva2009 = 4,
        Aamva2010 = 5,
        Aamva2011 = 6,
        Aamva2012 = 7,
        Aamva2013 = 8,
        Aamva2016 = 9,
        Aamva2020 = 10,
        Future = 99
    }
}

Add 2020 standard to version enum

Add 2020 standard to version enum


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

using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Graphics.Containers;
using osuTK;

namespace osu.Game.Rulesets.Edit
{
    public class ExpandingToolboxContainer : ExpandingContainer
    {
        protected override double HoverExpansionDelay => 250;

        public ExpandingToolboxContainer(float contractedWidth, float expandedWidth)
            : base(contractedWidth, expandedWidth)
        {
            RelativeSizeAxes = Axes.Y;

            FillFlow.Spacing = new Vector2(10);
        }

        protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos);

        public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos);

        private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.ScreenSpaceDrawQuad.Contains(screenSpacePos);

        protected override bool OnMouseDown(MouseDownEvent e) => true;

        protected override bool OnClick(ClickEvent e) => true;
    }
}

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

#nullable disable

using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Graphics.Containers;
using osuTK;

namespace osu.Game.Rulesets.Edit
{
    public class ExpandingToolboxContainer : ExpandingContainer
    {
        protected override double HoverExpansionDelay => 250;

        public ExpandingToolboxContainer(float contractedWidth, float expandedWidth)
            : base(contractedWidth, expandedWidth)
        {
            RelativeSizeAxes = Axes.Y;

            FillFlow.Spacing = new Vector2(5);
            Padding = new MarginPadding { Vertical = 5 };
        }

        protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos);

        public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos);

        private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.ScreenSpaceDrawQuad.Contains(screenSpacePos);

        protected override bool OnMouseDown(MouseDownEvent e) => true;

        protected override bool OnClick(ClickEvent e) => true;
    }
}

Adjust paddings to feel better now that backgrounds are visible of toolboxes


using System.IO;

namespace AWTY.Http.IntegrationTests
{
    /// <summary>
    ///     A non-optimised version of <see cref="MemoryStream"/> for use in tests.
    /// </summary>
    /// <remarks>
    ///     <see cref="MemoryStream"/> performs a bunch of optimisations unless subclassed.
    ///
    ///     Unfortunately, these optimisations break the tests.
    ///     Although you obviously wouldn't use a MemoryStream in real life, it's the simplest options for these tests.
    /// </remarks>
    public sealed class DumbMemoryStream
        : MemoryStream
    {
        public DumbMemoryStream()
            : base()
        {
        }
    }
}

using System.IO;

namespace AWTY.Http.IntegrationTests
{
    /// <summary>
    ///     A non-optimised version of <see cref="MemoryStream"/> for use in tests.
    /// </summary>
    /// <remarks>
    ///     <see cref="MemoryStream"/>'s CopyToAsync performs a bunch of optimisations unless subclassed.
    ///     https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/io/memorystream.cs#L450
    ///
    ///     Unfortunately, these optimisations break some of our tests.
    ///     Although you obviously wouldn't use a MemoryStream in real life, it's the simplest options for these tests.
    /// </remarks>
    public sealed class DumbMemoryStream
        : MemoryStream
    {
        public DumbMemoryStream()
            : base()
        {
        }
    }
}

Add link to MemoryStream.CopyToAsync source link.


// -----------------------------------------------------------------------
// <copyright file="Global.asax.cs" company="(none)">
//   Copyright © 2015 John Gietzen.  All Rights Reserved.
//   This source is subject to the MIT license.
//   Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------

namespace GitReview
{
    using System.Configuration;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;

    /// <summary>
    /// The GitReview application.
    /// </summary>
    public class GitReviewApplication : HttpApplication
    {
        /// <summary>
        /// Gets the path of the shared repository.
        /// </summary>
        public static string RepositoryPath
        {
            get { return ConfigurationManager.AppSettings["RepositoryPath"]; }
        }

        /// <summary>
        /// Starts the application.
        /// </summary>
        protected virtual void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

// -----------------------------------------------------------------------
// <copyright file="Global.asax.cs" company="(none)">
//   Copyright © 2015 John Gietzen.  All Rights Reserved.
//   This source is subject to the MIT license.
//   Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------

namespace GitReview
{
    using System.Configuration;
    using System.IO;
    using System.Web;
    using System.Web.Hosting;
    using System.Web.Mvc;
    using System.Web.Routing;
    using LibGit2Sharp;

    /// <summary>
    /// The GitReview application.
    /// </summary>
    public class GitReviewApplication : HttpApplication
    {
        /// <summary>
        /// Gets the path of the shared repository.
        /// </summary>
        public static string RepositoryPath
        {
            get { return HostingEnvironment.MapPath(ConfigurationManager.AppSettings["RepositoryPath"]); }
        }

        /// <summary>
        /// Starts the application.
        /// </summary>
        protected virtual void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            var path = GitReviewApplication.RepositoryPath;
            if (!Directory.Exists(path))
            {
                Repository.Init(path, isBare: true);
            }
        }
    }
}

Initialize git repo on startup.

Initialize git repo on startup.


@using CRP.Controllers
@using Microsoft.Web.Mvc
@model IEnumerable<CRP.Core.Domain.Transaction>

                Transaction
                Quantity
                Amount
                Payment Type
                Paid
                Active Eh

            @foreach (var item in Model.Where(a => a.ParentTransaction == null))
            {

                        @using (Html.BeginForm<ItemManagementController>
                        (x => x.ToggleTransactionIsActive(item.Id, Request.QueryString["Transactions-orderBy"], Request.QueryString["Transactions-page"])))
                        {
                            @Html.AntiForgeryToken()
                            @(item.IsActive ? "Deactivate" : "Activate")

                        }

                    @Html.DisplayFor(modelItem => item.TransactionNumber)
                    @Html.DisplayFor(modelItem => item.Quantity)
                    @Html.DisplayFor(modelItem => item.Amount)
                    @Html.DisplayFor(modelItem => item.Credit)
                    @Html.DisplayFor(modelItem => item.Paid)
                    @Html.DisplayFor(modelItem => item.IsActive)

            }

@using CRP.Controllers
@using Microsoft.Web.Mvc
@model IEnumerable<CRP.Core.Domain.Transaction>

                Transaction
                Quantity
                Amount
                Payment Type
                Paid
                Active

            @foreach (var item in Model.Where(a => a.ParentTransaction == null))
            {

                        @using (Html.BeginForm<ItemManagementController>
                        (x => x.ToggleTransactionIsActive(item.Id, Request.QueryString["Transactions-orderBy"], Request.QueryString["Transactions-page"])))
                        {
                            @Html.AntiForgeryToken()
                            @(item.IsActive ? "Deactivate" : "Activate")

                        }

                    @Html.DisplayFor(modelItem => item.TransactionNumber)
                    @Html.DisplayFor(modelItem => item.Quantity)
                    @Html.DisplayFor(modelItem => item.Amount)
                    @Html.DisplayFor(modelItem => item.Credit)
                    @Html.DisplayFor(modelItem => item.Paid)
                    @Html.DisplayFor(modelItem => item.IsActive)

            }

Remove Canadian Styling of bool

Remove Canadian Styling of bool


using Microsoft.AspNet.Identity.EntityFramework;
using NUnit.Framework;
using ZobShop.Models;

namespace ZobShop.Tests.Models.UserTests
{
    [TestFixture]
    public class UserConstructorTests
    {
        [Test]
        public void Constructor_Should_InitializeUserCorrectly()
        {
            var user = new User();

            Assert.IsNotNull(user);
        }

        [Test]
        public void Constructor_Should_BeInstanceOfIdentityUser()
        {
            var user = new User();

            Assert.IsInstanceOf<IdentityUser>(user);
        }
    }
}

using Microsoft.AspNet.Identity.EntityFramework;
using NUnit.Framework;
using ZobShop.Models;

namespace ZobShop.Tests.Models.UserTests
{
    [TestFixture]
    public class UserConstructorTests
    {
        [Test]
        public void Constructor_Should_InitializeUserCorrectly()
        {
            var user = new User();

            Assert.IsNotNull(user);
        }

        [Test]
        public void Constructor_Should_BeInstanceOfIdentityUser()
        {
            var user = new User();

            Assert.IsInstanceOf<IdentityUser>(user);
        }

        [TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
        public void Constructor_ShouldSetUsernameCorrectly(string username, string email, string name, string phoneNumber, string address)
        {
            var user = new User(username, email, name, phoneNumber, address);

            Assert.AreEqual(username, user.UserName);
        }

        [TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
        public void Constructor_ShouldSetNameCorrectly(string username, string email, string name, string phoneNumber, string address)
        {
            var user = new User(username, email, name, phoneNumber, address);

            Assert.AreEqual(name, user.Name);
        }

        [TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
        public void Constructor_ShouldSeEmailCorrectly(string username, string email, string name, string phoneNumber, string address)
        {
            var user = new User(username, email, name, phoneNumber, address);

            Assert.AreEqual(email, user.Email);
        }

        [TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
        public void Constructor_ShouldSetPhoneNumberCorrectly(string username, string email, string name, string phoneNumber, string address)
        {
            var user = new User(username, email, name, phoneNumber, address);

            Assert.AreEqual(phoneNumber, user.PhoneNumber);
        }

        [TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
        public void Constructor_ShouldSetAddressCorrectly(string username, string email, string name, string phoneNumber, string address)
        {
            var user = new User(username, email, name, phoneNumber, address);

            Assert.AreEqual(address, user.Address);
        }
    }
}

Add new user constructor tests

Add new user constructor tests


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BackupMessageHandler.cs" company="Naos">
//   Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Naos.Database.MessageBus.Handlers
{
    using System;

    using Its.Configuration;

    using Naos.Database.MessageBus.Contract;
    using Naos.Database.Tools;
    using Naos.Database.Tools.Backup;
    using Naos.MessageBus.HandlingContract;

    /// <summary>
    /// Naos.MessageBus handler for BackupMessages.
    /// </summary>
    public class BackupMessageHandler : IHandleMessages<BackupDatabaseMessage>
    {
        /// <inheritdoc />
        public void Handle(BackupDatabaseMessage message)
        {
            Action<string> logAction = s => { };

            var settings = Settings.Get<MessageHandlerSettings>();
            var backupDetails = new BackupDetails()
                                    {
                                        Name = message.BackupName,
                                        BackupTo = new Uri(settings.BackupDirectory),
                                        ChecksumOption = ChecksumOption.Checksum,
                                        Cipher = Cipher.NoEncryption,
                                        CompressionOption = CompressionOption.NoCompression,
                                        Description = message.Description,
                                        Device = Device.Disk,
                                        ErrorHandling = ErrorHandling.StopOnError,
                                    };

            DatabaseManager.BackupFull(
                settings.LocalhostConnectionString,
                message.DatabaseName,
                backupDetails,
                settings.DefaultTimeout,
                logAction);
        }
    }
}

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BackupMessageHandler.cs" company="Naos">
//   Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Naos.Database.MessageBus.Handlers
{
    using System;
    using System.IO;

    using Its.Configuration;

    using Naos.Database.MessageBus.Contract;
    using Naos.Database.Tools;
    using Naos.Database.Tools.Backup;
    using Naos.MessageBus.HandlingContract;

    /// <summary>
    /// Naos.MessageBus handler for BackupMessages.
    /// </summary>
    public class BackupMessageHandler : IHandleMessages<BackupDatabaseMessage>
    {
        /// <inheritdoc />
        public void Handle(BackupDatabaseMessage message)
        {
            Action<string> logAction = s => { };

            var settings = Settings.Get<MessageHandlerSettings>();
            var backupFileName = Path.Combine(settings.BackupDirectory, message.BackupName) + ".bak";
            var backupDetails = new BackupDetails()
                                    {
                                        Name = message.BackupName,
                                        BackupTo = new Uri(backupFileName),
                                        ChecksumOption = ChecksumOption.Checksum,
                                        Cipher = Cipher.NoEncryption,
                                        CompressionOption = CompressionOption.NoCompression,
                                        Description = message.Description,
                                        Device = Device.Disk,
                                        ErrorHandling = ErrorHandling.StopOnError,
                                    };

            DatabaseManager.BackupFull(
                settings.LocalhostConnectionString,
                message.DatabaseName,
                backupDetails,
                settings.DefaultTimeout,
                logAction);
        }
    }
}

Fix issue where the file name wasn't getting specified.


using System;
using System.Runtime.InteropServices;

namespace PlayerRank
{
    public class PlayerScore
    {
        public string Name { get; set; }
        public Points Points { get; internal set; }

        public PlayerScore(string name)
        {
            Name = name;
            Points = new Points(0);
        }

        internal void AddPoints(Points points)
        {
            Points += points;
        }

        /// Obsolete V1 API

        [Obsolete("Please use Points instead")]
        public double Score
        {
            get { return Points.GetValue(); }
            internal set { Points = new Points(value); }
        }

    }
}

using System;
using System.Runtime.InteropServices;

namespace PlayerRank
{
    public class PlayerScore
    {
        public string Name { get; set; }
        public Points Points { get; internal set; }

        public PlayerScore(string name)
        {
            Name = name;
            Points = new Points(0);
        }

        internal void AddPoints(Points points)
        {
            Points += points;
        }

        internal void SubtractPoints(Points points)
        {
            Points -= points;
        }

        /// Obsolete V1 API

        [Obsolete("Please use Points instead")]
        public double Score
        {
            get { return Points.GetValue(); }
            internal set { Points = new Points(value); }
        }

    }
}

Add method to subtract points from player


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Media.Capture;

namespace ZXing.Net.Mobile
{
    public class NotSupported
    {
        // Windows Phone 8.1 Native and Windows 8 RT are not supported

        // Microsoft left out the ability to (easily) marshal Camera Preview frames to managed code
        // Which is what ZXing.Net.Mobile needs to work

        // You should upgrade your wpa81 / win8 projects to use Windows Universal (UWP) instead!
    }
}

namespace ZXing.Mobile
{
    public class MobileBarcodeScanner : MobileBarcodeScannerBase
    {
        NotSupportedException ex = new NotSupportedException("Windows Phone 8.1 Native (wpa81) and Windows 8 Store (win8) are not supported, please use Windows Universal (UWP) instead!");

        public override Task<Result> Scan(MobileBarcodeScanningOptions options)
        {
            throw ex;
        }

        public override void ScanContinuously(MobileBarcodeScanningOptions options, Action<Result> scanHandler)
        {
            throw ex;
        }

        public override void Cancel()
        {
            throw ex;
        }

        public override void AutoFocus()
        {
            throw ex;
        }

        public override void Torch(bool on)
        {
            throw ex;
        }

        public override void ToggleTorch()
        {
            throw ex;
        }

        public override bool IsTorchOn
        {
            get
            {
                throw ex;
            }
        }
    }
 }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Media.Capture;

namespace ZXing.Net.Mobile
{
    public class NotSupported
    {
        // Windows Phone 8.1 Native and Windows 8 RT are not supported

        // Microsoft left out the ability to (easily) marshal Camera Preview frames to managed code
        // Which is what ZXing.Net.Mobile needs to work

        // You should upgrade your wpa81 / win8 projects to use Windows Universal (UWP) instead!
    }
}

namespace ZXing.Mobile
{
    public class MobileBarcodeScanner : MobileBarcodeScannerBase
    {
        NotSupportedException ex = new NotSupportedException("Windows Phone 8.1 Native (wpa81) and Windows 8 Store (win8) are not supported, please use Windows Universal (UWP) instead!");

        public override Task<Result> Scan(MobileBarcodeScanningOptions options)
        {
            throw ex;
        }

        public override void ScanContinuously(MobileBarcodeScanningOptions options, Action<Result> scanHandler)
        {
            throw ex;
        }

        public override void Cancel()
        {
            throw ex;
        }

        public override void AutoFocus()
        {
            throw ex;
        }

        public override void Torch(bool on)
        {
            throw ex;
        }

        public override void ToggleTorch()
        {
            throw ex;
        }

        public override void PauseAnalysis()
        {
            throw ex;
        }

        public override void ResumeAnalysis()
        {
            throw ex;
        }

        public override bool IsTorchOn
        {
            get
            {
                throw ex;
            }
        }
    }
 }

Fix PCL contract for Pause/Resume analysis change


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

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

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

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

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

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

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

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

[assembly: CollectionBehavior(DisableTestParallelization = true)]

Disable test parallelization for PerfView tests


using System;
using System.Diagnostics;
using Microsoft.Win32;

namespace Admo.Utilities
{
    public class SoftwareUtils
    {

        public static string GetChromeVersion()
        {
            var path = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
            if (path != null)
                return FileVersionInfo.GetVersionInfo(path.ToString()).FileVersion;
            return String.Empty;
        }
    }
}

using System;
using System.Diagnostics;
using Microsoft.Win32;

namespace Admo.Utilities
{
    public class SoftwareUtils
    {

        public static string GetChromeVersion()
        {
            //Handle both system wide and user installs of chrome
            var pathLocal = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
            var pathMachine = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
            if (pathLocal != null)
            {
                return FileVersionInfo.GetVersionInfo(pathLocal.ToString()).FileVersion;
            }
            if (pathMachine != null)
            {
                return FileVersionInfo.GetVersionInfo(pathMachine.ToString()).FileVersion;
            }
            return String.Empty;
        }
    }
}

Handle system wide installs of chrome

Handle system wide installs of chrome


using System;
using System.IO;
using Compilify.Models;

namespace Compilify.Services
{
    public class CSharpExecutor
    {
        public CSharpExecutor()
            : this(new CSharpCompilationProvider()) { }

        public CSharpExecutor(ICSharpCompilationProvider compilationProvider)
        {
            compiler = compilationProvider;
        }

        private readonly ICSharpCompilationProvider compiler;

        public ExecutionResult Execute(Post post)
        {
            var compilation = compiler.Compile(post);

            byte[] compiledAssembly;
            using (var stream = new MemoryStream())
            using (var fileStream = new FileStream("C:\\output2.dll", FileMode.Truncate))
            {
                var emitResult = compilation.Emit(stream);

                if (!emitResult.Success)
                {
                    return new ExecutionResult { Result = "[Compilation failed]" };
                }

                compilation.Emit(fileStream);

                compiledAssembly = stream.ToArray();
            }

            using (var sandbox = new Sandbox(compiledAssembly))
            {
                return sandbox.Run("EntryPoint", "Result", TimeSpan.FromSeconds(5));
            }
        }
    }
}

using System;
using System.IO;
using Compilify.Models;

namespace Compilify.Services
{
    public class CSharpExecutor
    {
        public CSharpExecutor()
            : this(new CSharpCompilationProvider()) { }

        public CSharpExecutor(ICSharpCompilationProvider compilationProvider)
        {
            compiler = compilationProvider;
        }

        private readonly ICSharpCompilationProvider compiler;

        public ExecutionResult Execute(Post post)
        {
            var compilation = compiler.Compile(post);

            byte[] compiledAssembly;
            using (var stream = new MemoryStream())
            {
                var emitResult = compilation.Emit(stream);

                if (!emitResult.Success)
                {
                    return new ExecutionResult { Result = "[Compilation failed]" };
                }

                compiledAssembly = stream.ToArray();
            }

            using (var sandbox = new Sandbox(compiledAssembly))
            {
                return sandbox.Run("EntryPoint", "Result", TimeSpan.FromSeconds(5));
            }
        }
    }
}

Remove fileStream used for debugging

Remove fileStream used for debugging


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

namespace JSNLog
{
    public static class AppBuilderExtensions
    {
        public static void UseJSNLog(this IAppBuilder app, string loggerUrlRegex = null)
        {
            app.Use<JsnlogMiddlewareComponent>(loggerUrlRegex);
        }
    }
}

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

namespace JSNLog
{
    public static class AppBuilderExtensions
    {
        public static void UseJSNLog(this IAppBuilder app)
        {
            app.Use<JsnlogMiddlewareComponent>();
        }
    }
}

Remove second parameter, bug not picked up by compiler


using System.Reflection;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

using System.Reflection;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

Set nuget package version to 1.0.0

Set nuget package version to 1.0.0


@Scripts.Render("~/Resources/JavaScript/Bootstrap")
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Popover")
@Scripts.Render("~/Resources/JavaScript/Framework")

@if (UserHelper.IsAdmin)
{
    @Scripts.Render("~/Resources/JavaScript/Bootstrap/Tour")
    @Scripts.Render("~/Resources/JavaScript/Bootstrap/Confirmation")
}

@Scripts.Render("~/Resources/JavaScript/Bootstrap")
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Confirmation")
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Popover")
@Scripts.Render("~/Resources/JavaScript/Framework")

@if (UserHelper.IsAdmin)
{
    @Scripts.Render("~/Resources/JavaScript/Bootstrap/Tour")
}

Load Confirmation plugin in PageBuilder

Load Confirmation plugin in PageBuilder


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

using BenchmarkDotNet.Attributes;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Timing;
using osuTK;

namespace osu.Framework.Benchmarks
{
    public class BenchmarkTransformUpdate : BenchmarkTest
    {
        private TestBox target;

        public override void SetUp()
        {
            base.SetUp();

            const int transforms_count = 10000;

            ManualClock clock;

            target = new TestBox { Clock = new FramedClock(clock = new ManualClock()) };

            // transform one target member over a long period
            target.RotateTo(360, transforms_count * 2);

            // transform another over the same period many times
            for (int i = 0; i < transforms_count; i++)
                target.Delay(i).MoveTo(new Vector2(0.01f), 1f);

            clock.CurrentTime = target.LatestTransformEndTime;
            target.Clock.ProcessFrame();
        }

        [Benchmark]
        public void UpdateTransformsWithManyPresent()
        {
            for (int i = 0; i < 10000; i++)
                target.UpdateTransforms();
        }

        private class TestBox : Box
        {
            public override bool RemoveCompletedTransforms => false;

            public new void UpdateTransforms() => base.UpdateTransforms();
        }
    }
}

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

using BenchmarkDotNet.Attributes;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Timing;
using osuTK;

namespace osu.Framework.Benchmarks
{
    public class BenchmarkTransformUpdate : BenchmarkTest
    {
        private TestBox target;
        private TestBox targetNoTransforms;

        public override void SetUp()
        {
            base.SetUp();

            const int transforms_count = 10000;

            ManualClock clock;

            targetNoTransforms = new TestBox { Clock = new FramedClock(clock = new ManualClock()) };
            target = new TestBox { Clock = new FramedClock(clock) };

            // transform one target member over a long period
            target.RotateTo(360, transforms_count * 2);

            // transform another over the same period many times
            for (int i = 0; i < transforms_count; i++)
                target.Delay(i).MoveTo(new Vector2(0.01f), 1f);

            clock.CurrentTime = target.LatestTransformEndTime;
            target.Clock.ProcessFrame();
        }

        [Benchmark]
        public void UpdateTransformsWithNonePresent()
        {
            for (int i = 0; i < 10000; i++)
                targetNoTransforms.UpdateTransforms();
        }

        [Benchmark]
        public void UpdateTransformsWithManyPresent()
        {
            for (int i = 0; i < 10000; i++)
                target.UpdateTransforms();
        }

        private class TestBox : Box
        {
            public override bool RemoveCompletedTransforms => false;

            public new void UpdateTransforms() => base.UpdateTransforms();
        }
    }
}

Add benchmark of updating transforms when none are added


using Hacknet;
using HarmonyLib;
using Pathfinder.Util;

namespace Pathfinder.BaseGameFixes.Performance
{
    [HarmonyPatch]
    internal static class NodeLookup
    {
        [HarmonyPostfix]
        [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.loadComputer))]
        internal static void PopulateOnComputerCreation(object __result)
        {
            ComputerLookup.PopulateLookups((Computer) __result);
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(Computer), nameof(Computer.load))]
        internal static void PopulateOnComputerLoad(Computer __result)
        {
            ComputerLookup.PopulateLookups(__result);
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
        internal static bool ModifyComputerLoaderLookup(out Computer __result, string target)
        {
            __result = ComputerLookup.FindById(target);
            return false;
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
        internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name)
        {
            __result = ComputerLookup.Find(ip_Or_ID_or_Name);
            return false;
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
        internal static void ClearOnQuitGame()
        {
            ComputerLookup.ClearLookups();
        }
    }
}

using Hacknet;
using HarmonyLib;
using Pathfinder.Event;
using Pathfinder.Event.Loading;
using Pathfinder.Util;

namespace Pathfinder.BaseGameFixes.Performance
{
    [HarmonyPatch]
    internal static class NodeLookup
    {
        [Util.Initialize]
        internal static void Initialize()
        {
            EventManager<SaveComputerLoadedEvent>.AddHandler(PopulateOnComputerLoad);
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.loadComputer))]
        internal static void PopulateOnComputerCreation(object __result)
        {
            if (__result == null)
                return;
            ComputerLookup.PopulateLookups((Computer) __result);
        }

        internal static void PopulateOnComputerLoad(SaveComputerLoadedEvent args)
        {
            ComputerLookup.PopulateLookups(args.Comp);
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
        internal static bool ModifyComputerLoaderLookup(out Computer __result, string target)
        {
            __result = ComputerLookup.FindById(target);
            return false;
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
        internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name)
        {
            __result = ComputerLookup.Find(ip_Or_ID_or_Name);
            return false;
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
        internal static void ClearOnQuitGame()
        {
            ComputerLookup.ClearLookups();
        }
    }
}

Fix node lookup not adding saved computers to dict


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

using osu.Framework.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;

namespace osu.Game.Rulesets.Osu.Edit.Masks
{
    public class HitCircleSelectionMask : SelectionMask
    {
        public HitCircleSelectionMask(DrawableHitCircle hitCircle)
            : base(hitCircle)
        {
            Origin = Anchor.Centre;
            AutoSizeAxes = Axes.Both;
            Position = hitCircle.Position;

            InternalChild = new HitCircleMask((HitCircle)hitCircle.HitObject);

            hitCircle.HitObject.PositionChanged += _ => Position = hitCircle.Position;
        }
    }
}

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

using osu.Framework.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;

namespace osu.Game.Rulesets.Osu.Edit.Masks
{
    public class HitCircleSelectionMask : SelectionMask
    {
        public HitCircleSelectionMask(DrawableHitCircle hitCircle)
            : base(hitCircle)
        {
            Origin = Anchor.Centre;
            AutoSizeAxes = Axes.Both;
            Position = hitCircle.Position;

            InternalChild = new HitCircleMask((HitCircle)hitCircle.HitObject);

            hitCircle.HitObject.PositionChanged += _ => Position = hitCircle.HitObject.StackedPosition;
            hitCircle.HitObject.StackHeightChanged += _ => Position = hitCircle.HitObject.StackedPosition;
        }
    }
}

Fix hitcircle selections not responding to stacking changes


using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace FFImageLoading.Helpers
{
    public class MD5Helper : IMD5Helper
    {
        public string MD5(Stream stream)
        {
            var hashProvider = new MD5CryptoServiceProvider();
            var bytes = hashProvider.ComputeHash(stream);
            return BitConverter.ToString(bytes)?.ToSanitizedKey();
        }

        public string MD5(string input)
        {
            var hashProvider = new MD5CryptoServiceProvider();
            var bytes = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(input));
            return BitConverter.ToString(bytes)?.ToSanitizedKey();
        }
    }
}

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace FFImageLoading.Helpers
{
    public class MD5Helper : IMD5Helper
    {
        public string MD5(Stream stream)
        {
            using (var hashProvider = new MD5CryptoServiceProvider())
            {
                var bytes = hashProvider.ComputeHash(stream);
                return BitConverter.ToString(bytes)?.ToSanitizedKey();
            }
        }

        public string MD5(string input)
        {
            using (var hashProvider = new MD5CryptoServiceProvider())
            {
                var bytes = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(input));
                return BitConverter.ToString(bytes)?.ToSanitizedKey();
            }
        }
    }
}

Put MD5CryptoServiceProvider into using clause


Update code references: extension -> contact


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;

namespace poshring
{
    public class CredentialsManager
    {
        public IEnumerable<Credential> GetCredentials()
        {
            int count;
            IntPtr ptr;
            if (!UnsafeAdvapi32.CredEnumerateW(null, 0x1, out count, out ptr))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            var credentials = Enumerable.Range(0, count)
                .Select(i => Marshal.ReadIntPtr(ptr, i*IntPtr.Size))
                .Select(p => new Credential((NativeCredential)Marshal.PtrToStructure(p, typeof(NativeCredential))));
            return credentials;
        }

        public void AddPasswordCredential(string targetName, string userName, string password, string comment)
        {
            using (var credential = new Credential
            {
                TargetName = targetName,
                UserName = userName,
                CredentialBlob = password,
                Comment = comment
            })
            {
                credential.Save();
            }
        }

        public void DeleteCredential(Credential credential)
        {
            if (!UnsafeAdvapi32.CredDeleteW(credential.TargetName, credential.Type, 0))
            {
                var error = (CredentialErrors)Marshal.GetLastWin32Error();
                throw new CredentialManagerException(error, "Could not delete credential.");
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;

namespace poshring
{
    public class CredentialsManager
    {
        public IEnumerable<Credential> GetCredentials()
        {
            int count;
            IntPtr ptr;
            if (!UnsafeAdvapi32.CredEnumerateW(null, 0x1, out count, out ptr))
            {
                var error = (CredentialErrors) Marshal.GetLastWin32Error();
                switch (error)
                {
                    case CredentialErrors.NotFound:
                        return Enumerable.Empty<Credential>();
                    case CredentialErrors.NoSuchLogonSession:
                    case CredentialErrors.InvalidFlags:
                        throw new Win32Exception((int)error);
                    default:
                        throw new InvalidOperationException("Unexpected error while fetching credentials.");
                }
            }

            var credentials = Enumerable.Range(0, count)
                .Select(i => Marshal.ReadIntPtr(ptr, i*IntPtr.Size))
                .Select(p => new Credential((NativeCredential)Marshal.PtrToStructure(p, typeof(NativeCredential))));
            return credentials;
        }

        public void AddPasswordCredential(string targetName, string userName, string password, string comment)
        {
            using (var credential = new Credential
            {
                TargetName = targetName,
                UserName = userName,
                CredentialBlob = password,
                Comment = comment
            })
            {
                credential.Save();
            }
        }

        public void DeleteCredential(Credential credential)
        {
            if (!UnsafeAdvapi32.CredDeleteW(credential.TargetName, credential.Type, 0))
            {
                var error = (CredentialErrors)Marshal.GetLastWin32Error();
                throw new CredentialManagerException(error, "Could not delete credential.");
            }
        }
    }
}

Return empty result when there are no credentials on the system.


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;

namespace Module1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Modules;

namespace Module1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .ConfigureServices(services =>
                {
                    services.AddSingleton(new ModuleInstanceIdProvider("Module1"));
                })
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

Fix Module1 to run as independent app

Fix Module1 to run as independent app


using System.Collections.Generic;
using UrlShortenerApi.Models;

namespace UrlShortenerApi.Repositories
{
    public interface IHeaderRepository
    {
        void Add(Microsoft.AspNetCore.Http.IHeaderDictionary request, int urlID);
        void Add(Header item);
    }
}

using System.Collections.Generic;
using UrlShortenerApi.Models;

namespace UrlShortenerApi.Repositories
{
    public interface IHeaderRepository
    {
        void Add(Microsoft.AspNetCore.Http.IHeaderDictionary headers, int urlID);
        void Add(Header item);
    }
}

Update variable name on Header Repository Interface

This name is more representative.


using Voxalia.ServerGame.WorldSystem;

namespace Voxalia.ServerGame.EntitySystem
{
    public abstract class EntityLiving: PhysicsEntity, EntityDamageable
    {
        public EntityLiving(Region tregion, bool ticks, float maxhealth)
            : base(tregion, ticks)
        {
            MaxHealth = maxhealth;
            Health = maxhealth;
        }

        public float Health = 100;

        public float MaxHealth = 100;

        public virtual float GetHealth()
        {
            return Health;
        }

        public virtual float GetMaxHealth()
        {
            return MaxHealth;
        }

        public virtual void SetHealth(float health)
        {
            Health = health;
            if (MaxHealth != 0 && Health <= 0)
            {
                Die();
            }
        }

        public virtual void Damage(float amount)
        {
            SetHealth(GetHealth() - amount);
        }

        public virtual void SetMaxHealth(float maxhealth)
        {
            MaxHealth = maxhealth;
        }

        public abstract void Die();
    }
}

using System;
using Voxalia.ServerGame.WorldSystem;

namespace Voxalia.ServerGame.EntitySystem
{
    public abstract class EntityLiving: PhysicsEntity, EntityDamageable
    {
        public EntityLiving(Region tregion, bool ticks, float maxhealth)
            : base(tregion, ticks)
        {
            MaxHealth = maxhealth;
            Health = maxhealth;
        }

        public float Health = 100;

        public float MaxHealth = 100;

        public virtual float GetHealth()
        {
            return Health;
        }

        public virtual float GetMaxHealth()
        {
            return MaxHealth;
        }

        public virtual void SetHealth(float health)
        {
            Health = Math.Min(health, MaxHealth);
            if (MaxHealth != 0 && Health <= 0)
            {
                Die();
            }
        }

        public virtual void Damage(float amount)
        {
            SetHealth(GetHealth() - amount);
        }

        public virtual void SetMaxHealth(float maxhealth)
        {
            MaxHealth = maxhealth;
        }

        public abstract void Die();
    }
}

CLean a potential hole in entityliving

CLean a potential hole in entityliving


using AppGet.Commands.Install;
using AppGet.Commands.Uninstall;
using AppGet.Manifests;
using AppGet.Processes;
using NLog;

namespace AppGet.Installers
{
    public abstract class InstallerWhispererBase : IInstallerWhisperer
    {
        private readonly IProcessController _processController;
        private readonly Logger _logger;

        protected InstallerWhispererBase(IProcessController processController, Logger logger)
        {
            _processController = processController;
            _logger = logger;
        }

        public abstract void Install(string installerLocation, PackageManifest packageManifest, InstallOptions installOptions);
        public abstract void Uninstall(PackageManifest packageManifest, UninstallOptions installOptions);
        public abstract bool CanHandle(InstallMethodType installMethod);

        protected virtual int Execute(string exectuable, string args)
        {
            var process = _processController.Start(exectuable, args, OnOutputDataReceived, OnErrorDataReceived);

            _processController.WaitForExit(process);

            return process.ExitCode;
        }

        protected virtual void OnOutputDataReceived(string message)
        {
            _logger.Info(message);
        }

        protected virtual void OnErrorDataReceived(string message)
        {
            _logger.Error(message);
        }
    }
}

using System.ComponentModel;
using AppGet.Commands.Install;
using AppGet.Commands.Uninstall;
using AppGet.Exceptions;
using AppGet.Manifests;
using AppGet.Processes;
using NLog;

namespace AppGet.Installers
{
    public abstract class InstallerWhispererBase : IInstallerWhisperer
    {
        private readonly IProcessController _processController;
        private readonly Logger _logger;

        protected InstallerWhispererBase(IProcessController processController, Logger logger)
        {
            _processController = processController;
            _logger = logger;
        }

        public abstract void Install(string installerLocation, PackageManifest packageManifest, InstallOptions installOptions);
        public abstract void Uninstall(PackageManifest packageManifest, UninstallOptions installOptions);
        public abstract bool CanHandle(InstallMethodType installMethod);

        protected virtual void Execute(string executable, string args)
        {
            try
            {
                var process = _processController.Start(executable, args, OnOutputDataReceived, OnErrorDataReceived);
                _processController.WaitForExit(process);

                if (process.ExitCode != 0)
                {
                    throw new AppGetException($"Installer '{process.ProcessName}' returned with a non-zero exit code. code: {process.ExitCode}");
                }
            }
            catch (Win32Exception e)
            {
                _logger.Error($"{e.Message}, try running AppGet as an administartor");
                throw;
            }
        }

        protected virtual void OnOutputDataReceived(string message)
        {
            _logger.Info(message);
        }

        protected virtual void OnErrorDataReceived(string message)
        {
            _logger.Error(message);
        }
    }
}

Throw error if installer returns a non-zero exist code.


using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

public class NetworkManager : MonoBehaviour {
    public List<string> ChatMessages;

    // Goal #1: Create a reasonable chat system using the NEW UI System
    public void AddChatMessage(string message) {
        PhotonView.Get(this).RPC("AddChatMessageRPC", PhotonTargets.All, message);
    }

    [RPC]
    private void AddChatMessageRPC(string message) {
        // TODO: If message is longer than x characters, split it into multiple messages so that it fits inside the textbox
        while (ChatMessages.Count >= maxChatMessages) {
            ChatMessages.RemoveAt(0);
        }
        ChatMessages.Add(message);
    }

    void Start() {
        PhotonNetwork.player.name = PlayerPrefs.GetString("Username", "Matt");
        ChatMessages = new List<string>();

        Connect();
    }

    void Update() {
    }

    void Connect() {
        PhotonNetwork.ConnectUsingSettings("FPS Test v001");
    }

    void OnGUI() {
        GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());

    }

    void OnJoinedLobby() {
        Debug.Log("OnJoinedLobby");
        PhotonNetwork.JoinRandomRoom();
    }

    void OnPhotonRandomJoinFailed() {
        Debug.Log("OnPhotonRandomJoinFailed");
        PhotonNetwork.CreateRoom(null);
    }

    void OnJoinedRoom() {
        Debug.Log("OnJoinedRoom");
        AddChatMessage("[SYSTEM] OnJoinedRoom!");
    }

    const int maxChatMessages = 7;
}

using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

public class NetworkManager : MonoBehaviour {
    public List<string> ChatMessages;
    public bool IsOfflineMode;

    // Goal #1: Create a reasonable chat system using the NEW UI System
    public void AddChatMessage(string message) {
        PhotonView.Get(this).RPC("AddChatMessageRPC", PhotonTargets.All, message);
    }

    [RPC]
    private void AddChatMessageRPC(string message) {
        // TODO: If message is longer than x characters, split it into multiple messages so that it fits inside the textbox
        while (ChatMessages.Count >= maxChatMessages) {
            ChatMessages.RemoveAt(0);
        }
        ChatMessages.Add(message);
    }

    void Start() {
        PhotonNetwork.player.name = PlayerPrefs.GetString("Username", "Matt");
        ChatMessages = new List<string>();

        if (IsOfflineMode) {
            PhotonNetwork.offlineMode = true;
            OnJoinedLobby();
        } else {
            Connect();
        }
    }

    void Update() {
    }

    void Connect() {
        PhotonNetwork.ConnectUsingSettings("FPS Test v001");
    }

    void OnGUI() {
        GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());

    }

    void OnJoinedLobby() {
        Debug.Log("OnJoinedLobby");
        PhotonNetwork.JoinRandomRoom();
    }

    void OnPhotonRandomJoinFailed() {
        Debug.Log("OnPhotonRandomJoinFailed");
        PhotonNetwork.CreateRoom(null);
    }

    void OnJoinedRoom() {
        Debug.Log("OnJoinedRoom");
        AddChatMessage("[SYSTEM] OnJoinedRoom!");
    }

    const int maxChatMessages = 7;
}

Enable offline mode by default.

Enable offline mode by default.


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

namespace CareerHub.Client.API.Students.Experiences {
    public class ExperienceModel {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Organisation { get; set; }
        public string Description { get; set; }

        public string ContactName { get; set; }
        public string ContactEmail { get; set; }
        public string ContactPhone { get; set; }

        public DateTime StartUtc { get; set; }
        public DateTime? EndUtc { get; set; }

        public DateTime Start { get; set; }
        public DateTime? End { get; set; }

        public string Type { get; set; }
        public string Hours { get; set; }
    }
}

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

namespace CareerHub.Client.API.Students.Experiences {
    public class ExperienceModel {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Organisation { get; set; }
        public string Description { get; set; }

        public string ContactName { get; set; }
        public string ContactEmail { get; set; }
        public string ContactPhone { get; set; }

        public DateTime StartUtc { get; set; }
        public DateTime? EndUtc { get; set; }

        public DateTime Start { get; set; }
        public DateTime? End { get; set; }

        public int? TypeID { get; set; }
        public string Type { get; set; }

        public int? HoursID { get; set; }
        public string Hours { get; set; }
    }
}

Add extra properties to experience model


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Phoebe.Base;
using Phoebe.Common;
using Phoebe.Model;

namespace Phoebe.FormClient
{
    static class Program
    {
        /// <summary>
        /// 全局操作
        /// </summary>
        public static GlobalControl GC = new GlobalControl();

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.Skins.SkinManager.EnableMdiFormSkins();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            LoginForm login = new LoginForm();
            if (login.ShowDialog() == DialogResult.OK)
            {
                Program.GC.CurrentUser = Program.GC.ConvertToLoginUser(login.User);
                Cache.Instance.Add("CurrentUser", Program.GC.CurrentUser); //缓存用户信息

                Application.Run(new MainForm());
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Phoebe.Base;
using Phoebe.Common;
using Phoebe.Model;

namespace Phoebe.FormClient
{
    static class Program
    {
        /// <summary>
        /// 全局操作
        /// </summary>
        public static GlobalControl GC = new GlobalControl();

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.Skins.SkinManager.EnableMdiFormSkins();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            LoginForm login = new LoginForm();
            if (login.ShowDialog() == DialogResult.OK)
            {
                Program.GC.CurrentUser = Program.GC.ConvertToLoginUser(login.User);
                Cache.Instance.Add("CurrentUser", Program.GC.CurrentUser); //缓存用户信息

                Application.Run(new MainForm());
            }
        }

        /// <summary>
        /// 异常消息处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ex"></param>
        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs ex)
        {
            string message = string.Format("{0}\r\n操作发生错误，您需要退出系统么？", ex.Exception.Message);
            if (MessageUtil.ConfirmYesNo(message) == DialogResult.Yes)
            {
                Application.Exit();
            }
        }
    }
}

Add global exception handle, not enable.

Signed-off-by: robertzml <321e7786a406a136366094c578d0f1193a3468e1@126.com>


using UnityEngine;

public class RollFudgeDie : RollSpecialDie
{
	public override string Examine(Vector3 worldPos = default)
	{
		return $"It is showing side {GetFudgeMessage()}";
	}

	protected override string GetMessage()
	{
		return $"The {dieName} lands a {GetFudgeMessage()}";
	}

	private string GetFudgeMessage()
	{
		if (result == 2)
		{
			return specialFaces[1].ToString();
		}

		return $"{specialFaces[result - 1]}.";
	}
}

using UnityEngine;

public class RollFudgeDie : RollSpecialDie
{
	public override string Examine(Vector3 worldPos = default)
	{
		return $"It is showing {GetFudgeMessage()}";
	}

	protected override string GetMessage()
	{
		return $"The {dieName} lands {GetFudgeMessage()}";
	}

	private string GetFudgeMessage()
	{
		// Result 2 is a strange side, we modify the formatting such that it reads "a... what?".
		if (result == 2)
		{
			return $"a{specialFaces[1]}";
		}

		return $"a {specialFaces[result - 1]}.";
	}
}

Clarify FudgeDie special case's formatting


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;

namespace OmniSharp.Utilities
{
    public class DirectoryEnumerator
    {
        private ILogger _logger;

        public DirectoryEnumerator(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
        }

        public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*")
        {
            var allFiles = Enumerable.Empty<string>();

            var directoryStack = new Stack<string>();
            directoryStack.Push(target);

            while (directoryStack.Any())
            {
                var current = directoryStack.Pop();

                try
                {
                    allFiles = allFiles.Concat(GetFiles(current, pattern));

                    foreach (var subdirectory in GetSubdirectories(current))
                    {
                        directoryStack.Push(subdirectory);
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    _logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current));
                }
            }

            return allFiles;
        }

        private IEnumerable<string> GetFiles(string path, string pattern)
        {
            try
            {
                return Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly);
            }
            catch (PathTooLongException)
            {
                _logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
                return Enumerable.Empty<string>();
            }
        }

        private IEnumerable<string> GetSubdirectories(string path)
        {
            try
            {
                return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
            }
            catch (PathTooLongException)
            {
                _logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
                return Enumerable.Empty<string>();
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;

namespace OmniSharp.Utilities
{
    public class DirectoryEnumerator
    {
        private ILogger _logger;

        public DirectoryEnumerator(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
        }

        public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*")
        {
            var allFiles = Enumerable.Empty<string>();

            var directoryStack = new Stack<string>();
            directoryStack.Push(target);

            while (directoryStack.Any())
            {
                var current = directoryStack.Pop();

                try
                {
                    var files = Directory.GetFiles(current, pattern);
                    allFiles = allFiles.Concat(files);

                    foreach (var subdirectory in Directory.EnumerateDirectories(current))
                    {
                        directoryStack.Push(subdirectory);
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    _logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current));
                }
                catch (PathTooLongException)
                {
                    _logger.LogWarning(string.Format("Path {0} is too long, skipping", current));
                }
            }

            return allFiles;
        }
    }
}

Simplify file enumeration and correctly handle path too long exceptions when enumerating sub directories


using System;
using System.IO;
using MonoHaven.Resources;
using MonoHaven.Resources.Layers;
using MonoHaven.Utils;
using NVorbis.OpenTKSupport;
using OpenTK.Audio;

namespace MonoHaven
{
	public class Audio : IDisposable
	{
		private readonly AudioContext context;
		private readonly OggStreamer streamer;

		public Audio()
		{
			context = new AudioContext();
			streamer = new OggStreamer();
		}

		public void Play(Delayed<Resource> res)
		{
			if (res.Value == null)
				return;

			var audio = res.Value.GetLayer<AudioData>();
			var ms = new MemoryStream(audio.Bytes);
			var oggStream = new OggStream(ms);
			oggStream.Play();
		}

		public void Dispose()
		{
			if (streamer != null)
				streamer.Dispose();
			if (context != null)
				context.Dispose();
		}
	}
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using MonoHaven.Resources;
using MonoHaven.Resources.Layers;
using MonoHaven.Utils;
using NVorbis.OpenTKSupport;
using OpenTK.Audio;

namespace MonoHaven
{
	public class Audio : IDisposable
	{
		private readonly AudioContext context;
		private readonly OggStreamer streamer;
		private readonly AudioPlayer player;

		public Audio()
		{
			context = new AudioContext();
			streamer = new OggStreamer();
			player = new AudioPlayer();
			player.Run();
		}

		public void Play(Delayed<Resource> res)
		{
			player.Queue(res);
		}

		public void Dispose()
		{
			player.Stop();

			if (streamer != null)
				streamer.Dispose();
			if (context != null)
				context.Dispose();
		}

		private class AudioPlayer : BackgroundTask
		{
			private readonly Queue<Delayed<Resource>> queue;

			public AudioPlayer() : base("Audio Player")
			{
				queue = new Queue<Delayed<Resource>>();
			}

			protected override void OnStart()
			{
				while (!IsCancelled)
				{
					lock (queue)
					{
						var item = queue.Count > 0 ? queue.Peek() : null;
						if (item != null && item.Value != null)
						{
							queue.Dequeue();

							var audio = item.Value.GetLayer<AudioData>();
							if (audio != null)
							{
								var ms = new MemoryStream(audio.Bytes);
								var oggStream = new OggStream(ms);
								oggStream.Play();
							}
						}
						Monitor.Wait(queue, TimeSpan.FromMilliseconds(100));
					}
				}
			}

			public void Queue(Delayed<Resource> res)
			{
				lock (queue)
				{
					queue.Enqueue(res);
					Monitor.PulseAll(queue);
				}
			}
		}
	}
}

Use separate task to queue sound effects so they can be played when they're loaded


using System;

namespace Braintree
{
    public class VenmoAccount : PaymentMethod
    {
        public string Token { get; protected set; }
        public string Username { get; protected set; }
        public string VenmoUserId { get; protected set; }
        public string SourceDescription { get; protected set; }
        public string ImageUrl { get; protected set; }
        public bool? IsDefault { get; protected set; }
        public string CustomerId { get; protected set; }
        public DateTime? CreatedAt { get; protected set; }
        public DateTime? UpdatedAt { get; protected set; }
        public Subscription[] Subscriptions { get; protected set; }

        protected internal VenmoAccount(NodeWrapper node, BraintreeGateway gateway)
        {
            Token = node.GetString("token");
            Username = node.GetString("username");
            VenmoUserId = node.GetString("venmo-user-id");
            SourceDescription = node.GetString("source-description");
            ImageUrl = node.GetString("image-url");

            IsDefault = node.GetBoolean("default");
            CustomerId = node.GetString("customer-id");

            CreatedAt = node.GetDateTime("created-at");
            UpdatedAt = node.GetDateTime("updated-at");

            var subscriptionXmlNodes = node.GetList("subscriptions/subscription");
            Subscriptions = new Subscription[subscriptionXmlNodes.Count];
            for (int i = 0; i < subscriptionXmlNodes.Count; i++)
            {
                Subscriptions[i] = new Subscription(subscriptionXmlNodes[i], gateway);
            }
        }
    }
}

using System;

namespace Braintree
{
    public class VenmoAccount : PaymentMethod
    {
        public string Token { get; protected set; }
        public string Username { get; protected set; }
        public string VenmoUserId { get; protected set; }
        public string SourceDescription { get; protected set; }
        public string ImageUrl { get; protected set; }
        public bool? IsDefault { get; protected set; }
        public string CustomerId { get; protected set; }
        public DateTime? CreatedAt { get; protected set; }
        public DateTime? UpdatedAt { get; protected set; }
        public Subscription[] Subscriptions { get; protected set; }

        protected internal VenmoAccount(NodeWrapper node, IBraintreeGateway gateway)
        {
            Token = node.GetString("token");
            Username = node.GetString("username");
            VenmoUserId = node.GetString("venmo-user-id");
            SourceDescription = node.GetString("source-description");
            ImageUrl = node.GetString("image-url");

            IsDefault = node.GetBoolean("default");
            CustomerId = node.GetString("customer-id");

            CreatedAt = node.GetDateTime("created-at");
            UpdatedAt = node.GetDateTime("updated-at");

            var subscriptionXmlNodes = node.GetList("subscriptions/subscription");
            Subscriptions = new Subscription[subscriptionXmlNodes.Count];
            for (int i = 0; i < subscriptionXmlNodes.Count; i++)
            {
                Subscriptions[i] = new Subscription(subscriptionXmlNodes[i], gateway);
            }
        }

        [Obsolete("Mock Use Only")]
        protected internal VenmoAccount() { }
    }
}

Add mock changes to new Venmo class

Add mock changes to new Venmo class