using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti;
using System;
using System.Threading.Tasks;

namespace SO115App.SignalR.Sender.GestioneUtenti
{
    public class NotificationDeleteUtente : INotifyDeleteUtente
    {
        private readonly IHubContext<NotificationHub> _notificationHubContext;
        private readonly IGetUtenteByCF _getUtenteByCF;

        public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
        {
            _notificationHubContext = notificationHubContext;
            _getUtenteByCF = getUtenteByCF;
        }

        public async Task Notify(DeleteUtenteCommand command)
        {
            var utente = _getUtenteByCF.Get(command.CodFiscale);
            await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
            await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
            await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id);
        }
    }
}

using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti;
using System;
using System.Threading.Tasks;

namespace SO115App.SignalR.Sender.GestioneUtenti
{
    public class NotificationDeleteUtente : INotifyDeleteUtente
    {
        private readonly IHubContext<NotificationHub> _notificationHubContext;
        private readonly IGetUtenteByCF _getUtenteByCF;

        public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
        {
            _notificationHubContext = notificationHubContext;
            _getUtenteByCF = getUtenteByCF;
        }

        public async Task Notify(DeleteUtenteCommand command)
        {
            var utente = _getUtenteByCF.Get(command.CodFiscale);
            //await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
            //await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
            await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id);
        }
    }
}

Fix - Modificata notifica delete utente

Fix - Modificata notifica delete utente


// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Wangkanai.Detection.Hosting
{
    public class ResponsivePageLocationExpander : IViewLocationExpander
    {
        private const string ValueKey = "device";

        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {
            context.Values.TryGetValue(ValueKey, out var device);

            if (!(context.ActionContext.ActionDescriptor is PageActionDescriptor))
                return viewLocations;

            if (string.IsNullOrEmpty(context.PageName) || string.IsNullOrEmpty(device))
                return viewLocations;

            var expandLocations = ExpandPageHierarchy().ToList();
            return expandLocations;

            IEnumerable<string> ExpandPageHierarchy()
            {
                foreach (var location in viewLocations)
                {
                    if (!location.Contains("/{1}/") && !location.Contains("/Shared/") || location.Contains("/Views/"))
                    {
                        yield return location;
                        continue;
                    }

                    yield return location.Replace("{0}", "{0}." + device);
                    yield return location;
                }
            }
        }

        public void PopulateValues(ViewLocationExpanderContext context)
        {
            context.Values[ValueKey] = context.ActionContext.HttpContext.GetDevice().ToString().ToLower();
        }
    }
}

// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Wangkanai.Detection.Hosting
{
    public class ResponsivePageLocationExpander : IViewLocationExpander
    {
        private const string ValueKey = "device";

        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {
            context.Values.TryGetValue(ValueKey, out var device);

            if (!(context.ActionContext.ActionDescriptor is PageActionDescriptor))
                return viewLocations;

            if (string.IsNullOrEmpty(context.PageName) || string.IsNullOrEmpty(device))
                return viewLocations;

            var expandLocations = ExpandPageHierarchy().ToList();
            return expandLocations;

            IEnumerable<string> ExpandPageHierarchy()
            {
                foreach (var location in viewLocations)
                {
                    if (!location.Contains("/{1}/") && !location.Contains("/Shared/") || location.Contains("/Views/"))
                    {
                        yield return location;
                        continue;
                    }

                    // Device View if exist on disk
                    yield return location.Replace("{0}", "{0}." + device);
                    // Fallback to the original default view
                    yield return location;
                }
            }
        }

        public void PopulateValues(ViewLocationExpanderContext context)
        {
            context.Values[ValueKey] = context.ActionContext.HttpContext.GetDevice().ToString().ToLower();
        }
    }
}

Add explanation of why having 2 yield return


namespace BatteryCommander.Web
{
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Hosting;
    using Serilog;
    using Serilog.Core;

    public class Program
    {
        public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);

        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder
                        .UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369")
                        .UseStartup<Startup>();
                })
                .ConfigureLogging((context, builder) =>
                {
                    Log.Logger =
                           new LoggerConfiguration()
                           .Enrich.FromLogContext()
                           .Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName)
                           .Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
                           .Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}")
                           .WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), compact: true, controlLevelSwitch: LogLevel)
                           .MinimumLevel.ControlledBy(LogLevel)
                           .CreateLogger();

                    builder.AddSerilog();
                });
    }
}

namespace BatteryCommander.Web
{
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Hosting;
    using Serilog;
    using Serilog.Core;

    public class Program
    {
        public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);

        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder
                        .UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369")
                        .UseStartup<Startup>();
                })
                .ConfigureLogging((context, builder) =>
                {
                    Log.Logger =
                           new LoggerConfiguration()
                           .Enrich.FromLogContext()
                           .Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName)
                           .Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
                           .Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}")
                           .WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), controlLevelSwitch: LogLevel)
                           .MinimumLevel.ControlledBy(LogLevel)
                           .CreateLogger();

                    builder.AddSerilog();
                });
    }
}

Remove Seq compact flag, default now

Remove Seq compact flag, default now


using System;
using System.Data;
using System.Text.Json;
using Dapper;

namespace Dommel.Json
{
    internal class JsonObjectTypeHandler : SqlMapper.ITypeHandler
    {
        private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions
        {
            AllowTrailingCommas = true,
            ReadCommentHandling = JsonCommentHandling.Skip,
        };

        public void SetValue(IDbDataParameter parameter, object? value)
        {
            parameter.Value = value is null || value is DBNull
                ? (object)DBNull.Value
                : JsonSerializer.Serialize(value, JsonOptions);
            parameter.DbType = DbType.String;
        }

        public object? Parse(Type destinationType, object? value) =>
            value is string str ? JsonSerializer.Deserialize(str, destinationType, JsonOptions) : null;
    }
}

using System;
using System.Data;
using System.Text.Json;
using System.Text.Json.Serialization;
using Dapper;

namespace Dommel.Json
{
    internal class JsonObjectTypeHandler : SqlMapper.ITypeHandler
    {
        private static readonly JsonSerializerOptions JsonOptions = new()
        {
            AllowTrailingCommas = true,
            ReadCommentHandling = JsonCommentHandling.Skip,
            NumberHandling = JsonNumberHandling.AllowReadingFromString,
        };

        public void SetValue(IDbDataParameter parameter, object? value)
        {
            parameter.Value = value is null || value is DBNull
                ? DBNull.Value
                : JsonSerializer.Serialize(value, JsonOptions);
            parameter.DbType = DbType.String;
        }

        public object? Parse(Type destinationType, object? value) =>
            value is string str ? JsonSerializer.Deserialize(str, destinationType, JsonOptions) : null;
    }
}

Allow reading numbers from strings in JSON


using System.Text;

namespace TweetDck.Plugins{
    static class PluginScriptGenerator{
        public static string GenerateConfig(PluginConfig config){
            return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"",config.DisabledPlugins)+"\"];" : string.Empty;
        }

        public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
            StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150);

            build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");

            build.Append("let tmp={");
            build.Append("id:\"").Append(pluginIdentifier).Append("\",");
            build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
            build.Append("});");

            build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
            build.Append("window.TD_PLUGINS.install(tmp);");

            build.Append("})(").Append(environment.GetScriptVariables()).Append(");");

            return build.ToString();
        }
    }
}

using System.Text;

namespace TweetDck.Plugins{
    static class PluginScriptGenerator{
        public static string GenerateConfig(PluginConfig config){
            return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"",config.DisabledPlugins)+"\"];" : string.Empty;
        }

        public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
            StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150);

            build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");

            build.Append("let tmp={");
            build.Append("id:\"").Append(pluginIdentifier).Append("\",");
            build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
            build.Append("};");

            build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
            build.Append("window.TD_PLUGINS.install(tmp);");

            build.Append("})(").Append(environment.GetScriptVariables()).Append(");");

            return build.ToString();
        }
    }
}

Fix plugin script generator causing JS syntax error


using FreecraftCore.Serializer.KnownTypes;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FreecraftCore.Serializer.Tests
{
	[TestFixture]
	public class StringTests
	{
		[Test]
		public static void Test_String_Serializer_Serializes()
		{
			//arrange
			SerializerService serializer = new SerializerService();
			serializer.Compile();

			//act
			string value = serializer.Deserialize<string>(serializer.Serialize("Hello!"));

			//assert
			Assert.AreEqual(value, "Hello!");
		}
	}
}

using FreecraftCore.Serializer.KnownTypes;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FreecraftCore.Serializer.Tests
{
	[TestFixture]
	public class StringTests
	{
		[Test]
		public static void Test_String_Serializer_Serializes()
		{
			//arrange
			SerializerService serializer = new SerializerService();
			serializer.Compile();

			//act
			string value = serializer.Deserialize<string>(serializer.Serialize("Hello!"));

			//assert
			Assert.AreEqual(value, "Hello!");
		}

		[Test]
		public static void Test_String_Serializer_Can_Serialize_Empty_String()
		{
			//arrange
			SerializerService serializer = new SerializerService();
			serializer.Compile();

			//act
			string value = serializer.Deserialize<string>(serializer.Serialize(""));

			//assert
			Assert.Null(value);
		}
	}
}

Add empty to null check

Add empty to null check


using System;
using System.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;

namespace AudioWorks.Extensions
{
    abstract class ExtensionContainerBase
    {
        static readonly DirectoryInfo _extensionRoot = new DirectoryInfo(Path.Combine(
            Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) ?? string.Empty,
            "Extensions"));

        protected static CompositionHost CompositionHost { get; } = new ContainerConfiguration()
            .WithAssemblies(_extensionRoot
                .EnumerateFiles("AudioWorks.Extensions.*.dll", SearchOption.AllDirectories)
                .Select(f => f.FullName)
                .Select(Assembly.LoadFrom))
            .CreateContainer();

        static ExtensionContainerBase()
        {
            // Search all extension directories for unresolved references

            // .NET Core
            AssemblyLoadContext.Default.Resolving += (context, name) =>
                AssemblyLoadContext.Default.LoadFromAssemblyPath(_extensionRoot
                    .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
                    .FirstOrDefault()?
                    .FullName);

            // Full Framework
            AppDomain.CurrentDomain.AssemblyResolve += (context, name) =>
                Assembly.LoadFrom(_extensionRoot
                    .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
                    .FirstOrDefault()?
                    .FullName);
        }
    }
}

using System;
using System.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;

namespace AudioWorks.Extensions
{
    abstract class ExtensionContainerBase
    {
        static readonly DirectoryInfo _extensionRoot = new DirectoryInfo(Path.Combine(
            Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) ?? string.Empty,
            "Extensions"));

        protected static CompositionHost CompositionHost { get; } = new ContainerConfiguration()
            .WithAssemblies(_extensionRoot
                .EnumerateFiles("AudioWorks.Extensions.*.dll", SearchOption.AllDirectories)
                .Select(f => f.FullName)
                .Select(Assembly.LoadFrom))
            .CreateContainer();

        static ExtensionContainerBase()
        {
            // Search all extension directories for unresolved references

            // Assembly.LoadFrom only works on the full framework
            if (RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework",
                StringComparison.Ordinal))
                AppDomain.CurrentDomain.AssemblyResolve += (context, name) =>
                    Assembly.LoadFrom(_extensionRoot
                        .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
                        .FirstOrDefault()?
                        .FullName);

            // Use AssemblyLoadContext on .NET Core
            else
                UseAssemblyLoadContext();
        }

        static void UseAssemblyLoadContext()
        {
            // Workaround - this needs to reside in a separate method to avoid a binding exception with the desktop
            // framework, as System.Runtime.Loader does not include a net462 library.
            AssemblyLoadContext.Default.Resolving += (context, name) =>
                AssemblyLoadContext.Default.LoadFromAssemblyPath(_extensionRoot
                    .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
                    .FirstOrDefault()?
                    .FullName);
        }
    }
}

Resolve binding exception on netfx.

Resolve binding exception on netfx.


@model JoinRpg.DataModel.MarkdownString
@{
  var requiredMsg = new MvcHtmlString("");
    var validation = false;
  foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
  {
      if (attr.Key == "data-val-required")
      {
          requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'");
          validation = true;
      }
  }
}

    Можно использовать MarkDown (**полужирный**, _курсив_)

    <textarea cols="100" id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents" name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents" @requiredMsg @(validation ? "data-val=true" : "") rows="4">@(Model == null ? "" : Model.Contents)</textarea>

@if (validation)
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
}

Add link to Markdown help

Add link to Markdown help


using Microsoft.Analytics.Interfaces;
using Microsoft.Analytics.Types.Sql;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;

// TweetAnalysis Assembly
// Show the use of a U-SQL user-defined function (UDF)
//
// Register this assembly at master.TweetAnalysis e`ither using Register Assembly on TweetAnalysisClass project in Visual Studio
// or by compiling the assembly, uploading it (if you want to run it in Azure), and registering it with REGISTER ASSEMBLY U-SQL script.
//
namespace TweetAnalysis
{
    public class Udfs
    {
        // SqlArray<string> get_mentions(string tweet)
        //
        // Returns a U-SQL array of string containing the twitter handles that were mentioned inside the tweet.
        //
        public static SqlArray<string> get_mentions(string tweet)
        {
            return new SqlArray<string>(
                tweet.Split(new char[] { ' ', ',', '.', ':', '!', ';', '"', '“' }).Where(x => x.StartsWith("@"))
                );
        }
    }
}

using Microsoft.Analytics.Interfaces;
using Microsoft.Analytics.Types.Sql;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;

// TweetAnalysis Assembly
// Show the use of a U-SQL user-defined function (UDF)
//
// Register this assembly at master.TweetAnalysis either using Register Assembly on TweetAnalysisClass project in Visual Studio
// or by compiling the assembly, uploading it (if you want to run it in Azure), and registering it with REGISTER ASSEMBLY U-SQL script.
//
namespace TweetAnalysis
{
    public class Udfs
    {
        // SqlArray<string> get_mentions(string tweet)
        //
        // Returns a U-SQL array of string containing the twitter handles that were mentioned inside the tweet.
        //
        public static SqlArray<string> get_mentions(string tweet)
        {
            return new SqlArray<string>(
                tweet.Split(new char[] { ' ', ',', '.', ':', '!', ';', '"', '“' }).Where(x => x.StartsWith("@"))
                );
        }
    }
}

Fix a typo in comment

Fix a typo in comment


using Microsoft.Build.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Microsoft.NET.Build.Tasks
{
    public class CheckForImplicitPackageReferenceOverrides : TaskBase
    {
        const string MetadataKeyForItemsToRemove = "IsImplicitlyDefined";

        [Required]
        public ITaskItem [] PackageReferenceItems { get; set; }

        [Required]
        public string MoreInformationLink { get; set; }

        [Output]
        public ITaskItem[] ItemsToRemove { get; set; }

        protected override void ExecuteCore()
        {
            var duplicateItems = PackageReferenceItems.GroupBy(i => i.ItemSpec.ToLowerInvariant()).Where(g => g.Count() > 1);
            var duplicateItemsToRemove = duplicateItems.SelectMany(g => g.Where(
                item => item.GetMetadata(MetadataKeyForItemsToRemove).Equals("true", StringComparison.OrdinalIgnoreCase)));

            ItemsToRemove = duplicateItemsToRemove.ToArray();

            foreach (var itemToRemove in ItemsToRemove)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Strings.PackageReferenceOverrideWarning,
                    itemToRemove.ItemSpec,
                    MoreInformationLink);

                Log.LogWarning(message);
            }
        }
    }
}

using Microsoft.Build.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Microsoft.NET.Build.Tasks
{
    public class CheckForImplicitPackageReferenceOverrides : TaskBase
    {
        const string MetadataKeyForItemsToRemove = "IsImplicitlyDefined";

        [Required]
        public ITaskItem [] PackageReferenceItems { get; set; }

        [Required]
        public string MoreInformationLink { get; set; }

        [Output]
        public ITaskItem[] ItemsToRemove { get; set; }

        protected override void ExecuteCore()
        {
            var duplicateItems = PackageReferenceItems.GroupBy(i => i.ItemSpec, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1);
            var duplicateItemsToRemove = duplicateItems.SelectMany(g => g.Where(
                item => item.GetMetadata(MetadataKeyForItemsToRemove).Equals("true", StringComparison.OrdinalIgnoreCase)));

            ItemsToRemove = duplicateItemsToRemove.ToArray();

            foreach (var itemToRemove in ItemsToRemove)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Strings.PackageReferenceOverrideWarning,
                    itemToRemove.ItemSpec,
                    MoreInformationLink);

                Log.LogWarning(message);
            }
        }
    }
}

Switch to OrdinalIgnoreCase comparison for PackageReference deduplication


using OpenTK;
using OpenTK.Graphics;
using StorybrewCommon.Mapset;
using StorybrewCommon.Scripting;
using StorybrewCommon.Storyboarding;
using StorybrewCommon.Storyboarding.Util;
using StorybrewCommon.Subtitles;
using StorybrewCommon.Util;
using System;
using System.Collections.Generic;
using System.Linq;

namespace StorybrewScripts
{
    public class %CLASSNAME% : StoryboardObjectGenerator
    {
        public override void Generate()
        {

        }
    }
}

Remove extra tab in the script template.


namespace Ooui
{
    public class Iframe : Element
    {
        public string Source
        {
            get => GetStringAttribute ("src", null);
            set => SetAttributeProperty ("src", value);
        }

        public Iframe ()
            : base ("iframe")
        {
        }
    }
}

namespace Ooui
{
    public class Iframe : Element
    {
        public string Source
        {
            get => GetStringAttribute ("src", null);
            set => SetAttributeProperty ("src", value);
        }

        public Iframe ()
            : base ("iframe")
        {
        }

        protected override bool HtmlNeedsFullEndElement => true;
    }
}

Fix closing tag on iframe

Fix closing tag on iframe

Fixes #223


using UnityEngine;

namespace Weapons.Projectiles.Behaviours
{
	/// <summary>
	/// Identical to ProjectileDecal.cs, but creates a decal upon despawning instead of on hitting something.
	/// </summary>
	public class ProjectileDecalOnDespawn : MonoBehaviour, IOnDespawn
	{
		[SerializeField] private GameObject decal = null;

		[Tooltip("Living time of decal.")]
		[SerializeField] private float animationTime = 0;

		[Tooltip("Spawn decal on collision?")]
		[SerializeField] private bool isTriggeredOnHit = true;

		public void OnDespawn(RaycastHit2D hit, Vector2 point)
		{
			if (isTriggeredOnHit && hit.collider != null)
			{
				OnBeamEnd(hit.point);
			}
			else
			{
				OnBeamEnd(point);
			}
		}

		private bool OnBeamEnd(Vector2 position)
		{
			var newDecal = Spawn.ClientPrefab(decal.name,
				position).GameObject;
			var timeLimitedDecal = newDecal.GetComponent<TimeLimitedDecal>();
			timeLimitedDecal.SetUpDecal(animationTime);
			return false;
		}
	}
}

using UnityEngine;

namespace Weapons.Projectiles.Behaviours
{
	/// <summary>
	/// Identical to ProjectileDecal.cs, but creates a decal upon despawning instead of on hitting something.
	/// </summary>
	public class ProjectileDecalOnDespawn : MonoBehaviour, IOnDespawn
	{
		[SerializeField] private GameObject decal = null;

		[Tooltip("Living time of decal.")]
		[SerializeField] private float animationTime = 0;

		[Tooltip("Spawn decal on collision?")]
		[SerializeField] private bool isTriggeredOnHit = true;

		public void OnDespawn(RaycastHit2D hit, Vector2 point)
		{
			if (isTriggeredOnHit && hit.collider != null)
			{
				OnBeamEnd(hit.point);
			}
			else
			{
				OnBeamEnd(point);
			}
		}

		private void OnBeamEnd(Vector2 position)
		{
			var newDecal = Spawn.ClientPrefab(decal.name,
				position).GameObject;
			var timeLimitedDecal = newDecal.GetComponent<TimeLimitedDecal>();
			timeLimitedDecal.SetUpDecal(animationTime);
		}
	}
}

Make decal on despawn script use void.

Make decal on despawn script use void.


@using Hops.Models;
@model ListModel<HopModel>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@{
    ViewBag.Title = "Search results - Hops";
}

@if (!string.IsNullOrEmpty(Model.Pagination.SearchTerm))
{

Search results for "@Model.Pagination.SearchTerm":

}

@Html.Partial("~/Views/Hop/List", Model)

@using Hops.Models;
@model ListModel<HopModel>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@{
    ViewBag.Title = "Search results - Hops";
}

@if (!string.IsNullOrEmpty(Model.Pagination.SearchTerm))
{

Search results for "@Model.Pagination.SearchTerm":

}

@Html.Partial("~/Views/Hop/List.cshtml", Model)

Fix search result when returning multiple results


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("Glob")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Glob")]
[assembly: AssemblyCopyright("Copyright ©  2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// 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.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("Glob.Tests")]
[assembly: InternalsVisibleTo("Glob.Benchmarks")]

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("Glob")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Glob")]
[assembly: AssemblyCopyright("Copyright ©  2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// 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: InternalsVisibleTo("Glob.Tests")]
[assembly: InternalsVisibleTo("Glob.Benchmarks")]

Fix extra assembly info attributes since they are generated by nuget


using System;
using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace Markdig.WebApp
{
    public class ApiController : Controller
    {
        // GET api/to_html?text=xxx&extensions=advanced
        [Route("api/to_html")]
        [HttpGet()]
        public object Get([FromQuery] string text, [FromQuery] string extension)
        {
            try
            {
                if (text == null)
                {
                    text = string.Empty;
                }

                if (text.Length > 1000)
                {
                    text = text.Substring(0, 1000);
                }

                var pipeline = new MarkdownPipelineBuilder().Configure(extension).Build();
                var result = Markdown.ToHtml(text, pipeline);

                return new {name = "markdig", html = result, version = Markdown.Version};
            }
            catch (Exception ex)
            {
                return new { name = "markdig", html = "exception: " + GetPrettyMessageFromException(ex), version = Markdown.Version };
            }
        }

        private static string GetPrettyMessageFromException(Exception exception)
        {
            var builder = new StringBuilder();
            while (exception != null)
            {
                builder.Append(exception.Message);
                exception = exception.InnerException;
            }
            return builder.ToString();
        }
    }
}

using System;
using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace Markdig.WebApp
{
    public class ApiController : Controller
    {
        [HttpGet()]
        [Route("")]
        public string Empty()
        {
            return string.Empty;
        }

        // GET api/to_html?text=xxx&extensions=advanced
        [Route("api/to_html")]
        [HttpGet()]
        public object Get([FromQuery] string text, [FromQuery] string extension)
        {
            try
            {
                if (text == null)
                {
                    text = string.Empty;
                }

                if (text.Length > 1000)
                {
                    text = text.Substring(0, 1000);
                }

                var pipeline = new MarkdownPipelineBuilder().Configure(extension).Build();
                var result = Markdown.ToHtml(text, pipeline);

                return new {name = "markdig", html = result, version = Markdown.Version};
            }
            catch (Exception ex)
            {
                return new { name = "markdig", html = "exception: " + GetPrettyMessageFromException(ex), version = Markdown.Version };
            }
        }

        private static string GetPrettyMessageFromException(Exception exception)
        {
            var builder = new StringBuilder();
            while (exception != null)
            {
                builder.Append(exception.Message);
                exception = exception.InnerException;
            }
            return builder.ToString();
        }
    }
}

Return an empty string for / on markdig webapi


using System;

namespace Python.Runtime.Codecs
{
    [Obsolete]
    public sealed class EnumPyIntCodec : IPyObjectEncoder, IPyObjectDecoder
    {
        public static EnumPyIntCodec Instance { get; } = new EnumPyIntCodec();

        public bool CanDecode(PyType objectType, Type targetType)
        {
            return targetType.IsEnum
                && objectType.IsSubclass(Runtime.PyLongType);
        }

        public bool CanEncode(Type type)
        {
            return type == typeof(object) || type == typeof(ValueType) || type.IsEnum;
        }

        public bool TryDecode<T>(PyObject pyObj, out T? value)
        {
            value = default;
            if (!typeof(T).IsEnum) return false;

            Type etype = Enum.GetUnderlyingType(typeof(T));

            if (!PyInt.IsIntType(pyObj)) return false;

            object? result;
            try
            {
                result = pyObj.AsManagedObject(etype);
            }
            catch (InvalidCastException)
            {
                return false;
            }

            if (Enum.IsDefined(typeof(T), result) || typeof(T).IsFlagsEnum())
            {
                value = (T)Enum.ToObject(typeof(T), result);
                return true;
            }

            return false;
        }

        public PyObject? TryEncode(object value)
        {
            if (value is null) return null;

            var enumType = value.GetType();
            if (!enumType.IsEnum) return null;

            return new PyInt(Convert.ToInt64(value));
        }

        private EnumPyIntCodec() { }
    }
}

using System;

namespace Python.Runtime.Codecs
{
    [Obsolete]
    public sealed class EnumPyIntCodec : IPyObjectEncoder, IPyObjectDecoder
    {
        public static EnumPyIntCodec Instance { get; } = new EnumPyIntCodec();

        public bool CanDecode(PyType objectType, Type targetType)
        {
            return targetType.IsEnum
                && objectType.IsSubclass(Runtime.PyLongType);
        }

        public bool CanEncode(Type type)
        {
            return type == typeof(object) || type == typeof(ValueType) || type.IsEnum;
        }

        public bool TryDecode<T>(PyObject pyObj, out T? value)
        {
            value = default;
            if (!typeof(T).IsEnum) return false;

            Type etype = Enum.GetUnderlyingType(typeof(T));

            if (!PyInt.IsIntType(pyObj)) return false;

            object? result;
            try
            {
                result = pyObj.AsManagedObject(etype);
            }
            catch (InvalidCastException)
            {
                return false;
            }

            if (Enum.IsDefined(typeof(T), result) || typeof(T).IsFlagsEnum())
            {
                value = (T)Enum.ToObject(typeof(T), result);
                return true;
            }

            return false;
        }

        public PyObject? TryEncode(object value)
        {
            if (value is null) return null;

            var enumType = value.GetType();
            if (!enumType.IsEnum) return null;

            try
            {
                return new PyInt(Convert.ToInt64(value));
            }
            catch (OverflowException)
            {
                return new PyInt(Convert.ToUInt64(value));
            }
        }

        private EnumPyIntCodec() { }
    }
}

Allow conversion of UInt64 based enums

Allow conversion of UInt64 based enums


/*
  Copyright © Iain McDonald 2010-2020

  This file is part of Decider.
*/
using System;
using System.Collections.Generic;
using System.Linq;

namespace Decider.Example.LeagueGeneration
{
	public class Program
	{
		static void Main(string[] args)
		{
            var leagueGeneration = new LeagueGeneration((args.Length >= 1) ? Int32.Parse(args[0]) : 20);
            leagueGeneration.Search();
            leagueGeneration.GenerateFixtures();

            for (var i = 0; i < leagueGeneration.FixtureWeeks.Length; ++i)
			{
				for (var j = 0; j < leagueGeneration.FixtureWeeks[i].Length; ++j)
					Console.Write(string.Format("{0,2}", leagueGeneration.FixtureWeeks[i][j]) + " ");

				Console.WriteLine();
			}

			Console.WriteLine();
			Console.WriteLine("Runtime:\t{0}\nBacktracks:\t{1}", leagueGeneration.State.Runtime, leagueGeneration.State.Backtracks);
			Console.WriteLine("Solutions:\t{0}", leagueGeneration.State.NumberOfSolutions);
        }
    }
}

Create first automated acceptance test

Create first automated acceptance test


using System;
using System.Diagnostics;

namespace Nett
{
    [DebuggerDisplay("{FromType} -> {ToType}")]
    internal sealed class TomlConverter<TFrom, TTo> : TomlConverterBase<TFrom, TTo>
    {
        private readonly Func<TFrom, TTo> convert;

        public TomlConverter(Func<TFrom, TTo> convert)
        {
            if (convert == null) { throw new ArgumentNullException(nameof(convert)); }

            this.convert = convert;
        }

        public override TTo Convert(TFrom from, Type targetType) => this.convert(from);
    }
}

using System;

namespace Nett
{
    internal sealed class TomlConverter<TFrom, TTo> : TomlConverterBase<TFrom, TTo>
    {
        private readonly Func<TFrom, TTo> convert;

        public TomlConverter(Func<TFrom, TTo> convert)
        {
            if (convert == null) { throw new ArgumentNullException(nameof(convert)); }

            this.convert = convert;
        }

        public override TTo Convert(TFrom from, Type targetType) => this.convert(from);
    }
}

Remove DebuggerDisplay attribute not applicable anymore


namespace TAUtil.Tdf
{
    using System.Collections.Generic;

    public class TdfNodeAdapter : ITdfNodeAdapter
    {
        private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>();

        public TdfNodeAdapter()
        {
            this.RootNode = new TdfNode();
            this.nodeStack.Push(this.RootNode);
        }

        public TdfNode RootNode { get; private set; }

        public void BeginBlock(string name)
        {
            TdfNode n = new TdfNode(name);
            this.nodeStack.Peek().Keys[name] = n;
            this.nodeStack.Push(n);
        }

        public void AddProperty(string name, string value)
        {
            this.nodeStack.Peek().Entries[name] = value;
        }

        public void EndBlock()
        {
            this.nodeStack.Pop();
        }
    }
}

namespace TAUtil.Tdf
{
    using System.Collections.Generic;

    public class TdfNodeAdapter : ITdfNodeAdapter
    {
        private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>();

        public TdfNodeAdapter()
        {
            this.RootNode = new TdfNode();
            this.nodeStack.Push(this.RootNode);
        }

        public TdfNode RootNode { get; private set; }

        public void BeginBlock(string name)
        {
            name = name.ToLowerInvariant();
            TdfNode n = new TdfNode(name);
            this.nodeStack.Peek().Keys[name] = n;
            this.nodeStack.Push(n);
        }

        public void AddProperty(string name, string value)
        {
            name = name.ToLowerInvariant();
            value = value.ToLowerInvariant();
            this.nodeStack.Peek().Entries[name] = value;
        }

        public void EndBlock()
        {
            this.nodeStack.Pop();
        }
    }
}

Make all strings in loaded TdfNodes lowercase

This fixes aliasing issues in TDFs
since TDF authors don't follow consistent case style.


@model ChatApp.Controllers.ChatMessagesViewModel
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@using ChatApp.Models

<!DOCTYPE html>

    <title>ChatApp</title>

        @foreach (Message msg in Model.OldMessages)
        {

                @msg.Author
                @msg.Text
                @msg.Timestamp

        }

    <form asp-action="SendNewMessage" method="post">
        <input asp-for="NewMessage.Author"/>
        <input asp-for="NewMessage.Text"/>
        <input type="submit" value="Send"/>
    </form>

@model ChatApp.Controllers.ChatMessagesViewModel
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@using ChatApp.Models

<!DOCTYPE html>

    <title>ChatApp</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css" async>

        @foreach (Message msg in Model.OldMessages)
        {

                @msg.Author:
                @msg.Text
                @msg.Timestamp

        }

    <form asp-action="SendNewMessage" method="post" class="w3-row">
        <input asp-for="NewMessage.Author" class="w3-input w3-border w3-col m2" placeholder="Name"/>
        <input asp-for="NewMessage.Text" class="w3-input w3-border w3-col m8" placeholder="Message"/>
        <input type="submit" value="Send" class="w3-btn w3-blue w3-col w3-large m2"/>
    </form>

Update UI look and feel

Update UI look and feel


using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.InteropServices;

[assembly: AssemblyCopyright(XsdDocMetadata.Copyright)]
[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("XML Schema Documenter")]

[assembly: CLSCompliant(false)]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]

[assembly: AssemblyVersion(XsdDocMetadata.Version)]
[assembly: AssemblyFileVersion(XsdDocMetadata.Version)]

internal static class XsdDocMetadata
{
    public const string Version = "15.10.10.0";
    public const string Copyright = "Copyright  2009-2015 Immo Landwerth";
}

using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.InteropServices;

[assembly: AssemblyCopyright(XsdDocMetadata.Copyright)]
[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("XML Schema Documenter")]

[assembly: CLSCompliant(false)]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]

[assembly: AssemblyVersion(XsdDocMetadata.Version)]
[assembly: AssemblyFileVersion(XsdDocMetadata.Version)]

internal static class XsdDocMetadata
{
    public const string Version = "16.9.17.0";
    public const string Copyright = "Copyright  2009-2015 Immo Landwerth";
}

Align XSD Doc version number with SHFB

Align XSD Doc version number with SHFB


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

[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("© Yevgeniy Shunevych 2018")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]

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

[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("© Yevgeniy Shunevych 2019")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]

Increment copyright year of projects to 2019


using SimpleStack.Orm.Expressions;

namespace SimpleStack.Orm.PostgreSQL
{
    /// A postgre SQL expression visitor.
    /// <typeparam name="T">Generic type parameter.</typeparam>
	public class PostgreSQLExpressionVisitor<T>:SqlExpressionVisitor<T>
	{
	    public PostgreSQLExpressionVisitor(IDialectProvider dialectProvider) : base(dialectProvider)
	    {
	    }

	    /// Gets the limit expression.
        /// <value>The limit expression.</value>
		public override string LimitExpression{
			get{
				if(!Rows.HasValue) return "";
				string offset;
				if(Skip.HasValue){
					offset= string.Format(" OFFSET {0}", Skip.Value );
				}
				else{
					offset=string.Empty;
				}
				return string.Format("LIMIT {0}{1}", Rows.Value, offset);
			}
		}

	}
}

using System.Linq.Expressions;
using SimpleStack.Orm.Expressions;

namespace SimpleStack.Orm.PostgreSQL
{
    /// A postgre SQL expression visitor.
    /// <typeparam name="T">Generic type parameter.</typeparam>
	public class PostgreSQLExpressionVisitor<T>:SqlExpressionVisitor<T>
	{
	    public PostgreSQLExpressionVisitor(IDialectProvider dialectProvider) : base(dialectProvider)
	    {
	    }

	    protected override string BindOperant(ExpressionType e)
	    {
	        switch (e)
	        {
                case ExpressionType.ExclusiveOr:
                    return "#";
            }

            return base.BindOperant(e);
	    }

	    /// Gets the limit expression.
        /// <value>The limit expression.</value>
		public override string LimitExpression{
			get{
				if(!Rows.HasValue) return "";
				string offset;
				if(Skip.HasValue){
					offset= string.Format(" OFFSET {0}", Skip.Value );
				}
				else{
					offset=string.Empty;
				}
				return string.Format("LIMIT {0}{1}", Rows.Value, offset);
			}
		}

	}
}

Add support for XOR in PostgreSQL

Add support for XOR in PostgreSQL


/*Problem 3. Check for a Play Card

    Classical play cards use the following signs to designate the card face: `2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K and A.
    Write a program that enters a string and prints “yes” if it is a valid card sign or “no” otherwise. Examples:

character 	Valid card sign?
5 	        yes
1 	        no
Q 	        yes
q 	        no
P 	        no
10 	        yes
500 	    no
*/

using System;

class CheckPlayCard
{
    static void Main()
    {
        Console.Title = "Check for a Play Card"; //Changing the title of the console.

        Console.Write("Please, enter a play card sign to check if it is valid: ");
        string cardSign = Console.ReadLine();

        switch (cardSign)
        {
            case "2":
            case "3":
            case "4":
            case "5":
            case "6":
            case "7":
            case "8":
            case "9":
            case "10":
            case "J":
            case "Q":
            case "K":
            case "A": Console.WriteLine("\nValid card sign?\nyes"); break;
            default: Console.WriteLine("\nValid card sign?\nno"); break;
        }

        Console.ReadKey(); // Keeping the console opened.
    }
}

/*Problem 3. Check for a Play Card

    Classical play cards use the following signs to designate the card face: `2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K and A.
    Write a program that enters a string and prints “yes” if it is a valid card sign or “no” otherwise. Examples:

character 	Valid card sign?
5 	        yes
1 	        no
Q 	        yes
q 	        no
P 	        no
10 	        yes
500 	    no
*/

using System;

class CheckPlayCard
{
    static void Main()
    {
        Console.Title = "Check for a Play Card"; //Changing the title of the console.

        Console.Write("Please, enter a play card sign to check if it is valid: ");
        string cardSign = Console.ReadLine();

        switch (cardSign)
        {
            case "2":
            case "3":
            case "4":
            case "5":
            case "6":
            case "7":
            case "8":
            case "9":
            case "10":
            case "J":
            case "Q":
            case "K":
            case "A": Console.WriteLine("\r\nValid card sign?\r\nyes"); break;
            default: Console.WriteLine("\r\nValid card sign?\r\nno"); break;
        }

        Console.ReadKey(); // Keeping the console opened.
    }
}

Update to Problem 3. Check for a Play Card


using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Bit.ViewModel.Implementations
{
    public class BitHttpClientHandler : HttpClientHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // ToDo:
            // Current-Time-Zone
            // Desired-Time-Zone
            // Client-App-Version
            // Client-Culture
            // Client-Route
            // Client-Theme
            // Client-Debug-Mode
            // System-Language
            // Client-Sys-Language
            // Client-Platform

            // ToDo: Use IDeviceService & IDateTimeProvider

            request.Headers.Add("Client-Type", "Xamarin");

            if (Device.Idiom != TargetIdiom.Unsupported)
                request.Headers.Add("Client-Screen-Size", Device.Idiom == TargetIdiom.Phone ? "MobileAndPhablet" : "DesktopAndTablet");

            request.Headers.Add("Client-Date-Time", DefaultDateTimeProvider.Current.GetCurrentUtcDateTime().UtcDateTime.ToString("o"));

            request.Headers.Add("X-CorrelationId", Guid.NewGuid().ToString());

            request.Headers.Add("Bit-Client-Type", "CS-Client");

            return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
        }
    }
}

using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Bit.ViewModel.Implementations
{
    public class BitHttpClientHandler :
#if Android
        Xamarin.Android.Net.AndroidClientHandler
#elif iOS
        NSUrlSessionHandler
#else
        HttpClientHandler
#endif
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // ToDo:
            // Current-Time-Zone
            // Desired-Time-Zone
            // Client-App-Version
            // Client-Culture
            // Client-Route
            // Client-Theme
            // Client-Debug-Mode
            // System-Language
            // Client-Sys-Language
            // Client-Platform

            // ToDo: Use IDeviceService & IDateTimeProvider

            request.Headers.Add("Client-Type", "Xamarin");

            if (Device.Idiom != TargetIdiom.Unsupported)
                request.Headers.Add("Client-Screen-Size", Device.Idiom == TargetIdiom.Phone ? "MobileAndPhablet" : "DesktopAndTablet");

            request.Headers.Add("Client-Date-Time", DefaultDateTimeProvider.Current.GetCurrentUtcDateTime().UtcDateTime.ToString("o"));

            request.Headers.Add("X-CorrelationId", Guid.NewGuid().ToString());

            request.Headers.Add("Bit-Client-Type", "CS-Client");

            return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
        }
    }
}

Use AndroidClientHandler for android & NSUrlSessionHandler for iOS by default in bit cs client


using System;
using System.Collections.Generic;
using System.Text;
using Csla.Core;
using Csla;

namespace DataBindingApp
{
    [Serializable()]
    public class ListObject : BusinessListBase<ListObject, ListObject.DataObject>
    {
        [Serializable()]
        public class DataObject : BusinessBase<DataObject>
        {
            private int _ID;
            private string _data;
            private int _number;

            public int Number
            {
                get { return _number; }
                set { _number = value; }
            }

            public string Data
            {
                get { return _data; }
                set { _data = value; }
            }

            public int ID
            {
                get { return _ID; }
                set { _ID = value; }
            }

            protected override object GetIdValue()
            {
                return _ID;
            }

            public DataObject(string data, int number)
            {
                this.MarkAsChild();
                _data = data;
                _number = number;
                this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(DataObject_PropertyChanged);
            }

            public void DataObject_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
            {
                Console.WriteLine("Property has changed");
            }
        }

        private ListObject()
        { }

        public static ListObject GetList()
        {
            ListObject list = new ListObject();

            for (int i = 0; i < 5; i++)
            {
                list.Add(new DataObject("element" + i, i));
            }

            return list;
        }

    }
}

using System;
using System.Collections.Generic;
using System.Text;
using Csla.Core;
using Csla;

namespace DataBindingApp
{
    [Serializable()]
    public class ListObject : BusinessListBase<ListObject, ListObject.DataObject>
    {
        [Serializable()]
        public class DataObject : BusinessBase<DataObject>
        {
            private int _ID;
            private string _data;
            private int _number;

            public int Number
            {
                get { return _number; }
                set { _number = value; }
            }

            public string Data
            {
                get { return _data; }
                set { _data = value; }
            }

            public int ID
            {
                get { return _ID; }
                set { _ID = value; }
            }

            protected override object GetIdValue()
            {
                 return _number;
            }

            public DataObject(string data, int number)
            {
                this.MarkAsChild();
                _data = data;
                _number = number;
                this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(DataObject_PropertyChanged);
            }

            public void DataObject_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
            {
                Console.WriteLine("Property has changed");
            }
        }

        private ListObject()
        { }

        public static ListObject GetList()
        {
            ListObject list = new ListObject();

            for (int i = 0; i < 5; i++)
            {
                list.Add(new DataObject("element" + i, i));
            }

            return list;
        }

    }
}

Make sure GetIdValue returns a unique value per object.


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

namespace ConsoleApp
{
    public class Table
    {
        private readonly string tableName;
        private readonly IEnumerable<Column> columns;

        public Table(string tableName, IEnumerable<Column> columns)
        {
            this.tableName = tableName;
            this.columns = columns;
        }

        public void OutputMigrationCode(TextWriter writer)
        {
            writer.Write(@"namespace Cucu
{
    [Migration(");
            writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss"));
            writer.WriteLine(@")]
    public class Vaca : Migration
    {
        public override void Up()
        {");
            writer.Write($"            Create.Table(\"{tableName}\")");

            columns.ToList().ForEach(c =>
            {
                writer.WriteLine();
                writer.Write(c.FluentMigratorCode());
            });

            writer.WriteLine(@";
        }

        public override void Down()
        {");
            writer.Write($"            Delete.Table(\"{tableName}\");");
            writer.WriteLine(@"
        }
    }
}");
        }
    }
}

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

namespace ConsoleApp
{
    public class Table
    {
        private readonly string tableName;
        private readonly IEnumerable<Column> columns;

        public Table(string tableName, IEnumerable<Column> columns)
        {
            this.tableName = tableName;
            this.columns = columns;
        }

        public void OutputMigrationCode(TextWriter writer)
        {
            const string format = "yyyyMMddHHmmss";
            writer.WriteLine(@"namespace Migrations
{");
            writer.WriteLine($"    [Migration(\"{DateTime.Now.ToString(format)}\")]");
            writer.Write($"    public class {tableName}Migration : Migration");
            writer.WriteLine(@"
    {
        public override void Up()
        {");
            writer.Write($"            Create.Table(\"{tableName}\")");

            columns.ToList().ForEach(c =>
            {
                writer.WriteLine();
                writer.Write(c.FluentMigratorCode());
            });

            writer.WriteLine(@";
        }

        public override void Down()
        {");
            writer.Write($"            Delete.Table(\"{tableName}\");");
            writer.WriteLine(@"
        }
    }
}");
        }
    }
}

Fix namespace & class name

Fix namespace & class name


using System;
using System.Linq;
using ExRam.Gremlinq.Core.Tests;
using FluentAssertions;
using Xunit;
using static ExRam.Gremlinq.Core.GremlinQuerySource;

namespace ExRam.Gremlinq.Providers.CosmosDb.Tests
{
    public class GroovySerializationTest : GroovySerializationTest<CosmosDbGroovyGremlinQueryElementVisitor>
    {
        [Fact]
        public void Limit_overflow()
        {
            g
                .V()
                .Limit((long)int.MaxValue + 1)
                .Invoking(x => new CosmosDbGroovyGremlinQueryElementVisitor().Visit(x))
                .Should()
                .Throw<ArgumentOutOfRangeException>();
        }

        [Fact]
        public void Where_property_array_intersects_empty_array2()
        {
            g
                .V<User>()
                .Where(t => t.PhoneNumbers.Intersect(new string[0]).Any())
                .Should()
                .SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())")
                .WithParameters("User");
        }
    }
}

using System;
using System.Linq;
using ExRam.Gremlinq.Core.Tests;
using FluentAssertions;
using Xunit;
using static ExRam.Gremlinq.Core.GremlinQuerySource;

namespace ExRam.Gremlinq.Providers.CosmosDb.Tests
{
    public class GroovySerializationTest : GroovySerializationTest<CosmosDbGroovyGremlinQueryElementVisitor>
    {
        [Fact]
        public void Limit_overflow()
        {
            g
                .V()
                .Limit((long)int.MaxValue + 1)
                .Invoking(x => new CosmosDbGroovyGremlinQueryElementVisitor().Visit(x))
                .Should()
                .Throw<ArgumentOutOfRangeException>();
        }

        [Fact]
        public void Where_property_array_intersects_empty_array()
        {
            g
                .V<User>()
                .Where(t => t.PhoneNumbers.Intersect(new string[0]).Any())
                .Should()
                .SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())")
                .WithParameters("User");
        }

        [Fact]
        public void Where_property_is_contained_in_empty_enumerable()
        {
            var enumerable = Enumerable.Empty<int>();

            g
                .V<User>()
                .Where(t => enumerable.Contains(t.Age))
                .Should()
                .SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())")
                .WithParameters("User");
        }

    }
}

Bring back integration test for CosmosDb.


using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Octokit.Internal;

namespace Octokit
{
    static class EnumExtensions
    {
        [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
        internal static string ToParameter(this Enum prop)
        {
            if (prop == null) return null;

            var propString = prop.ToString();
            var member = prop.GetType().GetMember(propString).FirstOrDefault();
            if (member == null) return null;

            var attribute = member.GetCustomAttributes(typeof(ParameterAttribute), false)
                .Cast<ParameterAttribute>()
                .FirstOrDefault();

            return attribute != null ? attribute.Value : propString.ToLowerInvariant();
        }
    }
}

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Octokit.Internal;

namespace Octokit
{
    static class EnumExtensions
    {
        [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
        internal static string ToParameter(this Enum prop)
        {
            if (prop == null) return null;

            var propString = prop.ToString();
            var member = prop.GetType().GetMember(propString).FirstOrDefault();
            if (member == null) return null;

            var attribute = member.GetCustomAttributes(typeof(ParameterAttribute), false)
                .Cast<ParameterAttribute>()
                .FirstOrDefault();

            return attribute != null ? attribute.Value : propString.ToLowerInvariant();
        }
    }
}

Add back in the reflection namespace

Add back in the reflection namespace


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

namespace MailChimp.Net.Api
{
    class PostHelpers
    {
        public static string PostJson(string url, string data)
        {
            var bytes = Encoding.Default.GetBytes(data);

            using (var client = new WebClient())
            {
                client.Headers.Add("Content-Type", "application/json");
                var response = client.UploadData(url, "POST", bytes);

                return Encoding.Default.GetString(response);
            }
        }
    }
}

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

namespace MailChimp.Net.Api
{
    class PostHelpers
    {
        public static string PostJson(string url, string data)
        {
            var bytes = Encoding.UTF8.GetBytes(data);

            using (var client = new WebClient())
            {
                client.Headers.Add("Content-Type", "application/json");
                var response = client.UploadData(url, "POST", bytes);

                return Encoding.Default.GetString(response);
            }
        }
    }
}

Update default encoding to utf8 for supporting non-us symbols


using Discord.Commands;
using Modix.Services.AutoCodePaste;
using System.Threading.Tasks;

namespace Modix.Modules
{
    [Name("Code Paste"), Summary("Paste some code to the internet.")]
    public class CodePasteModule : ModuleBase
    {
        private CodePasteService _service;

        public CodePasteModule(CodePasteService service) {
            _service = service;
    }
        [Command("paste"), Summary("Paste the rest of your message to the internet, and return the URL.")]
        public async Task Run([Remainder] string code)
        {
            string url = await _service.UploadCode(Context.Message, code);
            var embed = _service.BuildEmbed(Context.User, code, url);

            await ReplyAsync(Context.User.Mention, false, embed);
            await Context.Message.DeleteAsync();
        }
    }
}

using Discord.Commands;
using Modix.Services.AutoCodePaste;
using System.Net;
using System.Threading.Tasks;

namespace Modix.Modules
{
    [Name("Code Paste"), Summary("Paste some code to the internet.")]
    public class CodePasteModule : ModuleBase
    {
        private CodePasteService _service;

        public CodePasteModule(CodePasteService service)
        {
            _service = service;
        }

        [Command("paste"), Summary("Paste the rest of your message to the internet, and return the URL.")]
        public async Task Run([Remainder] string code)
        {
            string url = null;
            string error = null;
            try
            {
                url = await _service.UploadCode(Context.Message, code);
            }
            catch (WebException ex)
            {
                url = null;
                error = ex.Message;
            }

            if (url != null)
            {
                var embed = _service.BuildEmbed(Context.User, code, url);

                await ReplyAsync(Context.User.Mention, false, embed);
                await Context.Message.DeleteAsync();
            }
            else
            {
                await ReplyAsync(error);
            }
        }
    }
}

Handle hastebin failure in the CodePaste module


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(), 5);
            Assert.AreEqual(ClassLibrary1.Class1.ReturnSix(), 6);
        }

        [TestMethod]
        public void ShouldFail()
        {
            Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(),
                            ClassLibrary1.Class1.ReturnSix());
        }
    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(), 5);
            Assert.AreEqual(ClassLibrary1.Class1.ReturnSix(), 6);
        }
    }
}

Fix failing test ... by removing it

Fix failing test ... by removing it


using System;
using System.Linq;

using HtmlAgilityPack;

namespace ReverseMarkdown.Converters
{
    public class P : ConverterBase
    {
        public P(Converter converter) : base(converter)
        {
            Converter.Register("p", this);
        }

        public override string Convert(HtmlNode node)
        {
            var indentation = IndentationFor(node);
            return $"{indentation}{TreatChildren(node).Trim()}{Environment.NewLine}{Environment.NewLine}";
        }

        private static string IndentationFor(HtmlNode node)
        {
            var length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count();
            return node.ParentNode.Name.ToLowerInvariant() == "li" && node.ParentNode.FirstChild != node
                ? new string(' ', length * 4)
                : Environment.NewLine + Environment.NewLine;
        }
    }
}

using System;
using System.Linq;

using HtmlAgilityPack;

namespace ReverseMarkdown.Converters
{
    public class P : ConverterBase
    {
        public P(Converter converter) : base(converter)
        {
            Converter.Register("p", this);
        }

        public override string Convert(HtmlNode node)
        {
            var indentation = IndentationFor(node);
            return $"{indentation}{TreatChildren(node).Trim()}{Environment.NewLine}";
        }

        private static string IndentationFor(HtmlNode node)
        {
            var length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count();
            return node.ParentNode.Name.ToLowerInvariant() == "li" && node.ParentNode.FirstChild != node
                ? new string(' ', length * 4)
                : Environment.NewLine;
        }
    }
}

Fix to convert paragraph tag with single carriage return


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

namespace Microsoft.TeamFoundation.Authentication.Test
{
    /// <summary>
    /// A class to test <see cref="Configuration"/>.
    /// </summary>
    [TestClass]
    public class ConfigurationTests
    {
        [TestMethod]
        public void ParseGitConfig_Simple()
        {
            const string input = @"
[core]
    autocrlf = false
";

            var values = TestParseGitConfig(input);

            Assert.AreEqual("false", values["core.autocrlf"]);
        }

        private static Dictionary<string, string> TestParseGitConfig(string input)
        {
            var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            using (var sr = new StringReader(input))
            {
                Configuration.ParseGitConfig(sr, values);
            }
            return values;
        }
    }
}

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

namespace Microsoft.TeamFoundation.Authentication.Test
{
    /// <summary>
    /// A class to test <see cref="Configuration"/>.
    /// </summary>
    [TestClass]
    public class ConfigurationTests
    {
        [TestMethod]
        public void ParseGitConfig_Simple()
        {
            const string input = @"
[core]
    autocrlf = false
";

            var values = TestParseGitConfig(input);

            Assert.AreEqual("false", values["core.autocrlf"]);
        }

        [TestMethod]
        public void ParseGitConfig_OverwritesValues()
        {
            // http://thedailywtf.com/articles/What_Is_Truth_0x3f_
            const string input = @"
[core]
    autocrlf = true
    autocrlf = FileNotFound
    autocrlf = false
";

            var values = TestParseGitConfig(input);

            Assert.AreEqual("false", values["core.autocrlf"]);
        }

        private static Dictionary<string, string> TestParseGitConfig(string input)
        {
            var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            using (var sr = new StringReader(input))
            {
                Configuration.ParseGitConfig(sr, values);
            }
            return values;
        }
    }
}

Add test to verify overwriting of values.


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

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;

namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
    [Export(typeof(TestExtensionErrorHandler))]
    [Export(typeof(IExtensionErrorHandler))]
    internal class TestExtensionErrorHandler : IExtensionErrorHandler
    {
        private List<Exception> _exceptions = new List<Exception>();

        public void HandleError(object sender, Exception exception)
        {
            if (exception is ArgumentOutOfRangeException && ((ArgumentOutOfRangeException)exception).ParamName == "span")
            {
                // TODO: this is known bug 655591, fixed by Jack in changeset 931906
                // Remove this workaround once the fix reaches the DP branch and we all move over.
                return;
            }

            _exceptions.Add(exception);
        }

        public ICollection<Exception> GetExceptions()
        {
            // We'll clear off our list, so that way we don't report this for other tests
            var newExceptions = _exceptions;
            _exceptions = new List<Exception>();
            return newExceptions;
        }
    }
}

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

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;

namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
    [Export(typeof(TestExtensionErrorHandler))]
    [Export(typeof(IExtensionErrorHandler))]
    internal class TestExtensionErrorHandler : IExtensionErrorHandler
    {
        private List<Exception> _exceptions = new List<Exception>();

        public void HandleError(object sender, Exception exception)
        {
            _exceptions.Add(exception);
        }

        public ICollection<Exception> GetExceptions()
        {
            // We'll clear off our list, so that way we don't report this for other tests
            var newExceptions = _exceptions;
            _exceptions = new List<Exception>();
            return newExceptions;
        }
    }
}

Delete workaround for a long-fixed editor bug


using KeyPay.DomainModels.V2.PayRun;
using RestSharp;

namespace KeyPay.ApiFunctions.V2
{
    public class PayRunDeductionFunction : BaseFunction
    {
        public PayRunDeductionFunction(ApiRequestExecutor api)
            : base(api)
        {
        }

        public DeductionsResponse List(int businessId, int payRunId)
        {
            return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions");
        }

        public DeductionModel Submit(int businessId, SubmitDeductionsRequest deductions)
        {
            return ApiRequest<DeductionModel, SubmitDeductionsRequest>("/business/" + businessId + "/payrun/" + deductions.PayRunId + "/deductions", deductions, Method.POST);
        }

    }
}

using KeyPay.DomainModels.V2.PayRun;
using RestSharp;

namespace KeyPay.ApiFunctions.V2
{
    public class PayRunDeductionFunction : BaseFunction
    {
        public PayRunDeductionFunction(ApiRequestExecutor api)
            : base(api)
        {
        }

        public DeductionsResponse List(int businessId, int payRunId)
        {
            return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions");
        }

        public DeductionsResponse List(int businessId, int payRunId, int employeeId)
        {
            return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions/" + employeeId);
        }

        public DeductionModel Submit(int businessId, SubmitDeductionsRequest deductions)
        {
            return ApiRequest<DeductionModel, SubmitDeductionsRequest>("/business/" + businessId + "/payrun/" + deductions.PayRunId + "/deductions", deductions, Method.POST);
        }

    }
}

Add function to get deductions from a payrun for a specific employee


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

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

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

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

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/blueimp-gallery.css",
                      "~/Content/bootstrap-image-gallery.css",
                      "~/Content/bootstrap-social.css",
                      "~/Content/font-awesome.css",
                      "~/Content/ionicons.css",
                      "~/Content/site.css"));
        }
    }
}

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

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

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

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

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.min.css",
                      "~/Content/blueimp-gallery.min.css",
                      "~/Content/bootstrap-image-gallery.min.css",
                      "~/Content/bootstrap-social.css",
                      "~/Content/font-awesome.css",
                      "~/Content/ionicons.min.css",
                      "~/Content/site.css"));
        }
    }
}

Change app to use minified files

Change app to use minified files


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

namespace NBi.Core.Scalar.Resolver
{
    public interface IScalarResolver
    {
        object Execute();
    }

    public interface IScalarResolver<T> : IScalarResolver
    {
        T Execute();
    }
}

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

namespace NBi.Core.Scalar.Resolver
{
    public interface IScalarResolver
    {
        object Execute();
    }

    public interface IScalarResolver<T> : IScalarResolver
    {
        new T Execute();
    }
}

Remove warning about hidden versus new

Remove warning about hidden versus new


using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;

namespace Tgstation.Server.Host.Watchdog
{
	/// <summary>
	/// See <see cref="IActiveAssemblyDeleter"/> for Windows systems
	/// </summary>
	sealed class WindowsActiveAssemblyDeleter : IActiveAssemblyDeleter
	{
		/// <summary>
		/// Set a file located at <paramref name="path"/> to be deleted on reboot
		/// </summary>
		/// <param name="path">The file to delete on reboot</param>
		[ExcludeFromCodeCoverage]
		static void DeleteFileOnReboot(string path)
		{
			if (!NativeMethods.MoveFileEx(path, null, NativeMethods.MoveFileFlags.DelayUntilReboot))
				throw new Win32Exception(Marshal.GetLastWin32Error());
		}

		/// <inheritdoc />
		public void DeleteActiveAssembly(string assemblyPath)
		{
			if (assemblyPath == null)
				throw new ArgumentNullException(nameof(assemblyPath));

			//Can't use Path.GetTempFileName() because it may cross drives, which won't actually rename the file
			//Also append the long path prefix just in case we're running on .NET framework
			var tmpLocation = String.Concat(@"\\?\", assemblyPath, Guid.NewGuid());
			File.Move(assemblyPath, tmpLocation);
			DeleteFileOnReboot(tmpLocation);
		}
	}
}

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;

namespace Tgstation.Server.Host.Watchdog
{
	/// <summary>
	/// See <see cref="IActiveAssemblyDeleter"/> for Windows systems
	/// </summary>
	sealed class WindowsActiveAssemblyDeleter : IActiveAssemblyDeleter
	{
		/// <summary>
		/// Set a file located at <paramref name="path"/> to be deleted on reboot
		/// </summary>
		/// <param name="path">The file to delete on reboot</param>
		[ExcludeFromCodeCoverage]
		static void DeleteFileOnReboot(string path)
		{
			if (!NativeMethods.MoveFileEx(path, null, NativeMethods.MoveFileFlags.DelayUntilReboot))
				throw new Win32Exception(Marshal.GetLastWin32Error());
		}

		/// <inheritdoc />
		public void DeleteActiveAssembly(string assemblyPath)
		{
			if (assemblyPath == null)
				throw new ArgumentNullException(nameof(assemblyPath));

			//Can't use Path.GetTempFileName() because it may cross drives, which won't actually rename the file
			var tmpLocation = String.Concat(assemblyPath, Guid.NewGuid());
			File.Move(assemblyPath, tmpLocation);
			DeleteFileOnReboot(tmpLocation);
		}
	}
}

Remove windows long filename prefix

Remove windows long filename prefix


using MarcelloDB.Collections;
using MarcelloDB.Platform;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace MarcelloDB.uwp
{
    public class Platform : IPlatform
    {
        public Storage.IStorageStreamProvider CreateStorageStreamProvider(string rootPath)
        {
            return new FileStorageStreamProvider(GetFolderForPath(rootPath));
        }

        StorageFolder GetFolderForPath(string path)
        {
            var getFolderTask = StorageFolder.GetFolderFromPathAsync(path).AsTask();
            getFolderTask.ConfigureAwait(false);
            getFolderTask.Wait();
            return getFolderTask.Result;
        }
    }
}

using MarcelloDB.Collections;
using MarcelloDB.Platform;
using MarcelloDB.Storage;
using MarcelloDB.uwp.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace MarcelloDB.uwp
{
    public class Platform : IPlatform
    {
        public IStorageStreamProvider CreateStorageStreamProvider(string rootPath)
        {
            return new FileStorageStreamProvider(GetFolderForPath(rootPath));
        }

        StorageFolder GetFolderForPath(string path)
        {
            var getFolderTask = StorageFolder.GetFolderFromPathAsync(path).AsTask();
            getFolderTask.ConfigureAwait(false);
            getFolderTask.Wait();
            return getFolderTask.Result;
        }
    }
}

Fix namespace issue in uwp

Fix namespace issue in uwp


using System.Collections.Generic;

namespace BankFileParsers
{
    public class BaiDetail
    {
        public string TransactionDetail { get; private set; }
        public List<string> DetailContinuation { get; internal set; }
        public BaiDetail(string line)
        {
            TransactionDetail = line;
            DetailContinuation = new List<string>();
        }
    }
}

using System.Collections.Generic;

namespace BankFileParsers
{
    public class BaiDetail
    {
        public string TransactionDetail { get; private set; }
        public List<string> DetailContinuation { get; internal set; }
        public BaiDetail(string line)
        {
            TransactionDetail = line;
            DetailContinuation = new List<string>();
        }

        /// <summary>
        /// Overwrite the TransactionDetail line with a new string
        /// </summary>
        /// <param name="line">New string to overwrite with</param>
        public void SetTransactionDetail(string line)
        {
            TransactionDetail = line;
        }
    }
}

Add new method to overwrite TransactionDetail line with a new string.


using UnityEngine;

[CreateAssetMenu (menuName = "AI/Actions/Enemy_Patrol")]
public class Action_Patrol : Action
{
	public override void Act(StateController controller)
	{
		Act(controller as Enemy_StateController);
    }

	public void Act(Enemy_StateController controller)
    {
        Patrol(controller);
    }

    private void Patrol(Enemy_StateController controller)
    {
        controller.navMeshAgent.destination = controller.movementVariables.wayPointList [controller.movementVariables.nextWayPoint].position;
        controller.navMeshAgent.Resume ();

        if (controller.navMeshAgent.remainingDistance <= controller.navMeshAgent.stoppingDistance && !controller.navMeshAgent.pathPending)
        {
            controller.movementVariables.nextWayPoint = (controller.movementVariables.nextWayPoint + 1) % controller.movementVariables.wayPointList.Count;
        }
    }
}

using UnityEngine;

[CreateAssetMenu (menuName = "AI/Actions/Enemy_Patrol")]
public class Action_Patrol : Action
{
	public override void Act(StateController controller)
	{
		Act(controller as Enemy_StateController);
    }

	public void Act(Enemy_StateController controller)
    {
        Patrol(controller);
    }

    private void Patrol(Enemy_StateController controller)
    {
        controller.navMeshAgent.destination = controller.movementVariables.wayPointList [controller.movementVariables.nextWayPoint].position;
        controller.navMeshAgent.isStopped = false;

        if (controller.navMeshAgent.remainingDistance <= controller.navMeshAgent.stoppingDistance && !controller.navMeshAgent.pathPending)
        {
            controller.movementVariables.nextWayPoint = (controller.movementVariables.nextWayPoint + 1) % controller.movementVariables.wayPointList.Count;
        }
    }
}

Replace obsolete NavMeshAgent interface fot he newer one


using System.Reflection;

[assembly: AssemblyTitle("Autofac.Extras.Tests.AggregateService")]
[assembly: AssemblyDescription("")]

Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.


using OpenQA.Selenium;
using System;

namespace Atata
{
    // TODO: Review IWebElementExtensions class. Remove unused methods.
    public static class IWebElementExtensions
    {
        public static WebElementExtendedSearchContext Try(this IWebElement element)
        {
            return new WebElementExtendedSearchContext(element);
        }

        public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout)
        {
            return new WebElementExtendedSearchContext(element, timeout);
        }

        public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout, TimeSpan retryInterval)
        {
            return new WebElementExtendedSearchContext(element, timeout, retryInterval);
        }

        public static bool HasContent(this IWebElement element, string content)
        {
            return element.Text.Contains(content);
        }

        public static string GetValue(this IWebElement element)
        {
            return element.GetAttribute("value");
        }

        public static IWebElement FillInWith(this IWebElement element, string text)
        {
            element.Clear();
            if (!string.IsNullOrEmpty(text))
                element.SendKeys(text);
            return element;
        }
    }
}

using System;
using System.Linq;
using OpenQA.Selenium;

namespace Atata
{
    // TODO: Review IWebElementExtensions class. Remove unused methods.
    public static class IWebElementExtensions
    {
        public static WebElementExtendedSearchContext Try(this IWebElement element)
        {
            return new WebElementExtendedSearchContext(element);
        }

        public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout)
        {
            return new WebElementExtendedSearchContext(element, timeout);
        }

        public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout, TimeSpan retryInterval)
        {
            return new WebElementExtendedSearchContext(element, timeout, retryInterval);
        }

        public static bool HasContent(this IWebElement element, string content)
        {
            return element.Text.Contains(content);
        }

        public static bool HasClass(this IWebElement element, string className)
        {
            return element.GetAttribute("class").Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Contains(className);
        }

        public static string GetValue(this IWebElement element)
        {
            return element.GetAttribute("value");
        }

        public static IWebElement FillInWith(this IWebElement element, string text)
        {
            element.Clear();
            if (!string.IsNullOrEmpty(text))
                element.SendKeys(text);
            return element;
        }
    }
}

Add HasClass extension method for IWebElement


using System;
using Xamarin.Forms;

namespace XamarinTest
{
	public class App : Application
	{
		public App ()
		{
			// The root page of your application
			MainPage = new ContentPage {
				Content = new StackLayout {
					VerticalOptions = LayoutOptions.Center,
					Children = {
						new Label {
							XAlign = TextAlignment.Center,
							Text = "Welcome to Xamarin Forms!"
						}
					}
				}
			};
		}

		protected override void OnStart ()
		{
			TelemetryManager.TrackEvent ("My Shared Event");
		}

		protected override void OnSleep ()
		{
			// Handle when your app sleeps
		}

		protected override void OnResume ()
		{
			// Handle when your app resumes
		}
	}
}

using System;
using Xamarin.Forms;

namespace XamarinTest
{
	public class App : Application
	{
		public App ()
		{
			// The root page of your application
			MainPage = new ContentPage {
				Content = new StackLayout {
					VerticalOptions = LayoutOptions.Center,
					Children = {
						new Label {
							XAlign = TextAlignment.Center,
							Text = "Welcome to Xamarin Forms!"
						}
					}
				}
			};
		}

		protected override void OnStart ()
		{
			TelemetryManager.TrackEvent ("My Shared Event");
			ApplicationInsights.RenewSessionWithId ("MySession");
			ApplicationInsights.SetUserId ("Christoph");
			TelemetryManager.TrackMetric ("My custom metric", 2.2);
		}

		protected override void OnSleep ()
		{
			// Handle when your app sleeps
		}

		protected override void OnResume ()
		{
			// Handle when your app resumes
		}
	}
}

Use public interface in test app

Use public interface in test app


using NLog;
using Sandbox;
using Torch.API;
using Torch.Managers;
using VRage.Dedicated.RemoteAPI;

namespace Torch.Server.Managers
{
    public class RemoteAPIManager : Manager
    {
        /// <inheritdoc />
        public RemoteAPIManager(ITorchBase torchInstance) : base(torchInstance)
        {

        }

        /// <inheritdoc />
        public override void Attach()
        {
            if (MySandboxGame.ConfigDedicated.RemoteApiEnabled && !string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.RemoteSecurityKey))
            {
                var myRemoteServer = new MyRemoteServer(MySandboxGame.ConfigDedicated.RemoteApiPort, MySandboxGame.ConfigDedicated.RemoteSecurityKey);
                LogManager.GetCurrentClassLogger().Info($"Remote API started on port {myRemoteServer.Port}");
            }
            base.Attach();
        }
    }
}

using NLog;
using Sandbox;
using Torch.API;
using Torch.Managers;
using VRage.Dedicated.RemoteAPI;

namespace Torch.Server.Managers
{
    public class RemoteAPIManager : Manager
    {
        /// <inheritdoc />
        public RemoteAPIManager(ITorchBase torchInstance) : base(torchInstance)
        {

        }

        /// <inheritdoc />
        public override void Attach()
        {
            Torch.GameStateChanged += TorchOnGameStateChanged;
            base.Attach();
        }

        /// <inheritdoc />
        public override void Detach()
        {
            Torch.GameStateChanged -= TorchOnGameStateChanged;
            base.Detach();
        }

        private void TorchOnGameStateChanged(MySandboxGame game, TorchGameState newstate)
        {
            if (newstate == TorchGameState.Loading && MySandboxGame.ConfigDedicated.RemoteApiEnabled && !string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.RemoteSecurityKey))
            {
                var myRemoteServer = new MyRemoteServer(MySandboxGame.ConfigDedicated.RemoteApiPort, MySandboxGame.ConfigDedicated.RemoteSecurityKey);
                LogManager.GetCurrentClassLogger().Info($"Remote API started on port {myRemoteServer.Port}");
            }
        }
    }
}

Fix remote API load order

Fix remote API load order