using Microsoft.AspNetCore.Http;
using Obsidian.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Authentication;
using Obsidian.Application.OAuth20;

namespace Obsidian.Services
{
    public class SignInService : ISignInService
    {
        private readonly IHttpContextAccessor _accessor;

        const string Scheme = "Obsidian.Cookie";

        public SignInService(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        public async Task CookieSignInAsync(User user, bool isPersistent)
        {
            await CookieSignOutCurrentUserAsync();
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName)
            };
            var identity = new ClaimsIdentity(claims);
            var principal = new ClaimsPrincipal(identity);
            var context = _accessor.HttpContext;
            var props = new AuthenticationProperties{ IsPersistent = isPersistent };
            await context.Authentication.SignInAsync(Scheme, principal, props);
        }

        public async Task CookieSignOutCurrentUserAsync()
            => await _accessor.HttpContext.Authentication.SignOutAsync(Scheme);
    }
}

using Microsoft.AspNetCore.Http;
using Obsidian.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Authentication;
using Obsidian.Application.OAuth20;

namespace Obsidian.Services
{
    public class SignInService : ISignInService
    {
        private readonly IHttpContextAccessor _accessor;

        const string Scheme = "Obsidian.Cookie";

        public SignInService(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        public async Task CookieSignInAsync(User user, bool isPersistent)
        {
            await CookieSignOutCurrentUserAsync();
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.UserName)
            };
            var identity = new ClaimsIdentity(claims);
            var principal = new ClaimsPrincipal(identity);
            var context = _accessor.HttpContext;
            var props = new AuthenticationProperties{ IsPersistent = isPersistent };
            await context.Authentication.SignInAsync(Scheme, principal, props);
        }

        public async Task CookieSignOutCurrentUserAsync()
            => await _accessor.HttpContext.Authentication.SignOutAsync(Scheme);
    }
}

Revert "keep username only in sinin cookie"

This reverts commit 6a2a4dceca65d2457a80f205ee5d1dfa65b7278b.


#region Copyright and license
// // <copyright file="AlwaysTests.cs" company="Oliver Zick">
// //     Copyright (c) 2016 Oliver Zick. All rights reserved.
// // </copyright>
// // <author>Oliver Zick</author>
// // <license>
// //     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.
// // </license>
#endregion

namespace Delizious.Filtering
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public sealed class AlwaysTests
    {
        [TestMethod]
        public void Succeed__When_Value_Is_Null()
        {
            Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(null));
        }

        [TestMethod]
        public void Succeed__When_Value_Is_An_Instance()
        {
            Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(new GenericParameterHelper()));
        }
    }
}

#region Copyright and license
// // <copyright file="AlwaysTests.cs" company="Oliver Zick">
// //     Copyright (c) 2016 Oliver Zick. All rights reserved.
// // </copyright>
// // <author>Oliver Zick</author>
// // <license>
// //     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.
// // </license>
#endregion

namespace Delizious.Filtering
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public sealed class AlwaysTests
    {
        [TestMethod]
        public void Match_Succeeds_When_Value_To_Match_Is_Null()
        {
            Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(null));
        }

        [TestMethod]
        public void Match_Succeeds_When_Value_To_Match_Is_An_Instance()
        {
            Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(new GenericParameterHelper()));
        }
    }
}

Improve naming of tests to clearly indicate the feature to be tested


using NUnit.Framework;

[assembly: Category("IntegrationTest")]
[assembly: Parallelizable(ParallelScope.Fixtures)]
[assembly: LevelOfParallelism(32)]

using NUnit.Framework;

[assembly: Category("IntegrationTest")]
[assembly: Parallelizable(ParallelScope.Fixtures)]
[assembly: LevelOfParallelism(2)]

Reduce concurrency (not eliminate) in integration tests so that starting up a test suite run doesn't soak up all the threads in our thread pool.


void DownloadAudienceNetwork (Artifact artifact)
{
	var podSpec = artifact.PodSpecs [0];
	var id = podSpec.Name;
	var version = podSpec.Version;
	var url = $"https://origincache.facebook.com/developers/resources/?id={id}-{version}.zip";
	var basePath = $"./externals/{id}";
	DownloadFile (url, $"{basePath}.zip", new Cake.Xamarin.Build.DownloadFileSettings { UserAgent = "curl/7.43.0" });
	Unzip ($"{basePath}.zip", $"{basePath}");
	CopyDirectory ($"{basePath}/Dynamic/{id}.framework", $"./externals/{id}.framework");
}

void DownloadAudienceNetwork (Artifact artifact)
{
	var podSpec = artifact.PodSpecs [0];
	var id = podSpec.Name;
	var version = podSpec.Version;
	var url = $"https://developers.facebook.com/resources/{id}-{version}.zip";
	var basePath = $"./externals/{id}";
	DownloadFile (url, $"{basePath}.zip", new Cake.Xamarin.Build.DownloadFileSettings { UserAgent = "curl/7.43.0" });
	Unzip ($"{basePath}.zip", $"{basePath}");
	CopyDirectory ($"{basePath}/Dynamic/{id}.framework", $"./externals/{id}.framework");
}

[iOS][AudienceNetwork] Use same url Facebook uses to download bits


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

namespace PackageExplorerViewModel.Utilities
{
    public class TemporaryFile : IDisposable
    {
        public TemporaryFile(Stream stream, string extension)
        {
            if (stream == null)
                throw new ArgumentNullException(nameof(stream));

            if (!string.IsNullOrWhiteSpace(extension) || extension[0] != '.')
            {
                extension = string.Empty;
            }

            FileName = Path.GetTempFileName() + extension;

            stream.CopyToFile(FileName);
        }

        public string FileName { get; }

        bool disposed;

        public void Dispose()
        {
            if (!disposed)
            {
                disposed = true;
                try
                {
                    File.Delete(FileName);
                }
                catch // best effort
                {
                }
            }
        }

    }
}

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

namespace PackageExplorerViewModel.Utilities
{
    public class TemporaryFile : IDisposable
    {
        public TemporaryFile(Stream stream, string extension)
        {
            if (stream == null)
                throw new ArgumentNullException(nameof(stream));

            if (string.IsNullOrWhiteSpace(extension) || extension[0] != '.')
            {
                extension = string.Empty;
            }

            FileName = Path.GetTempFileName() + extension;

            stream.CopyToFile(FileName);
        }

        public string FileName { get; }

        bool disposed;

        public void Dispose()
        {
            if (!disposed)
            {
                disposed = true;
                try
                {
                    File.Delete(FileName);
                }
                catch // best effort
                {
                }
            }
        }

    }
}

Fix check so file extension is preserved


using System.Threading;
using System.Threading.Tasks;
using Console = System.Console;

namespace ConsoleWritePrettyOneDay.App
{
    class Program
    {
        static void Main(string[] args)
        {
            Spinner.Wait(() => Thread.Sleep(5000), "waiting for sleep");

            var task = Task.Run(() => Thread.Sleep(4000));
            Spinner.Wait(task, "waiting for task");

            Console.ReadLine();
        }
    }
}

using System.Threading;
using System.Threading.Tasks;
using Console = System.Console;

namespace ConsoleWritePrettyOneDay.App
{
    class Program
    {
        static void Main(string[] args)
        {
            Spinner.Wait(() => Thread.Sleep(5000), "waiting for sleep");

            var task = Task.Run(() => Thread.Sleep(4000));
            Spinner.Wait(task, "waiting for task");

            Console.WriteLine();
            Console.WriteLine("Press [enter] to exit.");
            Console.ReadLine();
        }
    }
}

Add message to press enter when sample App execution is complete


using System.Windows;

namespace twitch_tv_viewer.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Edit_Click(object sender, RoutedEventArgs e) => new Edit().ShowDialog();

        private void Add_Click(object sender, RoutedEventArgs e) => new Add().ShowDialog();
    }
}

using System.Windows;
using System.Windows.Input;

namespace twitch_tv_viewer.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Edit_Click(object sender, RoutedEventArgs e) => new Edit().ShowDialog();

        private void Add_Click(object sender, RoutedEventArgs e) => new Add().ShowDialog();

        private void Datagrid_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
                new Delete().ShowDialog();
        }
    }
}

Add simple binding for showing display of delete view


using System;

namespace uSync8.Core.Dependency
{
    [Flags]
    public enum DependencyFlags
    {
        None = 0,
        IncludeChildren = 2,
        IncludeAncestors = 4,
        IncludeDependencies = 8,
        IncludeViews = 16,
        IncludeMedia = 32,
        IncludeLinked = 64,
        IncludeMediaFiles = 128
    }
}

using System;

namespace uSync8.Core.Dependency
{
    [Flags]
    public enum DependencyFlags
    {
        None = 0,
        IncludeChildren = 2,
        IncludeAncestors = 4,
        IncludeDependencies = 8,
        IncludeViews = 16,
        IncludeMedia = 32,
        IncludeLinked = 64,
        IncludeMediaFiles = 128,
        IncludeConfig = 256
    }
}

Add config to the dependency flags.

Add config to the dependency flags.


using BmpListener.Extensions;
using System;
using System.Linq;

namespace BmpListener.Bgp
{
    public class CapabilityMultiProtocol : Capability
    {
        public CapabilityMultiProtocol(ArraySegment<byte> data) : base(data)
        {
            var afi = data.ToInt16(2);
            var safi = data.ElementAt(4);
        }
    }
}

using System;

namespace BmpListener.Bgp
{
    public class CapabilityMultiProtocol : Capability
    {
        public CapabilityMultiProtocol(ArraySegment<byte> data) : base(data)
        {
            Decode(CapabilityValue);
        }

        public AddressFamily Afi { get; set; }
        public SubsequentAddressFamily Safi { get; set; }

        // RFC 4760 - Reserved (8 bit) field. SHOULD be set to 0 by the
        // sender and ignored by the receiver.
        public byte Res { get { return 0; } }

        public void Decode(ArraySegment<byte> data)
        {
            Array.Reverse(CapabilityValue.Array, data.Offset, 2);
            Afi = (AddressFamily)BitConverter.ToInt16(data.Array, data.Offset);
            Safi = (SubsequentAddressFamily)data.Array[data.Offset + 3];
        }
    }
}

Fix Multiprotocol AFI and SAFI decoding

Fix Multiprotocol AFI and SAFI decoding


using System;

namespace Mammoth.Couscous.java.net {
    internal class URI {
        private readonly Uri _uri;

        internal URI(string uri) {
            try {
                _uri = new Uri(uri, UriKind.RelativeOrAbsolute);
            } catch (UriFormatException exception) {
                throw new URISyntaxException(exception.Message);
            }
        }

        internal URI(Uri uri) {
            _uri = uri;
        }

        internal bool isAbsolute() {
            return _uri.IsAbsoluteUri;
        }

        internal URL toURL() {
            return new URL(_uri.ToString());
        }

        internal URI resolve(string relativeUri) {
            if (new URI(relativeUri).isAbsolute()) {
                return new URI(relativeUri);
            } else if (_uri.IsAbsoluteUri) {
                return new URI(new Uri(_uri, relativeUri));
            } else {
                var path = _uri.ToString();
                var lastSlashIndex = path.LastIndexOf("/");
                var basePath = lastSlashIndex == -1
                    ?  "."
                    : path.Substring(0, lastSlashIndex + 1);
                return new URI(basePath + relativeUri);
            }
        }
    }
}

using System;

namespace Mammoth.Couscous.java.net {
    internal class URI {
        private readonly Uri _uri;

        internal URI(string uri) {
            try {
                _uri = new Uri(uri, UriKind.RelativeOrAbsolute);
            } catch (UriFormatException exception) {
                throw new URISyntaxException(exception.Message);
            }
        }

        internal URI(Uri uri) {
            _uri = uri;
        }

        internal bool isAbsolute() {
            return _uri.IsAbsoluteUri;
        }

        internal URL toURL() {
            return new URL(_uri.ToString());
        }

        internal URI resolve(string relativeUri) {
            if (new URI(relativeUri).isAbsolute()) {
                return new URI(relativeUri);
            } else if (_uri.IsAbsoluteUri) {
                return new URI(new Uri(_uri, relativeUri));
            } else {
                var path = _uri.ToString();
                var basePath = System.IO.Path.GetDirectoryName(path);
                return new URI(System.IO.Path.Combine(basePath, relativeUri));
            }
        }
    }
}

Handle paths on Windows properly

Handle paths on Windows properly


// Copyright (c) the authors of nanoGames. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt in the project root.

using NanoGames.Engine;
using System.Collections.Generic;
using System.Diagnostics;

namespace NanoGames.Application
{
    /// <summary>
    /// A view that measures and draws the current frames per second.
    /// </summary>
    internal sealed class FpsView : IView
    {
        private readonly Queue<long> _times = new Queue<long>();

        /// <inheritdoc/>
        public void Update(Terminal terminal)
        {
            var fontSize = 6;
            var color = new Color(0.60, 0.35, 0.05);

            if (DebugMode.IsEnabled)
            {
                terminal.Graphics.Print(color, fontSize, new Vector(0, 0), "DEBUG");
            }

            var time = Stopwatch.GetTimestamp();

            if (Settings.Instance.ShowFps && _times.Count > 0)
            {
                var fps = (double)Stopwatch.Frequency * _times.Count / (time - _times.Peek());
                var fpsString = ((int)(fps + 0.5)).ToString("D2");

                terminal.Graphics.Print(color, fontSize, new Vector(GraphicsConstants.Width - fpsString.Length * fontSize, 0), fpsString);
            }

            if (_times.Count > 128)
            {
                _times.Dequeue();
            }

            _times.Enqueue(time);
        }
    }
}

// Copyright (c) the authors of nanoGames. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt in the project root.

using NanoGames.Engine;
using System.Collections.Generic;
using System.Diagnostics;

namespace NanoGames.Application
{
    /// <summary>
    /// A view that measures and draws the current frames per second.
    /// </summary>
    internal sealed class FpsView : IView
    {
        private readonly Queue<long> _times = new Queue<long>();

        /// <inheritdoc/>
        public void Update(Terminal terminal)
        {
            var fontSize = 6;
            var color = new Color(0.60, 0.35, 0.05);

            if (DebugMode.IsEnabled)
            {
                terminal.Graphics.Print(color, fontSize, new Vector(0, 0), "DEBUG");
                for (int i = 0; i <= System.GC.MaxGeneration; ++i)
                {
                    terminal.Graphics.Print(color, fontSize, new Vector(0, (i + 1) * fontSize), string.Format("GC{0}: {1}", i, System.GC.CollectionCount(i)));
                }
            }

            var time = Stopwatch.GetTimestamp();

            if (Settings.Instance.ShowFps && _times.Count > 0)
            {
                var fps = (double)Stopwatch.Frequency * _times.Count / (time - _times.Peek());
                var fpsString = ((int)(fps + 0.5)).ToString("D2");

                terminal.Graphics.Print(color, fontSize, new Vector(GraphicsConstants.Width - fpsString.Length * fontSize, 0), fpsString);
            }

            if (_times.Count > 128)
            {
                _times.Dequeue();
            }

            _times.Enqueue(time);
        }
    }
}

Debug mode: Show the number of garbage collections


public static class AssemblyLine
{
    private const int ProductionRatePerHourForDefaultSpeed = 221;

    public static double ProductionRatePerHour(int speed) =>
        ProductionRatePerHourForSpeed(speed) * SuccessRate(speed);

    private static int ProductionRatePerHourForSpeed(int speed) =>
        ProductionRatePerHourForDefaultSpeed * speed;

    public static int WorkingItemsPerMinute(int speed) =>
        (int)ProductionRatePerHour(speed) / 60;

    private static double SuccessRate(int speed)
    {
        if (speed == 0)
            return 0.0;

        if (speed >= 9)
            return 0.77;

        if (speed < 5)
            return 1.0;

        return 0.9;
    }
}

public static class AssemblyLine
{
    private const int ProductionRatePerHourForDefaultSpeed = 221;

    public static double ProductionRatePerHour(int speed) =>
        ProductionRatePerHourForSpeed(speed) * SuccessRate(speed);

    private static int ProductionRatePerHourForSpeed(int speed) =>
        ProductionRatePerHourForDefaultSpeed * speed;

    public static int WorkingItemsPerMinute(int speed) =>
        (int)(ProductionRatePerHour(speed) / 60);

    private static double SuccessRate(int speed)
    {
        if (speed == 0)
            return 0.0;

        if (speed >= 9)
            return 0.77;

        if (speed < 5)
            return 1.0;

        return 0.9;
    }
}

Fix rounding error in numbers exercise

Fix rounding error in numbers exercise


using System;
using System.Net;

namespace PackageExplorerViewModel.Types
{
    public interface ICredentialManager
    {
        void TryAddUriCredentials(Uri feedUri);

        void Add(ICredentials credentials, Uri feedUri);

        ICredentials GetForUri(Uri uri);
    }
}

using System;
using System.Net;

namespace PackageExplorerViewModel.Types
{
    public interface ICredentialManager
    {
        void Add(ICredentials credentials, Uri feedUri);

        ICredentials GetForUri(Uri uri);
    }
}

Remove unused method from interface

Remove unused method from interface


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Catch.Skinning.Default;
using osu.Game.Rulesets.Objects.Pooling;
using osu.Game.Skinning;

namespace osu.Game.Rulesets.Catch.UI
{
    public class HitExplosion : PoolableDrawableWithLifetime<HitExplosionEntry>
    {
        private SkinnableDrawable skinnableExplosion;

        public HitExplosion()
        {
            RelativeSizeAxes = Axes.Both;
            Anchor = Anchor.BottomCentre;
            Origin = Anchor.BottomCentre;
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            InternalChild = skinnableExplosion = new SkinnableDrawable(new CatchSkinComponent(CatchSkinComponents.HitExplosion), _ => new DefaultHitExplosion())
            {
                CentreComponent = false,
                Anchor = Anchor.BottomCentre,
                Origin = Anchor.BottomCentre
            };
        }

        protected override void OnApply(HitExplosionEntry entry)
        {
            base.OnApply(entry);

            ApplyTransformsAt(double.MinValue, true);
            ClearTransforms(true);

            (skinnableExplosion.Drawable as IHitExplosion)?.Animate(entry);
            LifetimeEnd = skinnableExplosion.Drawable.LatestTransformEndTime;
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Catch.Skinning.Default;
using osu.Game.Rulesets.Objects.Pooling;
using osu.Game.Skinning;

namespace osu.Game.Rulesets.Catch.UI
{
    public class HitExplosion : PoolableDrawableWithLifetime<HitExplosionEntry>
    {
        private SkinnableDrawable skinnableExplosion;

        public HitExplosion()
        {
            RelativeSizeAxes = Axes.Both;
            Anchor = Anchor.BottomCentre;
            Origin = Anchor.BottomCentre;
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            InternalChild = skinnableExplosion = new SkinnableDrawable(new CatchSkinComponent(CatchSkinComponents.HitExplosion), _ => new DefaultHitExplosion())
            {
                CentreComponent = false,
                Anchor = Anchor.BottomCentre,
                Origin = Anchor.BottomCentre
            };
        }

        protected override void OnApply(HitExplosionEntry entry)
        {
            base.OnApply(entry);
            if (IsLoaded)
                apply(entry);
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();
            apply(Entry);
        }

        private void apply(HitExplosionEntry entry)
        {
            ApplyTransformsAt(double.MinValue, true);
            ClearTransforms(true);

            (skinnableExplosion.Drawable as IHitExplosion)?.Animate(entry);
            LifetimeEnd = skinnableExplosion.Drawable.LatestTransformEndTime;
        }
    }
}

Fix explosion reading out time values from wrong clock


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

using System;
using osu.Framework.Input.Bindings;
using osu.Game.Database;
using Realms;

namespace osu.Game.Input.Bindings
{
    [MapTo(nameof(KeyBinding))]
    public class RealmKeyBinding : RealmObject, IHasGuidPrimaryKey, IKeyBinding
    {
        [PrimaryKey]
        public Guid ID { get; set; }

        public int? RulesetID { get; set; }

        public int? Variant { get; set; }

        public KeyCombination KeyCombination
        {
            get => KeyCombinationString;
            set => KeyCombinationString = value.ToString();
        }

        public object Action
        {
            get => ActionInt;
            set => ActionInt = (int)value;
        }

        [MapTo(nameof(Action))]
        public int ActionInt { get; set; }

        [MapTo(nameof(KeyCombination))]
        public string KeyCombinationString { get; set; }
    }
}

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

using System;
using osu.Framework.Input.Bindings;
using osu.Game.Database;
using Realms;

namespace osu.Game.Input.Bindings
{
    [MapTo(nameof(KeyBinding))]
    public class RealmKeyBinding : RealmObject, IHasGuidPrimaryKey, IKeyBinding
    {
        [PrimaryKey]
        public string StringGuid { get; set; }

        [Ignored]
        public Guid ID
        {
            get => Guid.Parse(StringGuid);
            set => StringGuid = value.ToString();
        }

        public int? RulesetID { get; set; }

        public int? Variant { get; set; }

        public KeyCombination KeyCombination
        {
            get => KeyCombinationString;
            set => KeyCombinationString = value.ToString();
        }

        public object Action
        {
            get => ActionInt;
            set => ActionInt = (int)value;
        }

        [MapTo(nameof(Action))]
        public int ActionInt { get; set; }

        [MapTo(nameof(KeyCombination))]
        public string KeyCombinationString { get; set; }
    }
}

Switch Guid implementation temporarily to avoid compile time error


using UnityEngine;
using System.Collections;
using System;

public class AnimateToPoint : MonoBehaviour {
	private SimpleTween tween;
	private Vector3 sourcePos;
	private Vector3 targetPos;
	private Action onComplete;
	private float timeScale;
	private float timer;

	public void Trigger(SimpleTween tween, Vector3 point) {
		Trigger(tween, point, () => {});
	}

	public void Trigger(SimpleTween tween, Vector3 point, Action onComplete) {
		this.tween = tween;
		this.onComplete = onComplete;
		sourcePos = transform.position;
		targetPos = point;

		timeScale = 1.0f / tween.Duration;
		timer = 0.0f;
	}

	private void Update() {
		if (tween != null) {
			if (timer > 1.0f) {
				transform.position = targetPos;
				onComplete();
				tween = null;
			} else {
				transform.position = tween.Evaluate(sourcePos, targetPos, timer);
			}
			timer += timeScale * Time.deltaTime;
		}
	}
}

using UnityEngine;
using System.Collections;
using System;

public class AnimateToPoint : MonoBehaviour {
	private SimpleTween tween;
	private Vector3 sourcePos;
	private Vector3 targetPos;
	private Action onComplete;
	private float timeScale;
	private float timer;

	public void Trigger(SimpleTween tween, Vector3 point) {
		Trigger(tween, point, () => {});
	}

	public void Trigger(SimpleTween tween, Vector3 point, Action onComplete) {
		this.tween = tween;
		this.onComplete = onComplete;
		sourcePos = transform.position;
		targetPos = point;

		timeScale = 1.0f / tween.Duration;
		timer = 0.0f;
	}

	private void Update() {
		if (tween != null) {
			if (timer > 1.0f) {
				tween = null;
				transform.position = targetPos;
				onComplete();
			} else {
				transform.position = tween.Evaluate(sourcePos, targetPos, timer);
			}
			timer += timeScale * Time.deltaTime;
		}
	}
}

Fix ordering bug when chaining Tweens

Fix ordering bug when chaining Tweens


using UnityEngine;
using System.Collections;

public class AdminModeMessageWindow : MonoBehaviour {
    private const float WINDOW_WIDTH = 300;
    private const float WINDOW_HEIGHT = 120;
    private const float MESSAGE_HEIGHT = 60;
    private const float BUTTON_HEIGHT = 30;
    private const float BUTTON_WIDTH = 40;
    private string Message;

    public void Initialize() {
        Message = "Could not sync player records to server.\nReason \"Player " + PlayerOptions.Name  + " log corrupted\".\nAdmin mode enabled";
    }

    void OnGUI () {
        GUI.Window(0, WindowRect, MessageWindow, "Error");
    }

    void MessageWindow(int windowID) {
        GUI.Label(LabelRect, Message);
        if (GUI.Button(ButtonRect, "OK")) {
            enabled = false;
        }
    }

    private Rect WindowRect {
        get {
            var anchor = TransformToGuiFinder.Find(transform);
            return new Rect(anchor.x - WINDOW_WIDTH / 2, anchor.y - WINDOW_HEIGHT / 2, WINDOW_WIDTH, WINDOW_HEIGHT);
        }
    }

    private Rect LabelRect {
        get { return new Rect(10, 20, WINDOW_WIDTH, MESSAGE_HEIGHT); }
    }
    private Rect ButtonRect {
        get { return new Rect((WINDOW_WIDTH / 2) - (BUTTON_WIDTH / 2), 20 + MESSAGE_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT); }
    }

}

using UnityEngine;
using System.Collections;

public class AdminModeMessageWindow : MonoBehaviour {
    private const float WINDOW_WIDTH = 300;
    private const float WINDOW_HEIGHT = 120;
    private const float MESSAGE_HEIGHT = 60;
    private const float BUTTON_HEIGHT = 30;
    private const float BUTTON_WIDTH = 40;
    private string Message;

    public void Initialize() {
        Message = "Could not sync player records to server.\nReason \"Player " + PlayerOptions.Name  + " log corrupted\".\nAdmin mode enabled and player freed from track.";
    }

    void OnGUI () {
        GUI.Window(0, WindowRect, MessageWindow, "Error");
    }

    void MessageWindow(int windowID) {
        GUI.Label(LabelRect, Message);
        if (GUI.Button(ButtonRect, "OK")) {
            enabled = false;
        }
    }

    private Rect WindowRect {
        get {
            var anchor = TransformToGuiFinder.Find(transform);
            return new Rect(anchor.x - WINDOW_WIDTH / 2, anchor.y - WINDOW_HEIGHT / 2, WINDOW_WIDTH, WINDOW_HEIGHT);
        }
    }

    private Rect LabelRect {
        get { return new Rect(10, 20, WINDOW_WIDTH, MESSAGE_HEIGHT); }
    }
    private Rect ButtonRect {
        get { return new Rect((WINDOW_WIDTH / 2) - (BUTTON_WIDTH / 2), 20 + MESSAGE_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT); }
    }

}

Change message to indicate player is freed from track


using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Okanshi.Dashboard.Models;

namespace Okanshi.Dashboard
{
	public interface IGetMetrics
	{
		IEnumerable<Metric> Deserialize(string response);
	}

	public class GetMetrics : IGetMetrics
	{
		public IEnumerable<Metric> Deserialize(string response)
		{
			var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response);
			return deserializeObject
				.Select(x => new Metric
				{
					Name = x.Key,
					Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(),
					WindowSize = x.Value.windowSize.ToObject<float>()
				});
		}
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Okanshi.Dashboard.Models;

namespace Okanshi.Dashboard
{
	public interface IGetMetrics
	{
		IEnumerable<Metric> Deserialize(string response);
	}

	public class GetMetrics : IGetMetrics
	{
		public IEnumerable<Metric> Deserialize(string response)
		{
			var jObject = JObject.Parse(response);
			JToken versionToken;
			jObject.TryGetValue("version", out versionToken);
			var version = "0";
			if (versionToken != null && versionToken.HasValues)
			{
				version = versionToken.Value<string>();
			}

			if (version.Equals("0", StringComparison.OrdinalIgnoreCase))
			{
				var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response);
				return deserializeObject
					.Select(x => new Metric
					{
						Name = x.Key,
						Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(),
						WindowSize = x.Value.windowSize.ToObject<float>()
					});
			}

			return Enumerable.Empty<Metric>();
		}
	}
}

Handle optional version and fallback

Handle optional version and fallback


using System.Reactive.Linq;
using System.Threading.Tasks;
using NSubstitute;
using Xunit;
using UnitTests;
using GitHub.Models;
using System;
using GitHub.Services;
using GitHub.ViewModels;

public class PullRequestCreationViewModelTests : TempFileBaseClass
{
    [Fact]
    public async Task NullDescriptionBecomesEmptyBody()
    {
        var serviceProvider = Substitutes.ServiceProvider;
        var service = new PullRequestService();
        var notifications = Substitute.For<INotificationService>();

        var host = serviceProvider.GetRepositoryHosts().GitHubHost;
        var ms = Substitute.For<IModelService>();
        host.ModelService.Returns(ms);

        var repository = new SimpleRepositoryModel("name", new GitHub.Primitives.UriString("http://github.com/github/stuff"));
        var title = "a title";

        var vm = new PullRequestCreationViewModel(host, repository, service, notifications);
        vm.SourceBranch = new BranchModel() { Name = "source" };
        vm.TargetBranch = new BranchModel() { Name = "target" };
        vm.PRTitle = title;

        await vm.CreatePullRequest.ExecuteAsync();
        ms.Received().CreatePullRequest(repository, vm.PRTitle, String.Empty, vm.SourceBranch, vm.TargetBranch);
    }

}

using System.Reactive.Linq;
using System.Threading.Tasks;
using NSubstitute;
using Xunit;
using UnitTests;
using GitHub.Models;
using System;
using GitHub.Services;
using GitHub.ViewModels;

public class PullRequestCreationViewModelTests : TempFileBaseClass
{
    [Fact]
    public async Task NullDescriptionBecomesEmptyBody()
    {
        var serviceProvider = Substitutes.ServiceProvider;
        var service = new PullRequestService();
        var notifications = Substitute.For<INotificationService>();

        var host = serviceProvider.GetRepositoryHosts().GitHubHost;
        var ms = Substitute.For<IModelService>();
        host.ModelService.Returns(ms);

        var repository = new SimpleRepositoryModel("name", new GitHub.Primitives.UriString("http://github.com/github/stuff"));
        var title = "a title";

        var vm = new PullRequestCreationViewModel(host, repository, service, notifications);
        vm.SourceBranch = new BranchModel() { Name = "source" };
        vm.TargetBranch = new BranchModel() { Name = "target" };
        vm.PRTitle = title;

        await vm.CreatePullRequest.ExecuteAsync();
        var unused = ms.Received().CreatePullRequest(repository, vm.PRTitle, String.Empty, vm.SourceBranch, vm.TargetBranch);
    }

}

Fix code warning in test

Fix code warning in test


// ==========================================================================
//  SingleUrlsMiddleware.cs
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex Group
//  All rights reserved.
// ==========================================================================

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Squidex.Pipeline
{
    public sealed class SingleUrlsMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger<SingleUrlsMiddleware> logger;

        public SingleUrlsMiddleware(RequestDelegate next, ILoggerFactory factory)
        {
            this.next = next;

            logger = factory.CreateLogger<SingleUrlsMiddleware>();
        }

        public async Task Invoke(HttpContext context)
        {
            var currentUrl = string.Concat(context.Request.Scheme, "://", context.Request.Host, context.Request.Path);

            var hostName = context.Request.Host.ToString().ToLowerInvariant();
            if (hostName.StartsWith("www"))
            {
                hostName = hostName.Substring(3);
            }

            var requestPath = context.Request.Path.ToString();

            if (!requestPath.EndsWith("/") &&
                !requestPath.Contains("."))
            {
                requestPath = requestPath + "/";
            }

            var newUrl = string.Concat("https://", hostName, requestPath);

            if (!string.Equals(newUrl, currentUrl, StringComparison.OrdinalIgnoreCase))
            {
                logger.LogError("Invalid url: {0} instead {1}", currentUrl, newUrl);

                context.Response.Redirect(newUrl, true);
            }
            else
            {
                await next(context);
            }
        }
    }
}

// ==========================================================================
//  SingleUrlsMiddleware.cs
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex Group
//  All rights reserved.
// ==========================================================================

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Squidex.Pipeline
{
    public sealed class SingleUrlsMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger<SingleUrlsMiddleware> logger;

        public SingleUrlsMiddleware(RequestDelegate next, ILoggerFactory factory)
        {
            this.next = next;

            logger = factory.CreateLogger<SingleUrlsMiddleware>();
        }

        public async Task Invoke(HttpContext context)
        {
            var currentUrl = string.Concat(context.Request.Scheme, "://", context.Request.Host, context.Request.Path);

            var hostName = context.Request.Host.ToString().ToLowerInvariant();
            if (hostName.StartsWith("www"))
            {
                hostName = hostName.Substring(3);
            }

            var requestPath = context.Request.Path.ToString();

            if (!requestPath.EndsWith("/") &&
                !requestPath.Contains("."))
            {
                requestPath = requestPath + "/";
            }

            var newUrl = string.Concat("https://", hostName, requestPath);

            if (!string.Equals(newUrl, currentUrl, StringComparison.OrdinalIgnoreCase))
            {
                logger.LogError("Invalid url: {0} instead {1}", currentUrl, newUrl);

                context.Response.Redirect(newUrl + context.Request.QueryString, true);
            }
            else
            {
                await next(context);
            }
        }
    }
}

Fix the query string stuff

Fix the query string stuff


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

namespace SceneJect.Common
{
	public abstract class DepedencyInjectionFactoryService
	{
		/// <summary>
		/// Service for resolving dependencies.
		/// </summary>
		protected IResolver resolverService { get; }

		/// <summary>
		/// Strategy for injection.
		/// </summary>
		protected IInjectionStrategy injectionStrategy { get; }

		public DepedencyInjectionFactoryService(IResolver resolver, IInjectionStrategy injectionStrat)
		{
			if (resolver == null)
				throw new ArgumentNullException(nameof(resolver), $"Provided {nameof(IResolver)} service provided is null.");

			if (injectionStrategy == null)
				throw new ArgumentNullException(nameof(injectionStrategy), $"Provided {nameof(IInjectionStrategy)} service provided is null.");

			injectionStrategy = injectionStrat;
			resolverService = resolver;
		}
	}
}

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

namespace SceneJect.Common
{
	public abstract class DepedencyInjectionFactoryService
	{
		/// <summary>
		/// Service for resolving dependencies.
		/// </summary>
		protected IResolver resolverService { get; }

		/// <summary>
		/// Strategy for injection.
		/// </summary>
		protected IInjectionStrategy injectionStrategy { get; }

		public DepedencyInjectionFactoryService(IResolver resolver, IInjectionStrategy injectionStrat)
		{
			if (resolver == null)
				throw new ArgumentNullException(nameof(resolver), $"Provided {nameof(IResolver)} service provided is null.");

			if (injectionStrat == null)
				throw new ArgumentNullException(nameof(injectionStrat), $"Provided {nameof(IInjectionStrategy)} service provided is null.");

			injectionStrategy = injectionStrat;
			resolverService = resolver;
		}
	}
}

Fix Fault; Incorrect check in ctor

Fix Fault; Incorrect check in ctor

GameObjectFactory checked prop instead of param in ctor.


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

using System.Runtime.CompilerServices;
using ObjCRuntime;

// We publish our internal attributes to other sub-projects of the framework.
// Note, that we omit visual tests as they are meant to test the framework
// behavior "in the wild".

[assembly: InternalsVisibleTo("osu.Framework.Tests")]
[assembly: InternalsVisibleTo("osu.Framework.Tests.Dynamic")]

[assembly: LinkWith("libavcodec.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libavdevice.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libavfilter.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libavformat.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libavutil.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libbass.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libbass_fx.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libswresample.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libswscale.a", SmartLink = false, ForceLoad = true)]

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

using System.Runtime.CompilerServices;
using ObjCRuntime;

// We publish our internal attributes to other sub-projects of the framework.
// Note, that we omit visual tests as they are meant to test the framework
// behavior "in the wild".

[assembly: InternalsVisibleTo("osu.Framework.Tests")]
[assembly: InternalsVisibleTo("osu.Framework.Tests.Dynamic")]

[assembly: LinkWith("libavcodec.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libavdevice.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libavfilter.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libavformat.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libavutil.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libbass.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libbass_fx.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libbassmix.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libswresample.a", SmartLink = false, ForceLoad = true)]
[assembly: LinkWith("libswscale.a", SmartLink = false, ForceLoad = true)]

Include BASSmix native library in linker


using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace WootzJs.Mvc
{
    public class ControllerActionInvoker : IActionInvoker
    {
        public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action)
        {
            var parameters = action.GetParameters();
            var args = new object[parameters.Length];
            var lastParameter = parameters.LastOrDefault();

            // If async
            if (lastParameter != null && lastParameter.ParameterType == typeof(Action<ActionResult>))
            {
                return (Task<ActionResult>)action.Invoke(context.Controller, args);
            }
            // If synchronous
            else
            {
                var actionResult = (ActionResult)action.Invoke(context.Controller, args);
                return Task.FromResult(actionResult);
            }
        }
    }
}

using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace WootzJs.Mvc
{
    public class ControllerActionInvoker : IActionInvoker
    {
        public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action)
        {
            var parameters = action.GetParameters();
            var args = new object[parameters.Length];

            // If async
            if (action.ReturnType == typeof(Task<ActionResult>))
            {
                return (Task<ActionResult>)action.Invoke(context.Controller, args);
            }
            // If synchronous
            else
            {
                var actionResult = (ActionResult)action.Invoke(context.Controller, args);
                return Task.FromResult(actionResult);
            }
        }
    }
}

Fix logic to use the new task based async pattern


using FluentScheduler;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using System;

namespace BatteryCommander.Web.Jobs
{
    internal static class JobHandler
    {
        public static void WithScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            var logger = loggerFactory.CreateLogger(typeof(JobHandler));

            JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name);

            JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration);

            JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name);

            JobManager.UseUtcTime();

            JobManager.JobFactory = new JobFactory(app.ApplicationServices);

            var registry = new Registry();

            registry.Schedule<SqliteBackupJob>().ToRunNow().AndEvery(1).Days().At(hours: 12, minutes: 0);

            JobManager.Initialize(registry);
        }

        private class JobFactory : IJobFactory
        {
            private readonly IServiceProvider serviceProvider;

            public JobFactory(IServiceProvider serviceProvider)
            {
                this.serviceProvider = serviceProvider;
            }

            public IJob GetJobInstance<T>() where T : IJob
            {
                return serviceProvider.GetService(typeof(T)) as IJob;
            }
        }
    }
}

using FluentScheduler;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using System;

namespace BatteryCommander.Web.Jobs
{
    internal static class JobHandler
    {
        public static void WithScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            var logger = loggerFactory.CreateLogger(typeof(JobHandler));

            JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name);

            JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration);

            JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name);

            JobManager.UseUtcTime();

            JobManager.JobFactory = new JobFactory(app.ApplicationServices);

            var registry = new Registry();

            registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().At(hours: 12, minutes: 0);

            JobManager.Initialize(registry);
        }

        private class JobFactory : IJobFactory
        {
            private readonly IServiceProvider serviceProvider;

            public JobFactory(IServiceProvider serviceProvider)
            {
                this.serviceProvider = serviceProvider;
            }

            public IJob GetJobInstance<T>() where T : IJob
            {
                return serviceProvider.GetService(typeof(T)) as IJob;
            }
        }
    }
}

Fix registration to send nightly

Fix registration to send nightly


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

namespace Apache.Ignite.Core.Tests.TestDll
{
    using System.Linq;

    /// <summary>
    /// Extension methods for tests.
    /// </summary>
    public static class TestExtensions
    {
        /// <summary>
        /// Reverses the string.
        /// </summary>
        public static string ReverseString(this string str)
        {
            return new string(str.Reverse().ToArray());
        }
    }
}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

namespace Apache.Ignite.Core.Tests.TestDll
{
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;

    /// <summary>
    /// Extension methods for tests.
    /// </summary>
    [ExcludeFromCodeCoverage]
    public static class TestExtensions
    {
        /// <summary>
        /// Reverses the string.
        /// </summary>
        public static string ReverseString(this string str)
        {
            return new string(str.Reverse().ToArray());
        }
    }
}

.NET: Fix code coverage - exclude remote-only class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Core.CrossDomainImagesWeb
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            Uri redirectUrl;
            switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
            {
                case RedirectionStatus.Ok:
                    return;
                case RedirectionStatus.ShouldRedirect:
                    Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
                    break;
                case RedirectionStatus.CanNotRedirect:
                    Response.Write("An error occurred while processing your request.");
                    Response.End();
                    break;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
                using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
                {
                    //set access token in hidden field for client calls
                    hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb;

                    //set images
                    Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png";
                    Services.ImgService svc = new Services.ImgService();
                    Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Core.CrossDomainImagesWeb
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            Uri redirectUrl;
            switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
            {
                case RedirectionStatus.Ok:
                    return;
                case RedirectionStatus.ShouldRedirect:
                    Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
                    break;
                case RedirectionStatus.CanNotRedirect:
                    Response.Write("An error occurred while processing your request.");
                    Response.End();
                    break;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
            using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
            {
                //set access token in hidden field for client calls
                hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb;

                //set images
                Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png";
                Services.ImgService svc = new Services.ImgService();
                Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png");
            }
        }
    }
}

Revert "added try catch, test commit"

Revert "added try catch, test commit"

This reverts commit f19532d23cb74beb6bba8128bb7d9d544972c761.


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

using System;
using System.Threading;

namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
    public class Dialog_OutOfProc : OutOfProcComponent
    {
        public Dialog_OutOfProc(VisualStudioInstance visualStudioInstance)
            : base(visualStudioInstance)
        {
        }

        public void VerifyOpen(string dialogName)
        {
            // FindDialog will wait until the dialog is open, so the return value is unused.
            DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: true, CancellationToken.None);

            // Wait for application idle to ensure the dialog is fully initialized
            VisualStudioInstance.WaitForApplicationIdle(CancellationToken.None);
        }

        public void VerifyClosed(string dialogName)
        {
            // FindDialog will wait until the dialog is closed, so the return value is unused.
            DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: false, CancellationToken.None);
        }

        public void Click(string dialogName, string buttonName)
            => DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), dialogName, buttonName);

        private IntPtr GetMainWindowHWnd()
            => VisualStudioInstance.Shell.GetHWnd();
    }
}

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

using System;
using System.Threading;

namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
    public class Dialog_OutOfProc : OutOfProcComponent
    {
        public Dialog_OutOfProc(VisualStudioInstance visualStudioInstance)
            : base(visualStudioInstance)
        {
        }

        public void VerifyOpen(string dialogName)
        {
            using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout);

            // FindDialog will wait until the dialog is open, so the return value is unused.
            DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: true, cancellationTokenSource.Token);

            // Wait for application idle to ensure the dialog is fully initialized
            VisualStudioInstance.WaitForApplicationIdle(cancellationTokenSource.Token);
        }

        public void VerifyClosed(string dialogName)
        {
            using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout);

            // FindDialog will wait until the dialog is closed, so the return value is unused.
            DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: false, cancellationTokenSource.Token);
        }

        public void Click(string dialogName, string buttonName)
            => DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), dialogName, buttonName);

        private IntPtr GetMainWindowHWnd()
            => VisualStudioInstance.Shell.GetHWnd();
    }
}

Apply hang mitigating timeout in VerifyOpen and VerifyClosed


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

using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.Rooms;
using osuTK;

namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match.Playlist
{
    /// <summary>
    /// A historically-ordered list of <see cref="DrawableRoomPlaylistItem"/>s.
    /// </summary>
    public class MultiplayerHistoryList : DrawableRoomPlaylist
    {
        public MultiplayerHistoryList()
            : base(false, false, true)
        {
        }

        protected override FillFlowContainer<RearrangeableListItem<PlaylistItem>> CreateListFillFlowContainer() => new HistoryFillFlowContainer
        {
            Spacing = new Vector2(0, 2)
        };

        private class HistoryFillFlowContainer : FillFlowContainer<RearrangeableListItem<PlaylistItem>>
        {
            public override IEnumerable<Drawable> FlowingChildren => base.FlowingChildren.Reverse();
        }
    }
}

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

using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.Rooms;
using osuTK;

namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match.Playlist
{
    /// <summary>
    /// A historically-ordered list of <see cref="DrawableRoomPlaylistItem"/>s.
    /// </summary>
    public class MultiplayerHistoryList : DrawableRoomPlaylist
    {
        public MultiplayerHistoryList()
            : base(false, false, true)
        {
        }

        protected override FillFlowContainer<RearrangeableListItem<PlaylistItem>> CreateListFillFlowContainer() => new HistoryFillFlowContainer
        {
            Spacing = new Vector2(0, 2)
        };

        private class HistoryFillFlowContainer : FillFlowContainer<RearrangeableListItem<PlaylistItem>>
        {
            public override IEnumerable<Drawable> FlowingChildren => base.FlowingChildren.OfType<RearrangeableListItem<PlaylistItem>>().OrderByDescending(item => item.Model.GameplayOrder);
        }
    }
}

Update history list to also sort by gameplay order


using System;
using System.Data;
using NHibernate.Engine;

namespace NHibernate.Impl
{
	/// <summary>
	/// Summary description for BatchingBatcher.
	/// </summary>
	internal class BatchingBatcher : BatcherImpl
	{
		private int batchSize;
		private int[] expectedRowCounts;

		/// <summary>
		///
		/// </summary>
		/// <param name="session"></param>
		public BatchingBatcher( ISessionImplementor session ) : base( session )
		{
			expectedRowCounts = new int[ Factory.BatchSize ];
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="expectedRowCount"></param>
		public override void AddToBatch( int expectedRowCount )
		{
			throw new NotImplementedException( "Batching not implemented yet" );

			/*
			log.Info( "Adding to batch" );
			IDbCommand batchUpdate = CurrentStatment;
			*/
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="ps"></param>
		protected override void DoExecuteBatch( IDbCommand ps )
		{
			throw new NotImplementedException( "Batching not implemented yet" );
		}
	}
}

using System;
using System.Data;
using NHibernate.Engine;

namespace NHibernate.Impl
{
	/// <summary>
	/// Summary description for BatchingBatcher.
	/// </summary>
	internal class BatchingBatcher : BatcherImpl
	{
		//private int batchSize;
		private int[] expectedRowCounts;

		/// <summary>
		///
		/// </summary>
		/// <param name="session"></param>
		public BatchingBatcher( ISessionImplementor session ) : base( session )
		{
			expectedRowCounts = new int[ Factory.BatchSize ];
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="expectedRowCount"></param>
		public override void AddToBatch( int expectedRowCount )
		{
			throw new NotImplementedException( "Batching not implemented yet" );

			/*
			log.Info( "Adding to batch" );
			IDbCommand batchUpdate = CurrentStatment;
			*/
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="ps"></param>
		protected override void DoExecuteBatch( IDbCommand ps )
		{
			throw new NotImplementedException( "Batching not implemented yet" );
		}
	}
}

Comment out batchSize for now as not used

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@1312


using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using MvcSample.Web.Models;

namespace MvcSample.Web.RandomNameSpace
{
    public class Home2Controller
    {
        private User _user = new User() { Name = "User Name", Address = "Home Address" };

        [Activate]
        public HttpResponse Response
        {
            get; set;
        }

        public ActionContext ActionContext { get; set; }

        public string Index()
        {
            return "Hello World: my namespace is " + this.GetType().Namespace;
        }

        public ActionResult Something()
        {
            return new ContentResult
            {
                Content = "Hello World From Content"
            };
        }

        public ActionResult Hello()
        {
            return new ContentResult
            {
                Content = "Hello World",
            };
        }

        public void Raw()
        {
            Response.WriteAsync("Hello World raw");
        }

        public ActionResult UserJson()
        {
            var jsonResult = new JsonResult(_user);

            return jsonResult;
        }

        public User User()
        {
            return _user;
        }
    }
}

using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using MvcSample.Web.Models;

namespace MvcSample.Web.RandomNameSpace
{
    public class Home2Controller
    {
        private User _user = new User() { Name = "User Name", Address = "Home Address" };

        [Activate]
        public HttpResponse Response
        {
            get; set;
        }

        public ActionContext ActionContext { get; set; }

        public string Index()
        {
            return "Hello World: my namespace is " + this.GetType().Namespace;
        }

        public ActionResult Something()
        {
            return new ContentResult
            {
                Content = "Hello World From Content"
            };
        }

        public ActionResult Hello()
        {
            return new ContentResult
            {
                Content = "Hello World",
            };
        }

        public async Task Raw()
        {
            await Response.WriteAsync("Hello World raw");
        }

        public ActionResult UserJson()
        {
            var jsonResult = new JsonResult(_user);

            return jsonResult;
        }

        public User User()
        {
            return _user;
        }
    }
}

Fix the sample to await when writing directly to the output stream in a controller.


using System;
using System.Linq;
using Nest;
using Tests.Framework.ManagedElasticsearch.Nodes;
using Tests.Framework.ManagedElasticsearch.Plugins;

namespace Tests.Framework.ManagedElasticsearch.Tasks.ValidationTasks
{
	public class ValidatePluginsTask : NodeValidationTaskBase
	{
		public override void Validate(IElasticClient client, NodeConfiguration configuration)
		{
			var v = configuration.ElasticsearchVersion;

			var requiredMonikers = ElasticsearchPluginCollection.Supported
				.Where(plugin => plugin.IsValid(v) && configuration.RequiredPlugins.Contains(plugin.Plugin))
				.Select(plugin => plugin.Moniker)
				.ToList();

			if (!requiredMonikers.Any()) return;
			var checkPlugins = client.CatPlugins();

			if (!checkPlugins.IsValid)
				throw new Exception($"Failed to check plugins: {checkPlugins.DebugInformation}.");

			var missingPlugins = requiredMonikers
				.Except((checkPlugins.Records ?? Enumerable.Empty<CatPluginsRecord>()).Select(r => r.Component))
				.ToList();
			if (!missingPlugins.Any()) return;

			var pluginsString = string.Join(", ", missingPlugins);
			throw new Exception($"Already running elasticsearch missed the following plugin(s): {pluginsString}.");
		}
	}
}

using System;
using System.Linq;
using Nest;
using Tests.Document.Multiple.UpdateByQuery;
using Tests.Framework.ManagedElasticsearch.Nodes;
using Tests.Framework.ManagedElasticsearch.Plugins;

namespace Tests.Framework.ManagedElasticsearch.Tasks.ValidationTasks
{
	public class ValidatePluginsTask : NodeValidationTaskBase
	{
		public override void Validate(IElasticClient client, NodeConfiguration configuration)
		{
			var v = configuration.ElasticsearchVersion;

			var requiredMonikers = ElasticsearchPluginCollection.Supported
				.Where(plugin => plugin.IsValid(v) && configuration.RequiredPlugins.Contains(plugin.Plugin))
				.Select(plugin => plugin.Moniker)
				.ToList();

			if (!requiredMonikers.Any()) return;

			// 6.2.4 splits out X-Pack into separate plugin names
			if (requiredMonikers.Contains(ElasticsearchPlugin.XPack.Moniker()) && TestClient.VersionUnderTestSatisfiedBy(">=6.2.4"))
			{
				requiredMonikers.Remove(ElasticsearchPlugin.XPack.Moniker());
				requiredMonikers.Add(ElasticsearchPlugin.XPack.Moniker() + "-core");
			}

			var checkPlugins = client.CatPlugins();

			if (!checkPlugins.IsValid)
				throw new Exception($"Failed to check plugins: {checkPlugins.DebugInformation}.");

			var missingPlugins = requiredMonikers
				.Except((checkPlugins.Records ?? Enumerable.Empty<CatPluginsRecord>()).Select(r => r.Component))
				.ToList();
			if (!missingPlugins.Any()) return;

			var pluginsString = string.Join(", ", missingPlugins);
			throw new Exception($"Already running elasticsearch missed the following plugin(s): {pluginsString}.");
		}
	}
}

Validate existence of x-pack-core for 6.2.4+

This commit asserts that for integration tests running against 6.2.4+, plugin validation
checks for x-pack-core as opposed to x-pack; x-pack plugin was split out into separate
plugin names


using System.Reflection;
using P2E.Interfaces.DataObjects;

namespace P2E.DataObjects
{
    public class ApplicationInformation : IApplicationInformation
    {
        public string Name { get; }
        public string Version { get; }

        public ApplicationInformation()
        {
            Name = Assembly.GetEntryAssembly().GetName().Name;
            Version = Assembly.GetEntryAssembly().GetName().Version.ToString();
        }
    }
}

using System.Reflection;
using P2E.Interfaces.DataObjects;

namespace P2E.DataObjects
{
    public class ApplicationInformation : IApplicationInformation
    {
        public string Name => Assembly.GetEntryAssembly().GetName().Name;
        public string Version => Assembly.GetEntryAssembly().GetName().Version.ToString();
    }
}

Rewrite with expression bodies properties syntax.


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

namespace BitDiffer.Common.Misc
{
	public class Constants
	{
		public const string ProductName = "BitDiffer";
		public const string ProductSubTitle = "Assembly Comparison Tool";
        public const string HelpUrl = "https://github.com/grennis/bitdiffer/wiki";
		public const string ExtractionDomainPrefix = "Temp App Domain";
		public const string ComparisonEmailSubject = "BitDiffer Assembly Comparison Report";
	}
}

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

namespace BitDiffer.Common.Misc
{
	public class Constants
	{
		public const string ProductName = "BitDiffer";
		public const string ProductSubTitle = "Assembly Comparison Tool";
        	public const string HelpUrl = "https://github.com/bitdiffer/bitdiffer/wiki";
		public const string ExtractionDomainPrefix = "Temp App Domain";
		public const string ComparisonEmailSubject = "BitDiffer Assembly Comparison Report";
	}
}

Use correct URL for help

Use correct URL for help

Clicking on Help in the menu currently opens an old URL which displays the message "This repository has been deleted".


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SurveyMonkeyApi")]
[assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SurveyMonkeyApi")]
[assembly: AssemblyCopyright("Copyright © Ben Emmett")]
[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("da9e0373-83cd-4deb-87a5-62b313be61ec")]

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

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SurveyMonkeyApi")]
[assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SurveyMonkeyApi")]
[assembly: AssemblyCopyright("Copyright © Ben Emmett")]
[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("da9e0373-83cd-4deb-87a5-62b313be61ec")]

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

Bump assembly info for 1.3.0 release

Bump assembly info for 1.3.0 release


using ZobShop.Data.Contracts;
using ZobShop.Factories;
using ZobShop.Models;
using ZobShop.Services.Contracts;

namespace ZobShop.Services
{
    public class ProductRatingService : IProductRatingService
    {
        private readonly IRepository<User> userRepository;
        private readonly IRepository<ProductRating> productRatingRepository;
        private readonly IRepository<Product> productRepository;
        private readonly IUnitOfWork unitOfWork;
        private readonly IProductRatingFactory factory;

        public ProductRatingService(IRepository<User> userRepository,
            IRepository<Product> productRepository,
            IRepository<ProductRating> productRatingRepository,
            IUnitOfWork unitOfWork,
            IProductRatingFactory factory)
        {
            this.userRepository = userRepository;
            this.productRepository = productRepository;
            this.productRatingRepository = productRatingRepository;
            this.unitOfWork = unitOfWork;
            this.factory = factory;
        }

        public ProductRating CreateProductRating(int rating, string content, int productId, string userId)
        {
            var product = this.productRepository.GetById(productId);
            var user = this.userRepository.GetById(userId);

            var newRating = this.factory.CreateProductRating(rating, content, product, user);
            this.productRatingRepository.Add(newRating);
            this.unitOfWork.Commit();

            return newRating;
        }
    }
}

using System;
using ZobShop.Data.Contracts;
using ZobShop.Factories;
using ZobShop.Models;
using ZobShop.Services.Contracts;

namespace ZobShop.Services
{
    public class ProductRatingService : IProductRatingService
    {
        private readonly IRepository<User> userRepository;
        private readonly IRepository<ProductRating> productRatingRepository;
        private readonly IRepository<Product> productRepository;
        private readonly IUnitOfWork unitOfWork;
        private readonly IProductRatingFactory factory;

        public ProductRatingService(IRepository<User> userRepository,
            IRepository<Product> productRepository,
            IRepository<ProductRating> productRatingRepository,
            IUnitOfWork unitOfWork,
            IProductRatingFactory factory)
        {
            if (userRepository == null)
            {
                throw new ArgumentNullException("user repository cannot be null");
            }

            if (productRepository == null)
            {
                throw new ArgumentNullException("product repository cannot be null");
            }

            if (productRatingRepository == null)
            {
                throw new ArgumentNullException("product rating repository cannot be null");
            }

            if (unitOfWork == null)
            {
                throw new ArgumentNullException("unit of work repository cannot be null");
            }

            if (factory == null)
            {
                throw new ArgumentNullException("factory repository cannot be null");
            }

            this.userRepository = userRepository;
            this.productRepository = productRepository;
            this.productRatingRepository = productRatingRepository;
            this.unitOfWork = unitOfWork;
            this.factory = factory;
        }

        public ProductRating CreateProductRating(int rating, string content, int productId, string userId)
        {
            var product = this.productRepository.GetById(productId);
            var user = this.userRepository.GetById(userId);

            var newRating = this.factory.CreateProductRating(rating, content, product, user);
            this.productRatingRepository.Add(newRating);
            this.unitOfWork.Commit();

            return newRating;
        }
    }
}

Add checks in product rating service

Add checks in product rating service


using System;
using ValveResourceFormat.Serialization;

namespace GUI.Types.ParticleRenderer
{
    public interface INumberProvider
    {
        double NextNumber();
    }

    public class LiteralNumberProvider : INumberProvider
    {
        private readonly double value;

        public LiteralNumberProvider(double value)
        {
            this.value = value;
        }

        public double NextNumber() => value;
    }

    public static class INumberProviderExtensions
    {
        public static INumberProvider GetNumberProvider(this IKeyValueCollection keyValues, string propertyName)
        {
            var property = keyValues.GetProperty<object>(propertyName);

            if (property is IKeyValueCollection numberProviderParameters)
            {
                var type = numberProviderParameters.GetProperty<string>("m_nType");
                switch (type)
                {
                    case "PF_TYPE_LITERAL":
                        return new LiteralNumberProvider(numberProviderParameters.GetDoubleProperty("m_flLiteralValue"));
                    default:
                        throw new InvalidCastException($"Could not create number provider of type {type}.");
                }
            }
            else
            {
                return new LiteralNumberProvider(Convert.ToDouble(property));
            }
        }

        public static int NextInt(this INumberProvider numberProvider)
        {
            return (int)numberProvider.NextNumber();
        }
    }
}

using System;
using ValveResourceFormat.Serialization;

namespace GUI.Types.ParticleRenderer
{
    public interface INumberProvider
    {
        double NextNumber();
    }

    public class LiteralNumberProvider : INumberProvider
    {
        private readonly double value;

        public LiteralNumberProvider(double value)
        {
            this.value = value;
        }

        public double NextNumber() => value;
    }

    public static class INumberProviderExtensions
    {
        public static INumberProvider GetNumberProvider(this IKeyValueCollection keyValues, string propertyName)
        {
            var property = keyValues.GetProperty<object>(propertyName);

            if (property is IKeyValueCollection numberProviderParameters)
            {
                var type = numberProviderParameters.GetProperty<string>("m_nType");
                switch (type)
                {
                    case "PF_TYPE_LITERAL":
                        return new LiteralNumberProvider(numberProviderParameters.GetDoubleProperty("m_flLiteralValue"));
                    default:
                        if (numberProviderParameters.ContainsKey("m_flLiteralValue"))
                        {
                            Console.Error.WriteLine($"Number provider of type {type} is not directly supported, but it has m_flLiteralValue.");
                            return new LiteralNumberProvider(numberProviderParameters.GetDoubleProperty("m_flLiteralValue"));
                        }

                        throw new InvalidCastException($"Could not create number provider of type {type}.");
                }
            }
            else
            {
                return new LiteralNumberProvider(Convert.ToDouble(property));
            }
        }

        public static int NextInt(this INumberProvider numberProvider)
        {
            return (int)numberProvider.NextNumber();
        }
    }
}

Support all particle num providers with m_flLiteralValue


namespace LINQToTreeHelpers
{
    public static class Utils
    {
        /// <summary>
        /// Write out an object. Eventually, with ROOTNET improvements this will work better and perahps
        /// won't be needed!
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="dir"></param>
        internal static void InternalWriteObject(this ROOTNET.Interface.NTObject obj, ROOTNET.Interface.NTDirectory dir)
        {
            var h = obj as ROOTNET.Interface.NTH1;
            if (h != null)
            {
                var copy = h.Clone();
                dir.WriteTObject(copy); // Ugly from a memory pov, but...
                copy.SetNull();
            }
            else
            {
                dir.WriteTObject(obj);
                obj.SetNull();
            }
        }

        /// <summary>
        /// Take a string and "sanatize" it for a root name.
        /// </summary>
        /// <param name="name">Text name to be used as a ROOT name</param>
        /// <returns>argument name with spaces removes, as well as other characters</returns>
        public static string FixupForROOTName(this string name)
        {
            var result = name.Replace(" ", "");
            result = result.Replace("_{", "");
            result = result.Replace("{", "");
            result = result.Replace("}", "");
            result = result.Replace("-", "");
            result = result.Replace("\\", "");
            result = result.Replace("%", "");
            result = result.Replace("<", "");
            result = result.Replace(">", "");
            return result;
        }
    }
}

namespace LINQToTreeHelpers
{
    public static class Utils
    {
        /// <summary>
        /// Write out an object. Eventually, with ROOTNET improvements this will work better and perahps
        /// won't be needed!
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="dir"></param>
        internal static void InternalWriteObject(this ROOTNET.Interface.NTObject obj, ROOTNET.Interface.NTDirectory dir)
        {
            var h = obj as ROOTNET.Interface.NTH1;
            if (h != null)
            {
                var copy = h.Clone();
                dir.WriteTObject(copy); // Ugly from a memory pov, but...
                copy.SetNull();
            }
            else
            {
                dir.WriteTObject(obj);
                obj.SetNull();
            }
        }

        /// <summary>
        /// Take a string and "sanatize" it for a root name.
        /// </summary>
        /// <param name="name">Text name to be used as a ROOT name</param>
        /// <returns>argument name with spaces removes, as well as other characters</returns>
        public static string FixupForROOTName(this string name)
        {
            var result = name.Replace(" ", "");
            result = result.Replace("_{", "");
            result = result.Replace("{", "");
            result = result.Replace("}", "");
            result = result.Replace("-", "");
            result = result.Replace("\\", "");
            result = result.Replace("%", "");
            result = result.Replace("<", "lt");
            result = result.Replace(">", "gt");
            return result;
        }
    }
}

Improve translation when removing strings from names!


using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;

namespace DesktopWidgets.Widgets.Search
{
    public class ViewModel : WidgetViewModelBase
    {
        private string _searchText;

        public ViewModel(WidgetId id) : base(id)
        {
            Settings = id.GetSettings() as Settings;
            if (Settings == null)
                return;
            Go = new RelayCommand(GoExecute);
            OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
        }

        public Settings Settings { get; }

        public ICommand Go { get; set; }
        public ICommand OnKeyUp { get; set; }

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (_searchText != value)
                {
                    _searchText = value;
                    RaisePropertyChanged(nameof(SearchText));
                }
            }
        }

        private void GoExecute()
        {
            if (string.IsNullOrWhiteSpace(Settings.BaseUrl))
            {
                Popup.Show("You must set up a base URL first.", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }
            var searchText = SearchText;
            SearchText = string.Empty;
            Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}");
        }

        private void OnKeyUpExecute(KeyEventArgs args)
        {
            if (args.Key == Key.Enter)
                GoExecute();
        }
    }
}

using System.Diagnostics;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;

namespace DesktopWidgets.Widgets.Search
{
    public class ViewModel : WidgetViewModelBase
    {
        private string _searchText;

        public ViewModel(WidgetId id) : base(id)
        {
            Settings = id.GetSettings() as Settings;
            if (Settings == null)
                return;
            Go = new RelayCommand(GoExecute);
            OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
        }

        public Settings Settings { get; }

        public ICommand Go { get; set; }
        public ICommand OnKeyUp { get; set; }

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (_searchText != value)
                {
                    _searchText = value;
                    RaisePropertyChanged(nameof(SearchText));
                }
            }
        }

        private void GoExecute()
        {
            var searchText = SearchText;
            SearchText = string.Empty;
            Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}");
        }

        private void OnKeyUpExecute(KeyEventArgs args)
        {
            if (args.Key == Key.Enter)
                GoExecute();
        }
    }
}

Remove "Search" widget base URL warning

Remove "Search" widget base URL warning


//    #[license]
//    SmartsheetClient SDK for C#
//    %%
//    Copyright (C) 2014 SmartsheetClient
//    %%
//    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.
//    %[license]

using System.Runtime.Serialization;

namespace Smartsheet.Api.Models
{

	/// <summary>
	/// Represents specific objects that can be excluded in some responses.
	/// </summary>
	public enum ObjectExclusion
	{
		/// <summary>
		/// The discussions
		/// </summary>
		[EnumMember(Value = "nonexistentCells")]
		NONEXISTENT_CELLS
	}
}

//    #[license]
//    SmartsheetClient SDK for C#
//    %%
//    Copyright (C) 2014 SmartsheetClient
//    %%
//    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.
//    %[license]

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;

namespace Smartsheet.Api.Models
{

	/// <summary>
	/// Represents specific objects that can be excluded in some responses.
	/// </summary>
	[JsonConverter(typeof(StringEnumConverter))]
	public enum ObjectExclusion
	{
		/// <summary>
		/// The discussions
		/// </summary>
		[EnumMember(Value = "nonexistentCells")]
		NONEXISTENT_CELLS
	}
}

Make sure NONEXISTENT_CELLS is serialized into nonexistentCells


using System;

namespace FilterLists.Agent.Entities
{
    public class ListInfo
    {
        public int Id { get; }
        public Uri ViewUrl { get; }
    }
}

using System;

namespace FilterLists.Agent.Entities
{
    public class ListInfo
    {
        public int Id { get; private set; }
        public Uri ViewUrl { get; private set; }
    }
}

Revert "remove unused private setters"

Revert "remove unused private setters"

This reverts commit 0f6940904667a1a24c9605fe7a827d67a0d79905.


using UnityEngine;
using System.Collections;

public class Bullet : MonoBehaviour {
  public int bulletSpeed = 715;

	void Start () {
    GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * bulletSpeed);
	}
}

using UnityEngine;
using System.Collections;

public class Bullet : MonoBehaviour {
  public int bulletSpeed = 715;

	void Start() {
    GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * bulletSpeed);
	}

  void OnTriggerEnter(Collider other) {
    Destroy(gameObject);
  }
}

Destroy bullets on trigger event

Destroy bullets on trigger event


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

public class DropdownLanguageFontUpdater : MonoBehaviour
{
    [SerializeField]
    private Text textComponent;

	void Start ()
    {
        Font overrideFont = LocalizationManager.instance.getAllLanguages()[transform.GetSiblingIndex() - 1].overrideFont;
        if (overrideFont != null)
            textComponent.font = overrideFont;
	}

	void Update ()
    {

	}
}

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

public class DropdownLanguageFontUpdater : MonoBehaviour
{
    [SerializeField]
    private Text textComponent;

	void Start ()
    {
        var language = LocalizationManager.instance.getAllLanguages()[transform.GetSiblingIndex() - 1];
        if (language.overrideFont != null)
        {
            textComponent.font = language.overrideFont;
            if (language.forceUnbold)
                textComponent.fontStyle = FontStyle.Normal;
        }
	}

	void Update ()
    {

	}
}

Apply force unbold to dropdown options

Apply force unbold to dropdown options


// 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;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using Microsoft.AspNetCore.Mvc.ApplicationParts;

namespace Microsoft.AspNetCore.Mvc.Razor.Compilation
{
    public static class CompiledViewManfiest
    {
        public static readonly string PrecompiledViewsAssemblySuffix = ".PrecompiledViews";

        public static Type GetManifestType(AssemblyPart assemblyPart, string typeName)
        {
            EnsureFeatureAssembly(assemblyPart);

            var precompiledAssemblyName = new AssemblyName(assemblyPart.Assembly.FullName);
            precompiledAssemblyName.Name = precompiledAssemblyName.Name + PrecompiledViewsAssemblySuffix;

            return Type.GetType($"{typeName},{precompiledAssemblyName}");
        }

        private static void EnsureFeatureAssembly(AssemblyPart assemblyPart)
        {
            if (assemblyPart.Assembly.IsDynamic || string.IsNullOrEmpty(assemblyPart.Assembly.Location))
            {
                return;
            }

            var precompiledAssemblyFileName = assemblyPart.Assembly.GetName().Name
                + PrecompiledViewsAssemblySuffix
                + ".dll";
            var precompiledAssemblyFilePath = Path.Combine(
                Path.GetDirectoryName(assemblyPart.Assembly.Location),
                precompiledAssemblyFileName);

            if (File.Exists(precompiledAssemblyFilePath))
            {
                try
                {
                    Assembly.LoadFile(precompiledAssemblyFilePath);
                }
                catch (FileLoadException)
                {
                    // Don't throw if assembly cannot be loaded. This can happen if the file is not a managed assembly.
                }
            }
        }
    }
}

// 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;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using Microsoft.AspNetCore.Mvc.ApplicationParts;

namespace Microsoft.AspNetCore.Mvc.Razor.Compilation
{
    public static class CompiledViewManfiest
    {
        public static readonly string PrecompiledViewsAssemblySuffix = ".PrecompiledViews";

        public static Type GetManifestType(AssemblyPart assemblyPart, string typeName)
        {
            var assembly = GetFeatureAssembly(assemblyPart);
            return assembly?.GetType(typeName);
        }

        private static Assembly GetFeatureAssembly(AssemblyPart assemblyPart)
        {
            if (assemblyPart.Assembly.IsDynamic || string.IsNullOrEmpty(assemblyPart.Assembly.Location))
            {
                return null;
            }

            var precompiledAssemblyFileName = assemblyPart.Assembly.GetName().Name
                + PrecompiledViewsAssemblySuffix
                + ".dll";
            var precompiledAssemblyFilePath = Path.Combine(
                Path.GetDirectoryName(assemblyPart.Assembly.Location),
                precompiledAssemblyFileName);

            if (File.Exists(precompiledAssemblyFilePath))
            {
                try
                {
                    return Assembly.LoadFile(precompiledAssemblyFilePath);
                }
                catch (FileLoadException)
                {
                    // Don't throw if assembly cannot be loaded. This can happen if the file is not a managed assembly.
                }
            }

            return null;
        }
    }
}

Load the precompilation type from the loaded assembly


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Nest.Tests.MockData.Domain;
using NUnit.Framework;

namespace Nest.Tests.Unit.ObjectInitializer.Index
{
	[TestFixture]
	public class IndexRequestTests : BaseJsonTests
	{
		private readonly IElasticsearchResponse _status;

		public IndexRequestTests()
		{
			var newProject = new ElasticsearchProject
			{
				Id = 15,
				Name = "Some awesome new elasticsearch project"
			};
			var request = new IndexRequest<ElasticsearchProject>(newProject)
			{
				Replication = Replication.Async
			};
			//TODO Index(request) does not work as expected
			var response = this._client.Index<ElasticsearchProject>(request);
			this._status = response.ConnectionStatus;
		}

		public void SettingsTest()
		{

		}

		[Test]
		public void Url()
		{
			this._status.RequestUrl.Should().EndWith("/nest_test_data/elasticsearchprojects/15?replication=async");
			this._status.RequestMethod.Should().Be("PUT");
		}

		[Test]
		public void IndexBody()
		{
			this.JsonEquals(this._status.Request, MethodBase.GetCurrentMethod());
		}
	}

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Nest.Tests.MockData.Domain;
using NUnit.Framework;

namespace Nest.Tests.Unit.ObjectInitializer.Index
{
	[TestFixture]
	public class IndexRequestTests : BaseJsonTests
	{
		private readonly IElasticsearchResponse _status;

		public IndexRequestTests()
		{
			var newProject = new ElasticsearchProject
			{
				Id = 15,
				Name = "Some awesome new elasticsearch project"
			};
			var request = new IndexRequest<ElasticsearchProject>(newProject)
			{
				Replication = Replication.Async
			};
			//TODO Index(request) does not work as expected
			var response = this._client.Index<ElasticsearchProject>(request);
			this._status = response.ConnectionStatus;
		}

		[Test]
		public void Url()
		{
			this._status.RequestUrl.Should().EndWith("/nest_test_data/elasticsearchprojects/15?replication=async");
			this._status.RequestMethod.Should().Be("PUT");
		}

		[Test]
		public void IndexBody()
		{
			this.JsonEquals(this._status.Request, MethodBase.GetCurrentMethod());
		}
	}

}

Remove empty method checked in by mistake