using System.Collections.Generic;

namespace WalletWasabi.Fluent.ViewModels
{
	public class TestLineChartViewModel
	{
		public double XAxisCurrentValue { get; set; } = 36;

		public double XAxisMinValue { get; set; } = 2;

		public double XAxisMaxValue { get; set; } = 864;

		public List<string> XAxisLabels => new List<string>()
		{
			"1w",
			"3d",
			"1d",
			"12h",
			"6h",
			"3h",
			"1h",
			"30m",
			"20m",
			"fastest"
		};

		public List<double> XAxisValues => new List<double>()
		{
			1008,
			432,
			144,
			72,
			36,
			18,
			6,
			3,
			2,
			1,
		};

		public List<double> YAxisValues => new List<double>()
		{
			4,
			4,
			7,
			22,
			57,
			97,
			102,
			123,
			123,
			185
		};
	}
}

using System.Collections.Generic;

namespace WalletWasabi.Fluent.ViewModels
{
	public class TestLineChartViewModel
	{
		public double XAxisCurrentValue { get; set; } = 36;

		public double XAxisMinValue { get; set; } = 1;

		public double XAxisMaxValue { get; set; } = 1008;

		public List<string> XAxisLabels => new List<string>()
		{
			"1w",
			"3d",
			"1d",
			"12h",
			"6h",
			"3h",
			"1h",
			"30m",
			"20m",
			"fastest"
		};

		public List<double> XAxisValues => new List<double>()
		{
			1008,
			432,
			144,
			72,
			36,
			18,
			6,
			3,
			2,
			1,
		};

		public List<double> YAxisValues => new List<double>()
		{
			4,
			4,
			7,
			22,
			57,
			97,
			102,
			123,
			123,
			185
		};
	}
}

Set correct min and max values

Set correct min and max values


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

namespace StatoBot.Analytics
{
	public class Statistics : Dictionary<string, decimal>
	{
		private readonly Encoding encoder;
		private readonly object mutationLock;

		public Statistics()
		{
			encoder = Encoding.GetEncoding(
				"UTF-8",
				new EncoderReplacementFallback(string.Empty),
				new DecoderExceptionFallback()
			);

			mutationLock = new object();
		}

		public void Increment(string key)
		{
			key = SanitizeKey(key);

			lock (mutationLock)
			{
				if(!ContainsKey(key))
				{
					Add(key, 1);
				}
				else
				{
					TryGetValue(key, out var count);
					Remove(key);
					Add(key, count + 1);
				}
			}
		}

		private string SanitizeKey(string key)
		{
			return encoder.GetString(encoder.GetBytes(key));
		}
	}
}

using System;
using System.Text;
using System.Collections.Concurrent;

namespace StatoBot.Analytics
{
    public class Statistics : ConcurrentDictionary<string, decimal>
    {
        private readonly Encoding encoder;

        public Statistics()
        {
            encoder = Encoding.GetEncoding(
                "UTF-8",
                new EncoderReplacementFallback(string.Empty),
                new DecoderExceptionFallback()
            );
        }

        public void Increment(string key)
        {
            key = SanitizeKey(key);

            if (!ContainsKey(key))
            {
                TryAdd(key, 1);
            }
            else
            {
                TryGetValue(key, out var count);
                TryRemove(key, out decimal _);
                TryAdd(key, count + 1);
            }
        }

        private string SanitizeKey(string key)
        {
            return encoder.GetString(encoder.GetBytes(key));
        }
    }
}

Use ConcurrentDictionary instead of Dictionary to allow lock-free async access


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Interactivity;
using MahApps.Metro.Controls;

namespace MahApps.Metro.Behaviours
{
    public class GlowWindowBehavior : Behavior<Window>
    {
        private GlowWindow left, right, top, bottom;
        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.Loaded += (sender, e) =>
            {
                left = new GlowWindow(this.AssociatedObject, GlowDirection.Left);
                right = new GlowWindow(this.AssociatedObject, GlowDirection.Right);
                top = new GlowWindow(this.AssociatedObject, GlowDirection.Top);
                bottom = new GlowWindow(this.AssociatedObject, GlowDirection.Bottom);
                left.Owner = (MetroWindow)sender;
                right.Owner = (MetroWindow)sender;
                top.Owner = (MetroWindow)sender;
                bottom.Owner = (MetroWindow)sender;

                Show();

                left.Update();
                right.Update();
                top.Update();
                bottom.Update();
            };

            this.AssociatedObject.Closed += (sender, args) =>
            {
                if (left != null) left.Close();
                if (right != null) right.Close();
                if (top != null) top.Close();
                if (bottom != null) bottom.Close();
            };
        }

        public void Hide()
        {
            left.Hide();
            right.Hide();
            bottom.Hide();
            top.Hide();
        }

        public void Show()
        {
            left.Show();
            right.Show();
            top.Show();
            bottom.Show();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Interactivity;
using MahApps.Metro.Controls;

namespace MahApps.Metro.Behaviours
{
    public class GlowWindowBehavior : Behavior<Window>
    {
        private GlowWindow left, right, top, bottom;
        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.Loaded += (sender, e) =>
            {
                left = new GlowWindow(this.AssociatedObject, GlowDirection.Left);
                right = new GlowWindow(this.AssociatedObject, GlowDirection.Right);
                top = new GlowWindow(this.AssociatedObject, GlowDirection.Top);
                bottom = new GlowWindow(this.AssociatedObject, GlowDirection.Bottom);

                Show();

                left.Update();
                right.Update();
                top.Update();
                bottom.Update();
            };

            this.AssociatedObject.Closed += (sender, args) =>
            {
                if (left != null) left.Close();
                if (right != null) right.Close();
                if (top != null) top.Close();
                if (bottom != null) bottom.Close();
            };
        }

        public void Hide()
        {
            left.Hide();
            right.Hide();
            bottom.Hide();
            top.Hide();
        }

        public void Show()
        {
            left.Show();
            right.Show();
            top.Show();
            bottom.Show();
        }
    }
}

Revert "Fix The GlowWindow in the taskmanager"

This reverts commit 637febe9b632c3de7d13ee50460151f69e378857.


namespace NakedObjects.Web.UnitTests.Selenium
{
    public static class TestConfig
    {
        //public const string BaseUrl = "http://localhost:49998/";

        public const string BaseUrl = "http://nakedobjectstest.azurewebsites.net/";
    }
}

namespace NakedObjects.Selenium
{
    public static class TestConfig
    {
        //public const string BaseUrl = "http://localhost:49998/";

        public const string BaseUrl = "http://nakedobjectstest.azurewebsites.net/";
    }
}

Correct compile error in tests

Correct compile error in tests


using System;
using System.Windows.Forms;

namespace MultiMiner.Win.Notifications
{
    public partial class NotificationsControl : UserControl
    {
        //events
        //delegate declarations
        public delegate void NotificationsChangedHandler(object sender);

        //event declarations
        public event NotificationsChangedHandler NotificationsChanged;

        public NotificationsControl()
        {
            InitializeComponent();
        }

        public void AddNotification(int id, string text, Action clickHandler, string informationUrl = "")
        {
            NotificationControl notificationControl;

            foreach (Control control in containerPanel.Controls)
            {
                notificationControl = (NotificationControl)control;
                if ((int)notificationControl.Tag == id)
                    return;
            }

            notificationControl = new NotificationControl(text, clickHandler, (nc) => {
                nc.Parent = null;
                if (NotificationsChanged != null)
                    NotificationsChanged(this);
            }, informationUrl);

            notificationControl.Height = 28;
            notificationControl.Parent = containerPanel;
            notificationControl.Top = Int16.MaxValue;
            notificationControl.Tag = (object)id;

            notificationControl.BringToFront();

            notificationControl.Dock = DockStyle.Top;

            containerPanel.ScrollControlIntoView(notificationControl);

            if (NotificationsChanged != null)
                NotificationsChanged(this);
        }

        public int NotificationCount()
        {
            return containerPanel.Controls.Count;
        }
    }
}

using System;
using System.Windows.Forms;

namespace MultiMiner.Win.Notifications
{
    public partial class NotificationsControl : UserControl
    {
        //events
        //delegate declarations
        public delegate void NotificationsChangedHandler(object sender);

        //event declarations
        public event NotificationsChangedHandler NotificationsChanged;

        public NotificationsControl()
        {
            InitializeComponent();
        }

        public void AddNotification(string id, string text, Action clickHandler, string informationUrl = "")
        {
            NotificationControl notificationControl;

            foreach (Control control in containerPanel.Controls)
            {
                notificationControl = (NotificationControl)control;
                if ((string)notificationControl.Tag == id)
                    return;
            }

            notificationControl = new NotificationControl(text, clickHandler, (nc) => {
                nc.Parent = null;
                if (NotificationsChanged != null)
                    NotificationsChanged(this);
            }, informationUrl);

            notificationControl.Height = 28;
            notificationControl.Parent = containerPanel;
            notificationControl.Top = Int16.MaxValue;
            notificationControl.Tag = (object)id;

            notificationControl.BringToFront();

            notificationControl.Dock = DockStyle.Top;

            containerPanel.ScrollControlIntoView(notificationControl);

            if (NotificationsChanged != null)
                NotificationsChanged(this);
        }

        public int NotificationCount()
        {
            return containerPanel.Controls.Count;
        }
    }
}

Use strings for IDs (for flexibility)

Use strings for IDs (for flexibility)


using System;
using TrueCraft.API;
using TrueCraft.API.Logic;

namespace TrueCraft.Core.Logic.Blocks
{
    public class AirBlock : BlockProvider
    {
        public static readonly byte BlockID = 0x00;

        public override byte ID { get { return 0x00; } }

        public override double BlastResistance { get { return 0; } }

        public override double Hardness { get { return 100000; } }

        public override bool Opaque { get { return false; } }

        public override byte Luminance { get { return 0; } }

        public override string DisplayName { get { return "Air"; } }

        public override Tuple<int, int> GetTextureMap(byte metadata)
        {
            return new Tuple<int, int>(0, 0);
        }

        protected override ItemStack[] GetDrop(BlockDescriptor descriptor)
        {
            return new ItemStack[0];
        }
    }
}

using System;
using TrueCraft.API;
using TrueCraft.API.Logic;

namespace TrueCraft.Core.Logic.Blocks
{
    public class AirBlock : BlockProvider
    {
        public static readonly byte BlockID = 0x00;

        public override byte ID { get { return 0x00; } }

        public override double BlastResistance { get { return 0; } }

        public override double Hardness { get { return 0; } }

        public override bool Opaque { get { return false; } }

        public override byte Luminance { get { return 0; } }

        public override string DisplayName { get { return "Air"; } }

        public override Tuple<int, int> GetTextureMap(byte metadata)
        {
            return new Tuple<int, int>(0, 0);
        }

        protected override ItemStack[] GetDrop(BlockDescriptor descriptor)
        {
            return new ItemStack[0];
        }
    }
}

Fix error with liquid propegation through air


// Copyright(c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;

namespace GoogleCloudSamples.Controllers
{
    // [START login]
    public class SessionController : Controller
    {
        public ActionResult Login()
        {
            // Redirect to the Google OAuth 2.0 user consent screen
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                "Google"
            );
            return new HttpUnauthorizedResult();
        }

        // ...
        // [END login]

        // [START logout]
        public ActionResult Logout()
        {
            Request.GetOwinContext().Authentication.SignOut();
            return Redirect("/");
        }
        // [END logout]
    }
}

// Copyright(c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;

namespace GoogleCloudSamples.Controllers
{
    // [START login]
    public class SessionController : Controller
    {
        public void Login()
        {
            // Redirect to the Google OAuth 2.0 user consent screen
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                "Google"
            );
        }

        // ...
        // [END login]

        // [START logout]
        public ActionResult Logout()
        {
            Request.GetOwinContext().Authentication.SignOut();
            return Redirect("/");
        }
        // [END logout]
    }
}

Simplify Login() action - no explicit return necessary


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

using osu.Framework.Localisation;
using osu.Game.Online.API.Requests;
using osu.Game.Overlays.Profile.Sections.Beatmaps;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.Profile.Sections
{
    public class BeatmapsSection : ProfileSection
    {
        public override LocalisableString Title => UsersStrings.ShowExtraBeatmapsTitle;

        public override string Identifier => @"beatmaps";

        public BeatmapsSection()
        {
            Children = new[]
            {
                new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, UsersStrings.ShowExtraBeatmapsFavouriteTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Ranked, User, UsersStrings.ShowExtraBeatmapsRankedTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Loved, User, UsersStrings.ShowExtraBeatmapsLovedTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Pending, User, UsersStrings.ShowExtraBeatmapsPendingTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Guest, User, UsersStrings.ShowExtraBeatmapsGuestTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Graveyard, User, UsersStrings.ShowExtraBeatmapsGraveyardTitle)
            };
        }
    }
}

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

using osu.Framework.Localisation;
using osu.Game.Online.API.Requests;
using osu.Game.Overlays.Profile.Sections.Beatmaps;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.Profile.Sections
{
    public class BeatmapsSection : ProfileSection
    {
        public override LocalisableString Title => UsersStrings.ShowExtraBeatmapsTitle;

        public override string Identifier => @"beatmaps";

        public BeatmapsSection()
        {
            Children = new[]
            {
                new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, UsersStrings.ShowExtraBeatmapsFavouriteTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Ranked, User, UsersStrings.ShowExtraBeatmapsRankedTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Loved, User, UsersStrings.ShowExtraBeatmapsLovedTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Guest, User, UsersStrings.ShowExtraBeatmapsGuestTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Pending, User, UsersStrings.ShowExtraBeatmapsPendingTitle),
                new PaginatedBeatmapContainer(BeatmapSetType.Graveyard, User, UsersStrings.ShowExtraBeatmapsGraveyardTitle)
            };
        }
    }
}

Move guest participation beatmap up to below loved


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

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

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

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

        return _versionContext;
    }
}

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

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

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

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

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

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

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

        return _versionContext;
    }
}

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

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

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

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


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Interop;
using WindowsDesktop.Interop;

namespace WindowsDesktop.Internal
{
	internal abstract class RawWindow
	{
		public string Name { get; set; }

		public HwndSource Source { get; private set; }

		public IntPtr Handle => this.Source?.Handle ?? IntPtr.Zero;

		public virtual void Show()
		{
			this.Show(new HwndSourceParameters(this.Name));
		}

		protected void Show(HwndSourceParameters parameters)
		{
			this.Source = new HwndSource(parameters);
			this.Source.AddHook(this.WndProc);
		}

		public virtual void Close()
		{
			this.Source?.RemoveHook(this.WndProc);
			this.Source?.Dispose();
			this.Source = null;

			NativeMethods.CloseWindow(this.Handle);
		}

		protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
		{
			return IntPtr.Zero;
		}
	}
}

using System;
using System.Windows.Interop;
using System.Windows.Threading;
using WindowsDesktop.Interop;

namespace WindowsDesktop.Internal
{
	internal abstract class RawWindow
	{
		public string Name { get; set; }

		public HwndSource Source { get; private set; }

		public IntPtr Handle => this.Source?.Handle ?? IntPtr.Zero;

		public virtual void Show()
		{
			this.Show(new HwndSourceParameters(this.Name));
		}

		protected void Show(HwndSourceParameters parameters)
		{
			this.Source = new HwndSource(parameters);
			this.Source.AddHook(this.WndProc);
		}

		public virtual void Close()
		{
			this.Source?.RemoveHook(this.WndProc);
			// Source could have been created on a different thread, which means we
			// have to Dispose of it on the UI thread or it will crash.
			this.Source?.Dispatcher?.BeginInvoke(DispatcherPriority.Send, (Action)(() => this.Source?.Dispose()));
			this.Source = null;

			NativeMethods.CloseWindow(this.Handle);
		}

		protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
		{
			return IntPtr.Zero;
		}
	}
}

Fix crash when multiple threads may exist.

Based on a crash I experienced in an app I am developing, it appears that sometimes when the app is shutting down, the disposal will not happen from the UI thread, and Dispose() on the HwndSource causes an InvalidOperationException.

By running the Dispose on the UI thread immediately, disposal happens, and no crash is seen.

See https://github.com/Grabacr07/VirtualDesktop/pull/28/commits/e9ec9185d866ea6b75b2f6572870599ba690ea92


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using Certify.Models;

namespace Certify.Service.Tests.Integration
{
    [TestClass]
    public class ManagedCertificateTests : ServiceTestBase
    {
        [TestMethod]
        public async Task TestGetManagedCertificates()
        {
            var filter = new ManagedCertificateFilter();
            var result = await _client.GetManagedCertificates(filter);

            Assert.IsNotNull(result, $"Fetched {result.Count} managed sites");
        }

        [TestMethod]
        public async Task TestGetManagedCertificate()
        {
            //get full list
            var filter = new ManagedCertificateFilter { MaxResults = 10 };
            var results = await _client.GetManagedCertificates(filter);

            Assert.IsTrue(results.Count > 0, "Got one or more managed sites");

            //attempt to get single item
            var site = await _client.GetManagedCertificate(results[0].Id);
            Assert.IsNotNull(site, $"Fetched single managed site details");
        }
    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using Certify.Models;
using System.Collections.Generic;

namespace Certify.Service.Tests.Integration
{
    [TestClass]
    public class ManagedCertificateTests : ServiceTestBase
    {
        [TestMethod]
        public async Task TestGetManagedCertificates()
        {
            var filter = new ManagedCertificateFilter();
            var result = await _client.GetManagedCertificates(filter);

            Assert.IsNotNull(result, $"Fetched {result.Count} managed sites");
        }

        [TestMethod]
        public async Task TestGetManagedCertificate()
        {
            //get full list
            var filter = new ManagedCertificateFilter { MaxResults = 10 };
            var results = await _client.GetManagedCertificates(filter);

            Assert.IsTrue(results.Count > 0, "Got one or more managed sites");

            //attempt to get single item
            var site = await _client.GetManagedCertificate(results[0].Id);
            Assert.IsNotNull(site, $"Fetched single managed site details");
        }

        [TestMethod]
        [Ignore]
        public async Task TestCreateManagedCertificates()
        {
            //get full list

            var list = new List<ManagedCertificate>
            {
                GetExample("msdn.webprofusion.com", 12),
                GetExample("demo.webprofusion.co.uk", 45),
                GetExample("clients.dependencymanager.com",75),
                GetExample("soundshed.com",32),
                GetExample("*.projectbids.co.uk",48),
                GetExample("exchange.projectbids.co.uk",19),
                GetExample("remote.dependencymanager.com",7),
                GetExample("git.example.com",56)

            };

            foreach (var site in list)
            {

                await _client.UpdateManagedCertificate(site);
            }

        }

        private ManagedCertificate GetExample(string title, int numDays)
        {
            return new ManagedCertificate()
            {
                Id = Guid.NewGuid().ToString(),
                Name = title,
                DateExpiry = DateTime.Now.AddDays(numDays),
                DateLastRenewalAttempt = DateTime.Now.AddDays(-1),
                LastRenewalStatus = RequestState.Success

            };
        }
    }
}

Add standard demo sites setup as a test

Add standard demo sites setup as a test


using UnityEngine;
using System.Collections;

public class Bullet : MonoBehaviour {

    private float velocity = 35f;

    // Use this for initialization
    void Start ()
    {
    }

    // Update is called once per frame
    void Update ()
    {
        this.transform.Translate(0, Time.deltaTime * this.velocity, 0, Space.Self);
    }
}

using UnityEngine;
using System.Collections;

public class Bullet : MonoBehaviour {

    private float velocity = 35f;

    // Use this for initialization
    void Start ()
    {
    }

    // Update is called once per frame
    void Update ()
    {
        this.transform.Translate(0, Time.deltaTime * this.velocity, 0, Space.Self);

        // Destroy the bullet when it is out of bounds of screen
        if (isOutOfScreen()) {
            Destroy(this.gameObject);
        }
    }

    private bool isOutOfScreen ()
    {
        Vector3 posbullet  = Camera.main.WorldToScreenPoint(this.gameObject.transform.position);
        float screenWidth  = Camera.main.pixelWidth;
        float screenHeight = Camera.main.pixelHeight;

        if (posbullet.x < 0 || posbullet.x > screenWidth || posbullet.y < 0 || posbullet.y > screenHeight ) {
            return true;
        }

        return false;
    }
}

Destroy bullets when they are out of bounds


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

using FluentAssertions;
using Microsoft.DotNet.Cli.Utils;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.NET.TestFramework.Assertions;

namespace Microsoft.NET.TestFramework
{
    public static class CommandExtensions
    {
        public static ICommand EnsureExecutable(this ICommand command)
        {
            //  Workaround for https://github.com/NuGet/Home/issues/4424
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Command.Create("chmod", new[] { "755", command.CommandName })
                    .Execute()
                    .Should()
                    .Pass();
            }
            return command;
        }
    }
}

Add copyright notice to new file

Add copyright notice to new file


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

public class YoumuSlashTimingController : MonoBehaviour
{
    public delegate void BeatDelegate(int beat);
    public static BeatDelegate onBeat;

    [SerializeField]
    private YoumuSlashTimingData timingData;
    [SerializeField]
    private float StartDelay = .5f;

    private AudioSource musicSource;

    private int lastInvokedBeat;

    private void Awake()
    {
        onBeat = null;
        musicSource = GetComponent<AudioSource>();
        musicSource.clip = timingData.MusicClip;
        timingData.initiate(musicSource);
    }

    void Start()
    {
        AudioHelper.playScheduled(musicSource, StartDelay);
        lastInvokedBeat = -1;
        onBeat += checkForSongEnd;
        InvokeRepeating("callOnBeat", StartDelay, timingData.getBeatDuration());
    }

    void callOnBeat()
    {
        lastInvokedBeat++;
        onBeat(lastInvokedBeat);
    }

    void checkForSongEnd(int beat)
        print("Debug beat check");
        if (lastInvokedBeat > 1 && !musicSource.isPlaying)
            CancelInvoke();
    }

}

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

public class YoumuSlashTimingController : MonoBehaviour
{
    public delegate void BeatDelegate(int beat);
    public static BeatDelegate onBeat;

    [SerializeField]
    private YoumuSlashTimingData timingData;
    [SerializeField]
    private float StartDelay = .5f;

    private AudioSource musicSource;

    private int lastInvokedBeat;

    private void Awake()
    {
        onBeat = null;
        musicSource = GetComponent<AudioSource>();
        musicSource.clip = timingData.MusicClip;
        timingData.initiate(musicSource);
    }

    void Start()
    {
        AudioHelper.playScheduled(musicSource, StartDelay);
        lastInvokedBeat = -1;
        onBeat += checkForSongEnd;
        InvokeRepeating("callOnBeat", StartDelay, timingData.getBeatDuration());
    }

    void callOnBeat()
    {
        lastInvokedBeat++;
        onBeat(lastInvokedBeat);
    }

    void checkForSongEnd(int beat)
    {
        print("Debug beat check");
        if (lastInvokedBeat > 1 && !musicSource.isPlaying)
            CancelInvoke();
    }

}

Fix syntax error in TimingController

Fix syntax error in TimingController


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

using System.Collections.Generic;
using Microsoft.Extensions.Configuration;

namespace Microsoft.AspNet.Hosting
{
    public class WebHostConfiguration
    {
        public static IConfiguration GetDefault()
        {
            return GetDefault(args: null);
        }

        public static IConfiguration GetDefault(string[] args)
        {
            var defaultSettings = new Dictionary<string, string>
            {
                { WebHostDefaults.CaptureStartupErrorsKey, "true" }
            };

            // We are adding all environment variables first and then adding the ASPNET_ ones
            // with the prefix removed to unify with the command line and config file formats
            var configBuilder = new ConfigurationBuilder()
                .AddInMemoryCollection(defaultSettings)
                .AddJsonFile(WebHostDefaults.HostingJsonFile, optional: true)
                .AddEnvironmentVariables()
                .AddEnvironmentVariables(prefix: WebHostDefaults.EnvironmentVariablesPrefix);

            if (args != null)
            {
                configBuilder.AddCommandLine(args);
            }

            return configBuilder.Build();
        }
    }

}

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

using System.Collections.Generic;
using Microsoft.Extensions.Configuration;

namespace Microsoft.AspNet.Hosting
{
    public class WebHostConfiguration
    {
        public static IConfiguration GetDefault()
        {
            return GetDefault(args: null);
        }

        public static IConfiguration GetDefault(string[] args)
        {
            var defaultSettings = new Dictionary<string, string>
            {
                { WebHostDefaults.CaptureStartupErrorsKey, "true" }
            };

            // Setup the default locations for finding hosting configuration options
            // hosting.json, ASPNET_ prefixed env variables and command line arguments
            var configBuilder = new ConfigurationBuilder()
                .AddInMemoryCollection(defaultSettings)
                .AddJsonFile(WebHostDefaults.HostingJsonFile, optional: true)
                .AddEnvironmentVariables(prefix: WebHostDefaults.EnvironmentVariablesPrefix);

            if (args != null)
            {
                configBuilder.AddCommandLine(args);
            }

            return configBuilder.Build();
        }
    }

}

Remove top level environment variables from default config


using System;
using MessageBird.Exceptions;
using MessageBird.Objects;
using Newtonsoft.Json;

namespace MessageBird.Resources
{
    public abstract class Resource
    {
        public string Id
        {
            get
            {
                if (HasId)
                {
                   return Object.Id;
                }
                throw new ErrorException(String.Format("Resource {0} has no id", Name));
            }
        }

        public IIdentifiable<string> Object { get; protected set; }

        public bool HasId
        {
            get { return (Object != null) && !String.IsNullOrEmpty(Object.Id); }
        }

        public string Name { get; private set; }

        public virtual void Deserialize(string resource)
        {
            JsonConvert.PopulateObject(resource, Object);
        }

        public virtual string Serialize()
        {
            var settings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
            return JsonConvert.SerializeObject(Object, settings);
        }

        protected Resource(string name, IIdentifiable<string> attachedObject)
        {
            Name = name;
            Object = attachedObject;
        }
    }
}

using System;
using MessageBird.Exceptions;
using MessageBird.Objects;
using Newtonsoft.Json;

namespace MessageBird.Resources
{
    public abstract class Resource
    {
        public string Id
        {
            get
            {
                if (HasId)
                {
                   return Object.Id;
                }
                throw new ErrorException(String.Format("Resource {0} has no id", Name));
            }
        }

        public IIdentifiable<string> Object { get; protected set; }

        public bool HasId
        {
            get { return (Object != null) && !String.IsNullOrEmpty(Object.Id); }
        }

        public string Name { get; private set; }

        public virtual void Deserialize(string resource)
        {
            if (Object == null)
            {
                throw new ErrorException("Invalid resource, has no attached object", new NullReferenceException());
            }
            JsonConvert.PopulateObject(resource, Object);
        }

        public virtual string Serialize()
        {
            var settings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
            return JsonConvert.SerializeObject(Object, settings);
        }

        protected Resource(string name, IIdentifiable<string> attachedObject)
        {
            Name = name;
            Object = attachedObject;
        }
    }
}

Add a just in case null check before deserialization


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Net;

namespace MultiMiner.Xgminer.Discovery.Tests
{
    [TestClass]
    public class MinerFinderTests
    {
        [TestMethod]
        public void MinerFinder_FindsMiners()
        {
            const int times = 3;

            for (int i = 0; i < times; i++)
            {
                List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029);
                Assert.IsTrue(miners.Count >= 4);
            }
        }

        [TestMethod]
        public void MinerFinder_ChecksMiners()
        {
            List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029);
            int goodCount = miners.Count;

            miners.Add(new IPEndPoint(IPAddress.Parse("10.0.0.1"), 1000));

            int checkCount = MinerFinder.Check(miners).Count;

            Assert.IsTrue(checkCount == goodCount);
        }
    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Net;

namespace MultiMiner.Xgminer.Discovery.Tests
{
    [TestClass]
    public class MinerFinderTests
    {
        [TestMethod]
        public void MinerFinder_FindsMiners()
        {
            const int times = 3;

            for (int i = 0; i < times; i++)
            {
                List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029);
                Assert.IsTrue(miners.Count >= 3);
            }
        }

        [TestMethod]
        public void MinerFinder_ChecksMiners()
        {
            List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029);
            int goodCount = miners.Count;

            miners.Add(new IPEndPoint(IPAddress.Parse("10.0.0.1"), 1000));

            int checkCount = MinerFinder.Check(miners).Count;

            Assert.IsTrue(checkCount == goodCount);
        }
    }
}

Fix tests to pass with newer setup

Fix tests to pass with newer setup


// Copyright 2020 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Nuke.Common.IO;
using Nuke.Common.Utilities;
using Nuke.Common.ValueInjection;

namespace Nuke.Common.Tooling
{
    [PublicAPI]
    public class LatestMyGetVersionAttribute : ValueInjectionAttributeBase
    {
        private readonly string _feed;
        private readonly string _package;

        public LatestMyGetVersionAttribute(string feed, string package)
        {
            _feed = feed;
            _package = package;
        }

        public override object GetValue(MemberInfo member, object instance)
        {
            var rssFile = NukeBuild.TemporaryDirectory / $"{_feed}.xml";
            HttpTasks.HttpDownloadFile($"https://www.myget.org/RSS/{_feed}", rssFile);
            return XmlTasks.XmlPeek(rssFile, ".//title")
                // TODO: regex?
                .First(x => x.Contains($" {_package} "))
                .Split('(').Last()
                .Split(')').First()
                .TrimStart("version ");
        }
    }
}

// Copyright 2020 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Nuke.Common.IO;
using Nuke.Common.Utilities;
using Nuke.Common.ValueInjection;

namespace Nuke.Common.Tooling
{
    [PublicAPI]
    public class LatestMyGetVersionAttribute : ValueInjectionAttributeBase
    {
        private readonly string _feed;
        private readonly string _package;

        public LatestMyGetVersionAttribute(string feed, string package)
        {
            _feed = feed;
            _package = package;
        }

        public override object GetValue(MemberInfo member, object instance)
        {
            var rssFile = NukeBuild.TemporaryDirectory / $"{_feed}.xml";
            HttpTasks.HttpDownloadFile($"https://www.myget.org/RSS/{_feed}", rssFile);
            return XmlTasks.XmlPeek(rssFile, ".//title")
                // TODO: regex?
                .First(x => x.Contains($"/{_package} "))
                .Split('(').Last()
                .Split(')').First()
                .TrimStart("version ");
        }
    }
}

Fix scanning for MyGet versions

Fix scanning for MyGet versions


@model CodeEditorSettings

@if (Model.TextArea)
{
    <textarea name="@Model.EditorName" style="display: none"></textarea>
}

@if (!string.IsNullOrEmpty(Model.RevertContents))
{

}

Fix question submission truncation bug

Fix question submission truncation bug

This change fixes a bug where changes with < or > characters in certain
contexts would be truncated.


using System;

namespace Amazon.S3
{
    public readonly struct GetPresignedUrlRequest
    {
        public GetPresignedUrlRequest(
            string host,
            AwsRegion region,
            string bucketName,
            string objectKey,
            TimeSpan expiresIn)
        {
            Host       = host  ?? throw new ArgumentNullException(nameof(host));
            Region     = region;
            BucketName = bucketName ?? throw new ArgumentNullException(nameof(bucketName));
            Key        = objectKey;
            ExpiresIn  = expiresIn;
        }

        public readonly string Host;

        public readonly string BucketName;

        public readonly AwsRegion Region;

        public readonly string Key;

        public readonly TimeSpan ExpiresIn;
    }
}

using System;

namespace Amazon.S3
{
    public class GetPresignedUrlRequest
    {
        public GetPresignedUrlRequest(
            string method,
            string host,
            AwsRegion region,
            string bucketName,
            string objectKey,
            TimeSpan expiresIn)
        {
            Method = method ?? throw new ArgumentException(nameof(method));
            Host = host ?? throw new ArgumentNullException(nameof(host));
            Region = region;
            BucketName = bucketName ?? throw new ArgumentNullException(nameof(bucketName));
            Key = objectKey;
            ExpiresIn = expiresIn;
        }

        public string Method { get; }

        public string Host { get; }

        public string BucketName { get; }

        public AwsRegion Region { get; }

        public string Key { get; }

        public TimeSpan ExpiresIn { get; }
    }
}

[S3] Add method to GetPresignedUrlRequest and update to class


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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e2c08eff-8a14-4c77-abd3-c9e193ae81e8")]

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

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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e2c08eff-8a14-4c77-abd3-c9e193ae81e8")]

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

Change library version to 0.8.1

Change library version to 0.8.1


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Glimpse.Host.Web.Owin.Framework;

namespace Glimpse.Host.Web.Owin
{
    public class GlimpseMiddleware
    {
        private readonly Func<IDictionary<string, object>, Task> _innerNext;

        public GlimpseMiddleware(Func<IDictionary<string, object>, Task> innerNext)
        {
            _innerNext = innerNext;
        }

        public async Task Invoke(IDictionary<string, object> environment)
        {
            var newContext = new HttpContext(environment);

            await _innerNext(environment);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Glimpse.Host.Web.Owin.Framework;
using Glimpse.Agent.Web;

namespace Glimpse.Host.Web.Owin
{
    public class GlimpseMiddleware
    {
        private readonly Func<IDictionary<string, object>, Task> _innerNext;
        private readonly WebAgentRuntime _runtime;

        public GlimpseMiddleware(Func<IDictionary<string, object>, Task> innerNext)
        {
            _innerNext = innerNext;
            _runtime = new WebAgentRuntime();   // TODO: This shouldn't have this direct depedency
        }

        public async Task Invoke(IDictionary<string, object> environment)
        {
            var newContext = new HttpContext(environment);

            _runtime.Begin(newContext);

            await _innerNext(environment);

            _runtime.End(newContext);
        }
    }
}

Add agent to web owin middleware

Add agent to web owin middleware


using System;
using Android.Views;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Android.Graphics;
using System.ComponentModel;
using CrossPlatformTintedImage;
using CrossPlatformTintedImage.Droid;

[assembly:ExportRendererAttribute(typeof(TintedImage), typeof(TintedImageRenderer))]
namespace CrossPlatformTintedImage.Droid
{
    public class TintedImageRenderer : ImageRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
        {
            base.OnElementChanged(e);

            SetTint();
        }

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

            if (e.PropertyName == TintedImage.TintColorProperty.PropertyName)
                SetTint();
        }

        void SetTint()
        {
            if (Control != null && Element != null)
            {
                var colorFilter = new PorterDuffColorFilter(((TintedImage) Element).TintColor.ToAndroid(), PorterDuff.Mode.SrcIn);
                Control.SetColorFilter(colorFilter);
            }
        }
    }
}

using System;
using Android.Views;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Android.Graphics;
using System.ComponentModel;
using CrossPlatformTintedImage;
using CrossPlatformTintedImage.Droid;

[assembly:ExportRendererAttribute(typeof(TintedImage), typeof(TintedImageRenderer))]
namespace CrossPlatformTintedImage.Droid
{
    public class TintedImageRenderer : ImageRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
        {
            base.OnElementChanged(e);

            SetTint();
        }

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

            if (e.PropertyName == TintedImage.TintColorProperty.PropertyName)
                SetTint();
        }

        void SetTint()
        {
			if (Control == null || Element == null)
				return;

			if (((TintedImage)Element).TintColor.Equals(Xamarin.Forms.Color.Transparent))
			{
				//Turn off tinting

				if (Control.ColorFilter != null)
					Control.ClearColorFilter();

				return;
			}

			//Apply tint color
			var colorFilter = new PorterDuffColorFilter(((TintedImage)Element).TintColor.ToAndroid(), PorterDuff.Mode.SrcIn);
			Control.SetColorFilter(colorFilter);
        }
    }
}

Disable tinting option on Android

Disable tinting option on Android


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

namespace VVVV.DX11
{
    public interface IAttachableWindow
    {
        void AttachContext(DX11RenderContext renderContext);
        IntPtr WindowHandle { get; }
    }

    public interface IDX11RenderStartPoint
    {
        DX11RenderContext RenderContext { get; }
        bool Enabled { get; }
        void Present();
    }

    public interface IDX11RenderWindow : IDX11RenderStartPoint , IAttachableWindow
    {

    }
}

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

namespace VVVV.DX11
{
    public interface IAttachableWindow
    {
        void AttachContext(DX11RenderContext renderContext);
        IntPtr WindowHandle { get; }
    }

    public interface IDX11RenderStartPoint : IDX11RenderGraphPart
    {
        DX11RenderContext RenderContext { get; }
        bool Enabled { get; }
        void Present();
    }

    public interface IDX11RenderWindow : IDX11RenderStartPoint , IAttachableWindow
    {

    }
}

Mark render start point as graph part (obviously)


using System.Windows;

namespace GitMind.Common.MessageDialogs
{
	/// <summary>
	/// Interaction logic for MessageDialog.xaml
	/// </summary>
	public partial class MessageDialog : Window
	{
		public MessageDialog(
			Window owner,
			string message,
			string title,
			MessageBoxButton button,
			MessageBoxImage image)
		{
			Owner = owner;
			InitializeComponent();

			MessageDialogViewModel viewModel = new MessageDialogViewModel();
			DataContext = viewModel;

			viewModel.Title = title;
			viewModel.Message = message;

			viewModel.IsInfo = image == MessageBoxImage.Information;
			viewModel.IsQuestion = image == MessageBoxImage.Question;
			viewModel.IsWarn = image == MessageBoxImage.Warning;
			viewModel.IsError = image == MessageBoxImage.Error;

			if (button == MessageBoxButton.OK)
			{
				viewModel.OkText = "Ok";
				viewModel.IsCancelVisible = false;
			}
			else if (button == MessageBoxButton.OKCancel)
			{
				viewModel.OkText = "Ok";
				viewModel.CancelText = "Cancel";
				viewModel.IsCancelVisible = true;
			}
			else if (button == MessageBoxButton.YesNo)
			{
				viewModel.OkText = "Yes";
				viewModel.CancelText = "No";
				viewModel.IsCancelVisible = true;
			}
		}
	}
}

using System.Windows;

namespace GitMind.Common.MessageDialogs
{
	/// <summary>
	/// Interaction logic for MessageDialog.xaml
	/// </summary>
	public partial class MessageDialog : Window
	{
		public MessageDialog(
			Window owner,
			string message,
			string title,
			MessageBoxButton button,
			MessageBoxImage image)
		{
			Owner = owner;
			InitializeComponent();

			MessageDialogViewModel viewModel = new MessageDialogViewModel();
			DataContext = viewModel;

			viewModel.Title = title;
			viewModel.Message = message;

			viewModel.IsInfo = image == MessageBoxImage.Information;
			viewModel.IsQuestion = image == MessageBoxImage.Question;
			viewModel.IsWarn = image == MessageBoxImage.Warning;
			viewModel.IsError = image == MessageBoxImage.Error;

			if (button == MessageBoxButton.OK)
			{
				viewModel.OkText = "OK";
				viewModel.IsCancelVisible = false;
			}
			else if (button == MessageBoxButton.OKCancel)
			{
				viewModel.OkText = "OK";
				viewModel.CancelText = "Cancel";
				viewModel.IsCancelVisible = true;
			}
			else if (button == MessageBoxButton.YesNo)
			{
				viewModel.OkText = "Yes";
				viewModel.CancelText = "No";
				viewModel.IsCancelVisible = true;
			}
		}
	}
}

Change "Ok" to "OK" in message dialogs

Change "Ok" to "OK" in message dialogs


using System;
using DevLab.JmesPath.Interop;
using Newtonsoft.Json.Linq;

namespace DevLab.JmesPath.Functions
{
    public class ToNumberFunction : JmesPathFunction
    {
        public ToNumberFunction()
            : base("to_number", 1)
        {

        }
        public override bool Validate(params JToken[] args)
        {
            return true;
        }

        public override JToken Execute(params JToken[] args)
        {
            return new JValue(Convert.ToInt32(args[0].Value<int>()));
        }
    }
}

using System;
using System.Globalization;
using DevLab.JmesPath.Interop;
using Newtonsoft.Json.Linq;

namespace DevLab.JmesPath.Functions
{
    public class ToNumberFunction : JmesPathFunction
    {
        public ToNumberFunction()
            : base("to_number", 1)
        {

        }
        public override bool Validate(params JToken[] args)
        {
            return true;
        }

        public override JToken Execute(params JToken[] args)
        {
            var arg = args[0];
            if (args[0] == null)
                return null;

            switch (arg.Type)
            {
                case JTokenType.Integer:
                case JTokenType.Float:
                    return arg;

                case JTokenType.String:
                    {
                        var value = args[0].Value<string>();

                        int i =0 ;
                        double d = 0;
                        if (int.TryParse(value, out i))
                            return new JValue(i);
                        else if (double.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
                            return new JValue(d);

                        return null;
                    }

                default:
                    return null;
            }
        }
    }
}

Change - finished compliance for to_number function.


using System.Collections.Generic;

using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;

namespace PPWCode.Vernacular.NHibernate.I.Test
{
    public static class NhConfigurator
    {
        private const string ConnectionString = "Data Source=:memory:;Version=3;New=True;";

        private static readonly Configuration s_Configuration;
        private static readonly ISessionFactory s_SessionFactory;

        static NhConfigurator()
        {
            s_Configuration = new Configuration()
                .Configure()
                .DataBaseIntegration(
                    db =>
                    {
                        db.Dialect<SQLiteDialect>();
                        db.Driver<SQLite20Driver>();
                        db.ConnectionProvider<TestConnectionProvider>();
                        db.ConnectionString = ConnectionString;
                    })
                .SetProperty(Environment.CurrentSessionContextClass, "thread_static");

            IDictionary<string, string> props = s_Configuration.Properties;
            if (props.ContainsKey(Environment.ConnectionStringName))
            {
                props.Remove(Environment.ConnectionStringName);
            }

            s_SessionFactory = s_Configuration.BuildSessionFactory();
        }

        public static Configuration Configuration
        {
            get { return s_Configuration; }
        }

        public static ISessionFactory SessionFactory
        {
            get { return s_SessionFactory; }
        }
    }
}

using System.Collections.Generic;

using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;

namespace PPWCode.Vernacular.NHibernate.I.Test
{
    public static class NhConfigurator
    {
        private const string ConnectionString = "Data Source=:memory:;Version=3;New=True;";

        private static readonly object s_Locker = new object();

        private static volatile Configuration s_Configuration;
        private static volatile ISessionFactory s_SessionFactory;

        public static Configuration Configuration
        {
            get
            {
                if (s_Configuration == null)
                {
                    lock (s_Locker)
                    {
                        if (s_Configuration == null)
                        {
                            s_Configuration = new Configuration()
                                .Configure()
                                .DataBaseIntegration(
                                    db =>
                                    {
                                        db.Dialect<SQLiteDialect>();
                                        db.Driver<SQLite20Driver>();
                                        db.ConnectionProvider<TestConnectionProvider>();
                                        db.ConnectionString = ConnectionString;
                                    })
                                .SetProperty(Environment.CurrentSessionContextClass, "thread_static");

                            IDictionary<string, string> props = s_Configuration.Properties;
                            if (props.ContainsKey(Environment.ConnectionStringName))
                            {
                                props.Remove(Environment.ConnectionStringName);
                            }
                        }
                    }
                }
                return s_Configuration;
            }
        }

        public static ISessionFactory SessionFactory
        {
            get
            {
                if (s_SessionFactory == null)
                {
                    lock (s_Locker)
                    {
                        if (s_SessionFactory == null)
                        {
                            s_SessionFactory = Configuration.BuildSessionFactory();
                        }
                    }
                }
                return s_SessionFactory;
            }
        }
    }
}

Use static properties instead of static constructor
==> if exception is thrown, detailed information is available, else TypeInitialiser exception is thrown

git-svn-id: 487762061123e2098c3085380b713ad974003499@7632 463e38ab-4f4e-0410-907a-65d2b3888964


using System;
using System.Collections.Generic;
using Xunit;

namespace CSharpViaTest.IOs._10_HandleText
{
    /*
     * Description
     * ===========
     *
     * This test will introduce the concept of Codepoint and surrogate pair to you. But
     * for the most of the cases, the character can fit in 16-bit unicode character.
     *
     * Difficulty: Super Easy
     */
    public class CalculateTextCharLength
    {
        static IEnumerable<object[]> TestCases() =>
            new[]
            {
                new object[]{"", 0},
                new object[]{"1", 1},
                new object[]{char.ConvertFromUtf32(0x2A601), 1}
            };

        #region Please modifies the code to pass the test

        static int GetCharacterLength(string text)
        {
            throw new NotImplementedException();
        }

        #endregion

        [Theory]
        [MemberData(nameof(TestCases))]
        public void should_calculate_text_character_length(string testString, int expectedLength)
        {
            Assert.Equal(expectedLength, GetCharacterLength(testString));
        }
    }
}

using System;
using System.Collections.Generic;
using Xunit;

namespace CSharpViaTest.IOs._10_HandleText
{
    /*
     * Description
     * ===========
     *
     * This test will introduce the concept of Codepoint and surrogate pair to you. But
     * for the most of the cases, the character can fit in 16-bit unicode character.
     *
     * Difficulty: Super Easy
     */
    public class CalculateTextCharLength
    {
        static IEnumerable<object[]> TestCases() =>
            new[]
            {
                new object[]{"", 0},
                new object[]{"12345", 5},
                new object[]{char.ConvertFromUtf32(0x2A601) + "1234", 5}
            };

        #region Please modifies the code to pass the test

        static int GetCharacterLength(string text)
        {
            throw new NotImplementedException();
        }

        #endregion

        [Theory]
        [MemberData(nameof(TestCases))]
        public void should_calculate_text_character_length(string testString, int expectedLength)
        {
            Assert.Equal(expectedLength, GetCharacterLength(testString));
        }
    }
}

Add some complexity to test cases.

[liuxia] Add some complexity to test cases.


using Newtonsoft.Json;

namespace Dnn.PersonaBar.Library.Prompt.Models
{
    /// <summary>
    /// Standard response object sent to client
    /// </summary>
    public class ConsoleResultModel
    {
        // the returned result - text or HTML
        [JsonProperty(PropertyName = "output")]
        public string Output;
        // is the output an error message?
        [JsonProperty(PropertyName = "isError")]
        public bool IsError;
        // is the Output HTML?
        [JsonProperty(PropertyName = "isHtml")]
        public bool IsHtml;
        // should the client reload after processing the command
        [JsonProperty(PropertyName = "mustReload")]
        public bool MustReload;
        // the response contains data to be formatted by the client
        [JsonProperty(PropertyName = "data")]
        public object Data;
        // optionally tell the client in what order the fields should be displayed
        [JsonProperty(PropertyName = "fieldOrder")]
        public string[] FieldOrder;

        [JsonProperty(PropertyName = "pagingInfo")]
        public PagingInfo PagingInfo;

        [JsonProperty(PropertyName = "records")]
        public int Records { get; set; }

        public ConsoleResultModel()
        {
        }

        public ConsoleResultModel(string output)
        {
            Output = output;
        }
    }
}

using Newtonsoft.Json;

namespace Dnn.PersonaBar.Library.Prompt.Models
{
    /// <summary>
    /// Standard response object sent to client
    /// </summary>
    public class ConsoleResultModel
    {
        // the returned result - text or HTML
        [JsonProperty(PropertyName = "output")]
        public string Output;
        // is the output an error message?
        [JsonProperty(PropertyName = "isError")]
        public bool IsError;
        // is the Output HTML?
        [JsonProperty(PropertyName = "isHtml")]
        public bool IsHtml;
        // should the client reload after processing the command
        [JsonProperty(PropertyName = "mustReload")]
        public bool MustReload;
        // the response contains data to be formatted by the client
        [JsonProperty(PropertyName = "data")]
        public object Data;
        // optionally tell the client in what order the fields should be displayed
        [JsonProperty(PropertyName = "fieldOrder")]
        public string[] FieldOrder;

        [JsonProperty(PropertyName = "pagingInfo")]
        public PagingInfo PagingInfo;

        [JsonProperty(PropertyName = "nextPageCommand")]
        public string NextPageCommand;

        [JsonProperty(PropertyName = "records")]
        public int Records { get; set; }

        public ConsoleResultModel()
        {
        }

        public ConsoleResultModel(string output)
        {
            Output = output;
        }
    }
}

Add next page command property

DNN-10096: Add next page command property


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

namespace Fungus
{

	public class EventHandlerInfoAttribute : Attribute
	{
		public EventHandlerInfoAttribute(string category, string eventHandlerName, string helpText)
		{
			this.Category = category;
			this.EventHandlerName = eventHandlerName;
			this.HelpText = helpText;
		}

		public string Category { get; set; }
		public string EventHandlerName { get; set; }
		public string HelpText { get; set; }
	}

	/**
	 * A Sequence may have an associated Event Handler which starts executing the sequence when
	 * a specific event occurs.
	 * To create a custom Event Handler, simply subclass EventHandler and call the ExecuteSequence() method
	 * when the event occurs.
	 * Add an EventHandlerInfo attibute and your new EventHandler class will automatically appear in the
	 * 'Start Event' dropdown menu when a sequence is selected.
	 */
	public class EventHandler : MonoBehaviour
	{
		[HideInInspector]
		public Sequence parentSequence;

		/**
		 * The Event Handler should call this method when the event is detected.
		 */
		public virtual bool ExecuteSequence()
		{
			if (parentSequence == null)
			{
				return false;
			}

			FungusScript fungusScript = parentSequence.GetFungusScript();
			return fungusScript.ExecuteSequence(parentSequence);
		}
	}
}

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

namespace Fungus
{

	public class EventHandlerInfoAttribute : Attribute
	{
		public EventHandlerInfoAttribute(string category, string eventHandlerName, string helpText)
		{
			this.Category = category;
			this.EventHandlerName = eventHandlerName;
			this.HelpText = helpText;
		}

		public string Category { get; set; }
		public string EventHandlerName { get; set; }
		public string HelpText { get; set; }
	}

	/**
	 * A Sequence may have an associated Event Handler which starts executing the sequence when
	 * a specific event occurs.
	 * To create a custom Event Handler, simply subclass EventHandler and call the ExecuteSequence() method
	 * when the event occurs.
	 * Add an EventHandlerInfo attibute and your new EventHandler class will automatically appear in the
	 * 'Start Event' dropdown menu when a sequence is selected.
	 */
	[RequireComponent(typeof(Sequence))]
	[RequireComponent(typeof(FungusScript))]
	public class EventHandler : MonoBehaviour
	{
		[HideInInspector]
		public Sequence parentSequence;

		/**
		 * The Event Handler should call this method when the event is detected.
		 */
		public virtual bool ExecuteSequence()
		{
			if (parentSequence == null)
			{
				return false;
			}

			FungusScript fungusScript = parentSequence.GetFungusScript();
			return fungusScript.ExecuteSequence(parentSequence);
		}
	}
}

Add dependency on Sequence and Fungus Script components


@model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel

@if (Model.ReservedFundingToShow != null)
{

Apprenticeship funding secured

Legal entity:

@Model.ReservedFundingToShowLegalEntityName

Training course:

@Model.ReservedFundingToShow.CourseName

Start and end date:

@Model.ReservedFundingToShow.StartDate.ToString("MMMM yyyy") to @Model.ReservedFundingToShow.EndDate.ToString("MMMM yyyy")

}

@if (Model.RecentlyAddedReservationId != null &&
     Model.ReservedFundingToShow?.ReservationId != Model.RecentlyAddedReservationId)
{

We're dealing with your request for funding, please check back later.

}

Check and secure funding now

@model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel

@if (Model.ReservedFundingToShow != null)
{

Apprenticeship funding secured

Legal entity:

@Model.ReservedFundingToShowLegalEntityName

Training course:

@Model.ReservedFundingToShow.CourseName

Start and end date:

@Model.ReservedFundingToShow.StartDate.ToString("MMMM yyyy") to @Model.ReservedFundingToShow.EndDate.ToString("MMMM yyyy")

}

@if (Model.RecentlyAddedReservationId != null &&
     Model.ReservedFundingToShow?.ReservationId != Model.RecentlyAddedReservationId)
{

We're dealing with your request for funding, please check back later.

}

Manage reservations

Change link title to manage reservations


using System;
using System.Collections.Generic;

namespace DevelopmentInProgress.DipMapper.Test
{
    public class TestDapperClass
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime Date { get; set; }
        public IEnumerable<TestDapperClass> TestDataClasses { get; set; }
    }
}

using System;
using System.Collections.Generic;

namespace DevelopmentInProgress.DipMapper.Test
{
    public class TestDapperClass
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime Date { get; set; }
        public IEnumerable<TestDapperClass> TestDataClasses { get; set; }
        public IList<TestDapperClass> TestDataClasse { get; set; }
    }
}

Test for IList<T> and IEnumerable<T>

Test for IList<T> and IEnumerable<T>

Test for IList<T> and IEnumerable<T>


using System.Windows.Controls;

namespace PopulousStringEditor.Views
{
    /// <summary>
    /// Interaction logic for StringComparisonView.xaml
    /// </summary>
    public partial class StringComparisonView : UserControl
    {
		/// <summary>Gets or sets the visibility of the referenced strings.</summary>
        public System.Windows.Visibility ReferenceStringsVisiblity
        {
            get { return ReferenceStringsColumn.Visibility; }
            set { ReferenceStringsColumn.Visibility = value; }
        }

		/// <summary>
		/// Default constructor.
		/// </summary>
        public StringComparisonView()
        {
            InitializeComponent();
        }
    }
}

Correct inconsistent use of tabs and spaces.


using MessagePack;
using MessagePack.Resolvers;
using UnityEngine;

namespace Assets.Scripts
{
    class InitialSettings
    {
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
        static void RegisterResolvers()
        {
            MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions
                .WithResolver(
                    CompositeResolver.Create(
                        MagicOnion.Resolvers.MagicOnionResolver.Instance,
                        MessagePack.Resolvers.GeneratedResolver.Instance,
                        BuiltinResolver.Instance,
                        PrimitiveObjectResolver.Instance
                    )
                );
        }
    }
}

using MessagePack;
using MessagePack.Resolvers;
using UnityEngine;

namespace Assets.Scripts
{
    class InitialSettings
    {
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
        static void RegisterResolvers()
        {
            // NOTE: Currently, CompositeResolver doesn't work on Unity IL2CPP build. Use StaticCompositeResolver instead of it.
            StaticCompositeResolver.Instance.Register(
                MagicOnion.Resolvers.MagicOnionResolver.Instance,
                MessagePack.Resolvers.GeneratedResolver.Instance,
                BuiltinResolver.Instance,
                PrimitiveObjectResolver.Instance
            );

            MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions
                .WithResolver(StaticCompositeResolver.Instance);
        }
    }
}

Use StaticCompositeResolver instead of CompositeResolver.


using System;

namespace Take.Blip.Builder.Hosting
{
    public class ConventionsConfiguration : IConfiguration
    {
        public virtual TimeSpan InputProcessingTimeout => TimeSpan.FromMinutes(1);

        public virtual string RedisStorageConfiguration => "localhost";

        public virtual int RedisDatabase => 0;

        public virtual int MaxTransitionsByInput => 10;

        public virtual int TraceQueueBoundedCapacity => 512;

        public virtual int TraceQueueMaxDegreeOfParallelism => 512;

        public virtual TimeSpan TraceTimeout => TimeSpan.FromSeconds(5);

        public virtual string RedisKeyPrefix => "builder";

        public bool ContactCacheEnabled => true;

        public virtual TimeSpan ContactCacheExpiration => TimeSpan.FromMinutes(30);

        public virtual TimeSpan DefaultActionExecutionTimeout => TimeSpan.FromSeconds(30);

        public int ExecuteScriptLimitRecursion => 50;

        public int ExecuteScriptMaxStatements => 1000;

        public long ExecuteScriptLimitMemory => 0x100000; // 1MiB or 1 << 20

        public long ExecuteScriptLimitMemoryWarning => 0x80000; // 512KiB or 1 << 19

        public TimeSpan ExecuteScriptTimeout => TimeSpan.FromSeconds(5);
    }
}

using System;

namespace Take.Blip.Builder.Hosting
{
    public class ConventionsConfiguration : IConfiguration
    {
        public virtual TimeSpan InputProcessingTimeout => TimeSpan.FromMinutes(1);

        public virtual string RedisStorageConfiguration => "localhost";

        public virtual int RedisDatabase => 0;

        public virtual int MaxTransitionsByInput => 10;

        public virtual int TraceQueueBoundedCapacity => 512;

        public virtual int TraceQueueMaxDegreeOfParallelism => 512;

        public virtual TimeSpan TraceTimeout => TimeSpan.FromSeconds(5);

        public virtual string RedisKeyPrefix => "builder";

        public bool ContactCacheEnabled => true;

        public virtual TimeSpan ContactCacheExpiration => TimeSpan.FromMinutes(30);

        public virtual TimeSpan DefaultActionExecutionTimeout => TimeSpan.FromSeconds(30);

        public int ExecuteScriptLimitRecursion => 50;

        public int ExecuteScriptMaxStatements => 1000;

        public long ExecuteScriptLimitMemory => 1_000_000; // Nearly 1MB or 1 << 20

        public long ExecuteScriptLimitMemoryWarning => 500_000; // Nearly 512KB or 1 << 19

        public TimeSpan ExecuteScriptTimeout => TimeSpan.FromSeconds(5);
    }
}

Change configurations to decimal value

Change configurations to decimal value


// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.

namespace TerraFX.Audio
{
    /// Represents a type of <see cref="IAudioDeviceOptions"/>
    public enum AudioDeviceType
    {
        /// Indicates that this is a device used for recording.
        Recording,

        /// Indicates that this is a device used for playback.
        Playback
    }
}

// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.

namespace TerraFX.Audio
{
    /// Represents a type of <see cref="IAudioAdapter"/>
    public enum AudioDeviceType
    {
        /// Indicates that this is a device used for recording.
        Recording,

        /// Indicates that this is a device used for playback.
        Playback
    }
}

Fix doc comment cref being incorrect

Fix doc comment cref being incorrect


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

using System;

internal partial class Interop
{
    internal partial class mincore
    {
        internal static int DeleteVolumeMountPoint(string mountPoint)
        {
            // DeleteVolumeMountPointW is not available to store apps.
            // The expectation is that no store app would even have permission
            // to call this from the app container
            throw new UnauthorizedAccessException();
        }
    }
}

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

using System;

internal partial class Interop
{
    internal partial class mincore
    {
        internal static bool DeleteVolumeMountPoint(string mountPoint)
        {
            // DeleteVolumeMountPointW is not available to store apps.
            // The expectation is that no store app would even have permission
            // to call this from the app container
            throw new UnauthorizedAccessException();
        }
    }
}

Fix build breaks mirrored from Github

[Build] Fix build breaks mirrored from Github

/cc @pgavlin @jkuhne

[tfs-changeset: 1503449]


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

using System;
using O365.Security.ETW;

namespace hiddentreasure_etw_demo
{
    public static class PowerShellMethodExecution
    {
        public static void Run()
        {
            // For a more thorough example of how to implement this detection,
            // have a look at https://github.com/zacbrown/PowerShellMethodAuditor
            var filter = new EventFilter(Filter
                .EventIdIs(7937)
                .And(UnicodeString.Contains("Payload", "Started"))
                .And(UnicodeString.Contains("ContextInfo", "Command Type = Function")));

            filter.OnEvent += (IEventRecord r) => {
                var method = r.GetUnicodeString("ContextInfo");
                Console.WriteLine($"Method executed:\n{method}");
            };

            var provider = new Provider("Microsoft-Windows-PowerShell");
            provider.AddFilter(filter);

            var trace = new UserTrace();
            trace.Enable(provider);

            // Setup Ctrl-C to call trace.Stop();
            Helpers.SetupCtrlC(trace);

            // This call is blocking. The thread that calls UserTrace.Start()
            // is donating itself to the ETW subsystem to pump events off
            // of the buffer.
            trace.Start();
        }
    }
}

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

using System;
using O365.Security.ETW;

namespace hiddentreasure_etw_demo
{
    public static class PowerShellMethodExecution
    {
        public static void Run()
        {
            // For a more thorough example of how to implement this detection,
            // have a look at https://github.com/zacbrown/PowerShellMethodAuditor
            var filter = new EventFilter(Filter
                .EventIdIs(7937)
                .And(UnicodeString.Contains("Payload", "Started")));

            filter.OnEvent += (IEventRecord r) => {
                var method = r.GetUnicodeString("ContextInfo");
                Console.WriteLine($"Method executed:\n{method}");
            };

            var provider = new Provider("Microsoft-Windows-PowerShell");
            provider.AddFilter(filter);

            var trace = new UserTrace();
            trace.Enable(provider);

            // Setup Ctrl-C to call trace.Stop();
            Helpers.SetupCtrlC(trace);

            // This call is blocking. The thread that calls UserTrace.Start()
            // is donating itself to the ETW subsystem to pump events off
            // of the buffer.
            trace.Start();
        }
    }
}

Remove the function specific filter.

Remove the function specific filter.

Signed-off-by: Zac Brown (ODSP SECURITY) <a69bc40e0922c9f936432eef55ea97843f621148@microsoft.com>


using Newtonsoft.Json.Linq;
using SnapMD.ConnectedCare.Sdk.Models;

namespace SnapMD.ConnectedCare.Sdk
{
    public class PaymentsApi : ApiCall
    {
        public PaymentsApi(string baseUrl, string bearerToken, int hospitalId, string developerId, string apiKey)
            : base(baseUrl, bearerToken, developerId, apiKey)
        {
            HospitalId = hospitalId;
        }

        public PaymentsApi(string baseUrl, int hospitalId)
            : base(baseUrl)
        {
            HospitalId = hospitalId;
        }

        public int HospitalId { get; private set; }

        public JObject GetCustomerProfile(int userId)
        {
            //API looks so strange

            //hospital/{hospitalId}/payments/{userId}
            var result = MakeCall(string.Format("hospital/{0}/payments", HospitalId));
            return result;
        }

        public JObject RegisterProfile(int userId, object paymentData)
        {
            //hospital/{hospitalId}/payments/{userId}
            var result = Post(string.Format("patients/{0}/payments", userId), paymentData);
            return result;
        }

        public ApiResponse GetPaymentStatus(int consultationId)
        {
            var result = MakeCall<ApiResponse>(string.Format("patients/copay/{0}/paymentstatus", consultationId));
            return result;
        }
    }
}

using Newtonsoft.Json.Linq;
using SnapMD.ConnectedCare.Sdk.Models;

namespace SnapMD.ConnectedCare.Sdk
{
    public class PaymentsApi : ApiCall
    {
        public PaymentsApi(string baseUrl, string bearerToken, int hospitalId, string developerId, string apiKey)
            : base(baseUrl, bearerToken, developerId, apiKey)
        {
            HospitalId = hospitalId;
        }

        public PaymentsApi(string baseUrl, int hospitalId)
            : base(baseUrl)
        {
            HospitalId = hospitalId;
        }

        public int HospitalId { get; private set; }

        public JObject GetCustomerProfile(int userId)
        {
            var result = MakeCall(string.Format("patients/{0}/payments", userId));
            return result;
        }

        public JObject RegisterProfile(int userId, object paymentData)
        {
            var result = Post(string.Format("patients/{0}/payments", userId), paymentData);
            return result;
        }

        public ApiResponse GetPaymentStatus(int consultationId)
        {
            var result = MakeCall<ApiResponse>(string.Format("patients/copay/{0}/paymentstatus", consultationId));
            return result;
        }
    }
}

Fix path for Payments API

Fix path for Payments API


using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Sharpmake;

namespace SharpmakeGen
{
    [Generate]
    public class SharpmakeApplicationProject : Common.SharpmakeBaseProject
    {
        public SharpmakeApplicationProject()
            : base(generateXmlDoc: false)
        {
            Name = "Sharpmake.Application";
            ApplicationManifest = "app.manifest";
        }

        public override void ConfigureAll(Configuration conf, Target target)
        {
            base.ConfigureAll(conf, target);

            conf.Output = Configuration.OutputType.DotNetConsoleApp;

            conf.ReferencesByName.Add("System.Windows.Forms");

            conf.AddPrivateDependency<SharpmakeProject>(target);
            conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target);
            conf.AddPrivateDependency<Platforms.CommonPlatformsProject>(target);
        }
    }
}

using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Sharpmake;

namespace SharpmakeGen
{
    [Generate]
    public class SharpmakeApplicationProject : Common.SharpmakeBaseProject
    {
        public SharpmakeApplicationProject()
            : base(generateXmlDoc: false)
        {
            Name = "Sharpmake.Application";
            ApplicationManifest = "app.manifest";
        }

        public override void ConfigureAll(Configuration conf, Target target)
        {
            base.ConfigureAll(conf, target);

            conf.Output = Configuration.OutputType.DotNetConsoleApp;

            conf.Options.Add(Options.CSharp.AutoGenerateBindingRedirects.Enabled);

            conf.ReferencesByName.Add("System.Windows.Forms");

            conf.AddPrivateDependency<SharpmakeProject>(target);
            conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target);
            conf.AddPrivateDependency<Platforms.CommonPlatformsProject>(target);
        }
    }
}

Fix warning on linux/mac by adding AutoGenerateBindingRedirects


using System;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace GitHub.Collections
{
    public interface ITrackingCollection<T> : IDisposable, IList<T>  where T : ICopyable<T>
    {
        IObservable<T> Listen(IObservable<T> obs);
        IDisposable Subscribe();
        IDisposable Subscribe(Action onCompleted);
        void SetComparer(Func<T, T, int> theComparer);
        void SetFilter(Func<T, int, IList<T>, bool> filter);
        event NotifyCollectionChangedEventHandler CollectionChanged;
    }
}

using System;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace GitHub.Collections
{
    /// <summary>
    /// TrackingCollection is a specialization of ObservableCollection that gets items from
    /// an observable sequence and updates its contents in such a way that two updates to
    /// the same object (as defined by an Equals call) will result in one object on
    /// the list being updated (as opposed to having two different instances of the object
    /// added to the list).
    /// It is always sorted, either via the supplied comparer or using the default comparer
    /// for T
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface ITrackingCollection<T> : IDisposable, IList<T> where T : ICopyable<T>
    {
        /// <summary>
        /// Sets up an observable as source for the collection.
        /// </summary>
        /// <param name="obs"></param>
        /// <returns>An observable that will return all the items that are
        /// fed via the original observer, for further processing by user code
        /// if desired</returns>
        IObservable<T> Listen(IObservable<T> obs);
        IDisposable Subscribe();
        IDisposable Subscribe(Action<T> onNext, Action onCompleted);
        /// <summary>
        /// Set a new comparer for the existing data. This will cause the
        /// collection to be resorted and refiltered.
        /// </summary>
        /// <param name="theComparer">The comparer method for sorting, or null if not sorting</param>
        void SetComparer(Func<T, T, int> comparer);
        /// <summary>
        /// Set a new filter. This will cause the collection to be filtered
        /// </summary>
        /// <param name="theFilter">The new filter, or null to not have any filtering</param>
        void SetFilter(Func<T, int, IList<T>, bool> filter);
        void AddItem(T item);
        void RemoveItem(T item);
        event NotifyCollectionChangedEventHandler CollectionChanged;
    }
}

Fix and document the interface

Fix and document the interface


using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace Mirage.Urbanization.Simulation
{
    public class NeverEndingTask
    {
        private readonly CancellationToken _token;
        private readonly Task _task;
        public NeverEndingTask(string description, Action taskAction, CancellationToken token)
        {
            if (taskAction == null) throw new ArgumentNullException(nameof(taskAction));
            _token = token;
            _task = CreateTask(description.ToLower(), taskAction, token);
        }

        private static Task CreateTask(string description, Action taskAction, CancellationToken token)
        {
            return new Task(() =>
            {
                var stopWatch = new Stopwatch();
                while (true)
                {
                    stopWatch.Restart();

                    Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description}...");
                    taskAction();
                    Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description} completed in {stopWatch.Elapsed}.");
                    Task.Delay(2000, token).Wait(token);
                }
                // ReSharper disable once FunctionNeverReturns
            }, token);
        }

        public void Start()
        {
            _task.Start();
        }

        public void Wait()
        {
            try
            {
                _task.Wait(_token);
            }
            catch (OperationCanceledException ex)
            {
                Mirage.Urbanization.Logger.Instance.WriteLine(ex);
            }
        }
    }
}

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace Mirage.Urbanization.Simulation
{
    public class NeverEndingTask
    {
        private readonly CancellationToken _token;
        private readonly Task _task;
        public NeverEndingTask(string description, Action taskAction, CancellationToken token)
        {
            if (taskAction == null) throw new ArgumentNullException(nameof(taskAction));
            _token = token;
            _task = CreateTask(description.ToLower(), taskAction, token);
        }

        private static Task CreateTask(string description, Action taskAction, CancellationToken token)
        {
            return new Task(() =>
            {
                var stopWatch = new Stopwatch();
                while (true)
                {
                    stopWatch.Restart();

                    Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description}...");
                    taskAction();
                    Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description} completed in {stopWatch.Elapsed}.");
                    Thread.Sleep(2000);
                }
                // ReSharper disable once FunctionNeverReturns
            }, token);
        }

        public void Start()
        {
            _task.Start();
        }

        public void Wait()
        {
            try
            {
                _task.Wait(_token);
            }
            catch (OperationCanceledException ex)
            {
                Mirage.Urbanization.Logger.Instance.WriteLine(ex);
            }
        }
    }
}

Use 'Thread.Sleep' instead of 'await'-less 'Task.Delay'.


using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace Tranquire.Reporting
{
    partial class XmlDocumentObserver
    {
        ///
        /// Returns a HTML document that contains the report.
        ///
        /// <returns></returns>
        public string GetHtmlDocument()
        {
            var xmlDocument = GetXmlDocument();
            // enabling debug mode workaround an null reference exception occuring internally in .net core
            var xslt = new XslCompiledTransform(true);
            var xmlReader = XmlReader.Create(typeof(XmlDocumentObserver).Assembly.GetManifestResourceStream("Tranquire.Reporting.XmlReport.xsl"));
            xslt.Load(xmlReader);
            var result = new StringBuilder();
            var xmlWriter = XmlWriter.Create(result);
            xslt.Transform(xmlDocument.CreateNavigator(), xmlWriter);
            return result.ToString()
                         .Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<!DOCTYPE html>")
                         .Replace("", "");
        }
    }
}

using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace Tranquire.Reporting
{
    partial class XmlDocumentObserver
    {
        ///
        /// Returns a HTML document that contains the report.
        ///
        /// <returns></returns>
        public string GetHtmlDocument()
        {
            var xmlDocument = GetXmlDocument();
            var xslt = new XslCompiledTransform(false);
            var xmlReader = XmlReader.Create(typeof(XmlDocumentObserver).Assembly.GetManifestResourceStream("Tranquire.Reporting.XmlReport.xsl"));
            xslt.Load(xmlReader);
            var result = new StringBuilder();
            var xmlWriter = XmlWriter.Create(result);
            xslt.Transform(xmlDocument.CreateReader(), xmlWriter);
            return result.ToString()
                         .Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<!DOCTYPE html>")
                         .Replace("", "");
        }
    }
}

Remove workaround for xslt and use a XmlReader instead of a XPath navigator


using System.Globalization;

namespace OpenSage.Data.Utilities
{
    internal static class ParseUtility
    {
        public static float ParseFloat(string s)
        {
            return float.Parse(s, CultureInfo.InvariantCulture);
        }

        public static bool TryParseFloat(string s, out float result)
        {
            return float.TryParse(s, out result);
        }
    }
}

using System.Globalization;

namespace OpenSage.Data.Utilities
{
    internal static class ParseUtility
    {
        public static float ParseFloat(string s)
        {
            return float.Parse(s, CultureInfo.InvariantCulture);
        }

        public static bool TryParseFloat(string s, out float result)
        {
            return float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out result);
        }
    }
}

Use culture invariant version of float.TryParse


using System;

namespace HobknobClientNet
{
    public interface IHobknobClientFactory
    {
        IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed);
    }

    public class HobknobClientFactory : IHobknobClientFactory
    {
        public IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed)
        {
            var etcdKeysPath = string.Format("http://{0}:{1}/v2/keys/", etcdHost, etcdPort);

            var etcdClient = new EtcdClient(new Uri(etcdKeysPath));
            var featureToggleProvider = new FeatureToggleProvider(etcdClient, applicationName);
            var featureToggleCache = new FeatureToggleCache(featureToggleProvider, cacheUpdateInterval);
            var hobknobClient = new HobknobClient(featureToggleCache, applicationName);
            if (cacheUpdateFailed == null)
                throw new ArgumentNullException("cacheUpdateFailed", "Cached update handler is emtpy");
            featureToggleCache.CacheUpdateFailed += cacheUpdateFailed;

            featureToggleCache.Initialize();

            return hobknobClient;
        }
    }
}

using System;

namespace HobknobClientNet
{
    public interface IHobknobClientFactory
    {
        IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed);
    }

    public class HobknobClientFactory : IHobknobClientFactory
    {
        public IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed)
        {
            var etcdKeysPath = string.Format("http://{0}:{1}/v2/keys/", etcdHost, etcdPort);

            var etcdClient = new EtcdClient(new Uri(etcdKeysPath));
            var featureToggleProvider = new FeatureToggleProvider(etcdClient, applicationName);
            var featureToggleCache = new FeatureToggleCache(featureToggleProvider, cacheUpdateInterval);
            var hobknobClient = new HobknobClient(featureToggleCache, applicationName);
            if (cacheUpdateFailed == null)
                throw new ArgumentNullException("cacheUpdateFailed", "Cached update handler is empty");
            featureToggleCache.CacheUpdateFailed += cacheUpdateFailed;

            featureToggleCache.Initialize();

            return hobknobClient;
        }
    }
}

Fix cache update exception typo

Fix cache update exception typo


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

using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Testing;

namespace osu.Framework.Tests.Visual.UserInterface
{
    public class TestSceneColourPicker : FrameworkTestScene
    {
        [SetUpSteps]
        public void SetUpSteps()
        {
            ColourPicker colourPicker = null;

            AddStep("create picker", () => Child = colourPicker = new BasicColourPicker());
            AddStep("set colour externally", () => colourPicker.Current.Value = Colour4.Goldenrod);
            AddAssert("colour is correct", () => colourPicker.Current.Value == Colour4.Goldenrod);
        }
    }
}

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

using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;

namespace osu.Framework.Tests.Visual.UserInterface
{
    public class TestSceneColourPicker : FrameworkTestScene
    {
        [Test]
        public void TestExternalColourSetAfterCreation()
        {
            ColourPicker colourPicker = null;

            AddStep("create picker", () => Child = colourPicker = new BasicColourPicker());
            AddStep("set colour externally", () => colourPicker.Current.Value = Colour4.Goldenrod);
            AddAssert("colour is correct", () => colourPicker.Current.Value == Colour4.Goldenrod);
        }

        [Test]
        public void TestExternalColourSetAtCreation()
        {
            ColourPicker colourPicker = null;

            AddStep("create picker", () => Child = colourPicker = new BasicColourPicker
            {
                Current = { Value = Colour4.Goldenrod }
            });
            AddAssert("colour is correct", () => colourPicker.Current.Value == Colour4.Goldenrod);
        }
    }
}

Add failing test case for setting colour at creation