using System.Linq;
using UnityEngine;
using UnityEditor;

namespace EasyButtons
{
    /// <summary>
    /// Base class for making EasyButtons work
    /// </summary>
    public abstract class ButtonEditorBase : Editor
    {
        public override void OnInspectorGUI()
        {
            // Loop through all methods with the Button attribute and no arguments
            foreach (var method in target.GetType().GetMethods()
                .Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0)
                .Where(m => m.GetParameters().Length == 0))
            {
                // Draw a button which invokes the method
                if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name)))
                {
                    method.Invoke(target, null);
                }
            }
            // Draw the rest of the inspector as usual
            DrawDefaultInspector();
        }
    }

    /// <summary>
    /// Custom inspector for MonoBehaviour including derived classes.
    /// </summary>
    [CustomEditor(typeof(MonoBehaviour), true)]
    public class MonoBehaviourEditor : ButtonEditorBase { }

    /// <summary>
    /// Custom inspector for ScriptableObject including derived classes.
    /// </summary>
    [CustomEditor(typeof(ScriptableObject), true)]
    public class ScriptableObjectEditor : ButtonEditorBase { }
}

using System.Linq;
using UnityEngine;
using UnityEditor;

namespace EasyButtons
{
    /// <summary>
    /// Custom inspector for Object including derived classes.
    /// </summary>
    [CustomEditor(typeof(Object), true)]
    public class ObjectEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            // Loop through all methods with the Button attribute and no arguments
            foreach (var method in target.GetType().GetMethods()
                .Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0)
                .Where(m => m.GetParameters().Length == 0))
            {
                // Draw a button which invokes the method
                if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name)))
                {
                    method.Invoke(target, null);
                }
            }
            // Draw the rest of the inspector as usual
            DrawDefaultInspector();
        }
    }
}

Simplify the editor to work for any object


using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Update assembly version to 1.0

Update assembly version to 1.0

git-svn-id: 6d1cac2d86fac78d43d5e0dd3566a1010e844f91@55007 81fbe566-5dc4-48c1-bdea-7421811ca204


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

namespace SFA.DAS.EmployerUsers.Application
{
    public class InvalidRequestException : Exception
    {
        public  Dictionary<string,string> ErrorMessages { get; private set; }

        public InvalidRequestException(Dictionary<string,string> errorMessages)
            : base(BuildErrorMessage(errorMessages))
        {
            this.ErrorMessages = errorMessages;
        }

        private static string BuildErrorMessage(Dictionary<string, string> errorMessages)
        {
            return "Request is invalid:\n"
                   + errorMessages.Select(kvp => $"{kvp.Key}: {kvp.Value}").Aggregate((x, y) => $"{x}\n{y}");
        }
    }
}

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

namespace SFA.DAS.EmployerUsers.Application
{
    public class InvalidRequestException : Exception
    {
        public Dictionary<string, string> ErrorMessages { get; private set; }

        public InvalidRequestException(Dictionary<string, string> errorMessages)
            : base(BuildErrorMessage(errorMessages))
        {
            this.ErrorMessages = errorMessages;
        }

        private static string BuildErrorMessage(Dictionary<string, string> errorMessages)
        {
            if (errorMessages.Count == 0)
            {
                return "Request is invalid";
            }
            return "Request is invalid:\n"
                   + errorMessages.Select(kvp => $"{kvp.Key}: {kvp.Value}").Aggregate((x, y) => $"{x}\n{y}");
        }
    }
}

Fix error message building when no specific errors defined


using System.Text;

namespace SnippetsToMarkdown.Commands
{
    class WriteHeaderHtmlCommand : ICommand
    {
        private string directory;

        public WriteHeaderHtmlCommand(string directory)
        {
            this.directory = directory;
        }

        public void WriteToOutput(StringBuilder output)
        {
            output.AppendLine("
" + directory.Substring(directory.LastIndexOf('\\') + 1) + "
");
            output.AppendLine("
");
            output.AppendLine("
");

            output.AppendLine("
");
            output.AppendLine("
");
            output.AppendLine("Shortcut	");
            output.AppendLine("Name	");
            output.AppendLine("
");
            output.AppendLine("
");

            output.AppendLine("
");
        }
    }
}

Change HTML table header generation to use the correct th HTML tag.


using System.Linq;
using Kudu.Core.Deployment;
using Kudu.FunctionalTests.Infrastructure;
using Kudu.TestHarness;
using Xunit;

namespace Kudu.FunctionalTests
{
    public class GitStabilityTests
    {
        [Fact]
        public void NSimpleDeployments()
        {
            string repositoryName = "HelloKudu";
            string cloneUrl = "https://github.com/KuduApps/HelloKudu.git";
            using (Git.Clone(repositoryName, cloneUrl))
            {
                for (int i = 0; i < 5; i++)
                {
                    string applicationName = repositoryName + i;
                    ApplicationManager.Run(applicationName, appManager =>
                    {
                        // Act
                        appManager.AssertGitDeploy(repositoryName);
                        var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList();

                        // Assert
                        Assert.Equal(1, results.Count);
                        Assert.Equal(DeployStatus.Success, results[0].Status);
                        KuduAssert.VerifyUrl(appManager.SiteUrl, "Hello Kudu");
                    });
                }
            }
        }
    }
}

using System.Linq;
using Kudu.Core.Deployment;
using Kudu.FunctionalTests.Infrastructure;
using Kudu.TestHarness;
using Xunit;

namespace Kudu.FunctionalTests
{
    public class GitStabilityTests
    {
        [Fact]
        public void NSimpleDeployments()
        {
            string repositoryName = "HelloKudu";
            string cloneUrl = "https://github.com/KuduApps/HelloKudu.git";
            using (Git.Clone(repositoryName, cloneUrl))
            {
                for (int i = 0; i < 5; i++)
                {
                    string applicationName = KuduUtils.GetRandomWebsiteName(repositoryName + i);
                    ApplicationManager.Run(applicationName, appManager =>
                    {
                        // Act
                        appManager.AssertGitDeploy(repositoryName);
                        var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList();

                        // Assert
                        Assert.Equal(1, results.Count);
                        Assert.Equal(DeployStatus.Success, results[0].Status);
                        KuduAssert.VerifyUrl(appManager.SiteUrl, "Hello Kudu");
                    });
                }
            }
        }
    }
}

Use random app name to avoid 409 conflict error


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;

namespace OmniSharp.Utilities
{
    public class DirectoryEnumerator
    {
        private ILogger _logger;

        public DirectoryEnumerator(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
        }

        public IEnumerable<string> SafeEnumerateFiles(string path, string searchPattern)
        {
            if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
            {
                yield break;
            }

            string[] files = null;
            string[] directories = null;

            try
            {
                // Get the files and directories now so we can get any exceptions up front
                files = Directory.GetFiles(path, searchPattern);
                directories = Directory.GetDirectories(path);
            }
            catch (UnauthorizedAccessException)
            {
                _logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", path));
                yield break;
            }
            catch (PathTooLongException)
            {
                _logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
                yield break;
            }

            foreach (var file in files)
            {
                yield return file;
            }

            foreach (var file in directories.SelectMany(x => SafeEnumerateFiles(x, searchPattern)))
            {
                yield return file;
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;

namespace OmniSharp.Utilities
{
    public class DirectoryEnumerator
    {
        private ILogger _logger;

        public DirectoryEnumerator(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
        }

        public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*")
        {
            var allFiles = Enumerable.Empty<string>();

            var directoryStack = new Stack<string>();
            directoryStack.Push(target);

            while (directoryStack.Any())
            {
                var current = directoryStack.Pop();

                try
                {
                    allFiles = allFiles.Concat(GetFiles(current, pattern));

                    foreach (var subdirectory in GetSubdirectories(current))
                    {
                        directoryStack.Push(subdirectory);
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    _logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current));
                }
            }

            return allFiles;
        }

        private IEnumerable<string> GetFiles(string path, string pattern)
        {
            try
            {
                return Directory.EnumerateFiles(path, pattern, SearchOption.TopDirectoryOnly);
            }
            catch (PathTooLongException)
            {
                _logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
                return Enumerable.Empty<string>();
            }
        }

        private IEnumerable<string> GetSubdirectories(string path)
        {
            try
            {
                return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
            }
            catch (PathTooLongException)
            {
                _logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
                return Enumerable.Empty<string>();
            }
        }
    }
}

Replace recursive file enumeration with a stack based approach


using System;
using System.Collections.Generic;
using Autofac;
using NRules.Fluent;
using NRules.Fluent.Dsl;

namespace NRules.Integration.Autofac
{
    /// <summary>
    /// Rule activator that uses Autofac DI container.
    /// </summary>
    public class AutofacRuleActivator : IRuleActivator
    {
        private readonly ILifetimeScope _container;

        public AutofacRuleActivator(ILifetimeScope container)
        {
            _container = container;
        }

        public IEnumerable<Rule> Activate(Type type)
        {
            if (_container.IsRegistered(type))
                yield return (Rule) _container.Resolve(type);

            yield return (Rule)Activator.CreateInstance(type);
        }
    }
}

using System;
using System.Collections.Generic;
using Autofac;
using NRules.Fluent;
using NRules.Fluent.Dsl;

namespace NRules.Integration.Autofac
{
    /// <summary>
    /// Rule activator that uses Autofac DI container.
    /// </summary>
    public class AutofacRuleActivator : IRuleActivator
    {
        private readonly ILifetimeScope _container;

        public AutofacRuleActivator(ILifetimeScope container)
        {
            _container = container;
        }

        public IEnumerable<Rule> Activate(Type type)
        {
            if (_container.IsRegistered(type))
            {
                var collectionType = typeof (IEnumerable<>).MakeGenericType(type);
                return (IEnumerable<Rule>)_container.Resolve(collectionType);
            }

            return ActivateDefault(type);
        }

        private static IEnumerable<Rule> ActivateDefault(Type type)
        {
            yield return (Rule) Activator.CreateInstance(type);
        }
    }
}

Allow multiple rule instances in autofac activator


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

namespace DupImage
{
    /// <summary>
    /// Structure for containing image information and hash values.
    /// </summary>
    public class ImageStruct
    {
        /// <summary>
        /// Construct a new ImageStruct from FileInfo.
        /// </summary>
        /// <param name="file">FileInfo to be used.</param>
        public ImageStruct(FileInfo file)
        {
            if (file == null) throw new ArgumentNullException("file");

            ImagePath = file.FullName;

            // Init Hash
            Hash = new long[1];
        }

        /// <summary>
        /// Construct a new ImageStruct from image path.
        /// </summary>
        /// <param name="pathToImage">Image location</param>
        public ImageStruct(String pathToImage)
        {
            ImagePath = pathToImage;

            // Init Hash
            Hash = new long[1];
        }

        /// <summary>
        /// ImagePath information.
        /// </summary>
        public String ImagePath { get; private set; }

        /// <summary>
        /// Hash of the image. Uses longs instead of ulong to be CLS compliant.
        /// </summary>
        public long[] Hash { get; set; }

    }
}

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

namespace DupImage
{
    /// <summary>
    /// Structure for containing image information and hash values.
    /// </summary>
    public class ImageStruct
    {
        /// <summary>
        /// Construct a new ImageStruct from FileInfo.
        /// </summary>
        /// <param name="file">FileInfo to be used.</param>
        public ImageStruct(FileInfo file)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));

            ImagePath = file.FullName;

            // Init Hash
            Hash = new long[1];
        }

        /// <summary>
        /// Construct a new ImageStruct from image path.
        /// </summary>
        /// <param name="pathToImage">Image location</param>
        public ImageStruct(String pathToImage)
        {
            ImagePath = pathToImage;

            // Init Hash
            Hash = new long[1];
        }

        /// <summary>
        /// ImagePath information.
        /// </summary>
        public String ImagePath { get; private set; }

        /// <summary>
        /// Hash of the image. Uses longs instead of ulong to be CLS compliant.
        /// </summary>
        public long[] Hash { get; set; }

    }
}

Use nameof operator instead of magic string.


namespace Nett.Extensions
{
    using System;

    internal static class GenericExtensions
    {
        public static T CheckNotNull<T>(this T toCheck, string argName)
            where T : class
        {
            if (toCheck == null) { throw new ArgumentNullException(nameof(argName)); }

            return toCheck;
        }
    }
}

namespace Nett.Extensions
{
    using System;

    internal static class GenericExtensions
    {
        public static T CheckNotNull<T>(this T toCheck, string argName)
            where T : class
        {
            if (toCheck == null) { throw new ArgumentNullException(argName); }

            return toCheck;
        }
    }
}

Fix that check not null message didn't contain argument name


using ImageResizer.Plugins;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImageResizer.Sitecore.Plugin
{
    public class SitecoreVirtualImageProviderPlugin : IPlugin, IVirtualImageProvider
    {
        public IPlugin Install(global::ImageResizer.Configuration.Config c)
        {
            c.Plugins.add_plugin(this);
            return this;
        }

        public bool Uninstall(global::ImageResizer.Configuration.Config c)
        {
            c.Plugins.remove_plugin(this);
            return true;
        }

        private string FixVirtualPath(string virtualPath)
        {
            var subIndex = virtualPath.LastIndexOf("~");
            if (subIndex < 0)
            {
                subIndex = virtualPath.LastIndexOf("-");
            }

            if (subIndex > 0)
            {
                return virtualPath.Substring(subIndex);
            }
            else
            {
                return virtualPath;
            }
        }

        public bool FileExists(string virtualPath, NameValueCollection queryString)
        {
            virtualPath = FixVirtualPath(virtualPath);
            DynamicLink dynamicLink;

            return queryString.Count > 0 && DynamicLink.TryParse(virtualPath, out dynamicLink);
        }

        public IVirtualFile GetFile(string virtualPath, NameValueCollection queryString)
        {
            virtualPath = FixVirtualPath(virtualPath);

            return new SitecoreVirtualFile(virtualPath);
        }
    }
}

using ImageResizer.Plugins;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImageResizer.Sitecore.Plugin
{
    public class SitecoreVirtualImageProviderPlugin : IPlugin, IVirtualImageProvider
    {
        public IPlugin Install(global::ImageResizer.Configuration.Config c)
        {
            c.Plugins.add_plugin(this);
            return this;
        }

        public bool Uninstall(global::ImageResizer.Configuration.Config c)
        {
            c.Plugins.remove_plugin(this);
            return true;
        }

        private string FixVirtualPath(string virtualPath)
        {
            var subIndex = virtualPath.LastIndexOf("~");
            if (subIndex < 0)
            {
                subIndex = virtualPath.LastIndexOf("-");
            }

            if (subIndex > 0)
            {
                return virtualPath.Substring(subIndex);
            }
            else
            {
                return virtualPath;
            }
        }

        public bool FileExists(string virtualPath, NameValueCollection queryString)
        {
            if (virtualPath.StartsWith("/sitecore/shell/-"))
            {
                return false;
            }

            virtualPath = FixVirtualPath(virtualPath);
            DynamicLink dynamicLink;

            return queryString.Count > 0 && DynamicLink.TryParse(virtualPath, out dynamicLink);
        }

        public IVirtualFile GetFile(string virtualPath, NameValueCollection queryString)
        {
            virtualPath = FixVirtualPath(virtualPath);

            return new SitecoreVirtualFile(virtualPath);
        }
    }
}

Fix to the browse images coming up 404.

Fix to the browse images coming up 404.


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

public class MemberProperty : MonoBehaviour {
    public float E, I, length;
    public int number;
}

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

public class MemberProperty : MonoBehaviour {
    public float length;
    public int number,type;

    float[] E = { 1 };
    float[] I = { 1 };

    public float GetI()
    {
        return I[type];
    }

    public float GetE()
    {
        return E[type];
    }
}

Use type to find E I

Use type to find E I


using System;
using Simpler;
using Schedules.API.Models;
using Dapper;
using System.Linq;

namespace Schedules.API.Tasks
{
  public class CreateReminder: InOutTask<CreateReminder.Input, CreateReminder.Output>
  {
    public FetchReminderType FetchReminderType { get; set; }

    public class Input
    {
      public Reminder Reminder { get; set; }
      public String ReminderTypeName { get; set; }
    }

    public class Output
    {
      public Reminder Reminder { get; set; }
    }

    public override void Execute()
    {
      FetchReminderType.In.ReminderTypeName = In.ReminderTypeName;
      FetchReminderType.Execute();
      In.Reminder.ReminderType = FetchReminderType.Out.ReminderType;

      Out.Reminder = new Reminder ();

      using (var connection = Db.Connect ()) {
        try{
          Out.Reminder = connection.Query<Reminder, ReminderType, Reminder>(
            sql,
            (reminder, reminderType) => {reminder.ReminderType = reminderType; return reminder;},
            In.Reminder).SingleOrDefault();
        }
        catch(Exception ex){
          Console.WriteLine (ex);
        }
      }
    }

    const string sql = @"
      with insertReminder as (
        insert into Reminders(contact, message, verified, address, reminder_type_id)
        values(@Contact, @Message, @Verified, @Address, @ReminderTypeId) returning *
      )
      select *
      from insertReminder r
      left join reminder_types t
        on t.id = r.reminder_type_id
      ;
    ";
  }
}

using System;
using Simpler;
using Schedules.API.Models;
using Dapper;
using System.Linq;

namespace Schedules.API.Tasks
{
  public class CreateReminder: InOutTask<CreateReminder.Input, CreateReminder.Output>
  {
    public FetchReminderType FetchReminderType { get; set; }

    public class Input
    {
      public Reminder Reminder { get; set; }
      public String ReminderTypeName { get; set; }
    }

    public class Output
    {
      public Reminder Reminder { get; set; }
    }

    public override void Execute()
    {
      FetchReminderType.In.ReminderTypeName = In.ReminderTypeName;
      FetchReminderType.Execute();
      In.Reminder.ReminderType = FetchReminderType.Out.ReminderType;

      Out.Reminder = new Reminder ();

      using (var connection = Db.Connect ()) {
        try{
          Out.Reminder = connection.Query<Reminder, ReminderType, Reminder>(
            sql,
            (reminder, reminderType) => {reminder.ReminderType = reminderType; return reminder;},
            In.Reminder).SingleOrDefault();
        }
        catch(Exception ex){
          Console.WriteLine (ex);
        }
      }
    }

    const string sql = @"
      with insertReminder as (
        insert into Reminders(contact, message, remind_on, verified, address, reminder_type_id)
        values(@Contact, @Message, @RemindOn, @Verified, @Address, @ReminderTypeId) returning *
      )
      select *
      from insertReminder r
      left join reminder_types t
        on t.id = r.reminder_type_id
      ;
    ";
  }
}

Add remind_on to insert statement

Add remind_on to insert statement


// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System.Collections.Generic;
using Scriban.Parsing;
using Scriban.Syntax;

namespace Scriban.Runtime
{
    /// <summary>
    /// The empty object (unique singleton, cannot be modified, does not contain any properties)
    /// </summary>
    public sealed class EmptyScriptObject : IScriptObject
    {
        public static readonly EmptyScriptObject Default = new EmptyScriptObject();

        private EmptyScriptObject()
        {
        }

        public int Count => 0;

        public IEnumerable<string> GetMembers()
        {
            yield break;
        }

        public bool Contains(string member)
        {
            return false;
        }

        public bool IsReadOnly
        {
            get => true;
            set { }
        }

        public bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value)
        {
            value = null;
            return false;
        }

        public bool CanWrite(string member)
        {
            return false;
        }

        public void SetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly)
        {
            throw new ScriptRuntimeException(span, "Cannot set a property on the empty object");
        }

        public bool Remove(string member)
        {
            return false;
        }

        public void SetReadOnly(string member, bool readOnly)
        {
        }

        public IScriptObject Clone(bool deep)
        {
            return this;
        }
    }
}

// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using Scriban.Parsing;
using Scriban.Syntax;

namespace Scriban.Runtime
{
    /// <summary>
    /// The empty object (unique singleton, cannot be modified, does not contain any properties)
    /// </summary>
    [DebuggerDisplay("<empty object>")]
    public sealed class EmptyScriptObject : IScriptObject
    {
        public static readonly EmptyScriptObject Default = new EmptyScriptObject();

        private EmptyScriptObject()
        {
        }

        public int Count => 0;

        public IEnumerable<string> GetMembers()
        {
            yield break;
        }

        public bool Contains(string member)
        {
            return false;
        }

        public bool IsReadOnly
        {
            get => true;
            set { }
        }

        public bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value)
        {
            value = null;
            return false;
        }

        public bool CanWrite(string member)
        {
            return false;
        }

        public void SetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly)
        {
            throw new ScriptRuntimeException(span, "Cannot set a property on the empty object");
        }

        public bool Remove(string member)
        {
            return false;
        }

        public void SetReadOnly(string member, bool readOnly)
        {
        }

        public IScriptObject Clone(bool deep)
        {
            return this;
        }

        public override string ToString()
        {
            return string.Empty;
        }
    }
}

Add ToString method to empty object

Add ToString method to empty object


using System;

namespace THNETII.Common
{
    public static class ArgumentExtensions
    {
        public static T ThrowIfNull<T>(this T instance, string name) where T : class
            => instance ?? throw new ArgumentNullException(name);
    }
}

using System;

namespace THNETII.Common
{
    public static class ArgumentExtensions
    {
        public static T ThrowIfNull<T>(this T instance, string name) where T : class
            => instance ?? throw new ArgumentNullException(name);

        /// <exception cref="ArgumentException" />
        /// <exception cref="ArgumentNullException" />
        public static string ThrowIfNullOrWhiteSpace(this string value, string name)
        {
            if (string.IsNullOrWhiteSpace(value))
                throw value == null ? new ArgumentNullException(nameof(name)) : new ArgumentException("value must neither be empty, nor null, nor whitespace-only.", name);
            return value;
        }
    }
}

Add String Argument Extension method

Add String Argument Extension method


using System;

public static class ExtensionMethods
{
    public static string Str(this TimeSpan duration)
    {
        var hours = Math.Abs((int)duration.TotalHours);
        var minutes = Math.Abs(duration.Minutes);
        int seconds = Math.Abs(duration.Seconds);
        if (Math.Abs(duration.Milliseconds) >= 500)
            seconds++;

        if (duration >= TimeSpan.Zero)
            return string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
        else
            return string.Format("-{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
    }
}

using System;

public static class ExtensionMethods
{
    public static string Str(this TimeSpan duration)
    {
        var hours = Math.Abs((int)duration.TotalHours);
        var minutes = Math.Abs(duration.Minutes);
        int seconds = Math.Abs(duration.Seconds);

        if (duration >= TimeSpan.Zero)
            return string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
        else
            return string.Format("-{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
    }
}

Remove unnecessary, and wrong, check

MiscUtils: Remove unnecessary, and wrong, check


using System.Collections.Generic;

namespace Octokit
{
    public class OauthToken
    {
        public string TokenType { get; set; }
        public string AccessToken { get; set; }
        public IReadOnlyCollection<string> Scope { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;

namespace Octokit
{
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class OauthToken
    {
        /// <summary>
        /// The type of OAuth token
        /// </summary>
        public string TokenType { get; set; }

        /// <summary>
        /// The secret OAuth access token. Use this to authenticate Octokit.net's client.
        /// </summary>
        public string AccessToken { get; set; }

        /// <summary>
        /// The list of scopes the token includes.
        /// </summary>
        public IReadOnlyCollection<string> Scope { get; set; }

        internal string DebuggerDisplay
        {
            get
            {
                return String.Format(CultureInfo.InvariantCulture, "TokenType: {0}, AccessToken: {1}, Scopes: {2}",
                    TokenType,
                    AccessToken,
                    Scope);
            }
        }
    }
}

Add comments and debugger display

Add comments and debugger display


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;

namespace ClosedXML.Excel
{
    internal class XLCFDataBarConverter:IXLCFConverter
    {
        public ConditionalFormattingRule Convert(IXLConditionalFormat cf, Int32 priority, XLWorkbook.SaveContext context)
        {
            var conditionalFormattingRule = new ConditionalFormattingRule { Type = cf.ConditionalFormatType.ToOpenXml(), Priority = priority };

            var dataBar = new DataBar {ShowValue = !cf.ShowBarOnly};
            var conditionalFormatValueObject1 = new ConditionalFormatValueObject { Type = cf.ContentTypes[1].ToOpenXml()};
            if (cf.Values.Count >= 1) conditionalFormatValueObject1.Val = cf.Values[1].Value;

            var conditionalFormatValueObject2 = new ConditionalFormatValueObject { Type = cf.ContentTypes[2].ToOpenXml()};
            if (cf.Values.Count >= 2) conditionalFormatValueObject2.Val = cf.Values[2].Value;

            var color = new Color { Rgb = cf.Colors[1].Color.ToHex() };

            dataBar.Append(conditionalFormatValueObject1);
            dataBar.Append(conditionalFormatValueObject2);
            dataBar.Append(color);

            conditionalFormattingRule.Append(dataBar);

            return conditionalFormattingRule;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;

namespace ClosedXML.Excel
{
    internal class XLCFDataBarConverter : IXLCFConverter
    {
        public ConditionalFormattingRule Convert(IXLConditionalFormat cf, Int32 priority, XLWorkbook.SaveContext context)
        {
            var conditionalFormattingRule = new ConditionalFormattingRule { Type = cf.ConditionalFormatType.ToOpenXml(), Priority = priority };

            var dataBar = new DataBar { ShowValue = !cf.ShowBarOnly };
            var conditionalFormatValueObject1 = new ConditionalFormatValueObject { Type = cf.ContentTypes[1].ToOpenXml() };
            if (cf.Values.Any() && cf.Values[1]?.Value != null) conditionalFormatValueObject1.Val = cf.Values[1].Value;

            var conditionalFormatValueObject2 = new ConditionalFormatValueObject { Type = cf.ContentTypes[2].ToOpenXml() };
            if (cf.Values.Count >= 2 && cf.Values[2]?.Value != null) conditionalFormatValueObject2.Val = cf.Values[2].Value;

            var color = new Color();
            switch (cf.Colors[1].ColorType)
            {
                case XLColorType.Color:
                    color.Rgb = cf.Colors[1].Color.ToHex();
                    break;
                case XLColorType.Theme:
                    color.Theme = System.Convert.ToUInt32(cf.Colors[1].ThemeColor);
                    break;
                case XLColorType.Indexed:
                    color.Indexed = System.Convert.ToUInt32(cf.Colors[1].Indexed);
                    break;
            }

            dataBar.Append(conditionalFormatValueObject1);
            dataBar.Append(conditionalFormatValueObject2);
            dataBar.Append(color);

            conditionalFormattingRule.Append(dataBar);

            return conditionalFormattingRule;
        }
    }
}

Fix data bar for min/max

Fix data bar for min/max


@using Csla.Web.Mvc
@using ProjectTracker.Library

@model IEnumerable<ProjectTracker.Library.ProjectInfo>

@{
    ViewBag.Title = "Project list";
}

@ViewBag.Message

      @Html.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit), Html.ActionLink("Create New", "Create"), string.Empty)
      @if (Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit)))
      {
        @Html.ActionLink("Create New", "Create")
      }

                Name

    @foreach (var item in Model) {

                @Html.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectEdit), Html.ActionLink("Edit", "Edit", new { id = item.Id }), "Edit") |
                @Html.ActionLink("Details", "Details", new { id=item.Id }) |
                @Html.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectEdit), Html.ActionLink("Delete", "Delete", new { id = item.Id }), "Delete")

                @item.Name

    }

@using Csla.Web.Mvc
@using ProjectTracker.Library

@model IEnumerable<ProjectTracker.Library.ProjectInfo>

@{
    ViewBag.Title = "Project list";
}

@ViewBag.Message

      @Html.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit), Html.ActionLink("Create New", "Create"), string.Empty)

                Name

    @foreach (var item in Model) {

                @Html.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectEdit), Html.ActionLink("Edit", "Edit", new { id = item.Id }), "Edit") |
                @Html.ActionLink("Details", "Details", new { id=item.Id }) |
                @Html.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectEdit), Html.ActionLink("Delete", "Delete", new { id = item.Id }), "Delete")

                @item.Name

    }

Remove redundant code. bugid: 912

Remove redundant code.
bugid: 912


using System;
using System.Windows;

namespace CupCake.Client
{
    public static class Dispatch
    {
        public static void Invoke(Action callback)
        {
            Application.Current.Dispatcher.BeginInvoke(callback);
        }
    }
}

using System;
using System.Windows;

namespace CupCake.Client
{
    public static class Dispatch
    {
        public static void Invoke(Action callback)
        {
            Application.Current.Dispatcher.Invoke(callback);
        }
    }
}

Fix newConnection window is sometimes not displayed


using System.Linq;

using PicklesDoc.Pickles.ObjectModel;

namespace PicklesDoc.Pickles.TestFrameworks.XUnit
{
    public abstract class XUnitResultsBase<TSingleResult> : MultipleTestResults
        where TSingleResult : XUnitSingleResultsBase
    {
        public XUnitResultsBase(IConfiguration configuration, ISingleResultLoader singleResultLoader, XUnitExampleSignatureBuilder exampleSignatureBuilder)
            : base(true, configuration, singleResultLoader)
        {
            this.SetExampleSignatureBuilder(exampleSignatureBuilder);
        }

        public void SetExampleSignatureBuilder(XUnitExampleSignatureBuilder exampleSignatureBuilder)
        {
            foreach (var testResult in TestResults.OfType<TSingleResult>())
            {
                testResult.ExampleSignatureBuilder = exampleSignatureBuilder;
            }
        }

        public override TestResult GetExampleResult(ScenarioOutline scenarioOutline, string[] arguments)
        {
            var results = TestResults.OfType<TSingleResult>().Select(tr => tr.GetExampleResult(scenarioOutline, arguments)).ToArray();

            return EvaluateTestResults(results);
        }
    }
}

using System.Linq;

using PicklesDoc.Pickles.ObjectModel;

namespace PicklesDoc.Pickles.TestFrameworks.XUnit
{
    public abstract class XUnitResultsBase<TSingleResult> : MultipleTestResults
        where TSingleResult : XUnitSingleResultsBase
    {
        protected XUnitResultsBase(IConfiguration configuration, ISingleResultLoader singleResultLoader, XUnitExampleSignatureBuilder exampleSignatureBuilder)
            : base(true, configuration, singleResultLoader)
        {
            this.SetExampleSignatureBuilder(exampleSignatureBuilder);
        }

        public void SetExampleSignatureBuilder(XUnitExampleSignatureBuilder exampleSignatureBuilder)
        {
            foreach (var testResult in TestResults.OfType<TSingleResult>())
            {
                testResult.ExampleSignatureBuilder = exampleSignatureBuilder;
            }
        }

        public override TestResult GetExampleResult(ScenarioOutline scenarioOutline, string[] arguments)
        {
            var results = TestResults.OfType<TSingleResult>().Select(tr => tr.GetExampleResult(scenarioOutline, arguments)).ToArray();

            return EvaluateTestResults(results);
        }
    }
}

Make constructor of abstract class protected


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

namespace osu.Game.Overlays.Options.Sections.Audio
{
    public class AudioDevicesOptions : OptionsSubsection
    {
        protected override string Header => "Devices";

        public AudioDevicesOptions()
        {
            Children = new[]
            {
                new OptionLabel { Text = "Output device: TODO dropdown" }
            };
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Graphics;
using System.Collections.Generic;
using System.Linq;

namespace osu.Game.Overlays.Options.Sections.Audio
{
    public class AudioDevicesOptions : OptionsSubsection
    {
        protected override string Header => "Devices";

        private AudioManager audio;

        [BackgroundDependencyLoader]
        private void load(AudioManager audio)
        {
            this.audio = audio;
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            var deviceItems = new List<KeyValuePair<string, string>>();
            deviceItems.Add(new KeyValuePair<string, string>("Standard", ""));
            deviceItems.AddRange(audio.GetDeviceNames().Select(d => new KeyValuePair<string, string>(d, d)));
            Children = new Drawable[]
            {
                new OptionDropDown<string>()
                {
                    Items = deviceItems,
                    Bindable = audio.AudioDevice
                },
            };
        }
    }
}

Allow audio device selection in settings


using UnityEngine;
using System.Collections;

public class FollowCamera : MonoBehaviour {

  public GameObject global;
  public GameObject objectToFollow;

	// Use this for initialization
	void Start () {
    if (global == null)
    {
      return;
    }

    Global g = global.GetComponent<Global>();
    if (g == null)
    {
      return;
    }

    objectToFollow = g.hero;
	}

	// Update is called once per frame (use LateUpdate for cameras)
	void LateUpdate () {
    transform.LookAt(objectToFollow.transform);
	}
}

using UnityEngine;
using System.Collections;

public class FollowCamera : MonoBehaviour {

  public GameObject global;
  public GameObject objectToFollow;

	// Use this for initialization
	void Start () {
    if (global == null)
    {
      return;
    }

    Global g = global.GetComponent<Global>();
    if (g == null)
    {
      return;
    }

    objectToFollow = g.hero;
	}

	// Update is called once per frame (use LateUpdate for cameras)
	void LateUpdate () {
    if (objectToFollow != null)
    {
      transform.LookAt(objectToFollow.transform);
    }
    else
    {
      Global g = global.GetComponent<Global>();
      if (g == null)
      {
        return;
      }

      objectToFollow = g.hero;
    }
	}
}

Fix linking of follow camera to hero

Fix linking of follow camera to hero


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

using osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osu.Game.Input.Bindings;

namespace osu.Game.Overlays.Toolbar
{
    public class ToolbarMusicButton : ToolbarOverlayToggleButton
    {
        public ToolbarMusicButton()
        {
            Icon = FontAwesome.Solid.Music;
            TooltipMain = "Now playing";
            TooltipSub = "Manage the currently playing track";

            Hotkey = GlobalAction.ToggleNowPlaying;
        }

        [BackgroundDependencyLoader(true)]
        private void load(NowPlayingOverlay music)
        {
            StateContainer = music;
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Input.Bindings;

namespace osu.Game.Overlays.Toolbar
{
    public class ToolbarMusicButton : ToolbarOverlayToggleButton
    {
        protected override Anchor TooltipAnchor => Anchor.TopRight;

        public ToolbarMusicButton()
        {
            Icon = FontAwesome.Solid.Music;
            TooltipMain = "Now playing";
            TooltipSub = "Manage the currently playing track";

            Hotkey = GlobalAction.ToggleNowPlaying;
        }

        [BackgroundDependencyLoader(true)]
        private void load(NowPlayingOverlay music)
        {
            StateContainer = music;
        }
    }
}

Fix toolbar music button tooltip overflowing off-screen


namespace Miruken.Callback
{
    using System;

    public class Resolving : Inquiry, IResolveCallback
    {
        private bool _handled;

        public Resolving(object key, object callback)
            : base(key, true)
        {
            if (callback == null)
                throw new ArgumentNullException(nameof(callback));
            Callback = callback;
        }

        public object Callback { get; }

        object IResolveCallback.GetResolveCallback()
        {
            return this;
        }

        protected override bool IsSatisfied(
            object resolution, bool greedy, IHandler composer)
        {
            if (_handled && !greedy) return true;
            return _handled =
                Handler.Dispatch(resolution, Callback, ref greedy, composer)
                || _handled;
        }

        public static object GetDefaultResolvingCallback(object callback)
        {
            var dispatch = callback as IDispatchCallback;
            var policy   = dispatch?.Policy ?? HandlesAttribute.Policy;
            var handlers = policy.GetHandlers(callback);
            var bundle   = new Bundle(false);
            foreach (var handler in handlers)
                bundle.Add(h => h.Handle(new Resolving(handler, callback)));
            bundle.Add(h => h.Handle(callback));
            return bundle;
        }
    }
}

namespace Miruken.Callback
{
    using System;

    public class Resolving : Inquiry, IResolveCallback
    {
        private bool _handled;

        public Resolving(object key, object callback)
            : base(key, true)
        {
            if (callback == null)
                throw new ArgumentNullException(nameof(callback));
            Callback = callback;
        }

        public object Callback { get; }

        object IResolveCallback.GetResolveCallback()
        {
            return this;
        }

        protected override bool IsSatisfied(
            object resolution, bool greedy, IHandler composer)
        {
            if (_handled && !greedy) return true;
            return _handled =  Handler.Dispatch(
                resolution, Callback, ref greedy, composer)
                || _handled;
        }

        public static object GetDefaultResolvingCallback(object callback)
        {
            var dispatch = callback as IDispatchCallback;
            var policy   = dispatch?.Policy ?? HandlesAttribute.Policy;
            var handlers = policy.GetHandlers(callback);
            var bundle   = new Bundle(false);
            foreach (var handler in handlers)
                bundle.Add(h => h.Handle(new Resolving(handler, callback)));
            if (bundle.IsEmpty)
                bundle.Add(h => h.Handle(callback));
            return bundle;
        }
    }
}

Handle callback directly if resolve bundle is empty


using System;
using System.Linq;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Diploms.Core;
using System.Collections.Generic;

namespace Diploms.DataLayer
{
    public static class DiplomContentSystemExtensions
    {
        public static void EnsureSeedData(this DiplomContext context)
        {
            if (context.AllMigrationsApplied())
            {
                if (!context.Periods.Any())
                {
                    context.Periods.Add(Period.Current);
                }
                if (!context.Roles.Any())
                {
                    context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher);
                }
                if(!context.Users.Any())
                {
                    context.Users.Add(new User{
                        Id = 1,
                        Login = "admin",
                        PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=",
                        Roles = new List<UserRole>
                        {
                            new UserRole
                            {
                                UserId = 1,
                                RoleId = 1
                            }
                        }
                    });
                }
                context.SaveChanges();
            }
        }
        private static bool AllMigrationsApplied(this DiplomContext context)
        {
            var applied = context.GetService<IHistoryRepository>()
                .GetAppliedMigrations()
                .Select(m => m.MigrationId);

            var total = context.GetService<IMigrationsAssembly>()
                .Migrations
                .Select(m => m.Key);

            return !total.Except(applied).Any();
        }
    }
}

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Diploms.Core;
using System.Collections.Generic;

namespace Diploms.DataLayer
{
    public static class DiplomContentSystemExtensions
    {
        public static void EnsureSeedData(this DiplomContext context)
        {
            if (context.AllMigrationsApplied())
            {
                if (!context.Periods.Any())
                {
                    context.Periods.Add(Period.Current);
                }
                if (!context.TeachersPositions.Any())
                {
                    context.TeachersPositions.AddRange(TeacherPosition.HighTeacher, TeacherPosition.Professor, TeacherPosition.Doctor);
                }
                if (!context.Roles.Any())
                {
                    context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher);
                }
                if(!context.Users.Any())
                {
                    context.Users.Add(new User{
                        Id = 1,
                        Login = "admin",
                        PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=",
                        Roles = new List<UserRole>
                        {
                            new UserRole
                            {
                                UserId = 1,
                                RoleId = 1
                            }
                        }
                    });
                }
                context.SaveChanges();
            }
        }
        private static bool AllMigrationsApplied(this DiplomContext context)
        {
            var applied = context.GetService<IHistoryRepository>()
                .GetAppliedMigrations()
                .Select(m => m.MigrationId);

            var total = context.GetService<IMigrationsAssembly>()
                .Migrations
                .Select(m => m.Key);

            return !total.Except(applied).Any();
        }
    }
}

Add positions to db on startup

Add positions to db on startup


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

namespace BmpListener.Bmp
{
    public enum MessageType : byte
    {
        RouteMonitoring,
        StatisticsReport,
        PeerDown,
        PeerUp,
        Initiation,
        Termination,
        RouteMirroring
    }

    public enum PeerType : byte
    {
        Global,
        RD,
        Local
    }
}

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

namespace BmpListener.Bmp
{
    public enum MessageType
    {
        RouteMonitoring,
        StatisticsReport,
        PeerDown,
        PeerUp,
        Initiation,
        Termination,
        RouteMirroring
    }

    public enum PeerType
    {
        Global,
        RD,
        Local
    }
}

Remove enum underlying type declaration

Remove enum underlying type declaration


#region (c) 2010-2011 Lokad CQRS - New BSD License

// Copyright (c) Lokad SAS 2010-2011 (http://www.lokad.com)
// This code is released as Open Source under the terms of the New BSD Licence
// Homepage: http://lokad.github.com/lokad-cqrs/

#endregion

using System;
using System.Collections.Generic;
using ProtoBuf.Meta;

namespace Lokad.Cqrs.Core.Serialization
{
    public class DataSerializerWithProtoBuf : AbstractDataSerializer
    {
        public DataSerializerWithProtoBuf(ICollection<Type> knownTypes) : base(knownTypes)
        {
            if (knownTypes.Count == 0)
                throw new InvalidOperationException(
                    "ProtoBuf requires some known types to serialize. Have you forgot to supply them?");
        }

        protected override Formatter PrepareFormatter(Type type)
        {
            var name = ContractEvil.GetContractReference(type);
            var formatter = RuntimeTypeModel.Default.CreateFormatter(type);
            return new Formatter(name, formatter.Deserialize, (o, stream) => formatter.Serialize(stream,o));
        }
    }
}

#region (c) 2010-2011 Lokad CQRS - New BSD License

// Copyright (c) Lokad SAS 2010-2011 (http://www.lokad.com)
// This code is released as Open Source under the terms of the New BSD Licence
// Homepage: http://lokad.github.com/lokad-cqrs/

#endregion

using System;
using System.Collections.Generic;
using ProtoBuf.Meta;

namespace Lokad.Cqrs.Core.Serialization
{
    public class DataSerializerWithProtoBuf : AbstractDataSerializer
    {
        public DataSerializerWithProtoBuf(ICollection<Type> knownTypes) : base(knownTypes)
        {
        }

        protected override Formatter PrepareFormatter(Type type)
        {
            var name = ContractEvil.GetContractReference(type);
            var formatter = RuntimeTypeModel.Default.CreateFormatter(type);
            return new Formatter(name, formatter.Deserialize, (o, stream) => formatter.Serialize(stream,o));
        }
    }
}

Remove contract count check for protobuf


using NuGet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Squirrel
{
    public static class VersionExtensions
    {
        private static readonly Regex _suffixRegex = new Regex(@"(-full|-delta)?\.nupkg$", RegexOptions.Compiled);
        private static readonly Regex _versionRegex = new Regex(@"\d+(\.\d+){0,3}(-[a-z][0-9a-z-]*)?$", RegexOptions.Compiled);

        public static SemanticVersion ToSemanticVersion(this IReleasePackage package)
        {
            return package.InputPackageFile.ToSemanticVersion();
        }

        public static SemanticVersion ToSemanticVersion(this string fileName)
        {
            var name = _suffixRegex.Replace(fileName, "");
            var version = _versionRegex.Match(name).Value;
            return new SemanticVersion(version);
        }
    }
}

using NuGet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Squirrel
{
    public static class VersionExtensions
    {
        static readonly Regex _suffixRegex = new Regex(@"(-full|-delta)?\.nupkg$", RegexOptions.Compiled);
        static readonly Regex _versionRegex = new Regex(@"\d+(\.\d+){0,3}(-[a-z][0-9a-z-]*)?$", RegexOptions.Compiled);

        public static SemanticVersion ToSemanticVersion(this IReleasePackage package)
        {
            return package.InputPackageFile.ToSemanticVersion();
        }

        public static SemanticVersion ToSemanticVersion(this string fileName)
        {
            var name = _suffixRegex.Replace(fileName, "");
            var version = _versionRegex.Match(name).Value;
            return new SemanticVersion(version);
        }
    }
}

Remove private qualifier on version regexes


using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.Win32;

namespace EasySnippets.Utils
{
    [SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "Windows only app")]
    public class StartUpManager
    {
        public static void AddApplicationToCurrentUserStartup()
        {
            using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            var curAssembly = Assembly.GetExecutingAssembly();
            key?.SetValue(curAssembly.GetName().Name, curAssembly.Location);
        }

        public static void RemoveApplicationFromCurrentUserStartup()
        {
            using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            var curAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
            if (!string.IsNullOrWhiteSpace(curAssemblyName))
            {
                key?.DeleteValue(curAssemblyName, false);
            }

        }

        public static bool IsApplicationAddedToCurrentUserStartup()
        {
            using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            var curAssembly = Assembly.GetExecutingAssembly();
            var currentValue = key?.GetValue(curAssembly.GetName().Name, null)?.ToString();
            return currentValue?.Equals(curAssembly.Location, StringComparison.InvariantCultureIgnoreCase) ?? false;
        }
    }
}

using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.Win32;

namespace EasySnippets.Utils
{
    [SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "Windows only app")]
    public class StartUpManager
    {
        public static void AddApplicationToCurrentUserStartup()
        {
            using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            var curAssembly = Assembly.GetExecutingAssembly();
            key?.SetValue(curAssembly.GetName().Name, AppContext.BaseDirectory);
        }

        public static void RemoveApplicationFromCurrentUserStartup()
        {
            using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            var curAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
            if (!string.IsNullOrWhiteSpace(curAssemblyName))
            {
                key?.DeleteValue(curAssemblyName, false);
            }

        }

        public static bool IsApplicationAddedToCurrentUserStartup()
        {
            using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            var curAssembly = Assembly.GetExecutingAssembly();
            var currentValue = key?.GetValue(curAssembly.GetName().Name, null)?.ToString();
            return currentValue?.Equals(AppContext.BaseDirectory, StringComparison.InvariantCultureIgnoreCase) ?? false;
        }
    }
}

Use AppContext.BaseDirectory for application path


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

using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Game.Audio;
using osu.Game.Configuration;
using osu.Game.Rulesets.Scoring;
using osu.Game.Skinning;

namespace osu.Game.Screens.Play
{
    public class ComboEffects : CompositeDrawable
    {
        private readonly ScoreProcessor processor;

        private SkinnableSound comboBreakSample;

        private Bindable<bool> alwaysPlay;
        private bool firstTime = true;

        public ComboEffects(ScoreProcessor processor)
        {
            this.processor = processor;
        }

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            InternalChild = comboBreakSample = new SkinnableSound(new SampleInfo("combobreak"));
            alwaysPlay = config.GetBindable<bool>(OsuSetting.AlwaysPlayFirstComboBreak);
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();
            processor.Combo.BindValueChanged(onComboChange);
        }

        private void onComboChange(ValueChangedEvent<int> combo)
        {
            if (combo.NewValue == 0 && (combo.OldValue > 20 || alwaysPlay.Value && firstTime))
            {
                comboBreakSample?.Play();
                firstTime = false;
            }
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Game.Audio;
using osu.Game.Configuration;
using osu.Game.Rulesets.Scoring;
using osu.Game.Skinning;

namespace osu.Game.Screens.Play
{
    public class ComboEffects : CompositeDrawable
    {
        private readonly ScoreProcessor processor;

        private SkinnableSound comboBreakSample;

        private Bindable<bool> alwaysPlay;
        private bool firstTime = true;

        public ComboEffects(ScoreProcessor processor)
        {
            this.processor = processor;
        }

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            InternalChild = comboBreakSample = new SkinnableSound(new SampleInfo("combobreak"));
            alwaysPlay = config.GetBindable<bool>(OsuSetting.AlwaysPlayFirstComboBreak);
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();
            processor.Combo.BindValueChanged(onComboChange);
        }

        private void onComboChange(ValueChangedEvent<int> combo)
        {
            if (combo.NewValue == 0 && (combo.OldValue > 20 || (alwaysPlay.Value && firstTime)))
            {
                comboBreakSample?.Play();
                firstTime = false;
            }
        }
    }
}

Add implicit braces for clarity

Add implicit braces for clarity


using System;
using Abp;
using Abp.Collections.Extensions;
using Abp.Dependency;
using Castle.Facilities.Logging;
using Abp.Castle.Logging.Log4Net;

namespace AbpCompanyName.AbpProjectName.Migrator
{
    public class Program
    {
        private static bool _skipConnVerification = false;

        public static void Main(string[] args)
        {
            ParseArgs(args);

            using (var bootstrapper = AbpBootstrapper.Create<AbpProjectNameMigratorModule>())
            {
                bootstrapper.IocManager.IocContainer
                    .AddFacility<LoggingFacility>(f => f.UseAbpLog4Net()
                        .WithConfig("log4net.config")
                    );

                bootstrapper.Initialize();

                using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MultiTenantMigrateExecuter>())
                {
                    migrateExecuter.Object.Run(_skipConnVerification);
                }

                Console.WriteLine("Press ENTER to exit...");
                Console.ReadLine();
            }
        }

        private static void ParseArgs(string[] args)
        {
            if (args.IsNullOrEmpty())
            {
                return;
            }

            for (int i = 0; i < args.Length; i++)
            {
                var arg = args[i];
                switch (arg)
                {
                    case "-s":
                        _skipConnVerification = true;
                        break;
                }
            }
        }
    }
}

using System;
using Abp;
using Abp.Collections.Extensions;
using Abp.Dependency;
using Castle.Facilities.Logging;
using Abp.Castle.Logging.Log4Net;

namespace AbpCompanyName.AbpProjectName.Migrator
{
    public class Program
    {
        private static bool _skipConnVerification = false;

        public static void Main(string[] args)
        {
            ParseArgs(args);

            using (var bootstrapper = AbpBootstrapper.Create<AbpProjectNameMigratorModule>())
            {
                bootstrapper.IocManager.IocContainer
                    .AddFacility<LoggingFacility>(f => f.UseAbpLog4Net()
                        .WithConfig("log4net.config")
                    );

                bootstrapper.Initialize();

                using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MultiTenantMigrateExecuter>())
                {
                    migrateExecuter.Object.Run(_skipConnVerification);
                }

                if (!_skipConnVerification)
                {
                    Console.WriteLine("Press ENTER to exit...");
                    Console.ReadLine();
                }
            }
        }

        private static void ParseArgs(string[] args)
        {
            if (args.IsNullOrEmpty())
            {
                return;
            }

            for (int i = 0; i < args.Length; i++)
            {
                var arg = args[i];
                switch (arg)
                {
                    case "-s":
                        _skipConnVerification = true;
                        break;
                }
            }
        }
    }
}

Remove confirmation for exit with no verification

In order to use Migrator in Continuous Integration pipelines (which runs unattended), it should have a fully silent mode. So I suggest making the wait for exit confirmation at the end optional. I reused `_skipConnVerification` since no backward compatibility required for ABP templates.

BTW I doubt `_skipConnVerification` was correctly named in the first place, so feel free to alter the PR (add another optional parameter defaulting to wait for confirmation) to give the same effect.


using Microsoft.eShopOnContainers.Services.Ordering.Domain.SeedWork;
using System;
using System.Collections.Generic;

namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate
{
    public class Address : ValueObject
    {
        public String Street { get; }
        public String City { get; }
        public String State { get; }
        public String Country { get; }
        public String ZipCode { get; }

        private Address() { }

        public Address(string street, string city, string state, string country, string zipcode)
        {
            Street = street;
            City = city;
            State = state;
            Country = country;
            ZipCode = zipcode;
        }

        protected override IEnumerable<object> GetAtomicValues()
        {
            // Using a yield return statement to return each element one at a time
            yield return Street;
            yield return City;
            yield return State;
            yield return Country;
            yield return ZipCode;
        }
    }
}

using Microsoft.eShopOnContainers.Services.Ordering.Domain.SeedWork;
using System;
using System.Collections.Generic;

namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate
{
    public class Address : ValueObject
    {
        public String Street { get; private set; }
        public String City { get; private set; }
        public String State { get; private set; }
        public String Country { get; private set; }
        public String ZipCode { get; private set; }

        private Address() { }

        public Address(string street, string city, string state, string country, string zipcode)
        {
            Street = street;
            City = city;
            State = state;
            Country = country;
            ZipCode = zipcode;
        }

        protected override IEnumerable<object> GetAtomicValues()
        {
            // Using a yield return statement to return each element one at a time
            yield return Street;
            yield return City;
            yield return State;
            yield return Country;
            yield return ZipCode;
        }
    }
}

Add private setters so deserializing on integration event handler works as expected.


using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
    internal class ProductInformation
    {
        public const string Author = "amay077";
        public const string Name = "Xamarin.Forms.GoogleMaps";
        public const string Copyright = "Copyright © amay077. 2016 - 2019";
        public const string Trademark = "";
        public const string Version = "3.2.0.0";
    }
}

using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
    internal class ProductInformation
    {
        public const string Author = "amay077";
        public const string Name = "Xamarin.Forms.GoogleMaps";
        public const string Copyright = "Copyright © amay077. 2016 - 2019";
        public const string Trademark = "";
        public const string Version = "3.2.1.0";
    }
}

Update file version to 3.2.1.0

Update file version to 3.2.1.0


using System;
using System.ComponentModel;

namespace PcscDotNet
{
    public delegate void PcscExceptionHandler(PcscException error);

    public sealed class PcscException : Win32Exception
    {
        public SCardError Error => (SCardError)NativeErrorCode;

        public bool ThrowIt { get; set; } = true;

        public PcscException(int error) : base(error) { }

        public PcscException(SCardError error) : base((int)error) { }

        public PcscException(string message) : base(message) { }

        public PcscException(int error, string message) : base(error, message) { }

        public PcscException(string message, Exception innerException) : base(message, innerException) { }
    }
}

using System;
using System.ComponentModel;

namespace PcscDotNet
{
    public delegate void PcscExceptionHandler(PcscException error);

    public sealed class PcscException : Win32Exception
    {
        public SCardError Error { get; private set; }

        public bool ThrowIt { get; set; } = true;

        public PcscException(SCardError error) : base((int)error)
        {
            Error = error;
        }
    }
}

Update `PcscExcetpion` class. Assign the value of `Error` in constructor. Remove unused constructors.


namespace StraightSql
{
	using Npgsql;
	using System;

	public class CommandPreparer
		: ICommandPreparer
	{
		public void Prepare(NpgsqlCommand npgsqlCommand, IQuery query)
		{
			if (npgsqlCommand == null)
				throw new ArgumentNullException(nameof(npgsqlCommand));

			if (query == null)
				throw new ArgumentNullException(nameof(query));

			var queryText = query.Text;

			foreach (var literal in query.Literals)
			{
				var moniker = $":{literal.Key}";

				if (!queryText.Contains(moniker))
					throw new LiteralNotFoundException(literal.Key);

				queryText = queryText.Replace(moniker, literal.Value);
			}

			npgsqlCommand.CommandText = queryText;

			foreach (var queryParameter in query.Parameters)
			{
				npgsqlCommand.Parameters.Add(queryParameter);
			}
		}
	}
}

namespace StraightSql
{
    using Npgsql;
    using System;
    using System.Linq;

    public class CommandPreparer
		: ICommandPreparer
	{
		public void Prepare(NpgsqlCommand npgsqlCommand, IQuery query)
		{
			if (npgsqlCommand == null)
				throw new ArgumentNullException(nameof(npgsqlCommand));

			if (query == null)
				throw new ArgumentNullException(nameof(query));

			var queryText = query.Text;

			foreach (var literal in query.Literals.OrderByDescending(l => l.Key.Length))
			{
				var moniker = $":{literal.Key}";

				if (!queryText.Contains(moniker))
					throw new LiteralNotFoundException(literal.Key);

				queryText = queryText.Replace(moniker, literal.Value);
			}

			npgsqlCommand.CommandText = queryText;

			foreach (var queryParameter in query.Parameters)
			{
				npgsqlCommand.Parameters.Add(queryParameter);
			}
		}
	}
}

Replace literals in order of key length, e.g. most-specific first.


[assembly: Microsoft.Owin.OwinStartup(typeof(BatteryCommander.Web.Startup))]

namespace BatteryCommander.Web
{
    using Microsoft.AspNet.Identity;
    using Microsoft.Owin;
    using Microsoft.Owin.Security.Cookies;
    using Owin;
    using System;

    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Auth/Login"),
                LogoutPath = new PathString("/Auth/Logout"),
                ExpireTimeSpan = TimeSpan.FromHours(1),
                SlidingExpiration = true,
                CookieHttpOnly = true,
                CookieSecure = CookieSecureOption.SameAsRequest
                // CookieDomain = "",
                // CookieName = ""
            });

            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        }
    }
}

[assembly: Microsoft.Owin.OwinStartup(typeof(BatteryCommander.Web.Startup))]

namespace BatteryCommander.Web
{
    using Microsoft.AspNet.Identity;
    using Microsoft.Owin;
    using Microsoft.Owin.Security.Cookies;
    using Owin;
    using System;

    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Auth/Login"),
                LogoutPath = new PathString("/Auth/Logout"),
                ExpireTimeSpan = TimeSpan.FromDays(1),
                SlidingExpiration = true,
                CookieHttpOnly = true,
                CookieSecure = CookieSecureOption.SameAsRequest
                // CookieDomain = "",
                // CookieName = ""
            });

            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        }
    }
}

Extend cookie timeout to 1 day

Extend cookie timeout to 1 day


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Cloud.Storage.Queues;

namespace Cloud.Storage.AWS.Queues
{
	public class Queue : IQueue
	{
		public Task AddMessage(IMessage message)
		{
			throw new NotImplementedException();
		}

		public IMessage CreateMessage(byte[] messageContents)
		{
			throw new NotImplementedException();
		}

		public IMessage CreateMessage(string messageContents)
		{
			throw new NotImplementedException();
		}

		public Task<List<IMessage>> GetMessages(int numMessages, TimeSpan? visibilityTimeout = default(TimeSpan?))
		{
			throw new NotImplementedException();
		}

		public Task<IMessage> GetNextMessage(TimeSpan? visibilityTimeout = default(TimeSpan?))
		{
			throw new NotImplementedException();
		}

		public Task<List<IMessage>> PeekMessages(int numMessages)
		{
			throw new NotImplementedException();
		}

		public Task<IMessage> PeekNextMessage()
		{
			throw new NotImplementedException();
		}
	}
}

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Cloud.Storage.Queues;

namespace Cloud.Storage.AWS.Queues
{
	public class Queue : IQueue
	{
		public Task AddMessage(IMessage message)
		{
			throw new NotImplementedException();
		}

		public Task Clear()
		{
			throw new NotImplementedException();
		}

		public IMessage CreateMessage(byte[] messageContents)
		{
			throw new NotImplementedException();
		}

		public IMessage CreateMessage(string messageContents)
		{
			throw new NotImplementedException();
		}

		public int GetApproximateMessageCount()
		{
			throw new NotImplementedException();
		}

		public Task<List<IMessage>> GetMessages(int numMessages, TimeSpan? visibilityTimeout = default(TimeSpan?))
		{
			throw new NotImplementedException();
		}

		public Task<IMessage> GetNextMessage(TimeSpan? visibilityTimeout = default(TimeSpan?))
		{
			throw new NotImplementedException();
		}

		public Task<List<IMessage>> PeekMessages(int numMessages)
		{
			throw new NotImplementedException();
		}

		public Task<IMessage> PeekNextMessage()
		{
			throw new NotImplementedException();
		}
	}
}

Fix compilation issues on AWS side.

Fix compilation issues on AWS side.


namespace Microsoft.ApplicationInsights.AspNetCore.Common
{
    /// <summary>
    /// These values are listed to guard against malicious injections by limiting the max size allowed in an HTTP Response.
    /// These max limits are intentionally exaggerated to allow for unexpected responses, while still guarding against unreasonably large responses.
    /// Example: While a 32 character response may be expected, 50 characters may be permitted while a 10,000 character response would be unreasonable and malicious.
    /// </summary>
    public static class InjectionGuardConstants
    {
        /// <summary>
        /// Max length of AppId allowed in response from Breeze.
        /// </summary>
        public const int AppIdMaxLengeth = 50;

        /// <summary>
        /// Max length of incoming Request Header value allowed.
        /// </summary>
        public const int RequestHeaderMaxLength = 1024;

        /// <summary>
        /// Max length of context header key.
        /// </summary>
        public const int ContextHeaderKeyMaxLength = 50;

        /// <summary>
        /// Max length of context header value.
        /// </summary>
        public const int ContextHeaderValueMaxLength = 100;
    }
}

namespace Microsoft.ApplicationInsights.AspNetCore.Common
{
    /// <summary>
    /// These values are listed to guard against malicious injections by limiting the max size allowed in an HTTP Response.
    /// These max limits are intentionally exaggerated to allow for unexpected responses, while still guarding against unreasonably large responses.
    /// Example: While a 32 character response may be expected, 50 characters may be permitted while a 10,000 character response would be unreasonable and malicious.
    /// </summary>
    public static class InjectionGuardConstants
    {
        /// <summary>
        /// Max length of AppId allowed in response from Breeze.
        /// </summary>
        public const int AppIdMaxLengeth = 50;

        /// <summary>
        /// Max length of incoming Request Header value allowed.
        /// </summary>
        public const int RequestHeaderMaxLength = 1024;

        /// <summary>
        /// Max length of context header key.
        /// </summary>
        public const int ContextHeaderKeyMaxLength = 50;

        /// <summary>
        /// Max length of context header value.
        /// </summary>
        public const int ContextHeaderValueMaxLength = 1024;
    }
}

Adjust max size of contents read from incoming request headers to be 1k


using System;
using System.Collections.Concurrent;
using System.Linq;
using ARSoft.Tools.Net.Dns;

namespace DNSAgent
{
    internal class DnsCacheMessageEntry
    {
        public DnsCacheMessageEntry(DnsMessage message, int timeToLive)
        {
            Message = message;
            timeToLive =
                Math.Max(message.AnswerRecords.Concat(message.AuthorityRecords).Min(record => record.TimeToLive),
                    timeToLive);
            ExpireTime = DateTime.Now.AddSeconds(timeToLive);
        }

        public DnsMessage Message { get; set; }
        public DateTime ExpireTime { get; set; }

        public bool IsExpired
        {
            get { return DateTime.Now > ExpireTime; }
        }
    }

    internal class DnsMessageCache :
        ConcurrentDictionary<string, ConcurrentDictionary<RecordType, DnsCacheMessageEntry>>
    {
        public void Update(DnsQuestion question, DnsMessage message, int timeToLive)
        {
            if (!ContainsKey(question.Name))
                this[question.Name] = new ConcurrentDictionary<RecordType, DnsCacheMessageEntry>();

            this[question.Name][question.RecordType] = new DnsCacheMessageEntry(message, timeToLive);
        }
    }
}

using System;
using System.Collections.Concurrent;
using System.Linq;
using ARSoft.Tools.Net.Dns;

namespace DNSAgent
{
    internal class DnsCacheMessageEntry
    {
        public DnsCacheMessageEntry(DnsMessage message, int timeToLive)
        {
            Message = message;
            var records = message.AnswerRecords.Concat(message.AuthorityRecords).ToList();
            if (records.Any())
                timeToLive = Math.Max(records.Min(record => record.TimeToLive), timeToLive);
            ExpireTime = DateTime.Now.AddSeconds(timeToLive);
        }

        public DnsMessage Message { get; set; }
        public DateTime ExpireTime { get; set; }

        public bool IsExpired
        {
            get { return DateTime.Now > ExpireTime; }
        }
    }

    internal class DnsMessageCache :
        ConcurrentDictionary<string, ConcurrentDictionary<RecordType, DnsCacheMessageEntry>>
    {
        public void Update(DnsQuestion question, DnsMessage message, int timeToLive)
        {
            if (!ContainsKey(question.Name))
                this[question.Name] = new ConcurrentDictionary<RecordType, DnsCacheMessageEntry>();

            this[question.Name][question.RecordType] = new DnsCacheMessageEntry(message, timeToLive);
        }
    }
}

Fix "Sequence contains no elements" error.


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

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

namespace Borodar.RainbowItems.Editor.Settings
{
    public class CustomBrowserIconSettings : ScriptableObject
    {
        public List<Folder> Folders;

        public Sprite GetSprite(string folderName, bool small = true)
        {
            var folder = Folders.FirstOrDefault(x => x.FolderName.Contains(folderName));

            if (folder == null) { return null; }

            return small ? folder.SmallIcon : folder.LargeIcon;
        }
    }
}

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

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

namespace Borodar.RainbowItems.Editor.Settings
{
    public class CustomBrowserIconSettings : ScriptableObject
    {
        public List<Folder> Folders;

        public Sprite GetSprite(string folderName, bool small = true)
        {
            var folder = Folders.FirstOrDefault(x => x.FolderName.Equals(folderName));

            if (folder == null) { return null; }

            return small ? folder.SmallIcon : folder.LargeIcon;
        }
    }
}

Check for an exact match of item name

Check for an exact match of item name


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

#nullable enable

using System;

namespace osu.Framework.Utils
{
    public static class ThrowHelper
    {
        public static void ThrowInvalidOperationException(string? message) => throw new InvalidOperationException(message);
    }
}

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

#nullable enable

using System;

namespace osu.Framework.Utils
{
    /// <summary>
    /// Helper class for throwing exceptions in isolated methods, for cases where method inlining is beneficial.
    /// As throwing directly in that case causes JIT to disable inlining on the surrounding method.
    /// </summary>
    // todo: continue implementation and use where required, see https://github.com/ppy/osu-framework/issues/3470.
    public static class ThrowHelper
    {
        public static void ThrowInvalidOperationException(string? message) => throw new InvalidOperationException(message);
    }
}

Add xmldoc and TODO comment

Add xmldoc and TODO comment


using System;

namespace Avalonia.Metadata
{
    [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
    public sealed class XmlnsPrefixAttribute : Attribute
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="xmlNamespace">XML namespce</param>
        /// <param name="prefix">recommended prefix</param>
        public XmlnsPrefixAttribute(string xmlNamespace, string prefix)
        {
            XmlNamespace = xmlNamespace ?? throw new ArgumentNullException(nameof(xmlNamespace));

            Prefix = prefix ?? throw new ArgumentNullException(nameof(prefix));
        }

        /// <summary>
        /// XML Namespace
        /// </summary>
        public string XmlNamespace { get; }

        /// <summary>
        /// New Xml Namespace
        /// </summary>
        public string Prefix { get; }
    }
}

using System;

namespace Avalonia.Metadata
{
    /// <summary>
    /// Use to predefine the prefix associated to an xml namespace in a xaml file
    /// </summary>
    /// <remarks>
    /// example:
    /// [assembly: XmlnsPrefix("https://github.com/avaloniaui", "av")]
    /// xaml:
    /// xmlns:av="https://github.com/avaloniaui"
    /// </remarks>
    [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
    public sealed class XmlnsPrefixAttribute : Attribute
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="xmlNamespace">XML namespce</param>
        /// <param name="prefix">recommended prefix</param>
        public XmlnsPrefixAttribute(string xmlNamespace, string prefix)
        {
            XmlNamespace = xmlNamespace ?? throw new ArgumentNullException(nameof(xmlNamespace));

            Prefix = prefix ?? throw new ArgumentNullException(nameof(prefix));
        }

        /// <summary>
        /// XML Namespace
        /// </summary>
        public string XmlNamespace { get; }

        /// <summary>
        /// New Xml Namespace
        /// </summary>
        public string Prefix { get; }
    }
}

Add sumary and remark to class header

Add sumary and remark to class header


using System.Reflection;
using System.Resources;

[assembly: AssemblyCompany( "Carl Zeiss Innovationszentrum für Messtechnik GmbH" )]
[assembly: AssemblyProduct( "ZEISS PiWeb Api" )]
[assembly: AssemblyCopyright( "Copyright © 2019 Carl Zeiss Innovationszentrum für Messtechnik GmbH" )]
[assembly: AssemblyTrademark( "PiWeb" )]
[assembly: NeutralResourcesLanguage( "en" )]

[assembly: AssemblyVersion( "3.0.0" )]
[assembly: AssemblyInformationalVersion("3.0.0")]

[assembly: AssemblyFileVersion( "3.0.0" )]

using System.Reflection;
using System.Resources;

[assembly: AssemblyCompany( "Carl Zeiss Innovationszentrum für Messtechnik GmbH" )]
[assembly: AssemblyProduct( "ZEISS PiWeb Api" )]
[assembly: AssemblyCopyright( "Copyright © 2019 Carl Zeiss Innovationszentrum für Messtechnik GmbH" )]
[assembly: AssemblyTrademark( "PiWeb" )]
[assembly: NeutralResourcesLanguage( "en" )]

[assembly: AssemblyVersion( "4.0.0" )]
[assembly: AssemblyInformationalVersion("4.0.0")]

[assembly: AssemblyFileVersion( "4.0.0" )]

Update assembly version to 4.0.0 (+semver: major)


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

using System;
using Xunit.Sdk;

namespace Xunit
{
    /// <summary>
    /// Apply this attribute to your test method to specify this is a platform specific test.
    /// </summary>
    [TraitDiscoverer("Xunit.NetCore.Extensions.SkipOnTargetFrameworkDiscoverer", "Xunit.NetCore.Extensions")]
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
    public class SkipOnTargetFrameworkAttribute : Attribute, ITraitAttribute
    {
        public SkipOnTargetFrameworkAttribute(TargetFrameworkMonikers platform) { }
    }
}

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

using System;
using Xunit.Sdk;

namespace Xunit
{
    /// <summary>
    /// Apply this attribute to your test method to specify this is a platform specific test.
    /// </summary>
    [TraitDiscoverer("Xunit.NetCore.Extensions.SkipOnTargetFrameworkDiscoverer", "Xunit.NetCore.Extensions")]
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
    public class SkipOnTargetFrameworkAttribute : Attribute, ITraitAttribute
    {
        public SkipOnTargetFrameworkAttribute(TargetFrameworkMonikers platform, string reason = null) { }
    }
}

Allow specifying metadata for skip reason.


using UnityEngine;

public class LinkButton : MonoBehaviour {

	public void OpenUrl (string url) {
		Application.OpenURL(url);
	}
}

using UnityEngine;

public class LinkButton : MonoBehaviour {

	public void OpenUrl (string url) {
		if(Application.platform == RuntimePlatform.WebGLPlayer) {
			Application.ExternalEval("window.open(\"" + url + "\",\"_blank\")");
		} else {
			Application.OpenURL(url);
		}
	}
}

Fix link open in browsers

Fix link open in browsers


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Python.Runtime;
using Wox.Plugin;

namespace Wox.PluginLoader
{
    public class PythonPluginLoader : BasePluginLoader
    {
        public override List<PluginPair> LoadPlugin()
        {
            List<PluginPair> plugins = new List<PluginPair>();
            List<PluginMetadata> metadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.Python.ToUpper()).ToList();
            foreach (PluginMetadata metadata in metadatas)
            {
                PythonPluginWrapper python = new PythonPluginWrapper(metadata);
                PluginPair pair = new PluginPair()
                {
                    Plugin = python,
                    Metadata = metadata
                };
                plugins.Add(pair);
            }

            return plugins;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Python.Runtime;
using Wox.Plugin;
using Wox.Helper;

namespace Wox.PluginLoader
{
    public class PythonPluginLoader : BasePluginLoader
    {
        public override List<PluginPair> LoadPlugin()
        {
            if (!CheckPythonEnvironmentInstalled()) return new List<PluginPair>();

            List<PluginPair> plugins = new List<PluginPair>();
            List<PluginMetadata> metadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.Python.ToUpper()).ToList();
            foreach (PluginMetadata metadata in metadatas)
            {
                PythonPluginWrapper python = new PythonPluginWrapper(metadata);
                PluginPair pair = new PluginPair()
                {
                    Plugin = python,
                    Metadata = metadata
                };
                plugins.Add(pair);
            }

            return plugins;
        }

        private bool CheckPythonEnvironmentInstalled() {
            try
            {
                PythonEngine.Initialize();
                PythonEngine.Shutdown();
            }
            catch {
                Log.Error("Could't find python environment, all python plugins disabled.");
                return false;
            }
            return true;
        }
    }
}

Fix crash issue when user didn't install python.


using System.Linq;
using NUnit.Framework;
using SevenDigital.Api.Schema;
using SevenDigital.Api.Schema.Tags;

namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint
{
	[TestFixture]
	public class ArtistByTagTopTests
	{
		[Test]
		public void Can_hit_endpoint()
		{

			ArtistByTagTop tags = Api<ArtistByTagTop>.Create
				.WithParameter("tags", "rock,pop,2000s")
				.Please();

			Assert.That(tags, Is.Not.Null);
			Assert.That(tags.TaggedArtists.Count, Is.GreaterThan(0));
			Assert.That(tags.Type, Is.EqualTo(ItemType.artist));
			Assert.That(tags.TaggedArtists.FirstOrDefault().Artist.Name, Is.Not.Empty);
		}

		[Test]
		public void Can_hit_endpoint_with_paging()
		{

			ArtistByTagTop artistBrowse = Api<ArtistByTagTop>.Create
				.WithParameter("tags", "rock,pop,2000s")
				.WithParameter("page", "2")
				.WithParameter("pageSize", "20")
				.Please();

			Assert.That(artistBrowse, Is.Not.Null);
			Assert.That(artistBrowse.Page, Is.EqualTo(2));
			Assert.That(artistBrowse.PageSize, Is.EqualTo(20));
		}
	}
}

using System.Linq;
using NUnit.Framework;
using SevenDigital.Api.Schema;
using SevenDigital.Api.Schema.Tags;

namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint
{
	[TestFixture]
	public class ArtistByTagTopTests
	{
		private const string Tags = "rock,pop";

		[Test]
		public void Can_hit_endpoint()
		{

			ArtistByTagTop tags = Api<ArtistByTagTop>.Create
				.WithParameter("tags", Tags)
				.Please();

			Assert.That(tags, Is.Not.Null);
			Assert.That(tags.TaggedArtists.Count, Is.GreaterThan(0));
			Assert.That(tags.Type, Is.EqualTo(ItemType.artist));
			Assert.That(tags.TaggedArtists.FirstOrDefault().Artist.Name, Is.Not.Empty);
		}

		[Test]
		public void Can_hit_endpoint_with_paging()
		{

			ArtistByTagTop artistBrowse = Api<ArtistByTagTop>.Create
				.WithParameter("tags", Tags)
				.WithParameter("page", "2")
				.WithParameter("pageSize", "20")
				.Please();

			Assert.That(artistBrowse, Is.Not.Null);
			Assert.That(artistBrowse.Page, Is.EqualTo(2));
			Assert.That(artistBrowse.PageSize, Is.EqualTo(20));
		}
	}
}

Fix test failure After consulting with search team, we can get results needed for this test by searching for "rock,pop" not "rock,pop,2000s"


namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
    using Base.Get;
    using Objects.Basic;
    using Objects.Get.Movies.Common;

    internal class TraktMoviesMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedMovie>, TraktMostAnticipatedMovie>
    {
        internal TraktMoviesMostAnticipatedRequest(TraktClient client) : base(client) { }

        protected override string UriTemplate => "movies/anticipated{?extended,page,limit}";

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
    using Base;
    using Base.Get;
    using Objects.Basic;
    using Objects.Get.Movies.Common;

    internal class TraktMoviesMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedMovie>, TraktMostAnticipatedMovie>
    {
        internal TraktMoviesMostAnticipatedRequest(TraktClient client) : base(client) { }

        protected override string UriTemplate => "movies/anticipated{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}";

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        internal TraktMovieFilter Filter { get; set; }

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

Add filter property to most anticipated movies request.


using System;

namespace DiscogsClient.Data.Result
{
    public class DiscogsRelease : DiscogsReleaseBase
    {
        public DiscogsReleaseArtist[] extraartists { get; set; }
        public DiscogsReleaseLabel[] labels { get; set; }
        public DiscogsReleaseLabel[] companies { get; set; }
        public DiscogsFormat[] formats { get; set; }
        public DiscogsIdentifier[] identifiers { get; set; }
        public DiscogsCommunity community { get; set; }
        public DiscogsReleaseLabel[] series { get; set; }
        public string artists_sort { get; set; }
        public string catno { get; set; }
        public string country { get; set; }
        public DateTime date_added { get; set; }
        public DateTime date_changed { get; set; }
        public int estimated_weight { get; set; }
        public int format_quantity { get; set; }
        public int master_id { get; set; }
        public string master_url { get; set; }
        public string notes { get; set; }
        public string released { get; set; }
        public string released_formatted { get; set; }
        public string status { get; set; }
        public string thumb { get; set; }
    }
}

using System;

namespace DiscogsClient.Data.Result
{
    public class DiscogsRelease : DiscogsReleaseBase
    {
        public DiscogsReleaseArtist[] extraartists { get; set; }
        public DiscogsReleaseLabel[] labels { get; set; }
        public DiscogsReleaseLabel[] companies { get; set; }
        public DiscogsFormat[] formats { get; set; }
        public DiscogsIdentifier[] identifiers { get; set; }
        public DiscogsCommunity community { get; set; }
        public DiscogsReleaseLabel[] series { get; set; }
        public string artists_sort { get; set; }
        public string catno { get; set; }
        public string country { get; set; }
        public DateTime date_added { get; set; }
        public DateTime date_changed { get; set; }
        /// <remarks>Grams</remarks>
        public int estimated_weight { get; set; }
        public int format_quantity { get; set; }
        public decimal lowest_price { get; set; }
        public int master_id { get; set; }
        public string master_url { get; set; }
        public string notes { get; set; }
        public int num_for_sale { get; set; }
        public string released { get; set; }
        public string released_formatted { get; set; }
        public string status { get; set; }
        public string thumb { get; set; }
    }
}

Add DiscogRelease properties: lowest_price and num_for_sale