using System;
using System.IO;
using DataTool.ToolLogic.List;
using Utf8Json;
using Utf8Json.Resolvers;
using static DataTool.Helper.IO;
using static DataTool.Helper.Logger;

namespace DataTool.JSON {
    public class JSONTool {
        internal void OutputJSON(object jObj, ListFlags toolFlags) {
            CompositeResolver.RegisterAndSetAsDefault(new IJsonFormatter[] {
                new ResourceGUIDFormatter()
            }, new[] {
                StandardResolver.Default
            });
            byte[] json = JsonSerializer.NonGeneric.Serialize(jObj.GetType(), jObj);
            if (!string.IsNullOrWhiteSpace(toolFlags.Output)) {
                byte[] pretty = JsonSerializer.PrettyPrintByteArray(json);

                Log("Writing to {0}", toolFlags.Output);

                CreateDirectoryFromFile(toolFlags.Output);

                using (Stream file = File.OpenWrite(toolFlags.Output)) {
                    file.SetLength(0);
                    file.Write(pretty, 0, pretty.Length);
                }
            } else {
                Console.Error.WriteLine(JsonSerializer.PrettyPrint(json));
            }
        }
    }
}

using System;
using System.IO;
using DataTool.ToolLogic.List;
using Utf8Json;
using Utf8Json.Resolvers;
using static DataTool.Helper.IO;
using static DataTool.Helper.Logger;

namespace DataTool.JSON {
    public class JSONTool {
        internal void OutputJSON(object jObj, ListFlags toolFlags) {
            CompositeResolver.RegisterAndSetAsDefault(new IJsonFormatter[] {
                new ResourceGUIDFormatter()
            }, new[] {
                StandardResolver.Default
            });
            byte[] json = JsonSerializer.NonGeneric.Serialize(jObj.GetType(), jObj);
            if (!string.IsNullOrWhiteSpace(toolFlags.Output)) {
                byte[] pretty = JsonSerializer.PrettyPrintByteArray(json);

                Log("Writing to {0}", toolFlags.Output);

                CreateDirectoryFromFile(toolFlags.Output);

                var fileName = !toolFlags.Output.EndsWith(".json") ? $"{toolFlags.Output}.json" : toolFlags.Output;

                using (Stream file = File.OpenWrite(fileName)) {
                    file.SetLength(0);
                    file.Write(pretty, 0, pretty.Length);
                }
            } else {
                Console.Error.WriteLine(JsonSerializer.PrettyPrint(json));
            }
        }
    }
}

Append .json to end of filename when outputting JSON


// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using System.Linq;
using NUnit.Framework;

namespace NodaTime.Test
{
    /// <summary>
    /// Tests for DateTimeZoneProviders.
    /// </summary>
    public class DateTimeZoneProvidersTest
    {
        [Test]
        public void TzdbProviderUsesTzdbSource()
        {
            Assert.IsTrue(DateTimeZoneProviders.Tzdb.VersionId.StartsWith("TZDB: "));
        }

        [Test]
        public void AllTzdbTimeZonesLoad()
        {
            var allZones = DateTimeZoneProviders.Tzdb.Ids.Select(id => DateTimeZoneProviders.Tzdb[id]).ToList();
            // Just to stop the variable from being lonely. In reality, it's likely there'll be a breakpoint here to inspect a particular zone...
            Assert.IsTrue(allZones.Count > 50);
        }

        [Test]
        public void BclProviderUsesTimeZoneInfoSource()
        {
            Assert.IsTrue(DateTimeZoneProviders.Bcl.VersionId.StartsWith("TimeZoneInfo: "));
        }
    }
}

// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using System.Linq;
using NodaTime.Testing.TimeZones;
using NodaTime.Xml;
using NUnit.Framework;

namespace NodaTime.Test
{
    /// <summary>
    /// Tests for DateTimeZoneProviders.
    /// </summary>
    public class DateTimeZoneProvidersTest
    {
        [Test]
        public void TzdbProviderUsesTzdbSource()
        {
            Assert.IsTrue(DateTimeZoneProviders.Tzdb.VersionId.StartsWith("TZDB: "));
        }

        [Test]
        public void AllTzdbTimeZonesLoad()
        {
            var allZones = DateTimeZoneProviders.Tzdb.Ids.Select(id => DateTimeZoneProviders.Tzdb[id]).ToList();
            // Just to stop the variable from being lonely. In reality, it's likely there'll be a breakpoint here to inspect a particular zone...
            Assert.IsTrue(allZones.Count > 50);
        }

        [Test]
        public void BclProviderUsesTimeZoneInfoSource()
        {
            Assert.IsTrue(DateTimeZoneProviders.Bcl.VersionId.StartsWith("TimeZoneInfo: "));
        }

        [Test]
        public void SerializationDelegatesToXmlSerializerSettings()
        {
            var original = XmlSerializationSettings.DateTimeZoneProvider;

            try
            {
#pragma warning disable CS0618 // Type or member is obsolete
                var provider1 = new FakeDateTimeZoneSource.Builder().Build().ToProvider();
                DateTimeZoneProviders.Serialization = provider1;
                Assert.AreSame(provider1, XmlSerializationSettings.DateTimeZoneProvider);

                var provider2 = new FakeDateTimeZoneSource.Builder().Build().ToProvider();
                XmlSerializationSettings.DateTimeZoneProvider = provider2;
                Assert.AreSame(provider2, DateTimeZoneProviders.Serialization);
#pragma warning restore CS0618 // Type or member is obsolete
            }
            finally
            {
                XmlSerializationSettings.DateTimeZoneProvider = original;
            }
        }
    }
}

Add test for delegation in obsolete property

(This keeps the coverage of DateTimeZoneProviders at 100% :)


using System;
using Newtonsoft.Json;

namespace ErgastApi.Responses.Models
{
    public class Driver
    {
        [JsonProperty("driverId")]
        public string DriverId { get; private set; }

        /// <summary>
        /// Drivers who participated in the 2014 season onwards have a permanent driver number.
        /// However, this may differ from the value of the number attribute of the Result element in earlier seasons
        /// or  where the reigning champion has chosen to use "1" rather than his permanent driver number.
        /// </summary>
        [JsonProperty("permanentNumber")]
        public int? PermanentNumber { get; private set; }

        [JsonProperty("code")]
        public string Code { get; private set; }

        [JsonProperty("url")]
        public string WikiUrl { get; private set; }

        public string FullName => $"{FirstName} {LastName}";

        [JsonProperty("givenName")]
        public string FirstName { get; private set; }

        [JsonProperty("familyName")]
        public string LastName { get; private set; }

        [JsonProperty("dateOfBirth")]
        public DateTime DateOfBirth { get; private set; }

        [JsonProperty("nationality")]
        public string Nationality { get; private set; }
    }
}

using System;
using Newtonsoft.Json;

namespace ErgastApi.Responses.Models
{
    public class Driver
    {
        [JsonProperty("driverId")]
        public string DriverId { get; private set; }

        /// <summary>
        /// Drivers who participated in the 2014 season onwards have a permanent driver number.
        /// However, this may differ from the value of the number attribute of the Result element in earlier seasons
        /// or  where the reigning champion has chosen to use "1" rather than his permanent driver number.
        /// </summary>
        [JsonProperty("permanentNumber")]
        public int? PermanentNumber { get; private set; }

        [JsonProperty("code")]
        public string Code { get; private set; }

        [JsonProperty("url")]
        public string WikiUrl { get; private set; }

        public string FullName => $"{FirstName} {LastName}";

        [JsonProperty("givenName")]
        public string FirstName { get; private set; }

        [JsonProperty("familyName")]
        public string LastName { get; private set; }

        [JsonProperty("dateOfBirth")]
        public DateTime? DateOfBirth { get; private set; }

        [JsonProperty("nationality")]
        public string Nationality { get; private set; }
    }
}

Support drivers without a date of birth

Support drivers without a date of birth


using System.Linq.Expressions;
using Remotion.Linq.Parsing.ExpressionTreeVisitors.Transformation;

namespace NHibernate.Linq.ExpressionTransformers
{
	/// <summary>
	/// Remove redundant casts to the same type or to superclass (upcast) in <see cref="ExpressionType.Convert"/>, <see cref=" ExpressionType.ConvertChecked"/>
	/// and <see cref="ExpressionType.TypeAs"/> <see cref="UnaryExpression"/>s
	/// </summary>
	public class RemoveRedundantCast : IExpressionTransformer<UnaryExpression>
	{
		private static readonly ExpressionType[] _supportedExpressionTypes = new[]
			{
				ExpressionType.TypeAs,
				ExpressionType.Convert,
				ExpressionType.ConvertChecked,
			};

		public Expression Transform(UnaryExpression expression)
		{
			if (expression.Type != typeof(object) &&
				expression.Type.IsAssignableFrom(expression.Operand.Type) &&
				expression.Method != null &&
				!expression.IsLiftedToNull)
			{
				return expression.Operand;
			}

			return expression;
		}

		public ExpressionType[] SupportedExpressionTypes
		{
			get { return _supportedExpressionTypes; }
		}
	}
}

using System.Linq.Expressions;
using Remotion.Linq.Parsing.ExpressionTreeVisitors.Transformation;

namespace NHibernate.Linq.ExpressionTransformers
{
	/// <summary>
	/// Remove redundant casts to the same type or to superclass (upcast) in <see cref="ExpressionType.Convert"/>, <see cref=" ExpressionType.ConvertChecked"/>
	/// and <see cref="ExpressionType.TypeAs"/> <see cref="UnaryExpression"/>s
	/// </summary>
	public class RemoveRedundantCast : IExpressionTransformer<UnaryExpression>
	{
		private static readonly ExpressionType[] _supportedExpressionTypes = new[]
			{
				ExpressionType.TypeAs,
				ExpressionType.Convert,
				ExpressionType.ConvertChecked,
			};

		public Expression Transform(UnaryExpression expression)
		{
			if (expression.Type != typeof(object) &&
				expression.Type.IsAssignableFrom(expression.Operand.Type) &&
				expression.Method == null &&
				!expression.IsLiftedToNull)
			{
				return expression.Operand;
			}

			return expression;
		}

		public ExpressionType[] SupportedExpressionTypes
		{
			get { return _supportedExpressionTypes; }
		}
	}
}

Fix typo in last commit

Fix typo in last commit


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

using System;
using Microsoft.Azure.WebJobs.ServiceBus;

namespace Microsoft.Azure.WebJobs.Script.Description
{
    public class EventHubBindingMetadata : BindingMetadata
    {
        [AllowNameResolution]
        public string Path { get; set; }

        public override void ApplyToConfig(JobHostConfigurationBuilder configBuilder)
        {
            if (configBuilder == null)
            {
                throw new ArgumentNullException("configBuilder");
            }
            EventHubConfiguration eventHubConfig = configBuilder.EventHubConfiguration;

            string connectionString = null;
            if (!string.IsNullOrEmpty(Connection))
            {
                connectionString = Utility.GetAppSettingOrEnvironmentValue(Connection);
            }

            if (this.IsTrigger)
            {
                string eventProcessorHostName = Guid.NewGuid().ToString();

                string storageConnectionString = configBuilder.Config.StorageConnectionString;

                var eventProcessorHost = new Microsoft.ServiceBus.Messaging.EventProcessorHost(
                     eventProcessorHostName,
                     this.Path,
                     Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName,
                     connectionString,
                     storageConnectionString);

                eventHubConfig.AddEventProcessorHost(this.Path, eventProcessorHost);
            }
            else
            {
                var client = Microsoft.ServiceBus.Messaging.EventHubClient.CreateFromConnectionString(
                    connectionString, this.Path);

                eventHubConfig.AddEventHubClient(this.Path, client);
            }
        }
    }
}

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

using System;
using Microsoft.Azure.WebJobs.ServiceBus;

namespace Microsoft.Azure.WebJobs.Script.Description
{
    public class EventHubBindingMetadata : BindingMetadata
    {
        [AllowNameResolution]
        public string Path { get; set; }

        // Optional Consumer group
        public string ConsumerGroup { get; set; }

        public override void ApplyToConfig(JobHostConfigurationBuilder configBuilder)
        {
            if (configBuilder == null)
            {
                throw new ArgumentNullException("configBuilder");
            }
            EventHubConfiguration eventHubConfig = configBuilder.EventHubConfiguration;

            string connectionString = null;
            if (!string.IsNullOrEmpty(Connection))
            {
                connectionString = Utility.GetAppSettingOrEnvironmentValue(Connection);
            }

            if (this.IsTrigger)
            {
                string eventProcessorHostName = Guid.NewGuid().ToString();

                string storageConnectionString = configBuilder.Config.StorageConnectionString;

                string consumerGroup = this.ConsumerGroup;
                if (consumerGroup == null)
                {
                    consumerGroup = Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName;
                }

                var eventProcessorHost = new Microsoft.ServiceBus.Messaging.EventProcessorHost(
                     eventProcessorHostName,
                     this.Path,
                     consumerGroup,
                     connectionString,
                     storageConnectionString);

                eventHubConfig.AddEventProcessorHost(this.Path, eventProcessorHost);
            }
            else
            {
                var client = Microsoft.ServiceBus.Messaging.EventHubClient.CreateFromConnectionString(
                    connectionString, this.Path);

                eventHubConfig.AddEventHubClient(this.Path, client);
            }
        }
    }
}

Support EventHub Consumer Groups in Script


using Topshelf;

namespace MiNET.Service
{
	public class MiNetService
	{
		private MiNetServer _server;

		private void Start()
		{
			_server = new MiNetServer();
			_server.StartServer();
		}

		private void Stop()
		{
			_server.StopServer();
		}

		private static void Main(string[] args)
		{
			HostFactory.Run(host =>
			{
				host.Service<MiNetService>(s =>
				{
					s.ConstructUsing(construct => new MiNetService());
					s.WhenStarted(service => service.Start());
					s.WhenStopped(service => service.Stop());
				});

				host.RunAsLocalService();
				host.SetDisplayName("MiNET Service");
				host.SetDescription("MiNET MineCraft Pocket Edition server.");
				host.SetServiceName("MiNET");
			});
		}
	}
}

using System;
using Topshelf;

namespace MiNET.Service
{
	public class MiNetService
	{
		private MiNetServer _server;

		private void Start()
		{
			_server = new MiNetServer();
			_server.StartServer();
		}

		private void Stop()
		{
			_server.StopServer();
		}

		private static void Main(string[] args)
		{
			if (IsRunningOnMono())
			{
				var service = new MiNetService();
				service.Start();
				Console.WriteLine("MiNET runing. Press <enter> to stop service..");
				Console.ReadLine();
				service.Stop();
			}

			HostFactory.Run(host =>
			{
				host.Service<MiNetService>(s =>
				{
					s.ConstructUsing(construct => new MiNetService());
					s.WhenStarted(service => service.Start());
					s.WhenStopped(service => service.Stop());
				});

				host.RunAsLocalService();
				host.SetDisplayName("MiNET Service");
				host.SetDescription("MiNET MineCraft Pocket Edition server.");
				host.SetServiceName("MiNET");
			});
		}

		public static bool IsRunningOnMono()
		{
			return Type.GetType("Mono.Runtime") != null;
		}
	}
}

Fix mono support on startup. Bypass TopShelf service framework.


using System.Text;

namespace Microsoft.Build.Logging.StructuredLogger
{
    public class StringWriter
    {
        public static string GetString(object rootNode)
        {
            var sb = new StringBuilder();

            WriteNode(rootNode, sb, 0);

            return sb.ToString();
        }

        private static void WriteNode(object rootNode, StringBuilder sb, int indent = 0)
        {
            Indent(sb, indent);
            var text = rootNode.ToString();

            // when we injest strings we normalize on \n to save space.
            // when the strings leave our app via clipboard, bring \r\n back so that notepad works
            text = text.Replace("\n", "\r\n");

            sb.AppendLine(text);

            var treeNode = rootNode as TreeNode;
            if (treeNode != null && treeNode.HasChildren)
            {
                if (treeNode.HasChildren)
                {
                    foreach (var child in treeNode.Children)
                    {
                        WriteNode(child, sb, indent + 1);
                    }
                }
            }
        }

        private static void Indent(StringBuilder sb, int indent)
        {
            for (int i = 0; i < indent * 4; i++)
            {
                sb.Append(' ');
            }
        }
    }
}

using System.Text;

namespace Microsoft.Build.Logging.StructuredLogger
{
    public class StringWriter
    {
        public static string GetString(object rootNode)
        {
            var sb = new StringBuilder();

            WriteNode(rootNode, sb, 0);

            return sb.ToString();
        }

        private static void WriteNode(object rootNode, StringBuilder sb, int indent = 0)
        {
            Indent(sb, indent);
            var text = rootNode.ToString() ?? "";

            // when we injest strings we normalize on \n to save space.
            // when the strings leave our app via clipboard, bring \r\n back so that notepad works
            text = text.Replace("\n", "\r\n");

            sb.AppendLine(text);

            var treeNode = rootNode as TreeNode;
            if (treeNode != null && treeNode.HasChildren)
            {
                if (treeNode.HasChildren)
                {
                    foreach (var child in treeNode.Children)
                    {
                        WriteNode(child, sb, indent + 1);
                    }
                }
            }
        }

        private static void Indent(StringBuilder sb, int indent)
        {
            for (int i = 0; i < indent * 4; i++)
            {
                sb.Append(' ');
            }
        }
    }
}

Fix NRE when copying nodes when the ToString() is null

This happens more or less randomly with the following exception:

System.NullReferenceException was unhandled
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=StructuredLogger
  StackTrace:
       at Microsoft.Build.Logging.StructuredLogger.StringWriter.WriteNode(Object rootNode, StringBuilder sb, Int32 indent) in C:\MSBuildStructuredLog\src\StructuredLogger\Serialization\StringWriter.cs:line 23
       at Microsoft.Build.Logging.StructuredLogger.StringWriter.WriteNode(Object rootNode, StringBuilder sb, Int32 indent) in C:\MSBuildStructuredLog\src\StructuredLogger\Serialization\StringWriter.cs:line 32
       at Microsoft.Build.Logging.StructuredLogger.StringWriter.WriteNode(Object rootNode, StringBuilder sb, Int32 indent) in C:\MSBuildStructuredLog\src\StructuredLogger\Serialization\StringWriter.cs:line 32
       at Microsoft.Build.Logging.StructuredLogger.StringWriter.WriteNode(Object rootNode, StringBuilder sb, Int32 indent) in C:\MSBuildStructuredLog\src\StructuredLogger\Serialization\StringWriter.cs:line 32
       at Microsoft.Build.Logging.StructuredLogger.StringWriter.WriteNode(Object rootNode, StringBuilder sb, Int32 indent) in C:\MSBuildStructuredLog\src\StructuredLogger\Serialization\StringWriter.cs:line 32
       at Microsoft.Build.Logging.StructuredLogger.StringWriter.WriteNode(Object rootNode, StringBuilder sb, Int32 indent) in C:\MSBuildStructuredLog\src\StructuredLogger\Serialization\StringWriter.cs:line 32
       at Microsoft.Build.Logging.StructuredLogger.StringWriter.WriteNode(Object rootNode, StringBuilder sb, Int32 indent) in C:\MSBuildStructuredLog\src\StructuredLogger\Serialization\StringWriter.cs:line 32
       at Microsoft.Build.Logging.StructuredLogger.StringWriter.GetString(Object rootNode) in C:\MSBuildStructuredLog\src\StructuredLogger\Serialization\StringWriter.cs:line 11
       at StructuredLogViewer.Controls.BuildControl.Copy()
       at StructuredLogViewer.Controls.BuildControl.TreeView_KeyDown(Object sender, KeyEventArgs args)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
       at System.Windows.Input.InputManager.ProcessStagingArea()
       at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
       at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
       at System.Windows.Interop.HwndKeyboardInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawKeyboardActions actions, Int32 scanCode, Boolean isExtendedKey, Boolean isSystemKey, Int32 virtualKey)
       at System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction(MSG& msg, Boolean& handled)
       at System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(MSG& msg, ModifierKeys modifiers)
       at System.Windows.Interop.HwndSource.OnPreprocessMessage(Object param)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
       at System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(MSG& msg, Boolean& handled)
       at System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at StructuredLogViewer.Entrypoint.Main(String[] args)
  InnerException:


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

using osuTK;
using osuTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Game.Skinning;

namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections
{
    /// <summary>
    /// A single follow point positioned between two adjacent <see cref="DrawableOsuHitObject"/>s.
    /// </summary>
    public class FollowPoint : Container, IAnimationTimeReference
    {
        private const float width = 8;

        public override bool RemoveWhenNotAlive => false;

        public FollowPoint()
        {
            Origin = Anchor.Centre;

            Child = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.FollowPoint), _ => new CircularContainer
            {
                Masking = true,
                AutoSizeAxes = Axes.Both,
                EdgeEffect = new EdgeEffectParameters
                {
                    Type = EdgeEffectType.Glow,
                    Colour = Color4.White.Opacity(0.2f),
                    Radius = 4,
                },
                Child = new Box
                {
                    Size = new Vector2(width),
                    Blending = BlendingParameters.Additive,
                    Origin = Anchor.Centre,
                    Anchor = Anchor.Centre,
                    Alpha = 0.5f,
                }
            }, confineMode: ConfineMode.NoScaling);
        }

        public double AnimationStartTime { get; set; }
    }
}

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

using osuTK;
using osuTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Game.Skinning;

namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections
{
    /// <summary>
    /// A single follow point positioned between two adjacent <see cref="DrawableOsuHitObject"/>s.
    /// </summary>
    public class FollowPoint : Container, IAnimationTimeReference
    {
        private const float width = 8;

        public override bool RemoveWhenNotAlive => false;

        public FollowPoint()
        {
            Origin = Anchor.Centre;

            Child = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.FollowPoint), _ => new CircularContainer
            {
                Masking = true,
                AutoSizeAxes = Axes.Both,
                EdgeEffect = new EdgeEffectParameters
                {
                    Type = EdgeEffectType.Glow,
                    Colour = Color4.White.Opacity(0.2f),
                    Radius = 4,
                },
                Child = new Box
                {
                    Size = new Vector2(width),
                    Blending = BlendingParameters.Additive,
                    Origin = Anchor.Centre,
                    Anchor = Anchor.Centre,
                    Alpha = 0.5f,
                }
            });
        }

        public double AnimationStartTime { get; set; }
    }
}

Remove stray default value specification


Hello @ViewData.Model.FirstName,

Thank you for signing up for Rambla! You have taken the first step towards expanding your rentability.

@{
    string URL = Url.Action("activateaccount", "Account", new RouteValueDictionary(new { id = ViewData.Model.ActivationId }), Request.Url.Scheme.ToString(), Request.Url.Host);
}

Please click here to activate your account.

Regards,

Rambla Team

@{
    string URL = Url.Action("activateaccount", "Account", new RouteValueDictionary(new { id = ViewData.Model.ActivationId }), Request.Url.Scheme.ToString(), Request.Url.Host);
}

Hi @ViewData.Model.FirstName,

Welcome to Rambla, a marketplace that facilitates sharing of items between you and your community members. We're excited to have you as a member and can't wait to see what you have to share.

As a new member, here are a few suggestions to get you started with Rambla:

        Dig out that hammer drill that you do not need right now or that snowboard that you do not use too often and post it on Rambla. In fact, any unused item in your house can be of use to someone belonging to your community.

        Need a sleeping bag for your annual camping trip or an outdoor patio heater for your Christmas party? Search for it on Rambla There is always someone who has an item you are looking for and is willing to share it with you.

        Help your fellow community members find your stuff by using big images, writing thoughtful descriptions and addressing their queries promptly. You might just get rewarded for your exceptional conduct with a small gift from us. :-)

To get started with your Rambla experience, please click here to activate your account.

Thanks for joining and happy sharing!

- The Rambla Team

Update verbiage on user registration email


using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.BraceCompletion;
using Microsoft.VisualStudio.Utilities;

namespace DanTup.DartVS
{
	[Export(typeof(IBraceCompletionDefaultProvider))]
	[ContentType(DartContentTypeDefinition.DartContentType)]
	[BracePair('{', '}')]
	class BraceCompletionProvider : IBraceCompletionDefaultProvider
	{
	}
}

using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.BraceCompletion;
using Microsoft.VisualStudio.Utilities;

namespace DanTup.DartVS
{
	[Export(typeof(IBraceCompletionDefaultProvider))]
	[ContentType(DartContentTypeDefinition.DartContentType)]
	[BracePair('{', '}')]
	[BracePair('(', ')')]
	[BracePair('[', ']')]
	class BraceCompletionProvider : IBraceCompletionDefaultProvider
	{
	}
}

Support completion of parens and indexes too.


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

using System;
using osu.Game.Graphics;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Mods
{
    public abstract class ModSuddenDeath : Mod, IApplicableToScoreProcessor
    {
        public override string Name => "Sudden Death";
        public override string ShortenedName => "SD";
        public override FontAwesome Icon => FontAwesome.fa_osu_mod_suddendeath;
        public override ModType Type => ModType.DifficultyIncrease;
        public override string Description => "Miss a note and fail.";
        public override double ScoreMultiplier => 1;
        public override bool Ranked => true;
        public override Type[] IncompatibleMods => new[] { typeof(ModNoFail), typeof(ModRelax), typeof(ModAutoplay) };

        public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor)
        {
            scoreProcessor.FailConditions += FailCondition;
        }

        protected virtual bool FailCondition(ScoreProcessor scoreProcessor) => scoreProcessor.Combo.Value != scoreProcessor.HighestCombo.Value;
    }
}

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

using System;
using osu.Game.Graphics;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Mods
{
    public abstract class ModSuddenDeath : Mod, IApplicableToScoreProcessor
    {
        public override string Name => "Sudden Death";
        public override string ShortenedName => "SD";
        public override FontAwesome Icon => FontAwesome.fa_osu_mod_suddendeath;
        public override ModType Type => ModType.DifficultyIncrease;
        public override string Description => "Miss a note and fail.";
        public override double ScoreMultiplier => 1;
        public override bool Ranked => true;
        public override Type[] IncompatibleMods => new[] { typeof(ModNoFail), typeof(ModRelax), typeof(ModAutoplay) };

        public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor)
        {
            scoreProcessor.FailConditions += FailCondition;
        }

        protected virtual bool FailCondition(ScoreProcessor scoreProcessor) => scoreProcessor.Combo.Value == 0;
    }
}

Fix SD not failing for the first note

Fix SD not failing for the first note


using System;
using System.Collections.Generic;

namespace LessMsi.Cli
{
	internal class ShowHelpCommand : LessMsiCommand
	{
		public override void Run(List<string> args)
		{
			ShowHelp("");
		}

		public static void ShowHelp(string errorMessage)
		{
			string helpString =
				@"Usage:
lessmsi <command> [options] <msi_name> [<path_to_extract\>] [file_names]

Commands:
  x  Extracts all or specified files from the specified msi_name.
  l  Lists the contents of the specified msi table as CSV to stdout.
  v  Lists the value of the ProductVersion Property in the msi
     (typically this is the version of the MSI).
  o  Opens the specified msi_name in the GUI.
  h  Shows this help page.

For more information see http://lessmsi.activescott.com
";
			if (!string.IsNullOrEmpty(errorMessage))
			{
				helpString = "\r\nError: " + errorMessage + "\r\n\r\n" + helpString;
			}
			Console.WriteLine(helpString);
		}
	}
}

using System;
using System.Collections.Generic;

namespace LessMsi.Cli
{
	internal class ShowHelpCommand : LessMsiCommand
	{
		public override void Run(List<string> args)
		{
			ShowHelp("");
		}

		public static void ShowHelp(string errorMessage)
		{
			string helpString =
				@"Usage:
lessmsi <command> [options] <msi_name> [<path_to_extract\>] [file_names]

Commands:
  x  Extracts all or specified files from the specified msi_name.
  l  Lists the contents of the specified msi table as CSV to stdout. Table is
     specified with -t switch. Example: lessmsi l -t Component c:\foo.msi
  v  Lists the value of the ProductVersion Property in the msi
     (typically this is the version of the MSI).
  o  Opens the specified msi_name in the GUI.
  h  Shows this help page.

For more information see http://lessmsi.activescott.com
";
			if (!string.IsNullOrEmpty(errorMessage))
			{
				helpString = "\r\nError: " + errorMessage + "\r\n\r\n" + helpString;
			}
			Console.WriteLine(helpString);
		}
	}
}

Add help for -t switch

Add help for -t switch


using CefSharp;

namespace TweetDck.Core.Handling{
    class ContextMenuNotification : ContextMenuBase{
        public override void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model){
            model.Clear();

            base.OnBeforeContextMenu(browserControl,browser,frame,parameters,model);
            RemoveSeparatorIfLast(model);
        }

        public override bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags){
            return false;
        }
    }
}

using CefSharp;

namespace TweetDck.Core.Handling{
    class ContextMenuNotification : ContextMenuBase{
        public override void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model){
            model.Clear();

            base.OnBeforeContextMenu(browserControl,browser,frame,parameters,model);
            RemoveSeparatorIfLast(model);
        }
    }
}

Fix context menu not running any actions in notification Form


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("MonoGameUtils")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MonoGameUtils")]
[assembly: AssemblyCopyright("")]
[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("4ecedc75-1f2d-4915-9efe-368a5d104e41")]

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

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MonoGameUtils")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MonoGameUtils")]
[assembly: AssemblyCopyright("")]
[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("4ecedc75-1f2d-4915-9efe-368a5d104e41")]

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

Increment version number for new build.

Increment version number for new build.


using UnityEngine;

namespace Pear.InteractionEngine.Interactions
{
	/// <summary>
	/// Copies interactions from the current object to the supplied objects
	/// </summary>
	public class CopyInteractions: MonoBehaviour
	{
		[Tooltip("Objects that interactions will be copied to")]
		public GameObject[] CopyTo;

		private void Awake()
		{
			if (CopyTo != null)
			{
				//Copy alkl interactions from the current object to the specified object
				foreach (GameObject copyTo in CopyTo)
					Interaction.CopyAll(gameObject, copyTo);
			}
		}
	}
}

using UnityEngine;

namespace Pear.InteractionEngine.Interactions
{
	/// <summary>
	/// Copies interactions from the current object to the supplied objects
	/// </summary>
	public class CopyInteractions: MonoBehaviour
	{
		[Tooltip("Objects that interactions will be copied to")]
		public GameObject[] CopyTo;

		[Tooltip("Objects that the interactions will be copied from")]
		public GameObject[] CopyFrom;

		private void Awake()
		{
			if (CopyTo != null)
			{
				// Copy all interactions from the current object to the specified object
				foreach (GameObject copyTo in CopyTo)
					Interaction.CopyAll(gameObject, copyTo);
			}

			if(CopyFrom != null)
			{
				// Copy all interactions from the specified objects to this game object
				foreach (GameObject copyFrom in CopyFrom)
					Interaction.CopyAll(copyFrom, gameObject);
			}
		}
	}
}

Copy interactions from the given object

Copy interactions from the given object


@model WebEditor.Models.Create

@{
    ViewBag.Title = "New Game";
}

@section scripts {

}

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true, "Unable to create game. Please correct the errors below.")

            @Html.LabelFor(m => m.GameName)

            @Html.TextBoxFor(m => m.GameName, new { style = "width: 300px" })
            @Html.ValidationMessageFor(m => m.GameName)

            @Html.LabelFor(m => m.SelectedType)

            @Html.DropDownListFor(m => m.SelectedType, new SelectList(Model.AllTypes, Model.SelectedType))
            @Html.ValidationMessageFor(m => m.SelectedType)

            @Html.LabelFor(m => m.SelectedTemplate)

            @Html.DropDownListFor(m => m.SelectedTemplate, new SelectList(Model.AllTemplates, Model.SelectedTemplate))
            @Html.ValidationMessageFor(m => m.SelectedTemplate)

            <button id="submit-button" type="submit">Create</button>

}

@model WebEditor.Models.Create

@{
    ViewBag.Title = "New Game";
}

@section scripts {

}

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true, "Unable to create game. Please correct the errors below.")

            @Html.LabelFor(m => m.GameName):

            @Html.TextBoxFor(m => m.GameName, new { style = "width: 300px" })
            @Html.ValidationMessageFor(m => m.GameName)

                @Html.LabelFor(m => m.SelectedType):

                @Html.DropDownListFor(m => m.SelectedType, new SelectList(Model.AllTypes, Model.SelectedType))
                @Html.ValidationMessageFor(m => m.SelectedType)

            @Html.LabelFor(m => m.SelectedTemplate):

            @Html.DropDownListFor(m => m.SelectedTemplate, new SelectList(Model.AllTemplates, Model.SelectedTemplate))
            @Html.ValidationMessageFor(m => m.SelectedTemplate)

            <button id="submit-button" type="submit">Create</button>

}

Hide game type for now

Hide game type for now


using System.Net.Mail;

namespace StressMeasurementSystem.Models
{
    public class Patient
    {
        #region Structs

        public struct Name
        {
            public string Prefix { get; set; }
            public string First { get; set; }
            public string Middle { get; set; }
            public string Last { get; set; }
            public string Suffix { get; set; }
        }

        public struct Organization
        {
            public string Company { get; set; }
            public string JobTitle { get; set; }
        }

        public struct PhoneNumber
        {
            public enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other}

            public string Number { get; set; }
            public Type T { get; set; }
        }

        public struct Email
        {
            public enum Type {Home, Work, Other}

            public MailAddress Address { get; set; }
            public Type T { get; set; }
        }

        #endregion

        #region Fields

        private Name _name;
        private uint _age;
        private Organization _organization;
        private PhoneNumber _phoneNumber;
        private Email _email;

        #endregion

        #region Constructors

        public Patient(Name name, uint age, Organization organization, PhoneNumber phoneNumber, Email email)
        {
            _name = name;
            _age = age;
            _organization = organization;
            _phoneNumber = phoneNumber;
            _email = email;
        }

        #endregion
    }
}

using System.Collections.Generic;
using System.Net.Mail;

namespace StressMeasurementSystem.Models
{
    public class Patient
    {
        #region Structs

        public struct Name
        {
            public string Prefix { get; set; }
            public string First { get; set; }
            public string Middle { get; set; }
            public string Last { get; set; }
            public string Suffix { get; set; }
        }

        public struct Organization
        {
            public string Company { get; set; }
            public string JobTitle { get; set; }
        }

        public struct PhoneNumber
        {
            public enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other}

            public string Number { get; set; }
            public Type T { get; set; }
        }

        public struct Email
        {
            public enum Type {Home, Work, Other}

            public MailAddress Address { get; set; }
            public Type T { get; set; }
        }

        #endregion

        #region Fields

        private Name _name;
        private uint _age;
        private Organization _organization;
        private List<PhoneNumber> _phoneNumbers;
        private List<Email> _emails;

        #endregion

        #region Constructors

        public Patient(Name name, uint age, Organization organization,
            List<PhoneNumber> phoneNumbers, List<Email> emails)
        {
            _name = name;
            _age = age;
            _organization = organization;
            _phoneNumbers = phoneNumbers;
            _emails = emails;
        }

        #endregion
    }
}

Allow for multiple phone numbers and email addresses


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

namespace Leeroy
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		static void Main()
		{
			ServiceBase[] ServicesToRun;
			ServicesToRun = new ServiceBase[]
			{
				new Service()
			};
			ServiceBase.Run(ServicesToRun);
		}
	}
}

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

namespace Leeroy
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		static void Main(string[] args)
		{
			if (args.FirstOrDefault() == "/test")
			{
				Overseer overseer = new Overseer(new CancellationTokenSource().Token, "BradleyGrainger", "Configuration", "master");
				overseer.Run(null);
			}
			else
			{
				ServiceBase.Run(new ServiceBase[] { new Service() });
			}
		}
	}
}

Allow debugging without running as a service.

Pass the "/test" command-line argument to run the program as a simple console app.


Order: 10
Description: Tutorials to get you up and running quickly
RedirectFrom:
  - docs/overview
  - docs/overview/features
---

@Html.Partial("_ChildPages")

Order: 10
Description: Tutorials to get you up and running quickly
RedirectFrom:
  - docs/overview
  - docs/overview/features
---

        See also Community Resources for a lot of helpful courses, videos, presentations and blog posts which can help you get started with Cake.

@Html.Partial("_ChildPages")

Add link to resources to Getting Started guide


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("TextMatch")]
[assembly: AssemblyDescription("A library for matching texts with Lucene query expressions")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TextMatch")]
[assembly: AssemblyCopyright("Copyright ©  2015 Cris Almodovar")]
[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("2fe43f0a-b8c0-4de3-b2d5-6fc207385f7c")]

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

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TextMatch")]
[assembly: AssemblyDescription("A library for matching texts with Lucene query expressions")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TextMatch")]
[assembly: AssemblyCopyright("Copyright ©  2015 Cris Almodovar")]
[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("2fe43f0a-b8c0-4de3-b2d5-6fc207385f7c")]

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

Change version number to 0.6.5

Change version number to 0.6.5


/* Copyright  2018 Jeremy Herbison

This file is part of AudioWorks.

AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public
License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
version.

AudioWorks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.

You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see
<https://www.gnu.org/licenses/>. */

using System;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using JetBrains.Annotations;

namespace AudioWorks.Commands.Tests
{
    [UsedImplicitly]
    public sealed class ModuleFixture : IDisposable
    {
        const string _moduleProject = "AudioWorks.Commands";

        [NotNull]
        internal Runspace Runspace { get; }

        public ModuleFixture()
        {
            var state = InitialSessionState.CreateDefault();

            // This bypasses the execution policy (InitialSessionState.ExecutionPolicy isn't available with PowerShell 5)
            state.AuthorizationManager = new AuthorizationManager("Microsoft.PowerShell");

            state.ImportPSModule(
                Path.Combine(new DirectoryInfo(Directory.GetCurrentDirectory()).FullName, _moduleProject));

            Runspace = RunspaceFactory.CreateRunspace(state);
            Runspace.Open();
        }

        public void Dispose()
        {
            Runspace.Close();
        }
    }
}

/* Copyright  2018 Jeremy Herbison

This file is part of AudioWorks.

AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public
License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
version.

AudioWorks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.

You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see
<https://www.gnu.org/licenses/>. */

using System;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using JetBrains.Annotations;

namespace AudioWorks.Commands.Tests
{
    [UsedImplicitly]
    public sealed class ModuleFixture : IDisposable
    {
        const string _moduleProject = "AudioWorks.Commands";

        [NotNull]
        internal Runspace Runspace { get; }

        public ModuleFixture()
        {
            var state = InitialSessionState.CreateDefault();

            // This bypasses the execution policy (InitialSessionState.ExecutionPolicy isn't available with PowerShell 5)
            state.AuthorizationManager = new AuthorizationManager("Microsoft.PowerShell");

            state.ImportPSModule(new[]
            {
                Path.Combine(new DirectoryInfo(Directory.GetCurrentDirectory()).FullName, _moduleProject)
            });

            Runspace = RunspaceFactory.CreateRunspace(state);
            Runspace.Open();
        }

        public void Dispose()
        {
            Runspace.Close();
        }
    }
}

Revert change that broke tests on Windows PowerShell.


using Xunit.Abstractions;

namespace Cascara.Tests
{
    public abstract class CascaraTestFramework
    {
        public CascaraTestFramework(ITestOutputHelper output)
        {
            Output = output;
        }

        protected ITestOutputHelper Output
        {
            get;
        }
    }
}

using System;
using System.Xml.Linq;
using Xunit.Abstractions;

namespace Cascara.Tests
{
    public abstract class CascaraTestFramework
    {
        protected static string BuildXmlElement(string name, params Tuple<string, string>[] attrs)
        {
            return BuildXmlElement(name, "", attrs);
        }

        protected static string BuildXmlElement(string name, string innerData, params Tuple<string, string>[] attrs)
        {
            string attrString = "";
            foreach (Tuple<string, string> t in attrs)
            {
                attrString += string.Format(" {0}='{1}'", t.Item1, t.Item2);
            }

            return string.Format("<{0}{1}>{2}</{0}>", name, attrString, innerData);
        }

        protected static XElement ParseXmlElement(string data)
        {
            XDocument doc = XDocument.Parse(data, LoadOptions.SetLineInfo);

            return doc.Root;
        }

        public CascaraTestFramework(ITestOutputHelper output)
        {
            Output = output;
        }

        protected ITestOutputHelper Output
        {
            get;
        }
    }
}

Add static methods for building XML data strings


using System.ComponentModel;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace DesktopWidgets.Classes
{
    [ExpandableObject]
    [DisplayName("Intro Settings")]
    public class IntroData
    {
        [DisplayName("Duration")]
        public int Duration { get; set; } = -1;

        [DisplayName("Reversable")]
        public bool Reversable { get; set; } = false;

        [DisplayName("Activate")]
        public bool Activate { get; set; } = false;

        [DisplayName("Stay Open")]
        public bool HideOnFinish { get; set; } = true;

        [DisplayName("Execute Finish Action")]
        public bool ExecuteFinishAction { get; set; } = true;
    }
}

using System.ComponentModel;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace DesktopWidgets.Classes
{
    [ExpandableObject]
    [DisplayName("Intro Settings")]
    public class IntroData
    {
        [DisplayName("Duration")]
        public int Duration { get; set; } = -1;

        [DisplayName("Reversable")]
        public bool Reversable { get; set; } = false;

        [DisplayName("Activate")]
        public bool Activate { get; set; } = false;

        [DisplayName("Hide On Finish")]
        public bool HideOnFinish { get; set; } = true;

        [DisplayName("Execute Finish Action")]
        public bool ExecuteFinishAction { get; set; } = true;
    }
}

Fix intro settings "Hide On Finish" option name


using IO = System.IO;

namespace dokas.EncodingConverter.Logic
{
    internal sealed class FileData
    {
        public string Path { get; private set; }
        public string Name { get; private set; }
        public string Extension { get; private set; }

        public FileData(string path)
        {
            Path = path;
            Name = IO.Path.GetFileName(path);
            Extension = IO.Path.GetExtension(path);
        }
    }
}

using System;
using IO = System.IO;

namespace dokas.EncodingConverter.Logic
{
    internal sealed class FileData
    {
        public string Path { get; private set; }
        public string Name { get; private set; }
        public string Extension { get; private set; }

        public FileData(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            Path = path;
            Name = IO.Path.GetFileName(path);
            Extension = IO.Path.GetExtension(path);
        }

        public override bool Equals(object obj)
        {
            var otherFileData = obj as FileData;
            return otherFileData != null && Path.Equals(otherFileData.Path);
        }

        public override int GetHashCode()
        {
            return Path.GetHashCode();
        }
    }
}

Implement Equals/GetHashCode to comply with Distinct


@model Kooboo.CMS.Sites.ABTest.ABPageSetting
@using Kooboo.CMS.Sites.ABTest;
@{
    ViewBag.Title = "Edit A/B page setting";
    Layout = "~/Views/Shared/Blank.cshtml";
}
@section Panel{

                @Html.IconImage("save") @("Save".Localize())

                @Html.IconImage("cancel") @("Back".Localize())

}

@ViewBag.Title

    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)

                @Html.DisplayFor(o => o.RuleName)
                @Html.HiddenFor(o => o.RuleName)
                @Html.DisplayFor(o => o.MainPage)
                @Html.EditorFor(o => o.Items)
                @Html.EditorFor(o => o.ABTestGoalPage, new { HtmlAttributes = new { @class = "medium" } })

    }

@model Kooboo.CMS.Sites.ABTest.ABPageSetting
@using Kooboo.CMS.Sites.ABTest;
@{
    ViewBag.Title = "Edit A/B page setting";
    Layout = "~/Views/Shared/Blank.cshtml";
}
@section Panel{

                @Html.IconImage("save") @("Save".Localize())

                @Html.IconImage("cancel") @("Back".Localize())

}

@ViewBag.Title

    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)

                @Html.EditorFor(o => o.RuleName)
                @Html.DisplayFor(o => o.MainPage)
                @Html.EditorFor(o => o.Items)
                @Html.EditorFor(o => o.ABTestGoalPage, new { HtmlAttributes = new { @class = "medium" } })

    }

Make available to change the rule when editing A/B page setting.


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

using System;

namespace MsgPack.Rpc
{
	internal sealed class ExceptionModifiers
	{
		public static readonly ExceptionModifiers IsMatrioshkaInner = new ExceptionModifiers();
		private ExceptionModifiers() { }
	}
}

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

using System;

namespace MsgPack.Rpc
{
	internal static class ExceptionModifiers
	{
		public static readonly object IsMatrioshkaInner = String.Intern( typeof( ExceptionModifiers ).FullName + ".IsMatrioshkaInner" );
	}
}

Fix that the flag prevents serialization.


#region Copyright © 2014 Ricardo Amaral

/*
 * Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
 */

#endregion

using CefSharp;

namespace SlackUI {

    internal class BrowserRequestHandler : IRequestHandler {

        #region Public Methods

        public bool GetAuthCredentials(IWebBrowser browser, bool isProxy, string host, int port, string realm,
            string scheme, ref string username, ref string password) {
            // Let the Chromium web browser handle the event
            return false;
        }

        public ResourceHandler GetResourceHandler(IWebBrowser browser, IRequest request) {
            // Let the Chromium web browser handle the event
            return null;
        }

        public bool OnBeforeBrowse(IWebBrowser browser, IRequest request, bool isRedirect) {
            // Disable browser forward/back navigation with keyboard keys
            if(request.TransitionType == (TransitionType.Explicit | TransitionType.ForwardBack)) {
                return true;
            }

            // Let the Chromium web browser handle the event
            return false;
        }

        public bool OnBeforePluginLoad(IWebBrowser browser, string url, string policyUrl, IWebPluginInfo info) {
            // Let the Chromium web browser handle the event
            return false;
        }

        public bool OnBeforeResourceLoad(IWebBrowser browser, IRequest request, IResponse response) {
            // Let the Chromium web browser handle the event
            return false;
        }

        public void OnPluginCrashed(IWebBrowser browser, string pluginPath) {
            // No implementation required
        }

        public void OnRenderProcessTerminated(IWebBrowser browser, CefTerminationStatus status) {
            // No implementation required
        }

        #endregion

    }

}

#region Copyright © 2014 Ricardo Amaral

/*
 * Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
 */

#endregion

using CefSharp;

namespace SlackUI {

    internal class BrowserRequestHandler : IRequestHandler {

        #region Public Methods

        public bool GetAuthCredentials(IWebBrowser browser, bool isProxy, string host, int port, string realm,
            string scheme, ref string username, ref string password) {
            // Let the Chromium web browser handle the event
            return false;
        }

        public ResourceHandler GetResourceHandler(IWebBrowser browser, IRequest request) {
            // Let the Chromium web browser handle the event
            return null;
        }

        public bool OnBeforeBrowse(IWebBrowser browser, IRequest request, bool isRedirect) {
            // Disable browser forward/back navigation with keyboard keys
            if((request.TransitionType & TransitionType.ForwardBack) != 0) {
                return true;
            }

            // Let the Chromium web browser handle the event
            return false;
        }

        public bool OnBeforePluginLoad(IWebBrowser browser, string url, string policyUrl, IWebPluginInfo info) {
            // Let the Chromium web browser handle the event
            return false;
        }

        public bool OnBeforeResourceLoad(IWebBrowser browser, IRequest request, IResponse response) {
            // Let the Chromium web browser handle the event
            return false;
        }

        public void OnPluginCrashed(IWebBrowser browser, string pluginPath) {
            // No implementation required
        }

        public void OnRenderProcessTerminated(IWebBrowser browser, CefTerminationStatus status) {
            // No implementation required
        }

        #endregion

    }

}

Cover ALL forward/back navigation cases

Cover ALL forward/back navigation cases


using System;
using System.Collections.Generic;
using System.Net.Mail;

namespace StressMeasurementSystem.Models
{
    public class Patient
    {
        #region Structs

        public struct Name
        {
            public string Prefix { get; set; }
            public string First { get; set; }
            public string Middle { get; set; }
            public string Last { get; set; }
            public string Suffix { get; set; }
        }

        public struct Organization
        {
            public string Company { get; set; }
            public string JobTitle { get; set; }
        }

        public struct PhoneNumber
        {
            public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other }

            public string Number { get; set; }
            public Type T { get; set; }
        }

        public struct Email
        {
            public enum Type { Home, Work, Other }

            public MailAddress Address { get; set; }
            public Type T { get; set; }
        }

        #endregion

        #region Fields

        private Name? _name;
        private DateTime _dateOfBirth;
        private Organization? _organization;
        private List<PhoneNumber> _phoneNumbers;
        private List<Email> _emails;

        #endregion

        #region Constructors

        public Patient(Name? name, DateTime dateOfBirth, Organization? organization,
            List<PhoneNumber> phoneNumbers, List<Email> emails)
        {
            _name = name;
            _dateOfBirth = dateOfBirth;
            _organization = organization;
            _phoneNumbers = phoneNumbers;
            _emails = emails;
        }

        #endregion
    }
}

using System;
using System.Collections.Generic;
using System.Net.Mail;

namespace StressMeasurementSystem.Models
{
    public class Patient
    {
        #region Structs

        public struct Name
        {
            public string Prefix { get; set; }
            public string First { get; set; }
            public string Middle { get; set; }
            public string Last { get; set; }
            public string Suffix { get; set; }
        }

        public struct Organization
        {
            public string Company { get; set; }
            public string JobTitle { get; set; }
        }

        public struct PhoneNumber
        {
            public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other }

            public string Number { get; set; }
            public Type T { get; set; }
        }

        public struct EmailAddress
        {
            public enum Type { Home, Work, Other }

            public MailAddress Address { get; set; }
            public Type T { get; set; }
        }

        #endregion

        #region Fields

        private Name? _name;
        private DateTime _dateOfBirth;
        private Organization? _organization;
        private List<PhoneNumber> _phoneNumbers;
        private List<EmailAddress> _emailAddresses;

        #endregion

        #region Constructors

        public Patient(Name? name, DateTime dateOfBirth, Organization? organization,
            List<PhoneNumber> phoneNumbers, List<EmailAddress> emailAddresses)
        {
            _name = name;
            _dateOfBirth = dateOfBirth;
            _organization = organization;
            _phoneNumbers = phoneNumbers;
            _emailAddresses = emailAddresses;
        }

        #endregion
    }
}

Rename Email struct as EmailAddress; refactor as appropriate


using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("StripeTests")]

using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Newtonsoft.Json")]
[assembly: InternalsVisibleTo("StripeTests")]

Make internals visible to Newtonsoft.Json


using Dolstagis.Web;
using Dolstagis.Web.Sessions;

namespace WebApp
{
    public class HomeModule : Module
    {
        public HomeModule()
        {
            Services.For<ISessionStore>().Singleton().Use<InMemorySessionStore>();

            AddStaticFiles("~/content");
            AddViews("~/views");
            AddViews("~/errors");
            AddHandler<Index>();
        }
    }
}

using Dolstagis.Web;
using Dolstagis.Web.Sessions;

namespace WebApp
{
    public class HomeModule : Module
    {
        public HomeModule()
        {
            Services.For<ISessionStore>().Singleton().Use<InMemorySessionStore>();

            AddStaticFiles("~/content");
            AddViews("~/views");
            // Uncomment the following line to use custom error messages.
            // AddViews("~/errors");
            AddHandler<Index>();
        }
    }
}

Use default error messages in demo app.

Use default error messages in demo app.


using System;
using System.Linq.Expressions;
using Xunit;

namespace DelegateDecompiler.Tests
{
    public class EnumTests : DecompilerTestsBase
    {
        public enum TestEnum
        {
            Foo,
            Bar
        }

        [Fact]
        public void TestEnumParameterEqualsEnumConstant()
        {
            Expression<Func<TestEnum, bool>> expected = x => x == TestEnum.Bar;
            Func<TestEnum, bool> compiled = x => x == TestEnum.Bar;
            Test(expected, compiled);
        }

        [Fact]
        public void TestEnumConstantEqualsEnumParameter()
        {
            Expression<Func<TestEnum, bool>> expected = x => TestEnum.Bar == x;
            Func<TestEnum, bool> compiled = x => TestEnum.Bar == x;
            Test(expected, compiled);
        }
    }
}

using System;
using System.Linq.Expressions;
using Xunit;

namespace DelegateDecompiler.Tests
{
    public class EnumTests : DecompilerTestsBase
    {
        public enum TestEnum
        {
            Foo,
            Bar
        }

        [Fact]
        public void TestEnumParameterEqualsEnumConstant()
        {
            Expression<Func<TestEnum, bool>> expected = x => x == TestEnum.Bar;
            Func<TestEnum, bool> compiled = x => x == TestEnum.Bar;
            Test(expected, compiled);
        }

        [Fact]
        public void TestEnumConstantEqualsEnumParameter()
        {
            Expression<Func<TestEnum, bool>> expected = x => TestEnum.Bar == x;
            Func<TestEnum, bool> compiled = x => TestEnum.Bar == x;
            Test(expected, compiled);
        }

        [Fact]
        public void TestEnumParametersEqual()
        {
            Expression<Func<TestEnum, TestEnum, bool>> expected = (x, y) => x == y;
            Func<TestEnum, TestEnum, bool> compiled = (x, y) => x == y;
            Test(expected, compiled);
        }

        [Fact(Skip = "Needs optimization")]
        public void TestEnumParameterNotEqualsEnumConstant()
        {
            Expression<Func<TestEnum, bool>> expected = x => x != TestEnum.Bar;
            Func<TestEnum, bool> compiled = x => x != TestEnum.Bar;
            Test(expected, compiled);
        }

        [Fact(Skip = "Needs optimization")]
        public void TestEnumConstantNotEqualsEnumParameter()
        {
            Expression<Func<TestEnum, bool>> expected = x => TestEnum.Bar != x;
            Func<TestEnum, bool> compiled = x => TestEnum.Bar != x;
            Test(expected, compiled);
        }

        [Fact(Skip = "Needs optimization")]
        public void TestEnumParametersNotEqual()
        {
            Expression<Func<TestEnum, TestEnum, bool>> expected = (x, y) => x != y;
            Func<TestEnum, TestEnum, bool> compiled = (x, y) => x != y;
            Test(expected, compiled);
        }
    }
}

Add more tests for enums

Add more tests for enums


using Ardalis.GuardClauses;
using System;
using Xunit;

namespace GuardClauses.UnitTests
{
    public class GuardAgainsOutOfRange
    {
        [Fact]
        public void DoesNothingGivenInRangeValueUsingShortcutMethod()
        {
            Guard.AgainsOutOfRange(2, "index", 1, 5);
        }

        [Fact]
        public void DoesNothingGivenInRangeValueUsingExtensionMethod()
        {
            Guard.Against.OutOfRange(2, "index", 1, 5);
        }

        [Fact]
        public void ThrowsGivenOutOfRangeValueUsingShortcutMethod()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => Guard.AgainsOutOfRange(5, "index", 1, 4));
        }

        [Fact]
        public void ThrowsGivenOutOfRangeValueUsingExtensionMethod()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => Guard.Against.OutOfRange(5, "index", 1, 4));
        }
    }
}

using Ardalis.GuardClauses;
using System;
using Xunit;

namespace GuardClauses.UnitTests
{
    public class GuardAgainsOutOfRange
    {
        [Theory]
        [InlineData(1, 1, 5)]
        [InlineData(2, 1, 5)]
        [InlineData(3, 1, 5)]
        public void DoesNothingGivenInRangeValueUsingShortcutMethod(int input, int rangeFrom, int rangeTo)
        {
            Guard.AgainsOutOfRange(input, "index", rangeFrom, rangeTo);
        }

        [Theory]
        [InlineData(1, 1, 5)]
        [InlineData(2, 1, 5)]
        [InlineData(3, 1, 5)]
        public void DoesNothingGivenInRangeValueUsingExtensionMethod(int input, int rangeFrom, int rangeTo)
        {
            Guard.Against.OutOfRange(input, "index", rangeFrom, rangeTo);
        }

        [Theory]
        [InlineData(-1, 1, 5)]
        [InlineData(0, 1, 5)]
        [InlineData(6, 1, 5)]
        public void ThrowsGivenOutOfRangeValueUsingShortcutMethod(int input, int rangeFrom, int rangeTo)
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => Guard.AgainsOutOfRange(input, "index", rangeFrom, rangeTo));
        }

        [Theory]
        [InlineData(-1, 1, 5)]
        [InlineData(0, 1, 5)]
        [InlineData(6, 1, 5)]
        public void ThrowsGivenOutOfRangeValueUsingExtensionMethod(int input, int rangeFrom, int rangeTo)
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => Guard.Against.OutOfRange(input, "index", rangeFrom, rangeTo));
        }
    }
}

Improve tests with theory test cases

Improve tests with theory test cases


namespace Nancy.Owin.Tests
{
    using System;

    using global::Owin;

    using Microsoft.Owin.Testing;

    using Nancy.Testing;

    using Xunit;

    public class AppBuilderExtensionsFixture
    {
        /*[Fact]
        public void When_host_Nancy_via_IAppBuilder_then_should_handle_requests()
        {
            // Given
            var bootstrapper = new ConfigurableBootstrapper(config => config.Module<TestModule>());

            using(var server = TestServer.Create(app => app.UseNancy(opts => opts.Bootstrapper = bootstrapper)))
            {

                // When
                var response = server.HttpClient.GetAsync(new Uri("http://localhost/")).Result;

                // Then
                Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.OK);
            }
        }*/

        public class TestModule : NancyModule
        {
            public TestModule()
            {
                Get["/"] = _ => HttpStatusCode.OK;
            }
        }
    }
}

namespace Nancy.Owin.Tests
{
    using System;

    using global::Owin;

    using Microsoft.Owin.Testing;

    using Nancy.Testing;

    using Xunit;

    public class AppBuilderExtensionsFixture
    {
#if !__MonoCS__
        [Fact]
        public void When_host_Nancy_via_IAppBuilder_then_should_handle_requests()
        {
            // Given
            var bootstrapper = new ConfigurableBootstrapper(config => config.Module<TestModule>());

            using(var server = TestServer.Create(app => app.UseNancy(opts => opts.Bootstrapper = bootstrapper)))
            {

                // When
                var response = server.HttpClient.GetAsync(new Uri("http://localhost/")).Result;

                // Then
                Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.OK);
            }
        }
#endif

        public class TestModule : NancyModule
        {
            public TestModule()
            {
                Get["/"] = _ => HttpStatusCode.OK;
            }
        }
    }
}

Exclude AppBuilder test from running on Mono.


using System;
using System.Configuration;

namespace librato4net
{
    public class AppSettingsLibratoSettings : ILibratoSettings
    {
        // ReSharper disable once InconsistentNaming
        private static readonly AppSettingsLibratoSettings settings = new AppSettingsLibratoSettings();

        private const string DefaultApiEndPoint = "https://metrics-api.librato.com/v1/";

        public static AppSettingsLibratoSettings Settings
        {
            get { return settings; }
        }

        public string Username
        {
            get { return ConfigurationManager.AppSettings["Librato.Username"]; }
        }

        public string ApiKey
        {
            get { return ConfigurationManager.AppSettings["Librato.ApiKey"]; }
        }

        public Uri ApiEndpoint
        {
            get { return new Uri(ConfigurationManager.AppSettings["Librato.ApiEndpoint"] ?? DefaultApiEndPoint); }
        }

        public TimeSpan SendInterval
        {
            get { return TimeSpan.Parse(ConfigurationManager.AppSettings["Librato.SendInterval"] ?? "00:00:05"); }
        }
    }
}

using System;
using System.Configuration;

namespace librato4net
{
    public class AppSettingsLibratoSettings : ILibratoSettings
    {
        // ReSharper disable once InconsistentNaming
        private static readonly AppSettingsLibratoSettings settings = new AppSettingsLibratoSettings();

        private const string DefaultApiEndPoint = "https://metrics-api.librato.com/v1/";

        public static AppSettingsLibratoSettings Settings
        {
            get { return settings; }
        }

        public string Username
        {
            get
            {
                var username = ConfigurationManager.AppSettings["Librato.Username"];

                if (string.IsNullOrEmpty(username))
                {
                    throw new ConfigurationErrorsException("Librato.Username is required and cannot be empty");
                }

                return username;
            }
        }

        public string ApiKey
        {
            get
            {
                var apiKey = ConfigurationManager.AppSettings["Librato.ApiKey"];

                if (string.IsNullOrEmpty(apiKey))
                {
                    throw new ConfigurationErrorsException("Librato.ApiKey is required and cannot be empty");
                }

                return apiKey;
            }
        }

        public Uri ApiEndpoint
        {
            get { return new Uri(ConfigurationManager.AppSettings["Librato.ApiEndpoint"] ?? DefaultApiEndPoint); }
        }

        public TimeSpan SendInterval
        {
            get { return TimeSpan.Parse(ConfigurationManager.AppSettings["Librato.SendInterval"] ?? "00:00:05"); }
        }
    }
}

Validate Username and ApiKey from appSettings.


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 Width / 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"


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

namespace System.Diagnostics
{
    /// <summary>Provides a set of static methods for working with Exceptions.</summary>
    internal static class ExceptionHelpers
    {
        public static TException InitializeStackTrace<TException>(this TException e) where TException : Exception
        {
            Debug.Assert(e != null);
            Debug.Assert(e.StackTrace == null);

            try { throw e; }
            catch { return e; }
        }
    }
}

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

namespace System.Diagnostics
{
    /// <summary>Provides a set of static methods for working with Exceptions.</summary>
    internal static class ExceptionHelpers
    {
        public static TException InitializeStackTrace<TException>(this TException e) where TException : Exception
        {
            Debug.Assert(e != null);

            // Ideally we'd be able to populate e.StackTrace with the current stack trace.
            // We could throw the exception and catch it, but the populated StackTrace would
            // not extend beyond this frame.  Instead, we grab a stack trace and store it into
            // the exception's data dictionary, at least making the info available for debugging,
            // albeit not part of the string returned by e.ToString() or e.StackTrace.
            e.Data["StackTrace"] = Environment.StackTrace;

            return e;
        }
    }
}

Change InitializeStackTrace helper to store trace in Data

My previous attempt to get a better stack trace in exceptions was insufficient.  I was throwing/catching the exception to initialize the StackTrace, but I neglected the fact that the stack trace is filled in as the exception propagates, and so throwing/catching in the same frame means that the stack trace just stores that one frame, which isn't helpful.  Instead, this changes the helper to store the stack trace obtained via Environment.StackTrace into the Exception's Data dictionary.  This means the exception doesn't show up in a e.ToString() or e.StackTrace rendering, but it's at least stored for debugging purposes.


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

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

        // Add/Remove Users

        // Backup SQLite Db

        // Scrub Soldier Data

        private readonly Database db;

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

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

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

            var mimeType = "application/octet-stream";

            return File(data, mimeType);
        }

        public IActionResult Logs()
        {
            byte[] data;

            using (var stream = new FileStream($@"logs\{DateTime.Today:yyyyMMdd}.log"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (var reader = new StreamReader(stream))
            {
                data = System.Text.Encoding.Default.GetBytes(reader.ReadToEnd());
            }

            return File(data, "text/plain");
        }
    }
}

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

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

        // Add/Remove Users

        // Backup SQLite Db

        // Scrub Soldier Data

        private readonly Database db;

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

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

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

            var mimeType = "application/octet-stream";

            return File(data, mimeType);
        }

        public IActionResult Logs()
        {
            byte[] data;

            using (var stream = new FileStream($@"logs\{DateTime.Today:yyyyMMdd}.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (var reader = new StreamReader(stream))
            {
                data = System.Text.Encoding.Default.GetBytes(reader.ReadToEnd());
            }

            return File(data, "text/plain");
        }
    }
}

Fix imports on admin logs

Fix imports on admin logs


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

using System.Collections.Generic;

namespace osu.Game.Audio
{
    public class SampleInfoList : List<SampleInfo>
    {
        public SampleInfoList()
        {
        }

        public SampleInfoList(IEnumerable<SampleInfo> elements)
        {
            AddRange(elements);
        }
    }
}

Use CRLF instead of LF.

Use CRLF instead of LF.


@model Portal.CMS.Web.Areas.Builder.ViewModels.Build.CustomViewModel
@{
    ViewBag.Title = "Error";
    Layout = "";
}

<!DOCTYPE html>

    <title>Portal CMS: @ViewBag.Title</title>

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />

    @RenderSection("Styles", false)
    @Styles.Render("~/Resources/CSS/Bootstrap")
    @Styles.Render("~/Resources/CSS/FontAwesome")
    @Styles.Render("~/Resources/CSS/Framework")

    @RenderSection("HEADScripts", false)

Portal CMS

    @RenderBody()

    @RenderSection("DOMScripts", false)
    @Scripts.Render("~/Resources/JavaScript/Bootstrap")
    @Scripts.Render("~/Resources/JavaScript/Bootstrap/Confirmation")
    @Scripts.Render("~/Resources/JavaScript/Bootstrap/Modal")
    @Scripts.Render("~/Resources/JavaScript/Framework/Global")

@model Portal.CMS.Web.Areas.Builder.ViewModels.Build.CustomViewModel
@{
    ViewBag.Title = "Error";
    Layout = "";
}

<!DOCTYPE html>

    <title>Portal CMS: @ViewBag.Title</title>

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />

    @RenderSection("Styles", false)
    @Styles.Render("~/Resources/CSS/Bootstrap")
    @Styles.Render("~/Resources/CSS/FontAwesome")
    @Styles.Render("~/Resources/CSS/Framework")

    @Scripts.Render("~/Resources/JavaScript/JQuery")
    @Scripts.Render("~/Resources/JavaScript/JQueryUI")
    @RenderSection("HEADScripts", false)
    @Html.Partial("_Analytics")

Portal CMS

    @Html.Partial("_NavBar")
    @RenderBody()
    @Html.Partial("_DOMScripts")
    @RenderSection("DOMScripts", false)

Update Error Layout to Standardise Against Standard Layout


using UnityEngine;
using System.Collections;

public class BackToMenu : MonoBehaviour {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		if(Input.GetKeyDown(KeyCode.Escape)){
			Application.LoadLevel(0);
			GameObject GUI;
			GUI = GameObject.Find("GUISYSTEM");
			Destroy(GUI);
		}
	}
}

using UnityEngine;
using System.Collections;

public class BackToMenu : MonoBehaviour {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		if(Input.GetKeyDown(KeyCode.Escape)){
			Application.LoadLevel(0);
			GameObject guiSys;
			guiSys = GameObject.Find("GUISYSTEM");
			Destroy(guiSys);
			GameObject networkC;
			networkC = GameObject.Find("NetworkController");
			Destroy(networkC);
		}
	}
}

Destroy NetworkController when going back to menu


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

using System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.Utils;

namespace Microsoft.NET.TestFramework.Commands
{
    public class MSBuildTest
    {
        public static readonly MSBuildTest Stage0MSBuild = new MSBuildTest(RepoInfo.DotNetHostPath);

        private string DotNetHostPath { get; }

        public MSBuildTest(string dotNetHostPath)
        {
            DotNetHostPath = dotNetHostPath;
        }

        public ICommand CreateCommandForTarget(string target, params string[] args)
        {
            var newArgs = args.ToList();
            newArgs.Insert(0, $"/t:{target}");

            return CreateCommand(newArgs.ToArray());
        }

        private ICommand CreateCommand(params string[] args)
        {
            var newArgs = args.ToList();
            newArgs.Insert(0, $"msbuild");

            ICommand command = Command.Create(DotNetHostPath, newArgs);

            //  Set NUGET_PACKAGES environment variable to match value from build.ps1
            command = command.EnvironmentVariable("NUGET_PACKAGES", RepoInfo.PackagesPath);

            return command;
        }
    }
}

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

using System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.Utils;

namespace Microsoft.NET.TestFramework.Commands
{
    public class MSBuildTest
    {
        public static readonly MSBuildTest Stage0MSBuild = new MSBuildTest(RepoInfo.DotNetHostPath);

        private string DotNetHostPath { get; }

        public MSBuildTest(string dotNetHostPath)
        {
            DotNetHostPath = dotNetHostPath;
        }

        public ICommand CreateCommandForTarget(string target, params string[] args)
        {
            var newArgs = args.ToList();
            newArgs.Insert(0, $"/t:{target}");

            return CreateCommand(newArgs.ToArray());
        }

        private ICommand CreateCommand(params string[] args)
        {
            var newArgs = args.ToList();
            newArgs.Insert(0, $"msbuild");

            ICommand command = Command.Create(DotNetHostPath, newArgs);

            //  Set NUGET_PACKAGES environment variable to match value from build.ps1
            command = command.EnvironmentVariable("NUGET_PACKAGES", Path.Combine(RepoInfo.RepoRoot, "packages"));

            return command;
        }
    }
}

Fix NUGET_PACKAGES folder when running tests.

RepoInfo.PackagesPath is actually the output path for the .nupkg, and is configuration-specific.  NUGET_PACKAGES should just be the packages folder under the repo root.


using System;
using System.Threading;

namespace GitHub.Unity
{
    class GitCommitTask : ProcessTask<string>
    {
        private const string TaskName = "git commit";
        private readonly string arguments;

        public GitCommitTask(string message, string body,
            CancellationToken token, IOutputProcessor<string> processor = null)
            : base(token, processor ?? new SimpleOutputProcessor())
        {
            Guard.ArgumentNotNullOrWhiteSpace(message, "message");

            Name = TaskName;
            arguments = "commit ";
            arguments += String.Format(" -m \"{0}", message);
            if (!String.IsNullOrEmpty(body))
                arguments += String.Format("{0}{1}", Environment.NewLine, body);
            arguments += "\"";
        }

        public override string ProcessArguments { get { return arguments; } }
        public override TaskAffinity Affinity { get { return TaskAffinity.Exclusive; } }
    }
}

using System;
using System.Threading;

namespace GitHub.Unity
{
    class GitCommitTask : ProcessTask<string>
    {
        private const string TaskName = "git commit";
        private readonly string arguments;

        public GitCommitTask(string message, string body,
            CancellationToken token, IOutputProcessor<string> processor = null)
            : base(token, processor ?? new SimpleOutputProcessor())
        {
            Guard.ArgumentNotNullOrWhiteSpace(message, "message");

            Name = TaskName;
            arguments = "commit ";
            arguments += String.Format(" -m \"{0}\"", message);
            if (!String.IsNullOrEmpty(body))
                arguments += String.Format(" -m \"{0}\"", body);
        }

        public override string ProcessArguments { get { return arguments; } }
        public override TaskAffinity Affinity { get { return TaskAffinity.Exclusive; } }
    }
}

Split the commit message into the subject line and the body


using System;
using System.Collections.Generic;

namespace Hangman {
  public class Row {
    public Cell[] Cells;

    public Row(Cell[] cells) {
      Cells = cells;
    }

    public string Draw(int width) {
      // return new String(' ', width - Text.Length) + Text;
      return String.Join("\n", Lines());
    }

    private string[] Lines() {
      var lines = new List<string>();
      for (var i = 0; i < MaxCellDepth(); i++) {
        var line = LineAtIndex(i);
        lines.Add(String.Join("", line));
      }
      return lines.ToArray();
    }

    private string LineAtIndex(int index) {
      var line = new List<string>();
      int usedSpace = 0;
      foreach (var cell in Cells) {
        var part = cell.LineAtIndex(index);

        line.Add(part);
        usedSpace += part.Length;
      }
      return String.Join("", line);
    }

    private int MaxCellDepth() {
      int max = 0;
      foreach (var cell in Cells) {
        max = Math.Max(max, cell.Depth());
      }
      return max;
    }
  }
}

using System;
using System.Collections.Generic;

namespace Hangman {
  public class Row {
    public Cell[] Cells;
    private int Width;

    public Row(Cell[] cells) {
      Cells = cells;
    }

    public string Draw(int width) {
      // return new String(' ', width - Text.Length) + Text;
      Width = width;
      return String.Join("\n", Lines());
    }

    private string[] Lines() {
      var lines = new List<string>();
      for (var i = 0; i < MaxCellDepth(); i++) {
        var line = LineAtIndex(i);
        lines.Add(String.Join("", line));
      }
      return lines.ToArray();
    }

    private string LineAtIndex(int index) {
      var line = new List<string>();
      int usedSpace = 0;
      foreach (var cell in Cells) {
        var part = cell.LineAtIndex(index);
        var spacing = SpacingFor(cell);
        line.Add(spacing + part);
        usedSpace += part.Length;
      }
      return String.Join("", line);
    }

    private string SpacingFor(Cell cell) {
      return new String(' ', 4);
    }

    private int MaxCellDepth() {
      int max = 0;
      foreach (var cell in Cells) {
        max = Math.Max(max, cell.Depth());
      }
      return max;
    }
  }
}

Add dynamic left margin for line parts

Add dynamic left margin for line parts


// Copyright ©2017 Simonray (http://github.com/simonray). All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using ExchangeRate.Model;
using System.Net;
using System.Text.RegularExpressions;

namespace ExchangeRate.Providers
{
    /// <exclude />
    public class GoogleProvider : BaseProvider
    {
        /// <exclude />
        const string URL = "http://www.google.com/finance/converter?a=1&from={0}&to={1}";

        /// <exclude />
        public override string Name { get { return "Google"; } }

        /// <exclude />
        public override Rate Fetch(Pair pair)
        {
            string url = pair.Construct(URL);
            var data = new GZipWebClient().DownloadString(url);

            var result = Regex.Matches(data, "([^<]+)")[0].Groups[1].Value;
            if (result == null)
                ThrowFormatChanged();

            var value = Regex.Match(result, @"[0-9]*(?:\.[0-9]+)?");
            if (value == null)
                ThrowFormatChanged();

            return new Rate(double.Parse(value.Value));
        }
    }
}

// Copyright ©2017 Simonray (http://github.com/simonray). All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using ExchangeRate.Model;
using System.Net;
using System.Text.RegularExpressions;

namespace ExchangeRate.Providers
{
    /// <exclude />
    public class GoogleProvider : BaseProvider
    {
        /// <exclude />
        const string URL = "http://finance.google.com/finance/converter?a=1&from={0}&to={1}";

        /// <exclude />
        public override string Name { get { return "Google"; } }

        /// <exclude />
        public override Rate Fetch(Pair pair)
        {
            string url = pair.Construct(URL);
            var data = new GZipWebClient().DownloadString(url);

            var result = Regex.Matches(data, "([^<]+)")[0].Groups[1].Value;
            if (result == null)
                ThrowFormatChanged();

            var value = Regex.Match(result, @"[0-9]*(?:\.[0-9]+)?");
            if (value == null)
                ThrowFormatChanged();

            return new Rate(double.Parse(value.Value));
        }
    }
}

Update changes to Google finance url

Update changes to Google finance url