using System.Collections.Generic;

namespace Kazyx.RemoteApi
{
    /// <summary>
    /// Response of getMethodTypes API.
    /// </summary>
    public class MethodType
    {
        /// <summary>
        /// Name of API
        /// </summary>
        public string Name { set; get; }
        /// <summary>
        /// Request parameter types.
        /// </summary>
        public List<string> ReqTypes { set; get; }
        /// <summary>
        /// Response parameter types.
        /// </summary>
        public List<string> ResTypes { set; get; }
        /// <summary>
        /// Version of API
        /// </summary>
        public string Version { set; get; }
    }

    /// <summary>
    /// Set of current value and its candidates.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Capability<T>
    {
        /// <summary>
        /// Current value of the specified parameter.
        /// </summary>
        public virtual T Current { set; get; }

        /// <summary>
        /// Candidate values of the specified parameter.
        /// </summary>
        public virtual List<T> Candidates { set; get; }

        public override bool Equals(object o)
        {
            var other = o as Capability<T>;
            if (!Current.Equals(other.Current))
            {
                return false;
            }
            if (Candidates?.Count != other.Candidates?.Count)
            {
                return false;
            }

            for (int i = 0; i < Candidates.Count; i++)
            {
                if (!Candidates[i].Equals(other.Candidates[i]))
                {
                    return false;
                }
            }
            return true;
        }
    }
}

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

namespace Kazyx.RemoteApi
{
    /// <summary>
    /// Response of getMethodTypes API.
    /// </summary>
    public class MethodType
    {
        /// <summary>
        /// Name of API
        /// </summary>
        public string Name { set; get; }
        /// <summary>
        /// Request parameter types.
        /// </summary>
        public List<string> ReqTypes { set; get; }
        /// <summary>
        /// Response parameter types.
        /// </summary>
        public List<string> ResTypes { set; get; }
        /// <summary>
        /// Version of API
        /// </summary>
        public string Version { set; get; }
    }

    /// <summary>
    /// Set of current value and its candidates.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Capability<T>
    {
        /// <summary>
        /// Current value of the specified parameter.
        /// </summary>
        public virtual T Current { set; get; }

        /// <summary>
        /// Candidate values of the specified parameter.
        /// </summary>
        public virtual List<T> Candidates { set; get; }

        public override bool Equals(object o)
        {
            var other = o as Capability<T>;
            if (other == null) { return false; }
            if (!Current.Equals(other.Current)) { return false; }
            if (Candidates?.Count != other.Candidates?.Count) { return false; }
            return Candidates.SequenceEqual(other.Candidates);
        }
    }
}

Use SequenceEqual and check null

Use SequenceEqual and check null


// Copyright © 2010-2016 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;
using System.Windows;

namespace CefSharp.Wpf.Example.Handlers
{
    internal class GeolocationHandler : IGeolocationHandler
    {
        bool IGeolocationHandler.OnRequestGeolocationPermission(IWebBrowser browserControl, IBrowser browser, string requestingUrl, int requestId, IGeolocationCallback callback)
        {
            using (callback)
            {
                var result = MessageBox.Show(String.Format("{0} wants to use your computer's location.  Allow?  ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButton.YesNo);

                callback.Continue(result == MessageBoxResult.Yes);

                return result == MessageBoxResult.Yes;
            }
        }

        void IGeolocationHandler.OnCancelGeolocationPermission(IWebBrowser browserControl, IBrowser browser, int requestId)
        {
        }
    }
}

// Copyright © 2010-2016 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;
using System.Windows;

namespace CefSharp.Wpf.Example.Handlers
{
    internal class GeolocationHandler : IGeolocationHandler
    {
        bool IGeolocationHandler.OnRequestGeolocationPermission(IWebBrowser browserControl, IBrowser browser, string requestingUrl, int requestId, IGeolocationCallback callback)
        {
            //You can execute the callback inline
            //callback.Continue(true);
            //return true;

            //You can execute the callback in an `async` fashion
            //Open a message box on the `UI` thread and ask for user input.
            //You can open a form, or do whatever you like, just make sure you either
            //execute the callback or call `Dispose` as it's an `unmanaged` wrapper.
            var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
            chromiumWebBrowser.Dispatcher.BeginInvoke((Action)(() =>
            {
                //Callback wraps an unmanaged resource, so we'll make sure it's Disposed (calling Continue will also Dipose of the callback, it's safe to dispose multiple times).
                using (callback)
                {
                    var result = MessageBox.Show(String.Format("{0} wants to use your computer's location.  Allow?  ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButton.YesNo);

                    //Execute the callback, to allow/deny the request.
                    callback.Continue(result == MessageBoxResult.Yes);
                }
            }));

            //Yes we'd like to hadle this request ourselves.
            return true;
        }

        void IGeolocationHandler.OnCancelGeolocationPermission(IWebBrowser browserControl, IBrowser browser, int requestId)
        {
        }
    }
}

Update the GelocationHandler example - seems people are still struggling with the callback concept.


using System.Drawing;
using MonoHaven.UI.Widgets;

namespace MonoHaven.UI.Remote
{
	public class ServerInventoryWidget : ServerWidget
	{
		public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
		{
			var size = (Point)args[0];
			var widget = new InventoryWidget(parent.Widget);
			widget.SetInventorySize(size);
			return new ServerInventoryWidget(id, parent, widget);
		}

		public ServerInventoryWidget(ushort id, ServerWidget parent, InventoryWidget widget)
			: base(id, parent, widget)
		{
			widget.Drop += (p) => SendMessage("drop", p);
			widget.Transfer += OnTransfer;
		}

		private void OnTransfer(TransferEventArgs e)
		{
			var mods = ServerInput.ToServerModifiers(e.Modifiers);
			SendMessage("xfer", e.Delta, mods);
		}
	}
}

using System.Drawing;
using MonoHaven.UI.Widgets;

namespace MonoHaven.UI.Remote
{
	public class ServerInventoryWidget : ServerWidget
	{
		public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
		{
			var size = (Point)args[0];
			var widget = new InventoryWidget(parent.Widget);
			widget.SetInventorySize(size);
			return new ServerInventoryWidget(id, parent, widget);
		}

		private readonly InventoryWidget widget;

		public ServerInventoryWidget(ushort id, ServerWidget parent, InventoryWidget widget)
			: base(id, parent, widget)
		{
			this.widget = widget;
			this.widget.Drop += (p) => SendMessage("drop", p);
			this.widget.Transfer += OnTransfer;
		}

		public override void ReceiveMessage(string message, object[] args)
		{
			if (message == "sz")
				widget.SetInventorySize((Point)args[0]);
			else
				base.ReceiveMessage(message, args);
		}

		private void OnTransfer(TransferEventArgs e)
		{
			var mods = ServerInput.ToServerModifiers(e.Modifiers);
			SendMessage("xfer", e.Delta, mods);
		}
	}
}

Handle message changing inventory size

Handle message changing inventory size


using CommandLine;
using System;
using System.IO;
using System.Threading;
using WebScriptHook.Framework;
using WebScriptHook.Framework.BuiltinPlugins;
using WebScriptHook.Framework.Plugins;
using WebScriptHook.Service.Plugins;

namespace WebScriptHook.Service
{
    class Program
    {
        static WebScriptHookComponent wshComponent;

        static void Main(string[] args)
        {
            string componentName = Guid.NewGuid().ToString();
            Uri remoteUri;

            var options = new CommandLineOptions();
            if (Parser.Default.ParseArguments(args, options))
            {
                if (!string.IsNullOrWhiteSpace(options.Name)) componentName = options.Name;
                remoteUri = new Uri(options.ServerUriString);
            }
            else
            {
                return;
            }

            wshComponent = new WebScriptHookComponent(componentName, remoteUri, Console.Out, LogType.All);
            // Register custom plugins
            wshComponent.PluginManager.RegisterPlugin(new Echo());
            wshComponent.PluginManager.RegisterPlugin(new PluginList());
            wshComponent.PluginManager.RegisterPlugin(new PrintToScreen());
            // Load plugins in plugins directory if dir exists
            if (Directory.Exists("plugins"))
            {
                var plugins = PluginLoader.LoadAllPluginsFromDir("plugins", "*.dll");
                foreach (var plug in plugins)
                {
                    wshComponent.PluginManager.RegisterPlugin(plug);
                }
            }

            // Start WSH component
            wshComponent.Start();

            // TODO: Use a timer instead of Sleep
            while (true)
            {
                wshComponent.Update();
                Thread.Sleep(100);
            }
        }
    }
}

using CommandLine;
using System;
using System.IO;
using System.Threading;
using WebScriptHook.Framework;
using WebScriptHook.Framework.BuiltinPlugins;
using WebScriptHook.Framework.Plugins;
using WebScriptHook.Service.Plugins;

namespace WebScriptHook.Service
{
    class Program
    {
        static WebScriptHookComponent wshComponent;

        static void Main(string[] args)
        {
            string componentName = Guid.NewGuid().ToString();
            Uri remoteUri;

            var options = new CommandLineOptions();
            if (Parser.Default.ParseArguments(args, options))
            {
                if (!string.IsNullOrWhiteSpace(options.Name)) componentName = options.Name;
                remoteUri = new Uri(options.ServerUriString);
            }
            else
            {
                return;
            }

            wshComponent = new WebScriptHookComponent(componentName, remoteUri, TimeSpan.FromMilliseconds(30), Console.Out, LogType.All);
            // Register custom plugins
            wshComponent.PluginManager.RegisterPlugin(new Echo());
            wshComponent.PluginManager.RegisterPlugin(new PluginList());
            wshComponent.PluginManager.RegisterPlugin(new PrintToScreen());
            // Load plugins in plugins directory if dir exists
            if (Directory.Exists("plugins"))
            {
                var plugins = PluginLoader.LoadAllPluginsFromDir("plugins", "*.dll");
                foreach (var plug in plugins)
                {
                    wshComponent.PluginManager.RegisterPlugin(plug);
                }
            }

            // Start WSH component
            wshComponent.Start();

            // TODO: Use a timer instead of Sleep
            while (true)
            {
                wshComponent.Update();
                Thread.Sleep(100);
            }
        }
    }
}

Use polling rate of 30

Use polling rate of 30


using System;
using System.Collections.Generic;

namespace WootzJs.Injection
{
    public class Context
    {
        private ICache cache;
        private IDictionary<Type, IBinding> transientBindings;

        public Context(Context context = null, ICache cache = null, IDictionary<Type, IBinding> transientBindings = null)
        {
            cache = cache ?? new Cache();
            this.cache = context != null ? new HybridCache(cache, context.Cache) : cache;
            this.transientBindings = transientBindings;
        }

        public ICache Cache
        {
            get { return cache; }
        }

        public IBinding GetCustomBinding(Type type)
        {
            if (transientBindings == null)
                return null;

            IBinding result;
            transientBindings.TryGetValue(type, out result);
            return result;
        }
    }
}

using System;
using System.Collections.Generic;

namespace WootzJs.Injection
{
    public class Context
    {
        private ICache cache;
        private IDictionary<Type, IBinding> transientBindings;

        public Context(Context context = null, ICache cache = null, IDictionary<Type, IBinding> transientBindings = null)
        {
            cache = cache ?? new Cache();
            this.cache = context != null ? new HybridCache(cache, context.Cache) : cache;
            this.transientBindings = transientBindings;
        }

        public ICache Cache
        {
            get { return cache; }
        }

        public IBinding GetCustomBinding(Type type)
        {
            if (transientBindings == null)
                return null;

            while (type != null)
            {
                IBinding result;
                if (transientBindings.TryGetValue(type, out result))
                    return result;
                type = type.BaseType;
            }
            return null;
        }
    }
}

Fix handling of transient bindings to accomodate bindings that have been specified for an ancestral type


using System.Reflection;

[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.15")]

using System.Reflection;

[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]

Use 1.0.0 as the default informational version so it's easy to spot when it might have been un-patched during a build


#if NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestSetup = NUnit.Framework.SetUpAttribute;
#elif MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif

using UnitDriven;

namespace Csla.Test.Silverlight.Rollback
{
#if SILVERLIGHT
  [TestClass]
#endif
  public class RollbackTests : TestBase
  {
#if SILVERLIGHT
    [TestMethod]
    public void UnintializedProperty_RollsBack_AfterCancelEdit()
    {
      var context = GetContext();

      RollbackRoot.BeginCreateLocal((o, e) =>
      {
        var item = e.Object;
        var initialValue = 0;// item.UnInitedP;

        item.BeginEdit();
        item.UnInitedP = 1000;
        item.Another = "test";
        item.CancelEdit();

        context.Assert.AreEqual(initialValue, item.UnInitedP);
        context.Assert.Success();
      });

      context.Complete();
    }
#endif

  }
}

#if NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestSetup = NUnit.Framework.SetUpAttribute;
#elif MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif

using UnitDriven;

namespace Csla.Test.Silverlight.Rollback
{
#if SILVERLIGHT
  [TestClass]
#endif
  public class RollbackTests : TestBase
  {
#if SILVERLIGHT
    [TestMethod]
    public void UnintializedProperty_RollsBack_AfterCancelEdit()
    {
      var context = GetContext();

      RollbackRoot.BeginCreateLocal((o, e) =>
      {
        context.Assert.Try(() =>
          {
            var item = e.Object;
            var initialValue = 0;// item.UnInitedP;

            item.BeginEdit();
            item.UnInitedP = 1000;
            item.Another = "test";
            item.CancelEdit();

            context.Assert.AreEqual(initialValue, item.UnInitedP);
            context.Assert.Success();
          });
      });

      context.Complete();
    }
#endif

  }
}

Add Try block. bugid: 623

Add Try block.
bugid: 623


using System;
using System.Runtime.InteropServices;

namespace LibGPhoto2
{
	public class Context : Object
	{
		[DllImport ("libgphoto2.so")]
		internal static extern IntPtr gp_context_new ();

		public Context ()
		{
			this.handle = new HandleRef (this, gp_context_new ());
		}

		[DllImport ("libgphoto2.so")]
		internal static extern void gp_context_unref   (HandleRef context);

		protected override void Cleanup ()
		{
			System.Console.WriteLine ("cleanup context");
			gp_context_unref(handle);
		}
	}
}

using System;
using System.Runtime.InteropServices;

namespace LibGPhoto2
{
	public class Context : Object
	{
		[DllImport ("libgphoto2.so")]
		internal static extern IntPtr gp_context_new ();

		public Context ()
		{
			this.handle = new HandleRef (this, gp_context_new ());
		}

		[DllImport ("libgphoto2.so")]
		internal static extern void gp_context_unref   (HandleRef context);

		protected override void Cleanup ()
		{
			gp_context_unref(handle);
		}
	}
}

Remove random context cleanup console output

git-svn-id: 40dd595c6684d839db675001a64203a1457e7319@8996 67ed7778-7388-44ab-90cf-0a291f65f57c


// Copyright 2019 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

namespace VDrumExplorer.Data.Fields
{
    public interface IField
    {
        string Description { get; }
        FieldPath Path { get; }
        ModuleAddress Address { get; }
        int Size { get; }
        public FieldCondition? Condition { get; }
    }
}

// Copyright 2019 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

namespace VDrumExplorer.Data.Fields
{
    public interface IField
    {
        string Description { get; }
        FieldPath Path { get; }
        ModuleAddress Address { get; }
        int Size { get; }
        FieldCondition? Condition { get; }
    }
}

Remove redundant specification of public in interface


using JetBrains.Annotations;
using PlayGroups.Input;
using UI;
using UnityEngine;

public class MessageOnInteract : InputTrigger
{
	public string Message;
	// Use this for initialization
	void Start () {
	}

	// Update is called once per frame
	void Update () {

	}
	public override void Interact(GameObject originator, Vector3 position, string hand)
	{
		UIManager.Chat.AddChatEvent(new ChatEvent(Message, ChatChannel.Examine));
	}

}

using JetBrains.Annotations;
using PlayGroups.Input;
using UI;
using UnityEngine;

public class MessageOnInteract : InputTrigger
{
	public string Message;
	// Use this for initialization
	void Start () {
	}

	// Update is called once per frame
	void Update () {

	}
	public override void Interact(GameObject originator, Vector3 position, string hand)
	{
		ChatRelay.Instance.AddToChatLogClient(Message, ChatChannel.Examine);
	}

}

Use ChatRelay instead of UIManager when examining objects


namespace StackExchange.Exceptional.Internal
{
    /// <summary>
    /// Internal Exceptional static controls, not meant for consumption.
    /// This can and probably will break without warning. Don't use the .Internal namespace directly.
    /// </summary>
    public static class Statics
    {
        /// <summary>
        /// Settings for context-less logging.
        /// </summary>
        /// <remarks>
        /// In ASP.NET (non-Core) this is populated by the ConfigSettings load.
        /// In ASP.NET Core this is populated by .Configure() in the DI pipeline.
        /// </remarks>
        public static ExceptionalSettingsBase Settings { get; set; }

        /// <summary>
        /// Returns whether an error passed in right now would be logged.
        /// </summary>
        public static bool IsLoggingEnabled { get; set; } = true;
    }
}

namespace StackExchange.Exceptional.Internal
{
    /// <summary>
    /// Internal Exceptional static controls, not meant for consumption.
    /// This can and probably will break without warning. Don't use the .Internal namespace directly.
    /// </summary>
    public static class Statics
    {
        /// <summary>
        /// Settings for context-less logging.
        /// </summary>
        /// <remarks>
        /// In ASP.NET (non-Core) this is populated by the ConfigSettings load.
        /// In ASP.NET Core this is populated by .Configure() in the DI pipeline.
        /// </remarks>
        public static ExceptionalSettingsBase Settings { get; set; } = new ExceptionalSettingsDefault();

        /// <summary>
        /// Returns whether an error passed in right now would be logged.
        /// </summary>
        public static bool IsLoggingEnabled { get; set; } = true;
    }
}

Make sure Settings is never null

Make sure Settings is never null


namespace Mappy
{
    using System;
    using System.ComponentModel;
    using System.Reactive.Linq;
    using System.Reactive.Subjects;

    public static class ExtensionMethods
    {
        public static IObservable<TField> PropertyAsObservable<TSource, TField>(this TSource source, Func<TSource, TField> accessor, string name) where TSource : INotifyPropertyChanged
        {
            var subject = new BehaviorSubject<TField>(accessor(source));

            // FIXME: This is leaky.
            // We create a subscription to connect this to the subject
            // but we don't hold onto this subscription.
            // The subject we return can never be garbage collected
            // because the subscription cannot be freed.
            Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
                x => source.PropertyChanged += x,
                x => source.PropertyChanged -= x)
                .Where(x => x.EventArgs.PropertyName == name)
                .Select(_ => accessor(source))
                .Subscribe(subject);

            return subject;
        }
    }
}

namespace Mappy
{
    using System;
    using System.ComponentModel;
    using System.Reactive.Linq;
    using System.Reactive.Subjects;

    public static class ExtensionMethods
    {
        public static IObservable<TField> PropertyAsObservable<TSource, TField>(this TSource source, Func<TSource, TField> accessor, string name) where TSource : INotifyPropertyChanged
        {
            var obs = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
                x => source.PropertyChanged += x,
                x => source.PropertyChanged -= x)
                .Where(x => x.EventArgs.PropertyName == name)
                .Select(_ => accessor(source))
                .Multicast(new BehaviorSubject<TField>(accessor(source)));

            // FIXME: This is leaky.
            // We create a connection here but don't hold on to the reference.
            // We can never unregister our event handler without this.
            obs.Connect();

            return obs;
        }
    }
}

Use multicast instead of explicit BehaviourSubject setup


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

namespace TirkxDownloader.Framework.Interface
{
    /// <summary>
    /// This interface should be implemented for recieve JSON then parse it and return to caller
    /// </summary>
    /// <typeparam name="T">Type of message, must be JSON compatibility</typeparam>
    interface IMessageReciever<T>
    {
        ICollection<string> Prefixes { get; }

        bool IsRecieving { get; }

        Task<T> GetMessageAsync();

        /// <summary>
        /// Call this method when terminate application
        /// </summary>
        void Close();

        /// <summary>
        /// Call this method when you want to stop reciever
        /// </summary>
        void StopReciever();
    }
}

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

namespace TirkxDownloader.Framework.Interface
{
    /// <summary>
    /// This interface should be implemented for recieve JSON then parse it and return to caller
    /// </summary>
    /// <typeparam name="T">Type of message, must be JSON compatibility</typeparam>
    public interface IMessageReciever<T>
    {
        ICollection<string> Prefixes { get; }

        bool IsRecieving { get; }

        Task<T> GetMessageAsync();

        Task<T> GetMessageAsync(CancellationToken ct);

        /// <summary>
        /// Call this method when terminate application
        /// </summary>
        void Close();
    }
}

Delete stop reciever, to stop receiver use CancellationToken


#if NULLABLE_SHIMS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	public sealed class MaybeNullWhenAttribute : Attribute
	{
		public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; }

		public bool ReturnValue { get; }
	}
}
#endif

#if NULLABLE_SHIMS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; }

		public bool ReturnValue { get; }
	}
}
#endif

Change MaybeNullWhenAttribute to internal to remove collision with diagnostics ns


// 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.Collections.Generic;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.Framework.Configuration;

namespace Microsoft.AspNet.Server.Kestrel
{
    public class ServerInformation : IServerInformation, IKestrelServerInformation
    {
        public ServerInformation()
        {
            Addresses = new List<ServerAddress>();
        }

        public void Initialize(IConfiguration configuration)
        {
            var urls = configuration["server.urls"];
            if (!string.IsNullOrEmpty(urls))
            {
                urls = "http://+:5000/";
            }
            foreach (var url in urls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var address = ServerAddress.FromUrl(url);
                if (address != null)
                {
                    Addresses.Add(address);
                }
            }
        }

        public string Name
        {
            get
            {
                return "Kestrel";
            }
        }

        public IList<ServerAddress> Addresses { get; private set; }

        public int ThreadCount { get; set; }
    }
}

// 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.Collections.Generic;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.Framework.Configuration;

namespace Microsoft.AspNet.Server.Kestrel
{
    public class ServerInformation : IServerInformation, IKestrelServerInformation
    {
        public ServerInformation()
        {
            Addresses = new List<ServerAddress>();
        }

        public void Initialize(IConfiguration configuration)
        {
            var urls = configuration["server.urls"];
            if (string.IsNullOrEmpty(urls))
            {
                urls = "http://+:5000/";
            }
            foreach (var url in urls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var address = ServerAddress.FromUrl(url);
                if (address != null)
                {
                    Addresses.Add(address);
                }
            }
        }

        public string Name
        {
            get
            {
                return "Kestrel";
            }
        }

        public IList<ServerAddress> Addresses { get; private set; }

        public int ThreadCount { get; set; }
    }
}

Fix regression in reading config

Fix regression in reading config


using System;
using Pdelvo.Minecraft.Network;

namespace Pdelvo.Minecraft.Protocol.Packets
{
    [PacketUsage(PacketUsage.ServerToClient)]
    public class DisplayScoreboard : Packet
    {
        public byte Position { get; set; }
        public string ScoreName { get; set; }

        /// <summary>
        ///   Initializes a new instance of the <see cref="DisplayScoreboard" /> class.
        /// </summary>
        /// <remarks>
        /// </remarks>
        public DisplayScoreboard()
        {
            Code = 0xCF;
        }

        /// <summary>
        ///   Receives the specified reader.
        /// </summary>
        /// <param name="reader"> The reader. </param>
        /// <param name="version"> The version. </param>
        /// <remarks>
        /// </remarks>
        protected override void OnReceive(BigEndianStream reader, int version)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            Position = reader.ReadByte();
            ScoreName = reader.ReadString16();
        }

        /// <summary>
        ///   Sends the specified writer.
        /// </summary>
        /// <param name="writer"> The writer. </param>
        /// <param name="version"> The version. </param>
        /// <remarks>
        /// </remarks>
        protected override void OnSend(BigEndianStream writer, int version)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");
            writer.Write(Code);

            writer.Write(Position);
            writer.Write(ScoreName);
        }
    }
}

using System;
using Pdelvo.Minecraft.Network;

namespace Pdelvo.Minecraft.Protocol.Packets
{
    [PacketUsage(PacketUsage.ServerToClient)]
    public class DisplayScoreboard : Packet
    {
        public byte Position { get; set; }
        public string ScoreName { get; set; }

        /// <summary>
        ///   Initializes a new instance of the <see cref="DisplayScoreboard" /> class.
        /// </summary>
        /// <remarks>
        /// </remarks>
        public DisplayScoreboard()
        {
            Code = 0xD0;
        }

        /// <summary>
        ///   Receives the specified reader.
        /// </summary>
        /// <param name="reader"> The reader. </param>
        /// <param name="version"> The version. </param>
        /// <remarks>
        /// </remarks>
        protected override void OnReceive(BigEndianStream reader, int version)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            Position = reader.ReadByte();
            ScoreName = reader.ReadString16();
        }

        /// <summary>
        ///   Sends the specified writer.
        /// </summary>
        /// <param name="writer"> The writer. </param>
        /// <param name="version"> The version. </param>
        /// <remarks>
        /// </remarks>
        protected override void OnSend(BigEndianStream writer, int version)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");
            writer.Write(Code);

            writer.Write(Position);
            writer.Write(ScoreName);
        }
    }
}

Fix display scoreboard packet id

Fix display scoreboard packet id


using System.Resources;
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("ForecastPCL")]
[assembly: AssemblyDescription("An unofficial PCL for the forecast.io weather API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jerome Cheng")]
[assembly: AssemblyProduct("ForecastPCL")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

// 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("2.4.0.0")]
[assembly: AssemblyFileVersion("2.4.0.0")]

using System.Resources;
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("ForecastPCL")]
[assembly: AssemblyDescription("An unofficial PCL for the forecast.io weather API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jerome Cheng")]
[assembly: AssemblyProduct("ForecastPCL")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

// 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("2.5.0.0")]
[assembly: AssemblyFileVersion("2.5.0.0")]

Bump assembly version to 2.5.0.

Bump assembly version to 2.5.0.


using System;
using System.Runtime.InteropServices;
using Foundation;

// Generated by Objective Sharpie (https://download.xamarin.com/objective-sharpie/ObjectiveSharpie.pkg)
// > sharpie bind -output TestFairy -namespace TestFairyLib -sdk iphoneos10.1 TestFairy.h
namespace TestFairyLib
{
	public static class CFunctions
	{
		// extern void TFLog (NSString *format, ...) __attribute__((format(NSString, 1, 2)));
		[DllImport ("__Internal")]
		public static extern void TFLog (NSString format, IntPtr varArgs);

		// extern void TFLogv (NSString *format, va_list arg_list);
		[DllImport ("__Internal")]
		public static extern unsafe void TFLogv (NSString format, sbyte* arg_list);
	}
}

using System;
using System.Runtime.InteropServices;
using Foundation;

// Generated by Objective Sharpie (https://download.xamarin.com/objective-sharpie/ObjectiveSharpie.pkg)
// > sharpie bind -output TestFairy -namespace TestFairyLib -sdk iphoneos10.1 TestFairy.h
namespace TestFairyLib
{
	public static class CFunctions
	{
		// extern void TFLog (NSString *format, ...) __attribute__((format(NSString, 1, 2)));
		[DllImport ("__Internal")]
		public static extern void TFLog (IntPtr format, string arg0);

		// extern void TFLogv (NSString *format, va_list arg_list);
		[DllImport ("__Internal")]
		public static extern unsafe void TFLogv (IntPtr format, sbyte* arg_list);
	}
}

Use native pointer for format string

Use native pointer for format string


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

#nullable disable

using System;
using System.IO;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Input.Events;
using osu.Framework.Extensions.EnumExtensions;

namespace osu.Framework.Graphics.UserInterface
{
    public abstract class DirectorySelectorDirectory : DirectorySelectorItem
    {
        protected readonly DirectoryInfo Directory;
        protected override string FallbackName => Directory.Name;

        [Resolved]
        private Bindable<DirectoryInfo> currentDirectory { get; set; }

        protected DirectorySelectorDirectory(DirectoryInfo directory, string displayName = null)
            : base(displayName)
        {
            Directory = directory;

            try
            {
                bool isHidden = directory?.Attributes.HasFlagFast(FileAttributes.Hidden) == true;

                // On Windows, system drives are returned with `System | Hidden | Directory` file attributes,
                // but the expectation is that they shouldn't be shown in a hidden state.
                bool isSystemDrive = directory?.Parent == null;

                if (isHidden && !isSystemDrive)
                    ApplyHiddenState();
            }
            catch (UnauthorizedAccessException)
            {
                // checking attributes on access-controlled directories will throw an error so we handle it here to prevent a crash
            }
        }

        protected override bool OnClick(ClickEvent e)
        {
            currentDirectory.Value = Directory;
            return true;
        }
    }
}

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

#nullable disable

using System;
using System.IO;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Input.Events;
using osu.Framework.Extensions.EnumExtensions;

namespace osu.Framework.Graphics.UserInterface
{
    public abstract class DirectorySelectorDirectory : DirectorySelectorItem
    {
        protected readonly DirectoryInfo Directory;
        protected override string FallbackName => Directory.Name;

        [Resolved]
        private Bindable<DirectoryInfo> currentDirectory { get; set; }

        protected DirectorySelectorDirectory(DirectoryInfo directory, string displayName = null)
            : base(displayName)
        {
            Directory = directory;

            try
            {
                bool isHidden = directory?.Attributes.HasFlagFast(FileAttributes.Hidden) == true;

                // On Windows, system drives are returned with `System | Hidden | Directory` file attributes,
                // but the expectation is that they shouldn't be shown in a hidden state.
                bool isSystemDrive = directory?.Parent == null;

                if (isHidden && !isSystemDrive)
                    ApplyHiddenState();
            }
            catch (IOException)
            {
                // various IO exceptions could occur when attempting to read attributes.
                // one example is when a target directory is a drive which is locked by BitLocker:
                //
                // "Unhandled exception. System.IO.IOException: This drive is locked by BitLocker Drive Encryption. You must unlock this drive from Control Panel. : 'D:\'"
            }
            catch (UnauthorizedAccessException)
            {
                // checking attributes on access-controlled directories will throw an error so we handle it here to prevent a crash
            }
        }

        protected override bool OnClick(ClickEvent e)
        {
            currentDirectory.Value = Directory;
            return true;
        }
    }
}

Fix directory selector crashing when attempting to display a bitlocker locked drive

Closes #5477. Untested.


using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace PinSharp.Http
{
    internal class FormUrlEncodedContent : ByteArrayContent
    {
        private static readonly Encoding DefaultHttpEncoding = Encoding.GetEncoding("ISO-8859-1");

        public FormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
          : base(GetContentByteArray(nameValueCollection))
        {
            Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
        }

        private static byte[] GetContentByteArray(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
        {
            if (nameValueCollection == null) throw new ArgumentNullException(nameof(nameValueCollection));

            var stringBuilder = new StringBuilder();
            foreach (var keyValuePair in nameValueCollection)
            {
                if (stringBuilder.Length > 0)
                    stringBuilder.Append('&');
                stringBuilder.Append(Encode(keyValuePair.Key));
                stringBuilder.Append('=');
                stringBuilder.Append(Encode(keyValuePair.Value));
            }
            return DefaultHttpEncoding.GetBytes(stringBuilder.ToString());
        }

        private static string Encode(string data)
        {
            return string.IsNullOrEmpty(data) ? "" : Uri.EscapeDataString(data).Replace("%20", "+");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace PinSharp.Http
{
    internal class FormUrlEncodedContent : ByteArrayContent
    {
        private static readonly Encoding DefaultHttpEncoding = Encoding.GetEncoding("ISO-8859-1");

        public FormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
          : base(GetContentByteArray(nameValueCollection))
        {
            Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
        }

        private static byte[] GetContentByteArray(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
        {
            if (nameValueCollection == null) throw new ArgumentNullException(nameof(nameValueCollection));

            var stringBuilder = new StringBuilder();
            foreach (var keyValuePair in nameValueCollection)
            {
                if (stringBuilder.Length > 0)
                    stringBuilder.Append('&');
                stringBuilder.Append(Encode(keyValuePair.Key));
                stringBuilder.Append('=');
                stringBuilder.Append(Encode(keyValuePair.Value));
            }
            return DefaultHttpEncoding.GetBytes(stringBuilder.ToString());
        }

        private static string Encode(string data)
        {
            if (string.IsNullOrEmpty(data))
                return "";

            return EscapeLongDataString(data);
        }

        private static string EscapeLongDataString(string data)
        {
            // Uri.EscapeDataString() does not support strings longer than this
            const int maxLength = 65519;

            var sb = new StringBuilder();
            var iterationsNeeded = data.Length / maxLength;

            for (var i = 0; i <= iterationsNeeded; i++)
            {
                sb.Append(i < iterationsNeeded
                    ? Uri.EscapeDataString(data.Substring(maxLength * i, maxLength))
                    : Uri.EscapeDataString(data.Substring(maxLength * i)));
            }

            return sb.ToString().Replace("%20", "+");
        }
    }
}

Fix issue with long data string (e.g. base64)

#13


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[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("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]

// 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.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[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("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]

// 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.1.0.1")]
[assembly: AssemblyFileVersion("1.1.0.1")]

Increment build number to match NuGet

Increment build number to match NuGet


using System;
using System.Linq;
using System.Threading.Tasks;
using Bug2211;
using Marten;
using Marten.Testing.Harness;
using Shouldly;
using Weasel.Core;
using Xunit;

namespace DocumentDbTests.Bugs
{
    public class Bug_2211_select_transform_inner_object: BugIntegrationContext
    {
        [Fact]
        public async Task should_be_able_to_select_nested_objects()
        {
            using var documentStore = SeparateStore(x =>
            {
                x.AutoCreateSchemaObjects = AutoCreate.All;
                x.Schema.For<TestEntity>();
            });

            await documentStore.Advanced.Clean.DeleteAllDocumentsAsync();

            await using var session = documentStore.OpenSession();
            session.Store(new TestEntity { Name = "Test", Inner = new TestDto { Name = "TestDto" } });

            await session.SaveChangesAsync();

            await using var querySession = documentStore.QuerySession();

            var results = await querySession.Query<TestEntity>()
                .Select(x => new { Inner = x.Inner })
                .ToListAsync();

            results.Count.ShouldBe(1);
            results[0].Inner.Name.ShouldBe("Test Dto");
        }
    }
}

namespace Bug2211
{
    public class TestEntity
    {
        public Guid Id { get; set; }

        public string Name { get; set; }
        public TestDto Inner { get; set; }
    }

    public class TestDto
    {
        public string Name { get; set; }
    }
}

using System;
using System.Linq;
using System.Threading.Tasks;
using Bug2211;
using Marten;
using Marten.Testing.Harness;
using Shouldly;
using Weasel.Core;
using Xunit;

namespace DocumentDbTests.Bugs
{
    public class Bug_2211_select_transform_inner_object: BugIntegrationContext
    {
        [Fact]
        public async Task should_be_able_to_select_nested_objects()
        {
            using var documentStore = SeparateStore(x =>
            {
                x.AutoCreateSchemaObjects = AutoCreate.All;
                x.Schema.For<TestEntity>();
            });

            await documentStore.Advanced.Clean.DeleteAllDocumentsAsync();

            await using var session = documentStore.OpenSession();
            var testEntity = new TestEntity { Name = "Test", Inner = new TestDto { Name = "TestDto" } };
            session.Store(testEntity);

            await session.SaveChangesAsync();

            await using var querySession = documentStore.QuerySession();

            var results = await querySession.Query<TestEntity>()
                .Select(x => new { Inner = x.Inner })
                .ToListAsync();

            results.Count.ShouldBe(1);
            results[0].Inner.Name.ShouldBe(testEntity.Inner.Name);
        }
    }
}

namespace Bug2211
{
    public class TestEntity
    {
        public Guid Id { get; set; }

        public string Name { get; set; }
        public TestDto Inner { get; set; }
    }

    public class TestDto
    {
        public string Name { get; set; }
    }
}

Fix test referring to wrong value

Fix test referring to wrong value


using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
using UnityEngine;

namespace LiteNetLibHighLevel
{
    public class ServerSpawnSceneObjectMessage : LiteNetLibMessageBase
    {
        public uint objectId;
        public Vector3 position;

        public override void Deserialize(NetDataReader reader)
        {
            objectId = reader.GetUInt();
            position = new Vector3(reader.GetFloat(), reader.GetFloat(), reader.GetFloat());
        }

        public override void Serialize(NetDataWriter writer)
        {
            writer.Put(objectId);
            writer.Put(position.x);
            writer.Put(position.y);
            writer.Put(position.z);
        }
    }
}

using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
using UnityEngine;

namespace LiteNetLibHighLevel
{
    public class ServerSpawnSceneObjectMessage : ILiteNetLibMessage
    {
        public uint objectId;
        public Vector3 position;

        public void Deserialize(NetDataReader reader)
        {
            objectId = reader.GetUInt();
            position = new Vector3(reader.GetFloat(), reader.GetFloat(), reader.GetFloat());
        }

        public void Serialize(NetDataWriter writer)
        {
            writer.Put(objectId);
            writer.Put(position.x);
            writer.Put(position.y);
            writer.Put(position.z);
        }
    }
}

Change serialize/deserialze abstract class to interface


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

[assembly: System.Reflection.AssemblyVersion("1.0.*")]
[assembly: System.Reflection.AssemblyInformationalVersion("0.1.2")]

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

[assembly: System.Reflection.AssemblyVersion("1.0.*")]
[assembly: System.Reflection.AssemblyInformationalVersion("0.1.1")]

Set correct version number, v0.1.1

Set correct version number, v0.1.1


using UnityEngine;

namespace Pear.InteractionEngine.Converters
{
	/// <summary>
	/// Converts a Vector2 to Vector3
	/// </summary>
	public class Vector2ToVector3 : MonoBehaviour, IPropertyConverter<Vector2, Vector3>
	{
		public Vector3 Convert(Vector2 convertFrom)
		{
			return convertFrom;
		}
	}
}

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

namespace Pear.InteractionEngine.Converters
{
	/// <summary>
	/// Converts a Vector2 to Vector3
	/// </summary>
	public class Vector2ToVector3 : MonoBehaviour, IPropertyConverter<Vector2, Vector3>
	{
		[Tooltip("Where should the X value be set")]
		public VectorFields SetXOn = VectorFields.X;

		[Tooltip("Multiplied on the X value when it's set")]
		public float XMultiplier = 1;

		[Tooltip("Where should the Y value be set")]
		public VectorFields SetYOn = VectorFields.X;

		[Tooltip("Multiplied on the Y value when it's set")]
		public float YMultiplier = 1;

		public Vector3 Convert(Vector2 convertFrom)
		{
			float x = 0;
			float y = 0;
			float z = 0;

			Dictionary<VectorFields, Action<float>> setActions = new Dictionary<VectorFields, Action<float>>()
			{
				{ VectorFields.X, val => x = val },
				{ VectorFields.Y, val => y = val },
				{ VectorFields.Z, val => z = val },
			};

			setActions[SetXOn](convertFrom.x * XMultiplier);
			setActions[SetYOn](convertFrom.y * YMultiplier);

			return new Vector3(x, y, z);
		}
	}

	public enum VectorFields
	{
		X,
		Y,
		Z,
	}
}

Add more features to vector 2 -> vector 3 conversion


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("KeyPay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("KeyPay")]
[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("93365e33-3b92-4ea6-ab42-ffecbc504138")]

// 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: AssemblyInformationalVersion("1.1.0.13-rc1")]
[assembly: AssemblyFileVersion("1.0.0.0")]

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("KeyPay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("KeyPay")]
[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("93365e33-3b92-4ea6-ab42-ffecbc504138")]

// 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: AssemblyInformationalVersion("1.1.0.13")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Add Employee Standard Hours endpoints

Add Employee Standard Hours endpoints


@{
    ViewBag.Title = "Home Page";
}

            Vendo 5.0

The Future of Vending Machines

            Vendo 5.0 is among the first digitally integrated vending machines of the 21st century. It's so great, that we skipped the first four versions and
            went straight to 5. With Vendo 5.0, you have the ability to access our machines through your smartphone or P.C. Create an account with us and explore
            the Vendo lifestyle. You'll have access to each the machines in your area and the ability to control what the machine grabs for you. Whether it's candy,
            chips or soda, Vendo 5.0 can satisfy your nourishment. So, sign up today and live life the Vendo way!

    <img id="vendo" src='<%=ResolveUrl("~/img/Vendo.png") %>'  />

Add code to allow vendo img to show on Azure


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

[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.6.0.0")]
[assembly: AssemblyFileVersion("0.6.0.0")]

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

[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.7.0.0")]
[assembly: AssemblyFileVersion("0.7.0.0")]

Increase project version number to 0.7.0


using System;
using LinqToTTreeInterfacesLib;

namespace LINQToTTreeLib.Variables
{
    /// <summary>
    /// A simple variable (like int, etc.).
    /// </summary>
    public class VarSimple : IVariable
    {
        public string VariableName { get; private set; }
        public string RawValue { get; private set; }
        public Type Type { get; private set; }

        public VarSimple(System.Type type)
        {
            if (type == null)
                throw new ArgumentNullException("Must have a good type!");

            Type = type;
            VariableName = type.CreateUniqueVariableName();
            RawValue = VariableName;
        }

        public IValue InitialValue { get; set; }

        public bool Declare
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
    }
}

using System;
using LinqToTTreeInterfacesLib;

namespace LINQToTTreeLib.Variables
{
    /// <summary>
    /// A simple variable (like int, etc.).
    /// </summary>
    public class VarSimple : IVariable
    {
        public string VariableName { get; private set; }
        public string RawValue { get; private set; }
        public Type Type { get; private set; }

        public VarSimple(System.Type type)
        {
            if (type == null)
                throw new ArgumentNullException("Must have a good type!");

            Type = type;
            VariableName = type.CreateUniqueVariableName();
            RawValue = VariableName;
        }

        public IValue InitialValue { get; set; }

        /// <summary>
        /// Get/Set if this variable needs to be declared.
        /// </summary>
        public bool Declare { get; set; }
    }
}

Add the ability to have a simple variable declared inline.


// 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.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace MvcSandbox
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            app.UseDeveloperExceptionPage();
            app.UseStaticFiles();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args)
                .Build();

            host.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            new WebHostBuilder()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .ConfigureLogging(factory =>
                {
                    factory
                        .AddConsole()
                        .AddDebug();
                })
                .UseIISIntegration()
                .UseKestrel()
                .UseStartup<Startup>();
    }
}

// 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.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace MvcSandbox
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            app.UseDeveloperExceptionPage();
            app.UseStaticFiles();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args)
                .Build();

            host.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            new WebHostBuilder()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .ConfigureLogging(factory =>
                {
                    factory
                        .AddConsole()
                        .AddDebug();
                })
                .UseIISIntegration()
                .UseKestrel()
                .UseStartup<Startup>();
    }
}

Use latest compat version in MvcSandbox

Use latest compat version in MvcSandbox


// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System;
using NodaTime;
using Squidex.Domain.Apps.Core.Contents;
using Squidex.Infrastructure;

namespace Squidex.Domain.Apps.Entities.Contents
{
    public sealed class ScheduleJob
    {
        public Guid Id { get; }

        public Status Status { get; }

        public RefToken ScheduledBy { get; }

        public Instant DueTime { get; }

        public ScheduleJob(Guid id, Status status, RefToken by, Instant due)
        {
            Id = id;
            ScheduledBy = by;
            Status = status;
            DueTime = due;
        }

        public static ScheduleJob Build(Status status, RefToken by, Instant due)
        {
            return new ScheduleJob(Guid.NewGuid(), status, by, due);
        }
    }
}

// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System;
using NodaTime;
using Squidex.Domain.Apps.Core.Contents;
using Squidex.Infrastructure;

namespace Squidex.Domain.Apps.Entities.Contents
{
    public sealed class ScheduleJob
    {
        public Guid Id { get; }

        public Status Status { get; }

        public RefToken ScheduledBy { get; }

        public Instant DueTime { get; }

        public ScheduleJob(Guid id, Status status, RefToken scheduledBy, Instant due)
        {
            Id = id;
            ScheduledBy = scheduledBy;
            Status = status;
            DueTime = due;
        }

        public static ScheduleJob Build(Status status, RefToken by, Instant due)
        {
            return new ScheduleJob(Guid.NewGuid(), status, by, due);
        }
    }
}

Fix deserialization of scheduled job.

Fix deserialization of scheduled job.


using System.Linq;
using Diploms.Dto;
using Microsoft.AspNetCore.Mvc;

namespace Diploms.WebUI
{
    public static class ControllerExtensions
    {
        public static OperationResult GetErrors(this Controller controller, object model)
        {
            var result = new OperationResult();

            if (model == null)
            {
                result.Errors.Add("Ошибка ввода данных");
            }

            result.Errors.AddRange(controller.ModelState.Values.SelectMany(v => v.Errors
              .Where(b => !string.IsNullOrEmpty(b.ErrorMessage))
              .Select(b => b.ErrorMessage)));

            return result;
        }
    }
}

using System.Linq;
using Diploms.Dto;
using Microsoft.AspNetCore.Mvc;

namespace Diploms.WebUI
{
    public static class ControllerExtensions
    {
        public static OperationResult GetErrors(this Controller controller, object model)
        {
            var result = new OperationResult();

            if (model == null)
            {
                result.Errors.Add("Ошибка ввода данных");
            }

            result.Errors.AddRange(controller.ModelState.Values.SelectMany(v => v.Errors
              .Where(b => !string.IsNullOrEmpty(b.ErrorMessage))
              .Select(b => b.ErrorMessage)));

            return result;
        }

        public static IActionResult Unprocessable(this Controller controller, object value)
        {
            return controller.StatusCode(422, value);
        }
    }
}

Add special http method to return unprocessable entities


using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HipChatConnect.Controllers.Listeners.Github.Models;
using HipChatConnect.Controllers.Listeners.TeamCity;

namespace HipChatConnect.Controllers.Listeners.Github
{
    public class GithubAggregator
    {
        private IHipChatRoom Room { get; }

        public GithubAggregator(IHipChatRoom room)
        {
            Room = room;
        }

        public async Task Handle(GithubPushNotification notification)
        {
            await SendTeamsInformationAsync(notification);

        }

        private async Task SendTeamsInformationAsync(GithubPushNotification notification)
        {
            var githubModel = notification.GithubModel;

            (var title, var text) = BuildMessage(githubModel);

            var cardData = new SuccessfulTeamsActivityCardData
            {
                Title = title,
                Text = text
            };

            await Room.SendTeamsActivityCardAsync(cardData);
        }

        private static (string Title, string Text) BuildMessage(GithubModel model)
        {
            var branch = model.Ref.Replace("refs/heads/", "");
            var authorNames = model.Commits.Select(c => c.Author.Name).Distinct();

            var title = $"**{string.Join(", ", authorNames)}** committed on [{branch}]({model.Repository.HtmlUrl + "/tree/" + branch})";

            var stringBuilder = new StringBuilder();

            foreach (var commit in model.Commits)
            {
                stringBuilder.Append($@"* {commit.Message} [{commit.Id.Substring(0, 11)}]({commit.Url})");
            }

            return (title, stringBuilder.ToString());
        }
    }
}

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HipChatConnect.Controllers.Listeners.Github.Models;
using HipChatConnect.Controllers.Listeners.TeamCity;

namespace HipChatConnect.Controllers.Listeners.Github
{
    public class GithubAggregator
    {
        private IHipChatRoom Room { get; }

        public GithubAggregator(IHipChatRoom room)
        {
            Room = room;
        }

        public async Task Handle(GithubPushNotification notification)
        {
            await SendTeamsInformationAsync(notification);

        }

        private async Task SendTeamsInformationAsync(GithubPushNotification notification)
        {
            var githubModel = notification.GithubModel;

            (var title, var text) = BuildMessage(githubModel);

            var cardData = new SuccessfulTeamsActivityCardData
            {
                Title = title,
                Text = text
            };

            await Room.SendTeamsActivityCardAsync(cardData);
        }

        private static (string Title, string Text) BuildMessage(GithubModel model)
        {
            var branch = model.Ref.Replace("refs/heads/", "");
            var authorNames = model.Commits.Select(c => c.Author.Name).Distinct().ToList();

            var title = $"{string.Join(", ", authorNames)} committed on {branch}";

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine(
                $"**{string.Join(", ", authorNames)}** committed on [{branch}]({model.Repository.HtmlUrl + "/tree/" + branch})");

            foreach (var commit in model.Commits)
            {
                stringBuilder.AppendLine($@"* {commit.Message} [{commit.Id.Substring(0, 11)}]({commit.Url})");
                stringBuilder.AppendLine();
            }

            return (title, stringBuilder.ToString());
        }
    }
}

Fix some formatting for Teams

Fix some formatting for Teams


using System.Reflection;
using Microsoft.Xna.Framework;
using CocosDenshion;
using CocosSharp;

namespace Chess_Demo
{
    class AppDelegate : CCApplicationDelegate
    {
        static CCWindow sharedWindow;

        public static CCWindow SharedWindow
        {
            get { return sharedWindow; }
        }

        public static CCSize DefaultResolution;

        public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow)
        {
            application.ContentRootDirectory = "assets";

            sharedWindow = mainWindow;

            DefaultResolution = new CCSize(
                application.MainWindow.WindowSizeInPixels.Width,
                application.MainWindow.WindowSizeInPixels.Height);

            CCScene scene = new CCScene(sharedWindow);

            sharedWindow.RunWithScene(scene);
        }

        public override void ApplicationDidEnterBackground(CCApplication application)
        {
            application.Paused = true;
        }

        public override void ApplicationWillEnterForeground(CCApplication application)
        {
            application.Paused = false;
        }
    }
}

using System.Reflection;
using Microsoft.Xna.Framework;
using CocosDenshion;
using CocosSharp;

namespace Chess_Demo
{
    class AppDelegate : CCApplicationDelegate
    {
        static CCWindow sharedWindow;

        public static CCWindow SharedWindow
        {
            get { return sharedWindow; }
        }

        public static CCSize DefaultResolution;

        public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow)
        {
            application.ContentRootDirectory = "assets";

            sharedWindow = mainWindow;

            DefaultResolution = new CCSize(
                application.MainWindow.WindowSizeInPixels.Width,
                application.MainWindow.WindowSizeInPixels.Height);

            CCScene scene = new CCScene(sharedWindow);
            scene.AddChild(new ChessLayer());

            sharedWindow.RunWithScene(scene);
        }

        public override void ApplicationDidEnterBackground(CCApplication application)
        {
            application.Paused = true;
        }

        public override void ApplicationWillEnterForeground(CCApplication application)
        {
            application.Paused = false;
        }
    }
}

Add Layer to scene. Currently breaking on asset load


using Medallion.OData.Sql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Medallion.OData.Samples.Web.Models
{
    public class Provider : DatabaseProvider
    {
        protected override string GetSqlTypeName(Trees.ODataExpressionType oDataType)
        {
            throw new NotImplementedException();
        }

        protected override System.Collections.IEnumerable Execute(string sql, IReadOnlyList<Parameter> parameters, Type resultType)
        {
            throw new NotImplementedException();
        }

        protected override int ExecuteCount(string sql, IReadOnlyList<Parameter> parameters)
        {
            throw new NotImplementedException();
        }
    }
}

using Medallion.OData.Service.Sql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Medallion.OData.Samples.Web.Models
{
    public class Provider : DatabaseProvider
    {
        protected override string GetSqlTypeName(Trees.ODataExpressionType oDataType)
        {
            throw new NotImplementedException();
        }

        protected override System.Collections.IEnumerable Execute(string sql, IReadOnlyList<Parameter> parameters, Type resultType)
        {
            throw new NotImplementedException();
        }

        protected override int ExecuteCount(string sql, IReadOnlyList<Parameter> parameters)
        {
            throw new NotImplementedException();
        }
    }
}

Build fix after namespace adjustment

Build fix after namespace adjustment


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

namespace MemoryGames
{
   public class CardRandomPosition
    {
      private  List<CardFace> gameCard = new List<CardFace>();

      private  string[] cardName = new string[8];//here will be the name of the card

       private Random randomGenerator = new Random();

        public static void FillMatrix()
        {
        }

        internal static CardFace[,] GetRandomCardFace()
        {
            throw new NotImplementedException();
        }
    }
}

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

namespace MemoryGames
{
    public class CardRandomPosition
    {
        public static CardFace[,] GetRandomCardFace(int dimentionZero, int dimentionOne)
        {
            const int pair = 2;
            const int pairCount = 9;
            CardFace[,] cardFace = new CardFace[dimentionZero, dimentionOne];
            Random randomGenerator = new Random();
            List<CardFace> gameCard = new List<CardFace>();
            int allCard = dimentionZero * dimentionOne;
            int currentGameCardPair = allCard / pair;
            string[] cardName = new string[pairCount] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
            for (int element = 0, j = 0; element < allCard; element++, j++)
            {
                if (j == currentGameCardPair)
                {
                    j = 0;
                }
                gameCard.Add(new CardFace(cardName[j]));
            }
            for (int row = 0; row < dimentionZero; row++)
            {
                for (int col = 0; col < dimentionOne; col++)
                {
                    int randomElement = randomGenerator.Next(0, gameCard.Count);
                    cardFace[row, col] = gameCard[randomElement];
                    gameCard.RemoveAt(randomElement);

                }
            }
            return cardFace;
        }
    }
}

Add random position of card

Add random position of card


/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation.
 *
 * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
 * copy of the license can be found in the License.html file at the root of this distribution. If
 * you cannot locate the Apache License, Version 2.0, please send an email to
 * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
 * by the terms of the Apache License, Version 2.0.
 *
 * You must not remove this notice, or any other, from this software.
 *
 * ***************************************************************************/

using Microsoft.NodejsTools.Analysis;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AnalysisTests {
    [TestClass]
    internal class SerializedAnalysisTests : AnalysisTests {
        internal override ModuleAnalysis ProcessText(string text) {
            return SerializationTests.RoundTrip(ProcessOneText(text));
        }
    }
}

/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation.
 *
 * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
 * copy of the license can be found in the License.html file at the root of this distribution. If
 * you cannot locate the Apache License, Version 2.0, please send an email to
 * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
 * by the terms of the Apache License, Version 2.0.
 *
 * You must not remove this notice, or any other, from this software.
 *
 * ***************************************************************************/

using Microsoft.NodejsTools.Analysis;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AnalysisTests {
    [TestClass]
    public class SerializedAnalysisTests : AnalysisTests {
        internal override ModuleAnalysis ProcessText(string text) {
            return SerializationTests.RoundTrip(ProcessOneText(text));
        }
    }
}

Test needs to be public

Test needs to be public


using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Controllers.API
{
    public class WeaponsController : ApiController
    {
        public WeaponsController(Database db) : base(db)
        {
            // Nothing to do here
        }

        [HttpGet]
        public async Task<IEnumerable<dynamic>> Get()
        {
            // GET: api/weapons

            return
                await db
                .Weapons
                .Select(_ => new
                {
                    _.Id,
                    _.OpticSerial,
                    _.OpticType,
                    _.Serial,
                    _.StockNumber,
                    _.Type,
                    _.UnitId
                })
                .ToListAsync();
        }

        [HttpPost]
        public async Task<IActionResult> Post([FromBody]Weapon weapon)
        {
            await db.Weapons.AddAsync(weapon);

            await db.SaveChangesAsync();

            return Ok();
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {
            var weapon = await db.Weapons.FindAsync(id);

            db.Weapons.Remove(weapon);

            await db.SaveChangesAsync();

            return Ok();
        }
    }
}

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

namespace BatteryCommander.Web.Controllers.API
{
    public class WeaponsController : ApiController
    {
        public WeaponsController(Database db) : base(db)
        {
            // Nothing to do here
        }

        [HttpGet]
        public async Task<IActionResult> Get(int? unit)
        {
            // GET: api/weapons

            return Ok(
                await db
                .Weapons
                .Where(weapon => !unit.HasValue || weapon.UnitId == unit)
                .Select(_ => new
                {
                    _.Id,
                    _.OpticSerial,
                    _.OpticType,
                    _.Serial,
                    _.StockNumber,
                    _.Type,
                    _.UnitId
                })
                .ToListAsync());
        }

        [HttpPost]
        public async Task<IActionResult> Post([FromBody]Weapon weapon)
        {
            await db.Weapons.AddAsync(weapon);

            await db.SaveChangesAsync();

            return Ok();
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {
            var weapon = await db.Weapons.FindAsync(id);

            db.Weapons.Remove(weapon);

            await db.SaveChangesAsync();

            return Ok();
        }
    }
}

Allow filtering weapons by unit

Allow filtering weapons by unit


using System.Threading.Tasks;
using Auth0.AuthenticationApi;
using Auth0.AuthenticationApi.Models;
using Microsoft.Extensions.Configuration;

namespace Auth0.Tests.Shared
{
    public class TestBase
    {
        private readonly IConfigurationRoot _config;

        public TestBase()
        {
            _config = new ConfigurationBuilder()
                .AddJsonFile("client-secrets.json", true)
                .AddEnvironmentVariables()
                .Build();
        }

        protected async Task<string> GenerateManagementApiToken()
        {
            var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));

            // Get the access token
            var token = await authenticationApiClient.GetTokenAsync(new ClientCredentialsTokenRequest
            {
                ClientId = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_SECRET"),
                Audience = GetVariable("AUTH0_MANAGEMENT_API_AUDIENCE")
            });

            return token.AccessToken;
        }

        protected string GetVariable(string variableName)
        {
            return _config[variableName];
        }
    }
}

using System;
using System.Threading.Tasks;
using Auth0.AuthenticationApi;
using Auth0.AuthenticationApi.Models;
using Microsoft.Extensions.Configuration;

namespace Auth0.Tests.Shared
{
    public class TestBase
    {
        private readonly IConfigurationRoot _config;

        public TestBase()
        {
            _config = new ConfigurationBuilder()
                .AddJsonFile("client-secrets.json", true)
                .AddEnvironmentVariables()
                .Build();
        }

        protected async Task<string> GenerateManagementApiToken()
        {
            var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));

            // Get the access token
            var token = await authenticationApiClient.GetTokenAsync(new ClientCredentialsTokenRequest
            {
                ClientId = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_SECRET"),
                Audience = GetVariable("AUTH0_MANAGEMENT_API_AUDIENCE")
            });

            return token.AccessToken;
        }

        protected string GetVariable(string variableName)
        {
            var value = _config[variableName];
            if (String.IsNullOrEmpty(value))
                throw new ArgumentOutOfRangeException($"Configuration value '{variableName}' has not been set.");
            return value;
        }
    }
}

Check configuration values are set in tests


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Quartz Software SRL">
//   Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
//   Implements the program class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace ConfigurationConsole
{
    using System.Runtime.Loader;
    using System.Threading.Tasks;

    using StartupConsole.Application;

    class Program
    {
        public static async Task Main(string[] args)
        {
            AssemblyLoadContext.Default.Resolving += (context, name) =>
                {
                    if (name.Name.EndsWith(".resources"))
                    {
                        return null;
                    }

                    return null;
                };

            await new ConsoleShell().BootstrapAsync(args);
        }
    }
}

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Quartz Software SRL">
//   Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
//   Implements the program class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace ConfigurationConsole
{
    using System.Runtime.Loader;
    using System.Threading.Tasks;

    using StartupConsole.Application;

    class Program
    {
        public static async Task Main(string[] args)
        {
            //AssemblyLoadContext.Default.Resolving += (context, name) =>
            //    {
            //        if (name.Name.EndsWith(".resources"))
            //        {
            //            return null;
            //        }

            //        return null;
            //    };

            await new ConsoleShell().BootstrapAsync(args);
        }
    }
}

Comment out the resource not found fix for .NET Core


using System;

namespace Satrabel.OpenContent.Components.TemplateHelpers
{
    public class Ratio
    {
        private readonly float _ratio;

        public int Width { get; private set; }
        public int Height { get; private set; }
        public float AsFloat
        {
            get { return (float)Width / (float)Height); }
        }

        public Ratio(string ratioString)
        {
            Width = 1;
            Height = 1;
            var elements = ratioString.ToLowerInvariant().Split('x');
            if (elements.Length == 2)
            {
                int leftPart;
                int rightPart;
                if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
                {
                    Width = leftPart;
                    Height = rightPart;
                }
            }
            _ratio = AsFloat;
        }
        public Ratio(int width, int height)
        {
            if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
            if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
            Width = width;
            Height = height;
            _ratio = AsFloat;
        }

        public void SetWidth(int newWidth)
        {
            Width = newWidth;
            Height = Convert.ToInt32(newWidth / _ratio);
        }
        public void SetHeight(int newHeight)
        {
            Width = Convert.ToInt32(newHeight * _ratio);
            Height = newHeight;
        }
    }
}

using System;

namespace Satrabel.OpenContent.Components.TemplateHelpers
{
    public class Ratio
    {
        private readonly float _ratio;

        public int Width { get; private set; }
        public int Height { get; private set; }
        public float AsFloat
        {
            get { return (float)Width / (float)Height; }
        }

        public Ratio(string ratioString)
        {
            Width = 1;
            Height = 1;
            var elements = ratioString.ToLowerInvariant().Split('x');
            if (elements.Length == 2)
            {
                int leftPart;
                int rightPart;
                if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
                {
                    Width = leftPart;
                    Height = rightPart;
                }
            }
            _ratio = AsFloat;
        }
        public Ratio(int width, int height)
        {
            if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
            if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
            Width = width;
            Height = height;
            _ratio = AsFloat;
        }

        public void SetWidth(int newWidth)
        {
            Width = newWidth;
            Height = Convert.ToInt32(newWidth / _ratio);
        }
        public void SetHeight(int newHeight)
        {
            Width = Convert.ToInt32(newHeight * _ratio);
            Height = newHeight;
        }
    }
}

Fix issue where ratio was always returning "1"


using System;
using TeaCommerce.Api.Dependency;
using TeaCommerce.Api.Infrastructure.Caching;
using Umbraco.Core;
using Umbraco.Core.Cache;

namespace TeaCommerce.Umbraco.Application.Caching
{
    [SuppressDependency("TeaCommerce.Api.Infrastructure.Caching.ICacheService", "TeaCommerce.Api")]
    public class UmbracoRuntimeCacheService : ICacheService
    {
        private IRuntimeCacheProvider _runtimeCache;

        public UmbracoRuntimeCacheService()
            : this(ApplicationContext.Current.ApplicationCache.RuntimeCache)
        { }

        public UmbracoRuntimeCacheService(IRuntimeCacheProvider runtimeCache)
        {
            _runtimeCache = runtimeCache;
        }

        public T GetCacheValue<T>(string cacheKey) where T : class
        {
            return (T)_runtimeCache.GetCacheItem($"TeaCommerce_{cacheKey}");
        }

        public void Invalidate(string cacheKey)
        {
            _runtimeCache.ClearCacheItem($"TeaCommerce_{cacheKey}");
        }

        public void SetCacheValue(string cacheKey, object cacheValue)
        {
            _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue);
        }

        public void SetCacheValue(string cacheKey, object cacheValue, TimeSpan cacheDuration)
        {
            _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue, cacheDuration);
        }
    }
}

using System;
using TeaCommerce.Api.Dependency;
using TeaCommerce.Api.Infrastructure.Caching;
using Umbraco.Core;
using Umbraco.Core.Cache;

namespace TeaCommerce.Umbraco.Application.Caching
{
    [SuppressDependency("TeaCommerce.Api.Infrastructure.Caching.ICacheService", "TeaCommerce.Api")]
    public class UmbracoRuntimeCacheService : ICacheService
    {
        private IRuntimeCacheProvider _runtimeCache;

        public UmbracoRuntimeCacheService()
            : this(ApplicationContext.Current.ApplicationCache.RuntimeCache)
        { }

        public UmbracoRuntimeCacheService(IRuntimeCacheProvider runtimeCache)
        {
            _runtimeCache = runtimeCache;
        }

        public T GetCacheValue<T>(string cacheKey) where T : class
        {
            return (T)_runtimeCache.GetCacheItem($"TeaCommerce_{cacheKey}");
        }

        public void Invalidate(string cacheKey)
        {
            _runtimeCache.ClearCacheItem($"TeaCommerce_{cacheKey}");
        }

        public void SetCacheValue(string cacheKey, object cacheValue)
        {
            _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue);
        }

        public void SetCacheValue(string cacheKey, object cacheValue, TimeSpan cacheDuration)
        {
            _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue, cacheDuration, true);
        }
    }
}

Enable sliding expiration by default as that is what the Tea Commerce cache does


public class StudentControllerTests
{
	[SetUp]
	public void Setup()
	{
		_fixture = new DatabaseFixture();
		_controller = new StudentController(new StudentRepository(_fixture.Context));
	}

	[Test]
	public void IndexAction_ShowsAllStudentsOrderedByName()
	{
		var expectedStudents = new List<Student>
		{
			new Student("Joe", "Bloggs"),
			new Student("Jane", "Smith")
		};
		expectedStudents.ForEach(_fixture.SeedContext.Students.Add)
		_fixture.SeedContext.SaveChanges();

		List<StudentViewModel> viewModel;
		_controller.Index()
			.ShouldRenderDefaultView()
			.WithModel<List<StudentViewModel>>(vm => viewModel = vm);

		viewModel.Select(s => s.Name).ShouldBe(
			_existingStudents.OrderBy(s => s.FullName).Select(s => s.FullName))
	}

	private StudentController _controller;
	private DatabaseFixture _fixture;
}

public class StudentControllerTests
{
	[SetUp]
	public void Setup()
	{
		_fixture = new DatabaseFixture();
		_controller = new StudentController(new StudentRepository(_fixture.Context));
	}

	[Test]
	public void IndexAction_ShowsAllStudentsOrderedByName()
	{
		var expectedStudents = new List<Student>
		{
			new Student("Joe", "Bloggs"),
			new Student("Jane", "Smith")
		};
		expectedStudents.ForEach(_fixture.SeedContext.Students.Add)
		_fixture.SeedContext.SaveChanges();

		List<StudentViewModel> viewModel;
		_controller.Index()
			.ShouldRenderDefaultView()
			.WithModel<List<StudentViewModel>>(vm => viewModel = vm);

		viewModel.Select(s => s.Name).ShouldBe(
			_existingStudents.OrderBy(s => s.FullName).Select(s => s.FullName));
	}

	private StudentController _controller;
	private DatabaseFixture _fixture;
}

Fix a missing semicolon in an example

Fix a missing semicolon in an example


using UnityEditor;
using UnityEngine;

namespace GoogleMobileAds.Editor
{

    [InitializeOnLoad]
    [CustomEditor(typeof(GoogleMobileAdsSettings))]
    public class GoogleMobileAdsSettingsEditor : UnityEditor.Editor
    {
        [MenuItem("Assets/Google Mobile Ads/Settings...")]
        public static void OpenInspector()
        {
            Selection.activeObject = GoogleMobileAdsSettings.Instance;

            if (GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit) {
                EditorGUILayout.HelpBox(
                        "Delays app measurement until you explicitly initialize the Mobile Ads SDK or load an ad.",
                        MessageType.Info);
            }

            EditorGUI.indentLevel--;
            EditorGUILayout.Separator();

            if (GUI.changed)
            {
                OnSettingsChanged();
            }
        }

        private void OnSettingsChanged()
        {
            EditorUtility.SetDirty((GoogleMobileAdsSettings) target);
            GoogleMobileAdsSettings.Instance.WriteSettingsToFile();
        }
    }
}

using UnityEditor;
using UnityEngine;

namespace GoogleMobileAds.Editor
{

    [InitializeOnLoad]
    [CustomEditor(typeof(GoogleMobileAdsSettings))]
    public class GoogleMobileAdsSettingsEditor : UnityEditor.Editor
    {
        [MenuItem("Assets/Google Mobile Ads/Settings...")]
        public static void OpenInspector()
        {
            Selection.activeObject = GoogleMobileAdsSettings.Instance;
        }

        public override void OnInspectorGUI()
        {
            EditorGUILayout.LabelField("Google Mobile Ads App ID", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;

            GoogleMobileAdsSettings.Instance.GoogleMobileAdsAndroidAppId =
                    EditorGUILayout.TextField("Android",
                            GoogleMobileAdsSettings.Instance.GoogleMobileAdsAndroidAppId);

            GoogleMobileAdsSettings.Instance.GoogleMobileAdsIOSAppId =
                    EditorGUILayout.TextField("iOS",
                            GoogleMobileAdsSettings.Instance.GoogleMobileAdsIOSAppId);

            EditorGUILayout.HelpBox(
                    "Google Mobile  Ads App ID will look similar to this sample ID: ca-app-pub-3940256099942544~3347511713",
                    MessageType.Info);

            EditorGUI.indentLevel--;
            EditorGUILayout.Separator();

            EditorGUILayout.LabelField("AdMob-specific settings", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;

            EditorGUI.BeginChangeCheck();

            GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit =
                    EditorGUILayout.Toggle(new GUIContent("Delay app measurement"),
                    GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit);

            if (GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit) {
                EditorGUILayout.HelpBox(
                        "Delays app measurement until you explicitly initialize the Mobile Ads SDK or load an ad.",
                        MessageType.Info);
            }

            EditorGUI.indentLevel--;
            EditorGUILayout.Separator();

            if (GUI.changed)
            {
                OnSettingsChanged();
            }
        }

        private void OnSettingsChanged()
        {
            EditorUtility.SetDirty((GoogleMobileAdsSettings) target);
            GoogleMobileAdsSettings.Instance.WriteSettingsToFile();
        }
    }
}

Fix erroneous removal of code

Fix erroneous removal of code

PiperOrigin-RevId: 350625811