using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Xml.Linq;
using Ionic.Zip;

namespace ThreeDXMLLoader.Implementation.Model
{
    /// <summary>
    /// In memory archive implementation for the IThreeDArchive interface.
    /// </summary>
    class ThreeDRepFile : IThreeDArchive
    {
        private IDictionary<string, Stream> _files;

        private ThreeDRepFile()
        {

        }

        public static IThreeDArchive Create(Stream data)
        {
            var archive = new ThreeDRepFile();
            using (var zipArchive = ZipFile.Read(data))
            {
                foreach (var entry in zipArchive)
                {

                }
            }

            return archive;
        }

        public XDocument GetManifest()
        {
            throw new System.NotImplementedException();
        }

        public XDocument GetNextDocument(string name)
        {
            throw new System.NotImplementedException();
        }
    }

}

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Ionic.Zip;

namespace ThreeDXMLLoader.Implementation.Model
{
    /// <summary>
    /// In memory archive implementation for the IThreeDArchive interface.
    /// </summary>
    class ThreeDRepFile : IThreeDArchive
    {
        private IDictionary<string, Stream> _files;
        private const string ManifestName = "Manifest.xml";

        private ThreeDRepFile(IDictionary<string, Stream> files)
        {
            _files = files;
        }

        /// <summary>
        /// Creates a new in memory archive from a given stream of zipped data.
        /// </summary>
        /// <param name="data">the zip compressed 3dxml archive</param>
        /// <returns>a new instance of a ThreeDRepFile</returns>
        public static IThreeDArchive Create(Stream data)
        {
            var dict = new Dictionary<string, Stream>();
            using (var zipArchive = ZipFile.Read(data))
            {
                foreach (var entry in zipArchive.Where(entry => !entry.IsDirectory))
                {
                    var name = entry.FileName.ToLower();
                    var fileStream = new MemoryStream();
                    entry.Extract(fileStream);
                    dict.Add(name, fileStream);
                }
            }
            var archive = new ThreeDRepFile(dict);

            return archive;
        }

        public XDocument GetManifest()
        {
            return GetNextDocument(ManifestName);
        }

        public XDocument GetNextDocument(string name)
        {
            name = name.ToLower();
            if (!_files.ContainsKey(name))
            {
                throw new Exception($"File {name} not found in archive.");
            }
            var fileStream = _files[name];
            var reader = XmlReader.Create(fileStream);
            reader.MoveToContent();
            return XDocument.Load(reader);
        }
    }

}

Implement the in memory archive

Implement the in memory archive


using System;
using FezGame.Mod;

namespace FezGame {
    public class patch_Fez {

        public void orig_Exit() {
        }

        public void Exit() {
            orig_Exit();
            FEZMod.Exit();
        }

    }
}

using System;
using FezGame.Mod;

namespace FezGame {
    public class patch_Fez {

        public void OnExiting(Object sender, EventArgs args) {
            //It's possible that FEZ doesn't contain this method and thus orig_OnExiting won't exist.
            FEZMod.Exit();
        }

    }
}

Change when FEZMod.Exit gets called. Either LiveSplit doesn't crash on my PC or it's fixed now.


namespace SpotfireDomViewer
{
    using System.Reflection;

    public class MethodNode : DomNode
    {
        private object parentObject;

        private MethodInfo method;

        public MethodNode(object parentObj, MethodInfo m)
            : base(null, NodeTypes.Method, m.ToString())
        {
            parentObject = parentObj;
            method = m;
            CanInvoke = true;
        }
        public string Value
        {
            get
            {
                var v = this.Invoke();
                return v == null ? string.Empty : v.ToString();
            }
        }

        public object Invoke()
        {
            if (method != null)
            {
                return method.Invoke(parentObject, null);
            }

            return null;
        }
    }
}

namespace SpotfireDomViewer
{
    using System.Reflection;

    public class MethodNode : DomNode
    {
        private object parentObject;

        private MethodInfo method;

        public MethodNode(object parentObj, MethodInfo m)
            : base(null, NodeTypes.Method, m.ToString())
        {
            parentObject = parentObj;
            method = m;
            CanInvoke = true;
        }
        public string Value
        {
            get
            {
                // var v = this.Invoke();
                // return v == null ? string.Empty : v.ToString();
                return "Please invoke this method in right panel...";
            }
        }

        public object Invoke()
        {
            if (method != null)
            {
                return method.Invoke(parentObject, null);
            }

            return null;
        }
    }
}

Fix crash in Spotfire 7.0, remove pre-invoke at binding beginning.


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

using osu.Game.Skinning;

#nullable enable

namespace osu.Game.Screens.Edit
{
    /// <summary>
    /// A <see cref="SkinProvidingContainer"/> that fires <see cref="ISkinSource.SourceChanged"/> when users have made a change to the beatmap skin
    /// of the map being edited.
    /// </summary>
    public class EditorSkinProvidingContainer : RulesetSkinProvidingContainer
    {
        private readonly EditorBeatmapSkin? beatmapSkin;

        public EditorSkinProvidingContainer(EditorBeatmap editorBeatmap)
            : base(editorBeatmap.PlayableBeatmap.BeatmapInfo.Ruleset.CreateInstance(), editorBeatmap, editorBeatmap.BeatmapSkin)
        {
            beatmapSkin = editorBeatmap.BeatmapSkin;
        }

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

            if (beatmapSkin != null)
                beatmapSkin.BeatmapSkinChanged += TriggerSourceChanged;
        }

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

            if (beatmapSkin != null)
                beatmapSkin.BeatmapSkinChanged -= TriggerSourceChanged;
        }
    }
}

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

using osu.Game.Skinning;

#nullable enable

namespace osu.Game.Screens.Edit
{
    /// <summary>
    /// A <see cref="SkinProvidingContainer"/> that fires <see cref="ISkinSource.SourceChanged"/> when users have made a change to the beatmap skin
    /// of the map being edited.
    /// </summary>
    public class EditorSkinProvidingContainer : RulesetSkinProvidingContainer
    {
        private readonly EditorBeatmapSkin? beatmapSkin;

        public EditorSkinProvidingContainer(EditorBeatmap editorBeatmap)
            : base(editorBeatmap.PlayableBeatmap.BeatmapInfo.Ruleset.CreateInstance(), editorBeatmap.PlayableBeatmap, editorBeatmap.BeatmapSkin)
        {
            beatmapSkin = editorBeatmap.BeatmapSkin;
        }

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

            if (beatmapSkin != null)
                beatmapSkin.BeatmapSkinChanged += TriggerSourceChanged;
        }

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

            if (beatmapSkin != null)
                beatmapSkin.BeatmapSkinChanged -= TriggerSourceChanged;
        }
    }
}

Fix editor skin providing container not providing playable beatmap


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

namespace Training.CSharpWorkshop
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public RoleEnum Role { get; set; }
    }

    namespace Training.CSharpWorkshop
    {
        public class User
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public RoleEnum Role { get; set; }

            public virtual bool CanInsert()
            {
                return Role == RoleEnum.Admin;
            }

            public bool CanDelete()
            {
                return Role == RoleEnum.Admin;
            }

            public bool CanFind()
            {
                return Role != RoleEnum.None;
            }
        }
    }
}

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

namespace Training.CSharpWorkshop
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public RoleEnum Role { get; set; }
    }
}

Revert "Enum - Add methods to verify against the user's role if the user can add, delete, or find users"

This reverts commit 471ff585580ff97eb462ceef5e3325fc360d56f3.


using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.Internal.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.Setup;

namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
    [Export(typeof(IRoslynTelemetrySetup))]
    internal class RoslynTelemetrySetup : IRoslynTelemetrySetup
    {
        public void Initialize(IServiceProvider serviceProvider)
        {
            var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
            var workspace = componentModel.GetService<VisualStudioWorkspace>();

            // initialize host context on UI thread.
            var projectTypeLookup = workspace.Services.GetService<IProjectTypeLookupService>();

            // set initial logger
            var optionService = workspace.Services.GetService<IOptionService>();
            var loggingChecker = Logger.GetLoggingChecker(optionService);

            var telemetryService = serviceProvider.GetService(typeof(SVsTelemetryService)) as IVsTelemetryService;
            Logger.SetLogger(
                AggregateLogger.Create(
                    CodeMarkerLogger.Instance,
                    new EtwLogger(loggingChecker),
                    new VSTelemetryLogger(telemetryService),
                    new VSTelemetryActivityLogger(telemetryService),
                    Logger.GetLogger()));

            Logger.Log(FunctionId.Run_Environment, KeyValueLogMessage.Create(m => m["Version"] = FileVersionInfo.GetVersionInfo(typeof(VisualStudioWorkspace).Assembly.Location).FileVersion));
        }
    }
}

using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.Internal.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.Setup;

namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
    [Export(typeof(IRoslynTelemetrySetup))]
    internal class RoslynTelemetrySetup : IRoslynTelemetrySetup
    {
        public void Initialize(IServiceProvider serviceProvider)
        {
            var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
            var workspace = componentModel.GetService<VisualStudioWorkspace>();

            // set initial logger
            var optionService = workspace.Services.GetService<IOptionService>();
            var loggingChecker = Logger.GetLoggingChecker(optionService);

            var telemetryService = serviceProvider.GetService(typeof(SVsTelemetryService)) as IVsTelemetryService;
            Logger.SetLogger(
                AggregateLogger.Create(
                    CodeMarkerLogger.Instance,
                    new EtwLogger(loggingChecker),
                    new VSTelemetryLogger(telemetryService),
                    new VSTelemetryActivityLogger(telemetryService),
                    Logger.GetLogger()));

            Logger.Log(FunctionId.Run_Environment, KeyValueLogMessage.Create(m => m["Version"] = FileVersionInfo.GetVersionInfo(typeof(VisualStudioWorkspace).Assembly.Location).FileVersion));
        }
    }
}

Delete initialization of the IProjectTypeLookupService

This doesn't need to be initialized on the UI thread at all.


namespace CurrencyRates.Tests.Base.Extensions
{
    using System;

    using CurrencyRates.Base.Extensions;

    using NUnit.Framework;

    [TestFixture]
    public class StringUtilsTest
    {
        private static readonly object[] TruncateTestCases =
        {
            new object[] { string.Empty, 1, string.Empty },
            new object[] { "Example", 4, "E..." },
            new object[] { "Example", 6, "Exa..." },
            new object[] { "Example", 7, "Example" },
            new object[] { "Example", 8, "Example" }
        };

        [TestCaseSource(nameof(TruncateTestCases))]
        public void TestTruncate(string value, int maxLength, string truncated)
        {
            Assert.That(StringUtils.Truncate(value, maxLength), Is.EqualTo(truncated));
        }

        [Test]
        public void TestTruncateThrowsException()
        {
            var exception = Assert.Throws<ArgumentOutOfRangeException>(() => StringUtils.Truncate("Example", 3));

            Assert.That(exception.ParamName, Is.EqualTo("maxLength"));
            Assert.That(exception.Message, Does.Contain("maxLength must be at least 4"));
        }
    }
}

namespace CurrencyRates.Tests.Base.Extensions
{
    using System;

    using CurrencyRates.Base.Extensions;

    using NUnit.Framework;

    [TestFixture]
    public class StringUtilsTest
    {
        private static readonly object[] TruncateTestCases =
        {
            new object[] { string.Empty, 1, string.Empty },
            new object[] { "Example", 4, "E..." },
            new object[] { "Example", 6, "Exa..." },
            new object[] { "Example", 7, "Example" },
            new object[] { "Example", 8, "Example" }
        };

        [TestCaseSource(nameof(TruncateTestCases))]
        public void TestTruncate(string value, int maxLength, string truncated)
        {
            Assert.That(StringUtils.Truncate(value, maxLength), Is.EqualTo(truncated));
        }

        [Test]
        public void TestTruncateThrowsException()
        {
            Assert.That(
                () => StringUtils.Truncate("Example", 3),
                Throws
                    .TypeOf<ArgumentOutOfRangeException>()
                    .With.Property("ParamName").EqualTo("maxLength")
                    .With.Property("Message").Contain("maxLength must be at least 4")

            );
        }
    }
}

Refactor test to use modern assertions

Refactor test to use modern assertions


using System;
using Microsoft.Owin;
using Owin;
using ReferenceApiWeblessUmbraco.Application;
using ReferenceApiWeblessUmbraco.App_Start;

[assembly: OwinStartup(typeof(OwinStartup))]

namespace ReferenceApiWeblessUmbraco.App_Start
{
    public class OwinStartup
    {
        public void Configuration(IAppBuilder app)
        {
            StartUmbracoContext();
        }

        private void StartUmbracoContext()
        {
            var application = new ReferenceApiApplicationBase();
            application.Start(application, new EventArgs());
        }
    }
}

using System;
using Microsoft.Owin;
using Owin;
using ReferenceApiWeblessUmbraco.Application;
using ReferenceApiWeblessUmbraco.App_Start;
using UmbracoVault;

[assembly: OwinStartup(typeof(OwinStartup))]

namespace ReferenceApiWeblessUmbraco.App_Start
{
    public class OwinStartup
    {
        public void Configuration(IAppBuilder app)
        {
            StartUmbracoContext();
        }

        private void StartUmbracoContext()
        {
            var application = new ReferenceApiApplicationBase();
            application.Start(application, new EventArgs());

            Vault.SetOverrideContext(new UmbracoWeblessContext());
        }
    }
}

Set override Umbraco Vault context in app startup


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

namespace ScooterController
{
    class HardwareController
    {
        public HardwareController()
        {
            if (UsbRelayDevice.Init() != 0)
            {
                Console.WriteLine("Couldn't initialize!");
                return;
            }

            string serial = "FDP2R";
            int deviceHandle = UsbRelayDevice.OpenWithSerialNumber(serial, serial.Length);
            int openResult = UsbRelayDevice.OpenOneRelayChannel(deviceHandle, 1);
            if (openResult == 1)
            {
                Console.WriteLine("Got error from OpenOneRelayChannel!");
                return;
            }
            else if (openResult == 2)
            {
                Console.WriteLine("Index is out of range on the usb relay device");
                return;
            }
            int closeResult = UsbRelayDevice.CloseOneRelayChannel(deviceHandle, 1);

            var x = UsbRelayDevice.Enumerate();
            if (x == null)
            {

            }
        }
    }
}

using System;

namespace ScooterController
{
    class HardwareController
    {
        private readonly int deviceHandle;

        public static void LogError(string message)
        {
            throw new Exception(message);
        }

        public HardwareController(string serialNumber = "FDP2R")
        {
            if (UsbRelayDevice.Init() != 0)
            {
                LogError("Couldn't initialize!");
            }

            this.deviceHandle = UsbRelayDevice.OpenWithSerialNumber(serialNumber, serialNumber.Length);
        }
        ~HardwareController()
        {
            UsbRelayDevice.Close(this.deviceHandle);
        }
    }
}

Implement constructor and dispose method to open/close device


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

namespace PseudoInternationalization {

    class ProcessorFactory {

        private static readonly Dictionary<string, Type> _extensionMap = new Dictionary<string, Type> {
            { ".resx", typeof(ResxProcessor) },
            { ".xml", typeof(AndroidProcessor) },
            { ".strings", typeof(StringSplitOptions) }
        };

        public bool IsSupported(string path) => _extensionMap.ContainsKey(Path.GetExtension(path));

        public IProcessor GetProcessor(string path) {
            var extension = Path.GetExtension(path);
            if (_extensionMap.ContainsKey(extension)) {
                return (IProcessor)Activator.CreateInstance(_extensionMap[extension]);
            }
            else {
                throw new ArgumentException("File type not supported");
            }
        }

    }

}

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

namespace PseudoInternationalization {

    class ProcessorFactory {

        private static readonly Dictionary<string, Type> _extensionMap = new Dictionary<string, Type> {
            { ".resx", typeof(ResxProcessor) },
            { ".xml", typeof(AndroidProcessor) },
            { ".strings", typeof(StringsProcessor) }
        };

        public bool IsSupported(string path) => _extensionMap.ContainsKey(Path.GetExtension(path));

        public IProcessor GetProcessor(string path) {
            var extension = Path.GetExtension(path);
            if (_extensionMap.ContainsKey(extension)) {
                return (IProcessor)Activator.CreateInstance(_extensionMap[extension]);
            }
            else {
                throw new ArgumentException("File type not supported");
            }
        }

    }

}

Fix iOS strings processor loading

Fix iOS strings processor loading


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

using System;
using System.Drawing;
using OpenTK.Graphics.ES20;

namespace osu.Framework.Graphics.OpenGL.Textures
{
    public class TextureUpload : IDisposable
    {
        private static TextureBufferStack TextureBufferStack = new TextureBufferStack(10);

        public int Level;
        public PixelFormat Format = PixelFormat.Rgba;
        public Rectangle Bounds;
        public readonly byte[] Data;
        private bool shouldFreeBuffer;

        public TextureUpload(int size)
        {
            Data = TextureBufferStack.ReserveBuffer(size);
            shouldFreeBuffer = true;
        }

        public TextureUpload(byte[] data)
        {
            Data = data;
        }

        #region IDisposable Support
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (shouldFreeBuffer)
                {
                    TextureBufferStack.FreeBuffer(Data);
                }
                disposedValue = true;
            }
        }

        ~TextureUpload()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}

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

using System;
using System.Drawing;
using OpenTK.Graphics.ES20;

namespace osu.Framework.Graphics.OpenGL.Textures
{
    public class TextureUpload : IDisposable
    {
        private static TextureBufferStack bufferStack = new TextureBufferStack(10);

        public int Level;
        public PixelFormat Format = PixelFormat.Rgba;
        public Rectangle Bounds;
        public readonly byte[] Data;

        public TextureUpload(int size)
        {
            Data = bufferStack.ReserveBuffer(size);
        }

        public TextureUpload(byte[] data)
        {
            Data = data;
        }

        #region IDisposable Support
        private bool disposedValue = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                bufferStack.FreeBuffer(Data);
                disposedValue = true;
            }
        }

        ~TextureUpload()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}

Remove redundant buffer free check.

Remove redundant buffer free check.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplicationFireAndForget.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

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

namespace WebApplicationFireAndForget.Controllers
{
    public class HomeController : Controller
    {
        public async Task<ActionResult> Index()
        {
            await Task.Delay(100);

            Task t = StartAsyncStuffAndDontWaitForIt();

            return View();
        }

        async Task StartAsyncStuffAndDontWaitForIt()
        {
            await Task.Delay(5000);
            await Task.Delay(5000);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

Test async fire & forget

Test async fire & forget


using System;
using System.Diagnostics;
using System.ServiceModel;
using NUnit.Framework;
using TechTalk.SpecFlow;

namespace Host.Specs
{
    /// <summary>
    /// An **copy** of the interface specifying the contract for this service.
    /// </summary>
    [ServiceContract(
        Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
    public interface IHelloIndigoService
    {
        [OperationContract]
        string HelloIndigo();
    }

    [Binding]
    public class RunServiceHostSteps
    {
        [Given(@"that I have started the host")]
        public void GivenThatIHaveStartedTheHost()
        {
            Process.Start(@"..\..\..\Host\bin\Debug\Host.exe");
        }

        [When(@"I execute the ""(.*)"" method of the service")]
        public void WhenIExecuteTheMethodOfTheService(string p0)
        {
            var endPointAddress =
                new EndpointAddress(
                    "http://localhost:8000/HelloIndigo");
            var proxy =
                ChannelFactory<IHelloIndigoService>.CreateChannel(
                    new BasicHttpBinding(), endPointAddress);
            ScenarioContext.Current.Set(proxy);
        }

        [Then(@"I receive ""(.*)"" as a result")]
        public void ThenIReceiveAsAResult(string p0)
        {
            var proxy = ScenarioContext.Current.Get<IHelloIndigoService>();
            var result = proxy.HelloIndigo();
            Assert.That(result, Is.EqualTo("Hello Indigo"));
        }
    }
}

using System;
using System.Diagnostics;
using System.ServiceModel;
using NUnit.Framework;
using TechTalk.SpecFlow;

namespace Host.Specs
{
    /// <summary>
    /// An **copy** of the interface specifying the contract for this service.
    /// </summary>
    [ServiceContract(
        Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
    public interface IHelloIndigoService
    {
        [OperationContract]
        string HelloIndigo();
    }

    [Binding]
    public class RunServiceHostSteps
    {
        [Given(@"that I have started the host")]
        public void GivenThatIHaveStartedTheHost()
        {
            Process.Start(@"..\..\..\Host\bin\Debug\Host.exe");
        }

        [When(@"I execute the ""(.*)"" method of the service")]
        public void WhenIExecuteTheMethodOfTheService(string p0)
        {
            var endPointAddress =
                new EndpointAddress(
                    "http://localhost:8000/HelloIndigo/HelloIndigoService");
            var proxy =
                ChannelFactory<IHelloIndigoService>.CreateChannel(
                    new BasicHttpBinding(),
                    endPointAddress);
            ScenarioContext.Current.Set(proxy);
        }

        [Then(@"I receive ""(.*)"" as a result")]
        public void ThenIReceiveAsAResult(string p0)
        {
            var proxy = ScenarioContext.Current.Get<IHelloIndigoService>();
            var result = proxy.HelloIndigo();
            Assert.That(result, Is.EqualTo("Hello Indigo"));
        }
    }
}

Repair error by changing endpoint address.

Yowza! I do not yet understand how all the WCF pieces fit together. The
test passed by changing the `ServiceHost` URI from `http://localhost:8000/HelloIndigo/` to `http://localhost:8000/HelloIndigo/HelloIndigoService`.

Previously, in these exercises, the URI was `http://localhost:8000/HelloIndigoService/HelloIndigo/`. In the book instructions, the author then indicated the URI was `http://localhost:8000/HelloIndigo/`.

I do not at all understand why the message talked about a mismatch
between the message encoding at the server and the client. This message
seems to be utter misdirection.

I still have much to learn....


/**
 * This file is part of the MarkdownSharp package
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

using System;
using System.Text.RegularExpressions;

namespace MarkdownSharp.Extensions.Mal
{
    /// <summary>
    /// Create short link for http://myanimelist.net
    /// ex: http://myanimelist.net/profile/ritsufag => mal://ritsufag
    /// </summary>
    public class Profile : IExtensionInterface
    {
        private static Regex _malArticles = new Regex(@"
                    (?:http\:\/\/)
                    (?:www\.)?
                    myanimelist\.net\/profile\/
                    ([\w-]{2,16})", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);

        public string Transform(string text)
        {
            return _malArticles.Replace(text, new MatchEvaluator(ProfileEvaluator));
        }

        private string ProfileEvaluator(Match match)
        {
            string userName = match.Groups[1].Value;
            return String.Format(
                "[mal://{0}](http://myanimelist.net/profile/{1})",
                userName, userName
            );
        }
    }
}

/**
 * This file is part of the MarkdownSharp package
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

using System;
using System.Text.RegularExpressions;

namespace MarkdownSharp.Extensions.Mal
{
    /// <summary>
    /// Create short link for http://myanimelist.net
    /// ex: http://myanimelist.net/profile/ritsufag => mal://ritsufag
    /// </summary>
    public class Profile : IExtensionInterface
    {
        private static Regex _malProfiles = new Regex(@"
                    (?:http\:\/\/)
                    (?:www\.)?
                    myanimelist\.net\/profile\/
                    ([\w-]{2,16})", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);

        public string Transform(string text)
        {
            return _malProfiles.Replace(text, new MatchEvaluator(ProfileEvaluator));
        }

        private string ProfileEvaluator(Match match)
        {
            string userName = match.Groups[1].Value;
            return String.Format(
                "[mal://{0}](http://myanimelist.net/profile/{1})",
                userName, userName
            );
        }
    }
}

Fix MAL profile regex name

Fix MAL profile regex name


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;

namespace Sln2CMake
{
    internal class SolutionConverter
    {
        static public void Run(IServiceProvider serviceProvider, IVsStatusbar statusbar)
        {
            var dte = (DTE2)serviceProvider.GetService(typeof(DTE));
            var projects = dte.Solution.Projects;
            for (int i = 1, n = projects.Count; i <= n; ++i)
            {
                var project = projects.Item(i);
                System.Console.WriteLine("[{0} {1}", i, project.Name);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;

namespace Sln2CMake
{
    internal class SolutionConverter
    {
        static public void Run(IServiceProvider serviceProvider, IVsStatusbar statusbar)
        {
            uint cookie = 0;

            var dte = (DTE2)serviceProvider.GetService(typeof(DTE));
            var projects = dte.Solution.Projects;

            // Initialize the progress bar.
            statusbar.Progress(ref cookie, 1, "", 0, 0);

            for (uint i = 1, n = (uint)projects.Count; i <= n; ++i)
            {
                var project = projects.Item(i);
                statusbar.Progress(ref cookie, 1, "", i + 1, n);
                statusbar.SetText(string.Format("Converting {0}", project.Name));
            }

            // Clear the progress bar.
            statusbar.Progress(ref cookie, 0, "", 0, 0);
            statusbar.FreezeOutput(0);
            statusbar.Clear();
        }
    }
}

Add progress and project name in statusbar.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TwitchLib;
using TwitchLib.Models.Client;
using System.Speech.Synthesis;

namespace TwitchBot2002
{
    class Program
    {

        static SpeechSynthesizer synth;

        static void Main(string[] args)
        {
            MainAsync().GetAwaiter().GetResult();
        }

        static async Task MainAsync()
        {
            synth = new SpeechSynthesizer();
            synth.SetOutputToDefaultAudioDevice();

            var authTokens = System.IO.File.ReadLines("tokens.txt").ToArray();
            var client = new TwitchClient(new ConnectionCredentials(authTokens[0], authTokens[1]), "");
            client.OnMessageReceived += Client_OnMessageReceived;
            client.Connect();
            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }

        private static async void Client_OnMessageReceived(object sender, TwitchLib.Events.Client.OnMessageReceivedArgs e)
        {
            if (e.ChatMessage.Bits > 0)
            {
                // voice message!
                synth.SpeakAsync(e.ChatMessage.Message);
                Console.WriteLine($"Voice: {e.ChatMessage.Username}: {e.ChatMessage.Message}");
            }
            else
            {
                Console.WriteLine($"{e.ChatMessage.Username}: {e.ChatMessage.Message}");
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TwitchLib;
using TwitchLib.Models.Client;
using System.Speech.Synthesis;

namespace TwitchBot2002
{
    class Program
    {

        static SpeechSynthesizer synth;

        static void Main(string[] args)
        {
            MainAsync().GetAwaiter().GetResult();
        }

        static async Task MainAsync()
        {
            synth = new SpeechSynthesizer();
            synth.SetOutputToDefaultAudioDevice();

            var authTokens = System.IO.File.ReadLines("tokens.txt").ToArray();
            // Bot Username, API Key, Channel to join.
            var client = new TwitchClient(new ConnectionCredentials(authTokens[0], authTokens[1]), "");
            client.OnMessageReceived += Client_OnMessageReceived;
            client.Connect();
            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }

        private static async void Client_OnMessageReceived(object sender, TwitchLib.Events.Client.OnMessageReceivedArgs e)
        {
            if (e.ChatMessage.Bits > 0)
            {
                // voice message!
                synth.SpeakAsync(e.ChatMessage.Message);
                Console.WriteLine($"Voice: {e.ChatMessage.Username}: {e.ChatMessage.Message}");
            }
            else
            {
                Console.WriteLine($"{e.ChatMessage.Username}: {e.ChatMessage.Message}");
            }
        }
    }
}

Add commit for auth order

Add commit for auth order


using Microsoft.Extensions.Configuration;
using Nancy;
using Nancy.TinyIoc;
using NancyAzureFileUpload.Services;

namespace NancyAzureFileUpload.Helpers
{
    public class CustomBootstrapper : DefaultNancyBootstrapper
    {
        public IConfigurationRoot Configuration;
        public CustomBootstrapper()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(RootPathProvider.GetRootPath())
                .AddJsonFile("appsettings.json")
                .AddEnvironmentVariables();

                Configuration = builder.Build();
        }

        protected override void ConfigureApplicationContainer(TinyIoCContainer ctr)
        {
            ctr.Register<IConfiguration>(Configuration);
            ctr.Register<IDispatchFileService, DispatchFileService>();
        }

    }
}

using Microsoft.Extensions.Configuration;
using Nancy;
using Nancy.TinyIoc;
using NancyAzureFileUpload.Services;

namespace NancyAzureFileUpload.Helpers
{
    public class CustomBootstrapper : DefaultNancyBootstrapper
    {
        public IConfigurationRoot Configuration;
        public CustomBootstrapper()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(RootPathProvider.GetRootPath())
                .AddJsonFile("appsettings.json")
                .AddEnvironmentVariables();
            var tracingConfig = new TraceConfiguration(true, true);

                Configuration = builder.Build();
        }

        protected override void ConfigureApplicationContainer(TinyIoCContainer ctr)
        {
            ctr.Register<IConfiguration>(Configuration);
            ctr.Register<IDispatchFileService, DispatchFileService>();
        }

    }
}

Add TracingConfig to catch error

Add TracingConfig to catch error


using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;

namespace SeleniumTasksProject1._1
{
    [TestFixture]
    public class Chrome
    {
        private IWebDriver driver;
        private WebDriverWait wait;

        [SetUp]
        public void start()
        {
            driver = new ChromeDriver();
            wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
        }

        [Test]
        public void LoginTestInChrome()
        {
            driver.Url = "http://localhost:8082/litecart/admin/";
        }

        [TearDown]
        public void stop()
        {
            driver.Quit();
            driver = null;
        }
    }
}

using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;

namespace SeleniumTasksProject1._1
{
    [TestFixture]
    public class Chrome
    {
        private IWebDriver driver;
        private WebDriverWait wait;

        [SetUp]
        public void start()
        {
            driver = new ChromeDriver();
            wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
        }

        [Test]
        public void LoginTestInChrome()
        {
            driver.Url = "http://localhost:8082/litecart/admin/";
            driver.FindElement(By.Name("username")).SendKeys("admin");
            driver.FindElement(By.Name("password")).SendKeys("admin");
            driver.FindElement(By.Name("login")).Click();
            //wait.Until(ExpectedConditions.TitleIs("My Store"));
        }

        [TearDown]
        public void stop()
        {
            driver.Quit();
            driver = null;
        }
    }
}

Revert "Revert "LoginTest is completed""

This reverts commit 2ef38d17255b46d86a7e688d86251265eb144669.


// 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 Humanizer;
using osu.Game.Online.API.Requests.Responses;
using osuTK.Graphics;

namespace osu.Game.Overlays.Changelog
{
    public class ChangelogUpdateStreamItem : OverlayUpdateStreamItem<APIUpdateStream>
    {
        public ChangelogUpdateStreamItem(APIUpdateStream stream)
            : base(stream)
        {
        }

        protected override string GetMainText() => Value.DisplayName;

        protected override string GetAdditionalText() => Value.LatestBuild.DisplayVersion;

        protected override string GetInfoText() => Value.LatestBuild.Users > 0 ? $"{"user".ToQuantity(Value.LatestBuild.Users, "N0")} online" : null;

        protected override Color4 GetBarColour() => Value.Colour;
    }
}

// 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 Humanizer;
using osu.Game.Online.API.Requests.Responses;
using osuTK.Graphics;

namespace osu.Game.Overlays.Changelog
{
    public class ChangelogUpdateStreamItem : OverlayUpdateStreamItem<APIUpdateStream>
    {
        public ChangelogUpdateStreamItem(APIUpdateStream stream)
            : base(stream)
        {
        }

        protected override float GetWidth()
        {
            if (Value.IsFeatured)
                return base.GetWidth() * 2;

            return base.GetWidth();
        }

        protected override string GetMainText() => Value.DisplayName;

        protected override string GetAdditionalText() => Value.LatestBuild.DisplayVersion;

        protected override string GetInfoText() => Value.LatestBuild.Users > 0 ? $"{"user".ToQuantity(Value.LatestBuild.Users, "N0")} online" : null;

        protected override Color4 GetBarColour() => Value.Colour;
    }
}

Fix featured stream item width

Fix featured stream item width


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TramlineFive.Common;
using TramlineFive.Common.Models;
using TramlineFive.Views.Dialogs;

namespace TramlineFive.ViewModels
{
    public class ArrivalViewModel
    {
        public ObservableCollection<Arrival> Arrivals { get; set; }
        public StringViewModel StopTitle { get; set; }
        public StringViewModel AsOfTime { get; set; }

        public ArrivalViewModel()
        {
            Arrivals = new ObservableCollection<Arrival>();
            StopTitle = new StringViewModel();
            AsOfTime = new StringViewModel();
        }

        public async Task<bool> GetByStopCode(string stopCode)
        {
            Arrivals.Clear();
            StopTitle.Source = String.Empty;
            AsOfTime.Source = String.Empty;

            IEnumerable<Arrival> arrivals = await SumcManager.GetByStopAsync(stopCode, typeof(CaptchaDialog));

            if (arrivals?.Count() == 0)
                return false;

            foreach (Arrival arrival in arrivals ?? Enumerable.Empty<Arrival>())
                Arrivals.Add(arrival);

            StopTitle.Source = SumcParser.ParseStopTitle(Arrivals.FirstOrDefault()?.StopTitle);
            AsOfTime.Source = "Данни от " + DateTime.Now.ToString("HH:mm");

            return true;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TramlineFive.Common;
using TramlineFive.Common.Models;
using TramlineFive.Views.Dialogs;

namespace TramlineFive.ViewModels
{
    public class ArrivalViewModel
    {
        public ObservableCollection<Arrival> Arrivals { get; set; }
        public StringViewModel StopTitle { get; set; }
        public StringViewModel AsOfTime { get; set; }

        public ArrivalViewModel()
        {
            Arrivals = new ObservableCollection<Arrival>();
            StopTitle = new StringViewModel();
            AsOfTime = new StringViewModel();
        }

        public async Task<bool> GetByStopCode(string stopCode)
        {
            Arrivals.Clear();
            StopTitle.Source = String.Empty;
            AsOfTime.Source = String.Empty;

            IEnumerable<Arrival> arrivals = await SumcManager.GetByStopAsync(stopCode, typeof(CaptchaDialog));

            if (arrivals != null)
            {

                if (arrivals.Count() == 0)
                    return false;

                foreach (Arrival arrival in arrivals)
                    Arrivals.Add(arrival);

                StopTitle.Source = SumcParser.ParseStopTitle(Arrivals.FirstOrDefault().StopTitle);
                AsOfTime.Source = "Данни от " + DateTime.Now.ToString("HH:mm");
            }

            return true;
        }
    }
}

Fix UI bugs with time.

Fix UI bugs with time.


using System.Web;
using System.Web.Optimization;

namespace ExamSystem.Backend.Web
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));

            // Set EnableOptimizations to false for debugging. For more information,
            // visit http://go.microsoft.com/fwlink/?LinkId=301862
            BundleTable.EnableOptimizations = true;
        }
    }
}

using System.Web;
using System.Web.Optimization;

namespace ExamSystem.Backend.Web
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));

            // Set EnableOptimizations to false for debugging. For more information,
            // visit http://go.microsoft.com/fwlink/?LinkId=301862
            BundleTable.EnableOptimizations = false;
        }
    }
}

Fix for some css not working on the server


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ExcelDna.Integration;
using Qwack.Dates;
using Qwack.Excel.Services;
namespace Qwack.Excel.Dates
{
    public static class BusinessDateFunctions
    {
        [ExcelFunction(Description = "Checks if the given date is a holiday according to the specified calendars", Category = "QDates")]
        public static object QDates_IsHoliday(
            [ExcelArgument(Description = "The date to check")] DateTime DateToCheck,
            [ExcelArgument(Description = "The calendar(s) to check against")]string Calendar)
        {
            return ExcelHelper.Execute(() =>
            {
                Calendar cal;

                if (!StaticDataService.Instance.CalendarProvider.Collection.TryGetCalendar(Calendar, out cal))
                    return "Calendar not found in cache";

                return cal.IsHoliday(DateToCheck);
            });
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ExcelDna.Integration;
using Qwack.Dates;
using Qwack.Excel.Services;
namespace Qwack.Excel.Dates
{
    public static class BusinessDateFunctions
    {
        [ExcelFunction(Description = "Checks if the given date is a holiday according to the specified calendars", Category = "QDates")]
        public static object QDates_IsHoliday(
            [ExcelArgument(Description = "The date to check")] DateTime DateToCheck,
            [ExcelArgument(Description = "The calendar(s) to check against")]string Calendar)
        {
            return ExcelHelper.Execute(() =>
            {
                Calendar cal;

                if (!StaticDataService.Instance.CalendarProvider.Collection.TryGetCalendar(Calendar, out cal))
                    return "Calendar not found in cache";

                return cal.IsHoliday(DateToCheck);
            });
        }

        [ExcelFunction(Description = "Adds a specified period to a date, adjusting for holidays", Category = "QDates")]
        public static object QDates_AddPeriod(
            [ExcelArgument(Description = "Starting date")] DateTime StartDate,
            [ExcelArgument(Description = "Period specified as a string e.g. 1w")]string Period,
            [ExcelArgument(Description = "Roll method")]string RollMethod,
            [ExcelArgument(Description = "Calendar(s) to check against")]string Calendar)
        {
            return ExcelHelper.Execute(() =>
            {
                Calendar cal;
                if (!StaticDataService.Instance.CalendarProvider.Collection.TryGetCalendar(Calendar, out cal))
                    return $"Calendar {Calendar} not found in cache";

                RollType rollMethod;
                if(!Enum.TryParse<RollType>(RollMethod,out rollMethod))
                    return $"Unknown roll method {RollMethod}";

                Frequency period = new Frequency(Period);

                return StartDate.AddPeriod(rollMethod, cal, period);

            });
        }
    }
}

Add period exposed to excel

Add period exposed to excel


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

using System.Collections.Generic;
using System.Linq;
using osu.Framework.IO.Network;
using osu.Game.Online.Chat;

namespace osu.Game.Online.API.Requests
{
    public class GetChannelMessagesRequest : APIRequest<List<Message>>
    {
        private readonly List<ChannelChat> channels;
        private long? since;

        public GetChannelMessagesRequest(List<ChannelChat> channels, long? sinceId)
        {
            this.channels = channels;
            since = sinceId;
        }

        protected override WebRequest CreateWebRequest()
        {
            string channelString = string.Join(",", channels.Select(x => x.Id));

            var req = base.CreateWebRequest();
            req.AddParameter(@"channels", channelString);
            if (since.HasValue) req.AddParameter(@"since", since.Value.ToString());

            return req;
        }

        protected override string Target => @"chat/messages";
    }
}

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

using System.Collections.Generic;
using System.Linq;
using osu.Framework.IO.Network;
using osu.Game.Online.Chat;

namespace osu.Game.Online.API.Requests
{
    public class GetChannelMessagesRequest : APIRequest<List<Message>>
    {
        private readonly IEnumerable<ChannelChat> channels;
        private long? since;

        public GetChannelMessagesRequest(IEnumerable<ChannelChat> channels, long? sinceId)
        {
            this.channels = channels;
            since = sinceId;
        }

        protected override WebRequest CreateWebRequest()
        {
            string channelString = string.Join(",", channels.Select(x => x.Id));

            var req = base.CreateWebRequest();
            req.AddParameter(@"channels", channelString);
            if (since.HasValue) req.AddParameter(@"since", since.Value.ToString());

            return req;
        }

        protected override string Target => @"chat/messages";
    }
}

Use IEnumable instead of List

Use IEnumable instead of List


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

namespace Stripe
{
    public class StripeCouponUpdateOptions : StripeBaseOptions, ISupportMetadata
    {
        [JsonProperty("metadata")]
        public Dictionary<string, string> Metadata { get; set; }
    }
}

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

namespace Stripe
{
    public class StripeCouponUpdateOptions : StripeBaseOptions, ISupportMetadata
    {
        [JsonProperty("metadata")]
        public Dictionary<string, string> Metadata { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }
    }
}

Add support for updating a coupon's name


using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace MaterialForms.Controls
{
    /// <summary>
    /// Interaction logic for SingleLineTextControl.xaml
    /// </summary>
    public partial class PasswordTextControl : UserControl
    {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.Register("Password",
                typeof(SecureString),
                typeof(PasswordBox),
                new PropertyMetadata(default(SecureString)));

        public SecureString Password
        {
            get { return (SecureString)ValueHolderControl.GetValue(PasswordProperty); }
            set { ValueHolderControl.SetValue(PasswordProperty, value); }
        }

        public PasswordTextControl()
        {
            InitializeComponent();
            ValueHolderControl.PasswordChanged += (sender, args) =>
            {
                Password = ((PasswordBox)sender).SecurePassword;
            };

            var binding = new Binding("Value")
            {
                Mode = BindingMode.TwoWay,
                UpdateSourceTrigger = UpdateSourceTrigger.LostFocus
            };

            ValueHolderControl.SetBinding(PasswordProperty, binding);
        }
    }
}

using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace MaterialForms.Controls
{
    /// <summary>
    /// Interaction logic for SingleLineTextControl.xaml
    /// </summary>
    public partial class PasswordTextControl : UserControl
    {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.Register("Password",
                typeof(SecureString),
                typeof(PasswordBox),
                new PropertyMetadata(default(SecureString)));

        public SecureString Password
        {
            get { return (SecureString)ValueHolderControl.GetValue(PasswordProperty); }
            set { ValueHolderControl.SetValue(PasswordProperty, value); }
        }

        public PasswordTextControl()
        {
            InitializeComponent();
            ValueHolderControl.PasswordChanged += (sender, args) =>
            {
                Password = ((PasswordBox)sender).SecurePassword;
            };

            var binding = new Binding("Value")
            {
                Mode = BindingMode.TwoWay,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            };

            ValueHolderControl.SetBinding(PasswordProperty, binding);
        }
    }
}

Use UpdateSourceTrigger.PropertyChanged for password controls


using System;
using System.Net.Http;

namespace WebApiContrib.Http
{
    public static class HttpRequestMessageExtensions
    {
        private const string HttpContext = "MS_HttpContext";
        private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

        public static bool IsLocal(this HttpRequestMessage request)
        {
            var localFlag = request.Properties["MS_IsLocal"] as Lazy<bool>;
            return localFlag != null && localFlag.Value;
        }

        public static string GetClientIpAddress(this HttpRequestMessage request)
        {
            if (request.Properties.ContainsKey(HttpContext))
            {
                dynamic ctx = request.Properties[HttpContext];
                if (ctx != null)
                {
                    return ctx.Request.UserHostAddress;
                }
            }

            if (request.Properties.ContainsKey(RemoteEndpointMessage))
            {
                dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
                if (remoteEndpoint != null)
                {
                    return remoteEndpoint.Address;
                }
            }

            return null;
        }
    }
}

using System;
using System.Net.Http;

namespace WebApiContrib.Http
{
    public static class HttpRequestMessageExtensions
    {
        private const string HttpContext = "MS_HttpContext";
        private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
        private const string OwinContext = "MS_OwinContext";

        public static bool IsLocal(this HttpRequestMessage request)
        {
            var localFlag = request.Properties["MS_IsLocal"] as Lazy<bool>;
            return localFlag != null && localFlag.Value;
        }

        public static string GetClientIpAddress(this HttpRequestMessage request)
        {
            //Web-hosting
            if (request.Properties.ContainsKey(HttpContext))
            {
                dynamic ctx = request.Properties[HttpContext];
                if (ctx != null)
                {
                    return ctx.Request.UserHostAddress;
                }
            }
            //Self-hosting
            if (request.Properties.ContainsKey(RemoteEndpointMessage))
            {
                dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
                if (remoteEndpoint != null)
                {
                    return remoteEndpoint.Address;
                }
            }
            //Owin-hosting
            if (request.Properties.ContainsKey(OwinContext))
            {
                dynamic ctx = request.Properties[OwinContext];
                if (ctx != null)
                {
                    return ctx.Request.RemoteIpAddress;
                }
            }
            return null;
        }
    }
}

Fix for GetClientIpAddress in OWIN-hosting


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

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Serialization;

namespace Microsoft.CodeAnalysis.Remote.Shared
{
    /// <summary>
    /// provide asset from given map at the creation
    /// </summary>
    internal class SimpleAssetSource : AssetSource
    {
        private readonly IReadOnlyDictionary<Checksum, object> _map;

        public SimpleAssetSource(AssetStorage assetStorage, IReadOnlyDictionary<Checksum, object> map) :
            base(assetStorage)
        {
            _map = map;
        }

        public override Task<IList<(Checksum, object)>> RequestAssetsAsync(
            int serviceId, ISet<Checksum> checksums, ISerializerService serializerService, CancellationToken cancellationToken)
        {
            var list = new List<(Checksum, object)>();

            foreach (var checksum in checksums)
            {
                if (_map.TryGetValue(checksum, out var data))
                {
                    list.Add(ValueTuple.Create(checksum, data));
                    continue;
                }

                Debug.Fail("How?");
            }

            return Task.FromResult<IList<(Checksum, object)>>(list);
        }
    }
}

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

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Serialization;

namespace Microsoft.CodeAnalysis.Remote.Shared
{
    /// <summary>
    /// provide asset from given map at the creation
    /// </summary>
    internal class SimpleAssetSource : AssetSource
    {
        private readonly IReadOnlyDictionary<Checksum, object> _map;

        public SimpleAssetSource(AssetStorage assetStorage, IReadOnlyDictionary<Checksum, object> map) :
            base(assetStorage)
        {
            _map = map;
        }

        public override Task<IList<(Checksum, object)>> RequestAssetsAsync(
            int serviceId, ISet<Checksum> checksums, ISerializerService serializerService, CancellationToken cancellationToken)
        {
            var list = new List<(Checksum, object)>();

            foreach (var checksum in checksums)
            {
                if (_map.TryGetValue(checksum, out var data))
                {
                    list.Add(ValueTuple.Create(checksum, data));
                }
                else
                {
                    Debug.Fail($"Unable to find asset for {checksum}");
                }
            }

            return Task.FromResult<IList<(Checksum, object)>>(list);
        }
    }
}

Add a better message if the SimpleAssetService doesn't have an asset


using System.Runtime.Serialization;

namespace Web.Models
{
    [DataContract]
    public class RelationshipModel
    {
        [DataMember]
        public string Name { get; set; }
    }
}

Make a whitespace change to test the TeamCity upgrade.


using System;
using System.Threading;
using NUnit.Framework;

namespace Atata.WebDriverExtras.Tests
{
    [TestFixture]
    [Parallelizable(ParallelScope.None)]
    public class SafeWaitTests
    {
        private SafeWait<object> wait;

        [SetUp]
        public void SetUp()
        {
            wait = new SafeWait<object>(new object())
            {
                Timeout = TimeSpan.FromSeconds(.3),
                PollingInterval = TimeSpan.FromSeconds(.05)
            };
        }

        [Test]
        public void SafeWait_Success_Immediate()
        {
            using (StopwatchAsserter.Within(0, .01))
                wait.Until(_ =>
                {
                    return true;
                });
        }

        [Test]
        public void SafeWait_Timeout()
        {
            using (StopwatchAsserter.Within(.3, .01))
                wait.Until(_ =>
                {
                    return false;
                });
        }

        [Test]
        public void SafeWait_PollingInterval()
        {
            using (StopwatchAsserter.Within(.3, .2))
                wait.Until(_ =>
                {
                    Thread.Sleep(TimeSpan.FromSeconds(.1));
                    return false;
                });
        }

        [Test]
        public void SafeWait_PollingInterval_GreaterThanTimeout()
        {
            wait.PollingInterval = TimeSpan.FromSeconds(1);

            using (StopwatchAsserter.Within(.3, .01))
                wait.Until(_ =>
                {
                    return false;
                });
        }
    }
}

using System;
using System.Threading;
using NUnit.Framework;

namespace Atata.WebDriverExtras.Tests
{
    [TestFixture]
    [Parallelizable(ParallelScope.None)]
    public class SafeWaitTests
    {
        private SafeWait<object> wait;

        [SetUp]
        public void SetUp()
        {
            wait = new SafeWait<object>(new object())
            {
                Timeout = TimeSpan.FromSeconds(.3),
                PollingInterval = TimeSpan.FromSeconds(.05)
            };
        }

        [Test]
        public void SafeWait_Success_Immediate()
        {
            using (StopwatchAsserter.Within(0, .01))
                wait.Until(_ =>
                {
                    return true;
                });
        }

        [Test]
        public void SafeWait_Timeout()
        {
            using (StopwatchAsserter.Within(.3, .01))
                wait.Until(_ =>
                {
                    return false;
                });
        }

        [Test]
        public void SafeWait_PollingInterval()
        {
            using (StopwatchAsserter.Within(.3, .2))
                wait.Until(_ =>
                {
                    Thread.Sleep(TimeSpan.FromSeconds(.1));
                    return false;
                });
        }

        [Test]
        public void SafeWait_PollingInterval_GreaterThanTimeout()
        {
            wait.PollingInterval = TimeSpan.FromSeconds(1);

            using (StopwatchAsserter.Within(.3, .015))
                wait.Until(_ =>
                {
                    return false;
                });
        }
    }
}

Increase toleranceSeconds in SafeWait_PollingInterval_GreaterThanTimeout test


using System;
using Microsoft.Boogie;
using System.Diagnostics;

namespace symbooglix
{
    /// <summary>
    /// This duplicates Expr accept the identifier expr attached to symbolics
    /// </summary>
    public class NonSymbolicDuplicator : Duplicator
    {
        public NonSymbolicDuplicator()
        {
        }

        public override Expr VisitIdentifierExpr (IdentifierExpr node)
        {
            if (node.Decl is SymbolicVariable)
            {
                Debug.Assert(node == ( node.Decl as SymbolicVariable ).expr, "Mismatched Symbolic IdentifierExpr");
                return node;
            }
            else
                return base.VisitIdentifierExpr (node);
        }
    }
}

using System;
using Microsoft.Boogie;
using System.Diagnostics;

namespace symbooglix
{
    /// <summary>
    /// This duplicates Expr accept the identifier expr attached to symbolics
    /// </summary>
    public class NonSymbolicDuplicator : Duplicator
    {
        public NonSymbolicDuplicator()
        {
        }

        public override Expr VisitIdentifierExpr (IdentifierExpr node)
        {
            if (node.Decl is SymbolicVariable)
            {
                Debug.Assert(node == ( node.Decl as SymbolicVariable ).expr, "Mismatched Symbolic IdentifierExpr");
                if (node != ( node.Decl as SymbolicVariable ).expr)
                    throw new Exception("FIXME");
                return node;
            }
            else
                return base.VisitIdentifierExpr (node);
        }

        // FIXME: I think this is a bug in boogie. IdentifierExpr get cloned twice!
        // By also overriding this method we prevent IdentifierExpr belonging to symbolics getting cloned
        public override Expr VisitExpr(Expr node)
        {
            if (node is IdentifierExpr && (node as IdentifierExpr).Decl is SymbolicVariable)
                return (Expr) this.Visit(node); // Skip duplication
            else
                return base.VisitExpr(node); // Duplicate as normal
        }
    }
}

Fix Symbolic duplication bug (I think). It seems to be a bug in Boogie
that IdentifierExprs can be cloned twice

foo(symbolic_0) == foo(symbolic_0) seemed to expose this.

I should really fix Boogie at some point.


using System.Reflection;

// General info about the product
[assembly: AssemblyTitle("RestImageResize.EPiServer")]
[assembly: AssemblyProduct("RestImageResize")]
[assembly: AssemblyDescription("Includes required dependences and source code for easily start to use RestImageResize package in EPiServer CMS site.")]
[assembly: AssemblyCompany("Roman Mironets, Creuna Kharkiv office")]
[assembly: AssemblyCopyright("Copyright © Roman Mironets 2015")]

// Product version
[assembly: AssemblyVersion("1.1")]
[assembly: AssemblyFileVersion("1.1")]

using System.Reflection;

// General info about the product
[assembly: AssemblyTitle("RestImageResize.EPiServer")]
[assembly: AssemblyProduct("RestImageResize")]
[assembly: AssemblyDescription("Includes required dependences and source code for easily start to use RestImageResize package in EPiServer CMS site.")]
[assembly: AssemblyCompany("Roman Mironets, Creuna Kharkiv office")]
[assembly: AssemblyCopyright("Copyright © Roman Mironets 2015")]

// Product version
[assembly: AssemblyVersion("1.1")]
[assembly: AssemblyInformationalVersion("1.1")]

Replace assembly file version by informational version


using System.Collections.Generic;
using NBitcoin;

namespace MagicalCryptoWallet.Backend
{
	public class BlockFilterBuilder
	{
		private const int P = 20;

		public GolombRiceFilter Build(Block block)
		{
			var key = block.GetHash().ToBytes();

			var buffer = new List<byte[]>();
			buffer.Add(key);

			foreach (var tx in block.Transactions)
			{
				foreach (var txOutput in tx.Outputs)
				{
					var witDestination = PayToWitTemplate.Instance.ExtractScriptPubKeyParameters(txOutput.ScriptPubKey);
					var isValidPayToWitness = witDestination != null;

					if (isValidPayToWitness)
					{
						var scriptPubKeyBytes = txOutput.ScriptPubKey.ToBytes();
						buffer.Add(scriptPubKeyBytes);
					}
				}
			}

			return GolombRiceFilter.Build(key, P, buffer);
		}
	}
}

using System.Collections.Generic;
using NBitcoin;

namespace MagicalCryptoWallet.Backend
{
	public class BlockFilterBuilder
	{
		private const int P = 20;
		private static readonly PayToWitPubKeyHashTemplate P2wpkh = PayToWitPubKeyHashTemplate.Instance;

		public GolombRiceFilter Build(Block block)
		{
			var key = block.GetHash().ToBytes();

			var buffer = new List<byte[]>();
			buffer.Add(key);

			foreach (var tx in block.Transactions)
			{
				foreach (var txOutput in tx.Outputs)
				{
					var isValidPayToWitness = P2wpkh.CheckScriptPubKey(txOutput.ScriptPubKey);

					if (isValidPayToWitness)
					{
						var witKeyId = P2wpkh.ExtractScriptPubKeyParameters(txOutput.ScriptPubKey);
						buffer.Add(witKeyId.ToBytes());
					}
				}
			}

			return GolombRiceFilter.Build(key, P, buffer);
		}
	}
}

Build filters only for P2WPKH scripts

Build filters only for P2WPKH scripts

Previous version created filters for p2wpkh and p2wsh scripts. This
version generates the filters using the push data part of the p2wpkh.


using OAuth;

namespace Crunch.DotNet.Authorization
{
    public static class OAuthTokensExtensions
    {
        public static string GetAuthorisationHeader(this OAuthTokens tokens, string url, string restMethod, string realm = null)
        {
            var oauthClient = OAuthRequest.ForProtectedResource(restMethod, tokens.ConsumerKey, tokens.ConsumerSecret, tokens.Token, tokens.TokenSecret);
            oauthClient.RequestUrl = url;
            oauthClient.Realm = realm;
            return oauthClient.GetAuthorizationHeader();
        }
    }
}

using OAuth;

namespace Crunch.DotNet.Authorization
{
    public static class OAuthTokensExtensions
    {
        public static string GetAuthorisationHeader(this OAuthTokens tokens, string url, string restMethod, string realm = null)
        {
            var oauthClient = new OAuthRequest
            {
                Method = restMethod,
                Type = OAuthRequestType.ProtectedResource,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey = tokens.ConsumerKey,
                ConsumerSecret = tokens.ConsumerSecret,
                Token = tokens.Token,
                TokenSecret = tokens.TokenSecret,
                RequestUrl = url,
                Realm = realm
            };

            return oauthClient.GetAuthorizationHeader();
        }
    }
}

Fix broken auth when POSTing/PUTing data


// 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.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Graphics.Sprites;

namespace osu.Game.Tests.Visual.UserInterface
{
    [TestFixture]
    public class TestSceneHueAnimation : OsuTestScene
    {
        [BackgroundDependencyLoader]
        private void load(LargeTextureStore textures)
        {
            HueAnimation anim;

            Add(anim = new HueAnimation
            {
                RelativeSizeAxes = Axes.Both,
                FillMode = FillMode.Fit,
                Texture = textures.Get("Intro/Triangles/logo-background"),
                Colour = Colour4.White,
            });

            AddSliderStep("Progress", 0f, 1f, 0f, newValue => anim.AnimationProgress = newValue);
        }
    }
}

// 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.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;

namespace osu.Game.Tests.Visual.UserInterface
{
    [TestFixture]
    public class TestSceneHueAnimation : OsuTestScene
    {
        [BackgroundDependencyLoader]
        private void load(LargeTextureStore textures)
        {
            HueAnimation anim2;

            Add(anim2 = new HueAnimation
            {
                RelativeSizeAxes = Axes.Both,
                FillMode = FillMode.Fit,
                Texture = textures.Get("Intro/Triangles/logo-highlight"),
                Colour = Colour4.White,
            });

            HueAnimation anim;

            Add(anim = new HueAnimation
            {
                RelativeSizeAxes = Axes.Both,
                FillMode = FillMode.Fit,
                Texture = textures.Get("Intro/Triangles/logo-background"),
                Colour = OsuColour.Gray(0.6f),
            });

            AddSliderStep("Progress", 0f, 1f, 0f, newValue =>
            {
                anim2.AnimationProgress = newValue;
                anim.AnimationProgress = newValue;
            });
        }
    }
}

Add second layer to test scene

Add second layer to test scene


// 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.Allocation;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Timing;

namespace osu.Game.Tests.Visual.Editing
{
    [TestFixture]
    public class TestSceneTimingScreen : EditorClockTestScene
    {
        [Cached(typeof(EditorBeatmap))]
        private readonly EditorBeatmap editorBeatmap;

        public TestSceneTimingScreen()
        {
            editorBeatmap = new EditorBeatmap(new OsuBeatmap());
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
            Child = new TimingScreen();
        }
    }
}

// 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.Allocation;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Timing;

namespace osu.Game.Tests.Visual.Editing
{
    [TestFixture]
    public class TestSceneTimingScreen : EditorClockTestScene
    {
        [Cached(typeof(EditorBeatmap))]
        [Cached(typeof(IBeatSnapProvider))]
        private readonly EditorBeatmap editorBeatmap;

        public TestSceneTimingScreen()
        {
            editorBeatmap = new EditorBeatmap(new OsuBeatmap());
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
            Child = new TimingScreen();
        }
    }
}

Fix timing screen test crashing due to missing dependency


@model Portal.CMS.Entities.Entities.Page
@{
    ViewBag.Title = Model.PageName;
}

<div id="page-wrapper">
    @Html.Partial("/Areas/PageBuilder/Views/Page/_Page.cshtml", Model)
</div>

@model Portal.CMS.Entities.Entities.Page
@{
    ViewBag.Title = Model.PageName;
}

<div id="page-wrapper" class="visitor">
    @Html.Partial("/Areas/PageBuilder/Views/Page/_Page.cshtml", Model)
</div>

Resolve an issue with the FAQ / Spoiler Component where it does not open and close as intended


using System.Collections.Generic;

namespace Ploeh.AutoFixture.Xunit2
{
    internal class CustomizeAttributeComparer : Comparer<CustomizeAttribute>
    {
        public override int Compare(CustomizeAttribute x, CustomizeAttribute y)
        {
            if (x is FrozenAttribute && !(y is FrozenAttribute))
            {
                return 1;
            }

            if (y is FrozenAttribute && !(x is FrozenAttribute))
            {
                return -1;
            }

            return 0;
        }
    }
}

using System.Collections.Generic;

namespace Ploeh.AutoFixture.Xunit2
{
    internal class CustomizeAttributeComparer : Comparer<CustomizeAttribute>
    {
        public override int Compare(CustomizeAttribute x, CustomizeAttribute y)
        {
            var xfrozen = x is FrozenAttribute;
            var yfrozen = y is FrozenAttribute;

            if (xfrozen && !yfrozen)
            {
                return 1;
            }

            if (yfrozen && !xfrozen)
            {
                return -1;
            }

            return 0;
        }
    }
}

Fix the 'CA1800: Do not cast unnecessarily' code analysis error

https://msdn.microsoft.com/en-us/library/ms182271.aspx


using System.Windows.Input;
using ReactiveUI;

namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
	public class TestDialogViewModel : DialogViewModelBase<bool>
	{
		private NavigationStateViewModel _navigationState;
		private string _message;

		public TestDialogViewModel(NavigationStateViewModel navigationState, string message)
		{
			_navigationState = navigationState;
			_message = message;

			CancelCommand = ReactiveCommand.Create(() => Close(false));
			NextCommand = ReactiveCommand.Create(() => Close(true));
		}

		public string Message
		{
			get => _message;
			set => this.RaiseAndSetIfChanged(ref _message, value);
		}

		public ICommand CancelCommand { get; }
		public ICommand NextCommand { get; }

		protected override void OnDialogClosed()
		{
			_navigationState.HomeScreen?.Invoke().Router.NavigateAndReset.Execute(new AddWalletPageViewModel(_navigationState));
		}

		public void Close()
		{
			// TODO: Dialog.xaml back Button binding to Close() method on base class which is protected so exception is thrown.
			Close(false);
		}
	}
}

using System.Windows.Input;
using ReactiveUI;

namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
	public class TestDialogViewModel : DialogViewModelBase<bool>
	{
		private NavigationStateViewModel _navigationState;
		private string _message;

		public TestDialogViewModel(NavigationStateViewModel navigationState, string message)
		{
			_navigationState = navigationState;
			_message = message;

			CancelCommand = ReactiveCommand.Create(() => Close(false));
			NextCommand = ReactiveCommand.Create(() => Close(true));
		}

		public string Message
		{
			get => _message;
			set => this.RaiseAndSetIfChanged(ref _message, value);
		}

		public ICommand CancelCommand { get; }
		public ICommand NextCommand { get; }

		protected override void OnDialogClosed()
		{
			// TODO: Disable when using Dialog inside DialogScreenViewModel / Settings
			//_navigationState.HomeScreen?.Invoke().Router.NavigateAndReset.Execute(new AddWalletPageViewModel(_navigationState));
		}

		public void Close()
		{
			// TODO: Dialog.xaml back Button binding to Close() method on base class which is protected so exception is thrown.
			Close(false);
		}
	}
}

Disable OnDialogClosed navigation for now


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

#nullable enable

namespace osu.Game.Online.RealtimeMultiplayer
{
    public class MultiplayerClientState
    {
        public long CurrentRoomID { get; set; }

        public MultiplayerClientState(in long roomId)
        {
            CurrentRoomID = roomId;
        }
    }
}

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

using System;

#nullable enable

namespace osu.Game.Online.RealtimeMultiplayer
{
    [Serializable]
    public class MultiplayerClientState
    {
        public readonly long CurrentRoomID;

        public MultiplayerClientState(in long roomId)
        {
            CurrentRoomID = roomId;
        }
    }
}

Change get-only property for now

Change get-only property for now


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NBi.Core.Batch;
using System.Data.SqlClient;

namespace NBi.Core.SqlServer.Smo
{
    public class SmoBatchRunnerFactory : IBatchRunnerFatory
    {
        public IDecorationCommandImplementation Get(IBatchCommand command, IDbConnection connection)
        {
            if (command is IBatchRunCommand)
                return new BatchRunCommand(command as IBatchRunCommand, connection as SqlConnection);

            throw new ArgumentException();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NBi.Core.Batch;
using System.Data.SqlClient;

namespace NBi.Core.SqlServer.Smo
{
    public class SmoBatchRunnerFactory : IBatchRunnerFatory
    {
        public IDecorationCommandImplementation Get(IBatchCommand command, IDbConnection connection)
        {
            if (command is IBatchRunCommand)
            {
                if (connection == null)
                    throw new ArgumentNullException("connection");
                if (connection is SqlConnection)
                    throw new ArgumentException(
                        String.Format("To execute a SQL Batch on a SQL Server, you must provide a connection-string that is associated to a '{0}'. The connection-string '{1}' is associated to a '{2}'"
                            , typeof(SqlConnection).AssemblyQualifiedName
                            , connection.ConnectionString
                            , connection.GetType().AssemblyQualifiedName)
                        , "connection");
                return new BatchRunCommand(command as IBatchRunCommand, connection as SqlConnection);
            }

            throw new ArgumentException();
        }
    }
}

Add handlng of invalid arguments when instanciating a SmoBatchRunner


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using MbCacheTest.TestData;
using NUnit.Framework;
using SharpTestsEx;

namespace MbCacheTest.Logic.Performance
{
	public class CacheMissPerformanceTest : TestCase
	{
		private ObjectTakes100MsToFill instance;

		public CacheMissPerformanceTest(Type proxyType) : base(proxyType)
		{
		}

		protected override void TestSetup()
		{
			CacheBuilder.For<ObjectTakes100MsToFill>()
				.CacheMethod(c => c.Execute(0))
				.AsImplemented();

			var factory = CacheBuilder.BuildFactory();
			instance = factory.Create<ObjectTakes100MsToFill>();
		}

		[Test]
		public void MeasureCacheMissPerf()
		{
			var tasks = new List<Task>();
			10.Times(i =>
			{
				tasks.Add(Task.Factory.StartNew(() => instance.Execute(i)));
			});

			var stopwatch = new Stopwatch();
			stopwatch.Start();
			Task.WaitAll(tasks.ToArray());
			stopwatch.Stop();

			var timeTaken = stopwatch.Elapsed;
			Console.WriteLine(timeTaken);
			timeTaken.TotalMilliseconds.Should().Be.LessThan(100 * 3);
		}
	}
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using MbCacheTest.TestData;
using NUnit.Framework;
using SharpTestsEx;

namespace MbCacheTest.Logic.Performance
{
	public class CacheMissPerformanceTest : TestCase
	{
		private ObjectTakes100MsToFill instance;

		public CacheMissPerformanceTest(Type proxyType) : base(proxyType)
		{
		}

		protected override void TestSetup()
		{
			CacheBuilder.For<ObjectTakes100MsToFill>()
				.CacheMethod(c => c.Execute(0))
				.AsImplemented();

			var factory = CacheBuilder.BuildFactory();
			instance = factory.Create<ObjectTakes100MsToFill>();
		}

		[Test]
		public void MeasureCacheMissPerf()
		{
			if(Environment.ProcessorCount < 3)
				Assert.Ignore("Not enough power...");
			var tasks = new List<Task>();
			10.Times(i =>
			{
				tasks.Add(Task.Factory.StartNew(() => instance.Execute(i)));
			});

			var stopwatch = new Stopwatch();
			stopwatch.Start();
			Task.WaitAll(tasks.ToArray());
			stopwatch.Stop();

			var timeTaken = stopwatch.Elapsed;
			Console.WriteLine(timeTaken);
			//If global lock, approx 10 * 0.1 => 1s
			timeTaken.TotalMilliseconds.Should().Be.LessThan(700);
		}
	}
}

Make test work also in environments with few cores.


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

using System.Collections.Generic;
using Xunit;

namespace System.Globalization.Tests
{
    public class CultureInfoNativeName
    {
        public static IEnumerable<object[]> NativeName_TestData()
        {
            yield return new object[] { CultureInfo.CurrentCulture.Name, CultureInfo.CurrentCulture.NativeName };
            yield return new object[] { "en-US", "English (United States)" };
            yield return new object[] { "en-CA", "English (Canada)" };
        }

        [Theory]
        [MemberData(nameof(NativeName_TestData))]
        public void EnglishName(string name, string expected)
        {
            CultureInfo myTestCulture = new CultureInfo(name);
            Assert.Equal(expected, myTestCulture.EnglishName);
        }
    }
}

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

using System.Collections.Generic;
using Xunit;

namespace System.Globalization.Tests
{
    public class CultureInfoNativeName
    {
        public static IEnumerable<object[]> NativeName_TestData()
        {
            yield return new object[] { CultureInfo.CurrentCulture.Name, CultureInfo.CurrentCulture.NativeName };
            yield return new object[] { "en-US", "English (United States)" };
            yield return new object[] { "en-CA", "English (Canada)" };
        }

        [Theory]
        [MemberData(nameof(NativeName_TestData))]
        public void NativeName(string name, string expected)
        {
            CultureInfo myTestCulture = new CultureInfo(name);
            Assert.Equal(expected, myTestCulture.NativeName);
        }
    }
}

Fix a globalization test failure

Fix a globalization test failure


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

namespace ExpressRunner.TestProject
{
    public class ExampleTests
    {
        [Fact]
        public void Should_fail_always()
        {
            Assert.Equal("text", "wrong text");
        }

        [Fact]
        public void Should_pass_always()
        {
            Assert.True(true);
        }

        [Fact]
        public void Should_pass_also()
        {
            Assert.True(true);
        }

        [Theory]
        [InlineData(1)]
        [InlineData(2)]
        public void Should_support_theory(int input)
        {
            Assert.Equal(1, input);
        }

        [Fact]
        public void Should_take_a_long_time_to_run()
        {
            Thread.Sleep(5000);
            Assert.True(true);
        }
    }
}

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

namespace ExpressRunner.TestProject
{
    public class ExampleTests
    {
        [Fact]
        public void Should_fail_always()
        {
            Assert.Equal("text", "wrong text");
        }

        [Fact]
        public void Should_pass_always()
        {
            Assert.True(true);
        }

        [Fact]
        public void Should_pass_also()
        {
            Assert.True(true);
        }

        [Theory]
        [InlineData(1)]
        [InlineData(2)]
        public void Should_support_theory(int input)
        {
            Assert.Equal(1, input);
        }

        [Fact]
        public void Should_take_one_second_to_finish()
        {
            Thread.Sleep(1000);
            Assert.True(true);
        }
    }
}

Make sleep shorter in test project

Make sleep shorter in test project


using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reflection;
using System.Threading.Tasks;

namespace Glimpse.Agent
{
    public class DefaultAgentBroker : IAgentBroker
    {
        private readonly ISubject<IMessage> _subject;

        // TODO: Review if we care about unifying which thread message is published on
        //       and which thread it is recieved on. If so need to use IScheduler.

        public DefaultAgentBroker(IChannelSender channelSender)
        {
            _subject = new BehaviorSubject<IMessage>(null);

            // TODO: This probably shouldn't be here but don't want to setup more infrasture atm
            ListenAll().Subscribe(async msg => await channelSender.PublishMessage(msg));
        }

        public IObservable<T> Listen<T>()
            where T : IMessage
        {
            return ListenIncludeLatest<T>().Skip(1);
        }

        public IObservable<T> ListenIncludeLatest<T>()
            where T : IMessage
        {
            return _subject
                .Where(msg => typeof(T).GetTypeInfo().IsAssignableFrom(msg.GetType().GetTypeInfo()))
                .Select(msg => (T)msg);
        }
        public IObservable<IMessage> ListenAll()
        {
            return ListenAllIncludeLatest().Skip(1);
        }

        public IObservable<IMessage> ListenAllIncludeLatest()
        {
            return _subject;
        }

        public async Task SendMessage(IMessage message)
        {
            await Task.Run(() => _subject.OnNext(message));
        }
    }
}

using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reflection;
using System.Threading.Tasks;

namespace Glimpse.Agent
{
    public class DefaultAgentBroker : IAgentBroker
    {
        private readonly ISubject<IMessage> _subject;

        // TODO: Review if we care about unifying which thread message is published on
        //       and which thread it is recieved on. If so need to use IScheduler.

        public DefaultAgentBroker(IChannelSender channelSender)
        {
            _subject = new BehaviorSubject<IMessage>(null);

            // TODO: This probably shouldn't be here but don't want to setup
            //       more infrasture atm. Deciding whether it should be users
            //       code which instantiates listners or if we provider infrasturcture
            //       which starts them up and triggers the subscription.
            ListenAll().Subscribe(async msg => await channelSender.PublishMessage(msg));
        }

        public IObservable<T> Listen<T>()
            where T : IMessage
        {
            return ListenIncludeLatest<T>().Skip(1);
        }

        public IObservable<T> ListenIncludeLatest<T>()
            where T : IMessage
        {
            return _subject
                .Where(msg => typeof(T).GetTypeInfo().IsAssignableFrom(msg.GetType().GetTypeInfo()))
                .Select(msg => (T)msg);
        }
        public IObservable<IMessage> ListenAll()
        {
            return ListenAllIncludeLatest().Skip(1);
        }

        public IObservable<IMessage> ListenAllIncludeLatest()
        {
            return _subject;
        }

        public async Task SendMessage(IMessage message)
        {
            await Task.Run(() => _subject.OnNext(message));
        }
    }
}

Update reasoning behind why AgentBus hack exists


using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;

namespace Reni.FeatureTest.Reference
{
    [TestFixture]
    [ArrayReferenceDumpSimple]
    [Target(@"
repeat: /\ ^ while() then(^ body(), repeat(^));

o:
/\
{
    data: ^ array_reference ;
    count: ^ count;
    dump_print:
    /!\
    {
        !mutable position: count type instance (0) ;
        repeat
        (
            while: /\ position < count,
            body: /\
            (
                (data >> position) dump_print,
                position := (position + 1) enable_cut
            )
        )
    }
};

o('abcdef') dump_print
")]
    [Output("abcdef")]
    public sealed class ArrayReferenceDumpLoop : CompilerTest {}
}

using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;

namespace Reni.FeatureTest.Reference
{
    [TestFixture]
    [ArrayReferenceDumpSimple]
    [Target(@"
repeat: /\ ^ while() then(^ body(), repeat(^));

o:
/\
{
    data: ^ array_reference ;
    count: ^ count;
    dump_print:
    /!\
    {
        !mutable position: count type instance (0) ;
        repeat
        (
            while: /\ position < count,
            body: /\
            (
                data item(position) dump_print,
                position := (position + 1) enable_cut
            )
        )
    }
};

o('abcdef') dump_print
")]
    [Output("abcdef")]
    public sealed class ArrayReferenceDumpLoop : CompilerTest {}
}

Access operator for array is now "item"

Change: Access operator for array is now "item"


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

using Microsoft.WindowsAzure.MobileServices;

namespace MyDriving.AzureClient
{
    public class AzureClient : IAzureClient
    {
        const string DefaultMobileServiceUrl = "https://smartkar.azurewebsites.net/";
        IMobileServiceClient client;
        string mobileServiceUrl;
        public IMobileServiceClient Client => client ?? (client = CreateClient());

        IMobileServiceClient CreateClient()
        {
            client = new MobileServiceClient(DefaultMobileServiceUrl, new AuthHandler())
            {
                SerializerSettings = new MobileServiceJsonSerializerSettings()
                {
                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
                    CamelCasePropertyNames = true
                }
            };
            return client;
        }
    }
}

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

using Microsoft.WindowsAzure.MobileServices;

namespace MyDriving.AzureClient
{
    public class AzureClient : IAzureClient
    {
        const string DefaultMobileServiceUrl = "https://mydriving.azurewebsites.net";
        IMobileServiceClient client;
        string mobileServiceUrl;
        public IMobileServiceClient Client => client ?? (client = CreateClient());

        IMobileServiceClient CreateClient()
        {
            client = new MobileServiceClient(DefaultMobileServiceUrl, new AuthHandler())
            {
                SerializerSettings = new MobileServiceJsonSerializerSettings()
                {
                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
                    CamelCasePropertyNames = true
                }
            };
            return client;
        }
    }
}

Switch back to the correct url

Switch back to the correct url