using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NuGet.Test.Helpers;
using Sleet.Test.Common;

namespace Sleet.AmazonS3.Tests
{
    public class AmazonS3FileSystemTests
    {
        [EnvVarExistsFact(AmazonS3TestContext.EnvAccessKeyId)]
        public async Task GivenAS3AccountVerifyBucketOperations()
        {
            using (var testContext = new AmazonS3TestContext())
            {
                testContext.CreateBucketOnInit = false;
                await testContext.InitAsync();

                // Verify at the start
                (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse();
                (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse();

                // Create
                await testContext.FileSystem.CreateBucket(testContext.Logger, CancellationToken.None);

                (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeTrue();
                (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeTrue();

                // Delete
                await testContext.FileSystem.DeleteBucket(testContext.Logger, CancellationToken.None);

                (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse();
                (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse();

                await testContext.CleanupAsync();
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NuGet.Test.Helpers;
using Sleet.Test.Common;

namespace Sleet.AmazonS3.Tests
{
    public class AmazonS3FileSystemTests
    {
        [EnvVarExistsFact(AmazonS3TestContext.EnvAccessKeyId)]
        public async Task GivenAS3AccountVerifyBucketOperations()
        {
            using (var testContext = new AmazonS3TestContext())
            {
                testContext.CreateBucketOnInit = false;
                await testContext.InitAsync();

                // Verify at the start
                (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse();
                (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse();

                // Create
                await testContext.FileSystem.CreateBucket(testContext.Logger, CancellationToken.None);

                (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeTrue();
                (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeTrue();

                await testContext.CleanupAsync();
            }
        }
    }
}

Fix S3 create bucket test

Fix S3 create bucket test


using NGM.Forum.Models;

namespace NGM.Forum.ViewModels {
    public class PostBodyEditorViewModel {
        public PostPart PostPart { get; set; }

        public string Text {
            get { return PostPart.Record.Text; }
            set { PostPart.Record.Text = value; }
        }

        public string Format {
            get { return PostPart.Record.Format; }
            set { PostPart.Record.Format = value; }
        }

        public string EditorFlavor { get; set; }
    }
}

using NGM.Forum.Models;

namespace NGM.Forum.ViewModels {
    public class PostBodyEditorViewModel {
        public PostPart PostPart { get; set; }

        public string Text {
            get { return PostPart.Record.Text; }
            set { PostPart.Record.Text = string.IsNullOrWhiteSpace(value) ? value : value.TrimEnd(); }
        }

        public string Format {
            get { return PostPart.Record.Format; }
            set { PostPart.Record.Format = value; }
        }

        public string EditorFlavor { get; set; }
    }
}

Trim end of post on Save. Incase someone hits enter loads and then blows the size of the page. This will stop that.


using System;
using System.Web;

namespace Umbraco.Web
{
    internal class AspNetHttpContextAccessor : IHttpContextAccessor
    {
        public HttpContextBase HttpContext
        {
            get
            {
                return new HttpContextWrapper(System.Web.HttpContext.Current);
            }
            set
            {
                throw new NotSupportedException();
            }
        }
    }
}

using System;
using System.Web;

namespace Umbraco.Web
{
    internal class AspNetHttpContextAccessor : IHttpContextAccessor
    {
        public HttpContextBase HttpContext
        {
            get
            {
                var httpContext = System.Web.HttpContext.Current;
                return httpContext is null ? null : new HttpContextWrapper(httpContext);
            }
            set
            {
                throw new NotSupportedException();
            }
        }
    }
}

Fix if httpContext is null we cannot wrap it


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;

namespace ADWS.Models
{
    [DataContract]
    public class UserInfoResponse
    {
        [DataMember]
        public string Title { set; get; }

        [DataMember]
        public string DisplayName { set; get; }

        [DataMember]
        public string FirstName { set; get; }

        [DataMember]
        public string LastName { set; get; }

        [DataMember]
        public string SamAccountName { set; get; }

        [DataMember]
        public string Upn { set; get; }

        [DataMember]
        public string EmailAddress { set; get; }

        [DataMember]
        public string EmployeeId { set; get; }

        [DataMember]
        public string Department { set; get; }

        [DataMember]
        public string BusinessPhone { get; set; }

        [DataMember]
        public string Telephone { get; set; }

        [DataMember]
        public string SipAccount { set; get; }

        [DataMember]
        public string PrimaryHomeServerDn { get; set; }

        [DataMember]
        public string PoolName { set; get; }

        [DataMember]
        public string PhysicalDeliveryOfficeName { set; get; }

        [DataMember]
        public string OtherTelphone { get; set; }

    }

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;

namespace ADWS.Models
{
    [DataContract]
    public class UserInfoResponse
    {
        [DataMember]
        public string Title { set; get; }

        [DataMember]
        public string DisplayName { set; get; }

        [DataMember]
        public string FirstName { set; get; }

        [DataMember]
        public string LastName { set; get; }

        [DataMember]
        public string SamAccountName { set; get; }

        [DataMember]
        public string Upn { set; get; }

        [DataMember]
        public string EmailAddress { set; get; }

        [DataMember]
        public string EmployeeId { set; get; }

        [DataMember]
        public string Department { set; get; }

        [DataMember]
        public string BusinessPhone { get; set; }

        [DataMember]
        public string Telephone { get; set; }

        [DataMember]
        public string SipAccount { set; get; }

        [DataMember]
        public string PrimaryHomeServerDn { get; set; }

        [DataMember]
        public string PoolName { set; get; }

        [DataMember]
        public string PhysicalDeliveryOfficeName { set; get; }

        [DataMember]
        public string OtherTelphone { get; set; }

        [DataMember]
        public string Message { get; set; }

    }

}

Add message inside this class to convey exception


using System;
using System.Threading.Tasks;
using MediatR;
using NLog;
using SFA.DAS.EmployerUsers.Application.Commands.DeleteUser;
using SFA.DAS.EmployerUsers.Application.Queries.GetUsersWithExpiredRegistrations;

namespace SFA.DAS.EmployerUsers.RegistrationTidyUpJob.RegistrationManagement
{
    public class RegistrationManager
    {
        private readonly IMediator _mediator;
        private readonly ILogger _logger;

        public RegistrationManager(IMediator mediator, ILogger logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        public async Task RemoveExpiredRegistrations()
        {
            _logger.Info("Starting deletion of expired registrations");

            try
            {
                var users = await _mediator.SendAsync(new GetUsersWithExpiredRegistrationsQuery());
                _logger.Info($"Found {users.Length} users with expired registrations");

                foreach (var user in users)
                {
                    _logger.Info($"Deleting user with email '{user.Email}' (id: '{user.Id}')");
                    await _mediator.SendAsync(new DeleteUserCommand
                    {
                        User = user
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw;
            }

            _logger.Info("Finished deletion of expired registrations");
        }
    }
}

using System;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Azure;
using NLog;
using SFA.DAS.EmployerUsers.Application.Commands.DeleteUser;
using SFA.DAS.EmployerUsers.Application.Queries.GetUsersWithExpiredRegistrations;

namespace SFA.DAS.EmployerUsers.RegistrationTidyUpJob.RegistrationManagement
{
    public class RegistrationManager
    {
        private readonly IMediator _mediator;
        private readonly ILogger _logger;

        public RegistrationManager(IMediator mediator, ILogger logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        public async Task RemoveExpiredRegistrations()
        {
            _logger.Info("Starting deletion of expired registrations");

            _logger.Info($"AuditApiBaseUrl: {CloudConfigurationManager.GetSetting("AuditApiBaseUrl")}");

            try
            {
                var users = await _mediator.SendAsync(new GetUsersWithExpiredRegistrationsQuery());
                _logger.Info($"Found {users.Length} users with expired registrations");

                foreach (var user in users)
                {
                    _logger.Info($"Deleting user with email '{user.Email}' (id: '{user.Id}')");
                    await _mediator.SendAsync(new DeleteUserCommand
                    {
                        User = user
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw;
            }

            _logger.Info("Finished deletion of expired registrations");
        }
    }
}

Add log for audit api

Add log for audit api


using System;
using System.IO;
using hutel.Filters;
using hutel.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace server
{
    public class Startup
    {
        private const string _envUseBasicAuth = "HUTEL_USE_BASIC_AUTH";

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddMvc()
                .AddJsonOptions(opt =>
                {
                    opt.SerializerSettings.DateParseHandling = DateParseHandling.None;
                });
            services.AddScoped<ValidateModelStateAttribute>();
            services.AddMemoryCache();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(LogLevel.Trace);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            if (Environment.GetEnvironmentVariable(_envUseBasicAuth) == "1")
            {
                app.UseBasicAuthMiddleware();
            }
            app.UseRedirectToHttpsMiddleware();
            app.UseMvc();
            app.UseStaticFiles();
        }
    }
}

using System;
using System.IO;
using hutel.Filters;
using hutel.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace server
{
    public class Startup
    {
        private const string _envUseBasicAuth = "HUTEL_USE_BASIC_AUTH";

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddMvc()
                .AddJsonOptions(opt =>
                {
                    opt.SerializerSettings.DateParseHandling = DateParseHandling.None;
                });
            services.AddScoped<ValidateModelStateAttribute>();
            services.AddMemoryCache();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(LogLevel.Trace);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRedirectToHttpsMiddleware();
            if (Environment.GetEnvironmentVariable(_envUseBasicAuth) == "1")
            {
                app.UseBasicAuthMiddleware();
            }
            app.UseMvc();
            app.UseStaticFiles();
        }
    }
}

Move https redirection above basic auth

Move https redirection above basic auth


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

namespace RailPhase.Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a simple web app and serve content on to URLs.
            var app = new App();

            // Define the URL patterns to respond to incoming requests.
            // Any request that does not match one of these patterns will
            // be served by app.NotFoundView, which defaults to a simple
            // 404 message.

            // Easiest way to respond to a request: return a string
            app.AddStringView("^/$", (request) => "Hello World");
            // More complex response, see below
            app.AddStringView("^/info$", InfoView);

            // Start listening for HTTP requests. Default port is 8080.
            // This method does never return!
            app.RunHttpServer();

            // Now you should be able to visit me in your browser on http://localhost:8080
        }

        /// <summary>
        /// A view that generates a simple request info page
        /// </summary>
        static string InfoView(RailPhase.Context context)
        {
            // Get the template for the info page.
            var render = Template.FromFile("InfoTemplate.html");

            // Pass the HttpRequest as the template context, because we want
            // to display information about the request. Normally, we would
            // pass some custom object here, containing the information we
            // want to display.
			return render(null, context);
        }
    }

    public class DemoData
    {
        public string Heading;
        public string Username;
    }
}

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

namespace RailPhase.Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a simple web app and serve content on to URLs.
            var app = new App();

            // Define the URL patterns to respond to incoming requests.
            // Any request that does not match one of these patterns will
            // be served by app.NotFoundView, which defaults to a simple
            // 404 message.

            // Easiest way to respond to a request: return a string
            app.AddStringView("^/$", (request) => "Hello World");
            // More complex response, see below
            app.AddStringView("^/info$", InfoView);

            // Start listening for HTTP requests. Default port is 8080.
            // This method does never return!
            app.RunHttpServer("http://localhost:18080/");

            // Now you should be able to visit me in your browser on http://localhost:18080/
        }

        /// <summary>
        /// A view that generates a simple request info page
        /// </summary>
        static string InfoView(RailPhase.Context context)
        {
            // Get the template for the info page.
            var render = Template.FromFile("InfoTemplate.html");

            // Pass the HttpRequest as the template context, because we want
            // to display information about the request. Normally, we would
            // pass some custom object here, containing the information we
            // want to display.
			return render(null, context);
        }
    }

    public class DemoData
    {
        public string Heading;
        public string Username;
    }
}

Use port for demo application that doesn't need privileges


using System;

namespace Casper {

	public class CasperException : Exception {
		public const int EXIT_CODE_COMPILATION_ERROR = 1;
		public const int EXIT_CODE_MISSING_TASK = 2;
		public const int EXIT_CODE_CONFIGURATION_ERROR = 3;
		public const int EXIT_CODE_TASK_FAILED = 4;
		public const int EXIT_CODE_UNHANDLED_EXCEPTION = 255;

		private readonly int exitCode;

		public CasperException(int exitCode, string message, params object[] args)
			: base(string.Format(message, args)) {
			this.exitCode = exitCode;
		}

		public CasperException(int exitCode, Exception innerException)
			: base(innerException.Message, innerException) {
			this.exitCode = exitCode;
		}

		public int ExitCode {
			get {
				return exitCode;
			}
		}
	}
}

using System;

namespace Casper {

	public class CasperException : Exception {
		public const int EXIT_CODE_COMPILATION_ERROR = 1;
		public const int EXIT_CODE_MISSING_TASK = 2;
		public const int EXIT_CODE_CONFIGURATION_ERROR = 3;
		public const int EXIT_CODE_TASK_FAILED = 4;
		public const int EXIT_CODE_UNHANDLED_EXCEPTION = 255;

		private readonly int exitCode;

		public CasperException(int exitCode, string message)
			: base(message) {
			this.exitCode = exitCode;
		}

		public CasperException(int exitCode, string message, params object[] args)
			: this(exitCode, string.Format(message, args)) {
		}

		public CasperException(int exitCode, Exception innerException)
			: base(innerException.Message, innerException) {
			this.exitCode = exitCode;
		}

		public int ExitCode {
			get {
				return exitCode;
			}
		}
	}
}

Fix formatting exception when script compilation fails with certain error messages


using Raven.Abstractions.Data;
using System;

namespace Dotnet.Microservice.Health.Checks
{
    public class RavenDbHealthCheck
    {
        public static HealthResponse CheckHealth(string connectionString)
        {
            try
            {
                ConnectionStringParser<RavenConnectionStringOptions> parser = ConnectionStringParser<RavenConnectionStringOptions>.FromConnectionString(connectionString);
                parser.Parse();
                var store = new Raven.Client.Document.DocumentStore
                {
                    Url = parser.ConnectionStringOptions.Url,
                    DefaultDatabase = parser.ConnectionStringOptions.DefaultDatabase
                };
                store.Initialize();

                return HealthResponse.Healthy(new { server = store.Url, database = store.DefaultDatabase });
            }
            catch (Exception ex)
            {
                return HealthResponse.Unhealthy(ex);
            }
        }
    }
}

using Raven.Abstractions.Data;
using System;

namespace Dotnet.Microservice.Health.Checks
{
    public class RavenDbHealthCheck
    {
        public static HealthResponse CheckHealth(string connectionString)
        {
            try
            {
                ConnectionStringParser<RavenConnectionStringOptions> parser = ConnectionStringParser<RavenConnectionStringOptions>.FromConnectionString(connectionString);
                parser.Parse();
                var store = new Raven.Client.Document.DocumentStore
                {
                    Url = parser.ConnectionStringOptions.Url,
                    DefaultDatabase = parser.ConnectionStringOptions.DefaultDatabase
                };
                store.Initialize();
                // Client doesn't seem to throw an exception until we try to do something so let's just do something simple and get the build number of the server.
                var build = store.DatabaseCommands.GlobalAdmin.GetBuildNumber();
                // Dispose the store object
                store.Dispose();

                return HealthResponse.Healthy(new { server = store.Url, database = store.DefaultDatabase, serverBuild = build.BuildVersion });
            }
            catch (Exception ex)
            {
                return HealthResponse.Unhealthy(ex);
            }
        }
    }
}

Make the client request the RavenDB server version. If we don't do this the client doesn't appear to raise an exception in the case of a dead server so the health check will still return healthy.


using System;

namespace GraphQL.Types
{
    public interface IInputObjectGraphType : IComplexGraphType
    {
    }

    public class InputObjectGraphType : InputObjectGraphType<object>
    {
    }

    public class InputObjectGraphType<TSourceType> : ComplexGraphType<TSourceType>, IInputObjectGraphType
    {
        public override FieldType AddField(FieldType fieldType)
        {
            if(fieldType.Type == typeof(ObjectGraphType))
            {
                throw new ArgumentException(nameof(fieldType.Type),
                    "InputObjectGraphType cannot have fields containing a ObjectGraphType.");
            }

            return base.AddField(fieldType);
        }
    }
}

using System;

namespace GraphQL.Types
{
    public interface IInputObjectGraphType : IComplexGraphType
    {
    }

    public class InputObjectGraphType : InputObjectGraphType<object>
    {
    }

    public class InputObjectGraphType<TSourceType> : ComplexGraphType<TSourceType>, IInputObjectGraphType
    {
        public override FieldType AddField(FieldType fieldType)
        {
            if(fieldType.Type == typeof(ObjectGraphType))
            {
                throw new ArgumentException("InputObjectGraphType cannot have fields containing a ObjectGraphType.", nameof(fieldType.Type));
            }

            return base.AddField(fieldType);
        }
    }
}

Fix argument name param order

Fix argument name param order


using FluentEmail.Core;
using FluentScheduler;
using System;

namespace BatteryCommander.Web.Jobs
{
    public class SqliteBackupJob : IJob
    {
        private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable

        private readonly IFluentEmail emailSvc;

        public SqliteBackupJob(IFluentEmail emailSvc)
        {
            this.emailSvc = emailSvc;
        }

        public virtual void Execute()
        {
            emailSvc
                .To(Recipient)
                .Subject("Nightly Db Backup")
                .Body("Please find the nightly database backup attached.")
                .Attach(new FluentEmail.Core.Models.Attachment
                {
                    ContentType = "application/octet-stream",
                    Filename = "Data.db",
                    Data = System.IO.File.OpenRead("Data.db")
                })
                .Send();
        }
    }
}

using FluentEmail.Core;
using FluentScheduler;
using System;

namespace BatteryCommander.Web.Jobs
{
    public class SqliteBackupJob : IJob
    {
        private const String Recipient = "Backups@RedLeg.app";

        private readonly IFluentEmail emailSvc;

        public SqliteBackupJob(IFluentEmail emailSvc)
        {
            this.emailSvc = emailSvc;
        }

        public virtual void Execute()
        {
            emailSvc
                .To(Recipient)
                .Subject("Nightly Db Backup")
                .Body("Please find the nightly database backup attached.")
                .Attach(new FluentEmail.Core.Models.Attachment
                {
                    ContentType = "application/octet-stream",
                    Filename = "Data.db",
                    Data = System.IO.File.OpenRead("Data.db")
                })
                .Send();
        }
    }
}

Switch to new backup email recipient

Switch to new backup email recipient


using System;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Utils;

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

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

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

        public IValue InitialValue { get; set; }

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

        /// <summary>
        /// TO help with debugging...
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return VariableName + " = (" + Type.Name + ") " + RawValue;
        }

        public void RenameRawValue(string oldname, string newname)
        {
            if (InitialValue != null)
                InitialValue.RenameRawValue(oldname, newname);
            if (RawValue == oldname)
            {
                RawValue = newname;
                VariableName = newname;
            }
        }
    }
}

using System;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Utils;

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

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

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

        public IValue InitialValue { get; set; }

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

        /// <summary>
        /// TO help with debugging...
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            var s = string.Format("{0} {1}", Type.Name, VariableName);
            if (InitialValue != null)
                s = string.Format("{0} = {1}", s, InitialValue.RawValue);
            return s;
        }

        public void RenameRawValue(string oldname, string newname)
        {
            if (InitialValue != null)
                InitialValue.RenameRawValue(oldname, newname);
            if (RawValue == oldname)
            {
                RawValue = newname;
                VariableName = newname;
            }
        }
    }
}

Fix up how we generate debugging info for var simple.


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

[CustomEditor(typeof(MicrogameCollection))]
public class MicrogameCollectionEditor : Editor
{
	public override void OnInspectorGUI()
	{
		MicrogameCollection collection = (MicrogameCollection)target;
		if (GUILayout.Button("Update Microgames"))
		{
			collection.updateMicrogames();
            EditorUtility.SetDirty(collection);
        }
		DrawDefaultInspector();
	}

}

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

[CustomEditor(typeof(MicrogameCollection))]
public class MicrogameCollectionEditor : Editor
{
	public override void OnInspectorGUI()
	{
		MicrogameCollection collection = (MicrogameCollection)target;
		if (GUILayout.Button("Update Microgames"))
		{
			collection.updateMicrogames();
            EditorUtility.SetDirty(collection);
        }
        if (GUILayout.Button("Update Build Path"))
        {
            collection.updateBuildPath();
            EditorUtility.SetDirty(collection);
        }
        DrawDefaultInspector();
	}

}

Add editor button to update build path

Add editor button to update build path


using System;

namespace DynamixelServo.Quadruped
{
    static class MathExtensions
    {
        public static double RadToDegree(this double angle)
        {
            return angle * (180.0 / Math.PI);
        }

        public static float RadToDegree(this float angle)
        {
            return angle * (180f / (float)Math.PI);
        }

        public static double DegreeToRad(this double angle)
        {
            return Math.PI * angle / 180.0;
        }

        public static float DegreeToRad(this float angle)
        {
            return (float)Math.PI * angle / 180f;
        }

        public static double ToPower(this double number, double powerOf)
        {
            return Math.Pow(number, powerOf);
        }
    }
}

using System;

namespace DynamixelServo.Quadruped
{
    static class MathExtensions
    {
        public static double RadToDegree(this double angle)
        {
            return angle * (180.0 / Math.PI);
        }

        public static float RadToDegree(this float angle)
        {
            return angle * (180f / (float)Math.PI);
        }

        public static double DegreeToRad(this double angle)
        {
            return Math.PI * angle / 180.0;
        }

        public static float DegreeToRad(this float angle)
        {
            return (float)Math.PI * angle / 180f;
        }

        public static double ToPower(this double number, double powerOf)
        {
            return Math.Pow(number, powerOf);
        }

        public static float Square(this float number)
        {
            return number * number;
        }
    }
}

Add square extension method to floats

Add square extension method to floats


using System;
using Eto.Forms;
using JabbR.Eto.Interface.Dialogs;
using JabbR.Eto.Model.JabbR;
using System.Diagnostics;

namespace JabbR.Eto.Actions
{
	public class AddServer : ButtonAction
	{
		public const string ActionID = "AddServer";

		public bool AutoConnect { get; set; }

		public AddServer ()
		{
			this.ID = ActionID;
			this.MenuText = "Add Server...";
		}

		protected override void OnActivated (EventArgs e)
		{
			base.OnActivated (e);
			var server = new JabbRServer { Name = "JabbR.net", Address = "http://jabbr.net", JanrainAppName = "jabbr" };
			using (var dialog = new ServerDialog(server, true, true)) {
				dialog.DisplayMode = DialogDisplayMode.Attached;
				var ret = dialog.ShowDialog (Application.Instance.MainForm);
				if (ret == DialogResult.Ok) {
					Debug.WriteLine ("Added Server, Name: {0}", server.Name);
					var config = JabbRApplication.Instance.Configuration;
					config.AddServer (server);
					JabbRApplication.Instance.SaveConfiguration ();
					if (AutoConnect) {
						Application.Instance.AsyncInvoke(delegate {
							server.Connect ();
						});
					}
				}
			}

		}
	}
}

using System;
using Eto.Forms;
using JabbR.Eto.Interface.Dialogs;
using JabbR.Eto.Model.JabbR;
using System.Diagnostics;

namespace JabbR.Eto.Actions
{
	public class AddServer : ButtonAction
	{
		public const string ActionID = "AddServer";

		public bool AutoConnect { get; set; }

		public AddServer ()
		{
			this.ID = ActionID;
			this.MenuText = "Add Server...";
		}

		protected override void OnActivated (EventArgs e)
		{
			base.OnActivated (e);
			var server = new JabbRServer { Name = "JabbR.net", Address = "https://jabbr.net", JanrainAppName = "jabbr" };
			using (var dialog = new ServerDialog(server, true, true)) {
				dialog.DisplayMode = DialogDisplayMode.Attached;
				var ret = dialog.ShowDialog (Application.Instance.MainForm);
				if (ret == DialogResult.Ok) {
					Debug.WriteLine ("Added Server, Name: {0}", server.Name);
					var config = JabbRApplication.Instance.Configuration;
					config.AddServer (server);
					JabbRApplication.Instance.SaveConfiguration ();
					if (AutoConnect) {
						Application.Instance.AsyncInvoke(delegate {
							server.Connect ();
						});
					}
				}
			}

		}
	}
}

Use https by default for new servers

Use https by default for new servers


@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = "_Layout.cshtml";
}

@{ Html.RenderPartial("PageHeading"); }

        @{
            var members = Umbraco.TypedContentAtXPath("//OrganizationMember")
                .Where(m => m.GetPropertyValue<string>("Position") != "Coach");
        }

            @foreach (var item in members)
            {

                                @if (item.HasValue("ProfilePhoto"))
                                {

                                }

                                    @item.GetPropertyValue("FirstName") @item.GetPropertyValue("LastName")

                                @if (item.HasValue("HomeTown"))
                                {

@item.GetPropertyValue("HomeTown")

                                }

            }

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = "_Layout.cshtml";
}

@{ Html.RenderPartial("PageHeading"); }

        @{
            var members = Umbraco.TypedContentAtXPath("//OrganizationMember")
                .Where(m => m.GetPropertyValue<string>("Position") != "Coach")
                .OrderBy(m => m.GetPropertyValue("LastName"))
                    .ThenBy(m => m.GetPropertyValue("FirstName"));
        }

            @foreach (var item in members)
            {

                                @if (item.HasValue("ProfilePhoto"))
                                {

                                }

                                    @item.GetPropertyValue("FirstName") @item.GetPropertyValue("LastName")

                                @if (item.HasValue("HomeTown"))
                                {

@item.GetPropertyValue("HomeTown")

                                }

            }

Order organization members by name.

Order organization members by name.


using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Eto.Platform.iOS.Forms;
using Eto.Forms;

namespace Eto.Platform.iOS
{
	[MonoTouch.Foundation.Register("EtoAppDelegate")]
	public class EtoAppDelegate : UIApplicationDelegate
	{
		public EtoAppDelegate ()
		{
		}

		public override bool WillFinishLaunching (UIApplication application, NSDictionary launchOptions)
		{
			ApplicationHandler.Instance.Initialize(this);
			return true;
		}
	}
}

using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Eto.Platform.iOS.Forms;
using Eto.Forms;

namespace Eto.Platform.iOS
{
	[MonoTouch.Foundation.Register("EtoAppDelegate")]
	public class EtoAppDelegate : UIApplicationDelegate
	{
		public EtoAppDelegate ()
		{
		}

		public override bool FinishedLaunching (UIApplication application, NSDictionary launcOptions)
		{
			ApplicationHandler.Instance.Initialize(this);
			return true;
		}
	}
}

Fix running on < iOS 6.0

iOS: Fix running on < iOS 6.0


using Newtonsoft.Json;

namespace SurveyMonkey.Containers
{
    [JsonConverter(typeof(TolerantJsonConverter))]
    public class QuestionDisplayOptionsCustomOptions
    {
    }
}

using Newtonsoft.Json;
using System.Collections.Generic;

namespace SurveyMonkey.Containers
{
    [JsonConverter(typeof(TolerantJsonConverter))]
    public class QuestionDisplayOptionsCustomOptions
    {
        public List<string> OptionSet { get; set; }
        public int StartingPosition { get; set; }
        public int StepSize { get; set; }
    }
}

Add custom display option props based on sliders


using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

namespace Presentation.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            // Turns off self reference looping when serializing models in API controlllers
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            // Support polymorphism in web api JSON output
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;

            // Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#)
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            //Format datetime correctly. From: http://stackoverflow.com/questions/20143739/date-format-in-mvc-4-api-controller
            var dateTimeConverter = new IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            };

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
                               .Converters.Add(dateTimeConverter);
        }
    }
}

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Presentation.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            // Turns off self reference looping when serializing models in API controlllers
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            // Support polymorphism in web api JSON output
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;

            // Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#)
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // Convert all dates to UTC
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
        }
    }
}

Convert all dates to UTC time

Convert all dates to UTC time


namespace BmpListener.Bgp
{
    public class ASPathSegment
    {
        public ASPathSegment(Type type, int[] asns)
        {
            SegmentType = Type;
            ASNs = asns;
        }

        public enum Type
        {
            AS_SET = 1,
            AS_SEQUENCE,
            AS_CONFED_SEQUENCE,
            AS_CONFED_SET
        }

        public Type SegmentType { get; set; }
        public int[] ASNs { get; set; }
    }
}

using System.Collections.Generic;

namespace BmpListener.Bgp
{
    public class ASPathSegment
    {
        public ASPathSegment(Type type, IList<int> asns)
        {
            SegmentType = type;
            ASNs = asns;
        }

        public enum Type
        {
            AS_SET = 1,
            AS_SEQUENCE,
            AS_CONFED_SEQUENCE,
            AS_CONFED_SET
        }

        public Type SegmentType { get; set; }
        public IList<int> ASNs { get; set; }
    }
}

Change ASN int array to IList

Change ASN int array to IList


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SurveyMonkeyApi")]
[assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SurveyMonkeyApi")]
[assembly: AssemblyCopyright("Copyright © Ben Emmett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("da9e0373-83cd-4deb-87a5-62b313be61ec")]

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

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SurveyMonkeyApi")]
[assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SurveyMonkeyApi")]
[assembly: AssemblyCopyright("Copyright © Ben Emmett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("da9e0373-83cd-4deb-87a5-62b313be61ec")]

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

Bump assembly info for 1.2.2 release

Bump assembly info for 1.2.2 release


// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEditor;

namespace Microsoft.MixedReality.Toolkit.Input.Editor
{
    [CustomEditor(typeof(MixedRealityControllerVisualizer))]
    public class MixedRealityControllerVisualizerInspector : ControllerPoseSynchronizerInspector { }
}

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEditor;

namespace Microsoft.MixedReality.Toolkit.Input.Editor
{
    [CustomEditor(typeof(MixedRealityControllerVisualizer), true)]
    public class MixedRealityControllerVisualizerInspector : ControllerPoseSynchronizerInspector { }
}

Use inspector for child classes

Use inspector for child classes


using System.Diagnostics.CodeAnalysis;
using System.Web.Optimization;

namespace T4MVCHostMvcApp.App_Start
{
    public static class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")]
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new StyleBundle(Links.Bundles.Content.Styles).Include(
                Links.Bundles.Content.Assets.Site_css
            ));

        }
    }
}

namespace Links
{
    public static partial class Bundles
    {
        public static partial class Content
        {
            public const string Styles = "~/content/styles";
        }
    }
}

using System.Diagnostics.CodeAnalysis;
using System.Web.Optimization;

namespace T4MVCHostMvcApp.App_Start
{
    public static class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")]
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle(Links.Bundles.Scripts.jquery).Include("~/scripts/jquery-{version}.js"));
            bundles.Add(new StyleBundle(Links.Bundles.Styles.bootstrap).Include("~/styles/bootstrap*.css"));
            bundles.Add(new StyleBundle(Links.Bundles.Styles.common).Include(Links.Bundles.Content.Assets.Site_css));

        }
    }
}

namespace Links
{
    public static partial class Bundles
    {
        public static partial class Scripts
        {
            public static readonly string jquery = "~/scripts/jquery";
            public static readonly string jqueryui = "~/scripts/jqueryui";
        }
        public static partial class Styles
        {
            public static readonly string bootstrap = "~/styles/boostrap";
            public static readonly string theme = "~/styles/theme";
            public static readonly string common = "~/styles/common";
        }
    }
}

Update bundle config to match exampe in wiki page


using System.Collections.Generic;

namespace slang.Lexing.Trees.Nodes
{
    public class Transitions : Dictionary<char,Node>
    {
    }
}

using System.Collections.Generic;

namespace slang.Lexing.Trees.Nodes
{
    public class Transitions : Dictionary<Character,Transition>
    {
    }
}

Use character class as transition key

Use character class as transition key


// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using SmugMug.v2.Authentication;
using System.Threading.Tasks;

namespace SmugMug.v2.Types
{
    public class SiteEntity : SmugMugEntity
    {
        public SiteEntity(OAuthToken token)
        {
            _oauthToken = token;
        }

        public async Task<UserEntity> GetAuthenticatedUserAsync()
        {
            // !authuser
            string requestUri = string.Format("{0}!authuser", SmugMug.v2.Constants.Addresses.SmugMugApi);

            return await RetrieveEntityAsync<UserEntity>(requestUri);
        }

        public async Task<UserEntity[]> SearchForUser(string query)
        {
            // api/v2/user!search?q=
            string requestUri = string.Format("{0}/user!search?q={1}", SmugMug.v2.Constants.Addresses.SmugMugApi, query);

            return await RetrieveEntityArrayAsync<UserEntity>(requestUri);
        }
    }
}

// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using SmugMug.v2.Authentication;
using System.Threading.Tasks;

namespace SmugMug.v2.Types
{
    public class SiteEntity : SmugMugEntity
    {
        public SiteEntity(OAuthToken token)
        {
            _oauthToken = token;
        }

        public async Task<UserEntity> GetAuthenticatedUserAsync()
        {
            // !authuser
            string requestUri = string.Format("{0}!authuser", SmugMug.v2.Constants.Addresses.SmugMugApi);

            return await RetrieveEntityAsync<UserEntity>(requestUri);
        }

        public async Task<CatalogVendorEntity[]> GetVendors()
        {
            // /catalog!vendors
            string requestUri = string.Format("{0}/catalog!vendors", SmugMug.v2.Constants.Addresses.SmugMugApi);

            return await RetrieveEntityArrayAsync<CatalogVendorEntity>(requestUri);
        }

        public async Task<UserEntity[]> SearchForUser(string query)
        {
            // api/v2/user!search?q=
            string requestUri = string.Format("{0}/user!search?q={1}", SmugMug.v2.Constants.Addresses.SmugMugApi, query);

            return await RetrieveEntityArrayAsync<UserEntity>(requestUri);
        }
    }
}

Add a way to get the vendors from the Site entity.


using System.ComponentModel.Composition;
using Microsoft.EntityFrameworkCore;
using Waf.BookLibrary.Library.Applications.Data;
using Waf.BookLibrary.Library.Applications.Services;
using Waf.BookLibrary.Library.Domain;

namespace Test.BookLibrary.Library.Applications.Services
{
    [Export, Export(typeof(IDBContextService))]
    public class MockDBContextService : IDBContextService
    {
        public DbContext GetBookLibraryContext(out string dataSourcePath)
        {
            dataSourcePath = @"C:\Test.db";
            var options = new DbContextOptionsBuilder<BookLibraryContext>().UseInMemoryDatabase(databaseName: "TestDatabase").Options;
            var context = new BookLibraryContext(options, modelBuilder =>
            {
                modelBuilder.Entity<Book>().Ignore(x => x.Errors).Ignore(x => x.HasErrors);
                modelBuilder.Entity<Person>().Ignore(x => x.Errors).Ignore(x => x.HasErrors);
            });
            return context;
        }
    }
}

using System.ComponentModel.Composition;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Waf.BookLibrary.Library.Applications.Data;
using Waf.BookLibrary.Library.Applications.Services;
using Waf.BookLibrary.Library.Domain;

namespace Test.BookLibrary.Library.Applications.Services
{
    [Export, Export(typeof(IDBContextService))]
    public class MockDBContextService : IDBContextService
    {
        public DbContext GetBookLibraryContext(out string dataSourcePath)
        {
            dataSourcePath = @"C:\Test.db";
            var options = new DbContextOptionsBuilder<BookLibraryContext>().UseInMemoryDatabase(databaseName: "TestDatabase",
                databaseRoot: new InMemoryDatabaseRoot()).Options;
            var context = new BookLibraryContext(options, modelBuilder =>
            {
                modelBuilder.Entity<Book>().Ignore(x => x.Errors).Ignore(x => x.HasErrors);
                modelBuilder.Entity<Person>().Ignore(x => x.Errors).Ignore(x => x.HasErrors);
            });
            return context;
        }
    }
}

Fix InMemory context for unit tests

BookLib: Fix InMemory context for unit tests


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

using System;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;

namespace osu.Game.Overlays.Settings
{
    public class SettingsEnumDropdown<T> : SettingsDropdown<T>
        where T : struct, Enum
    {
        protected override OsuDropdown<T> CreateDropdown() => new DropdownControl();

        protected new class DropdownControl : OsuEnumDropdown<T>
        {
            public DropdownControl()
            {
                Margin = new MarginPadding { Top = 5 };
                RelativeSizeAxes = Axes.X;
            }

            protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = 200);
        }
    }
}

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

using System;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;

namespace osu.Game.Overlays.Settings
{
    public class SettingsEnumDropdown<T> : SettingsDropdown<T>
        where T : struct, Enum
    {
        protected override OsuDropdown<T> CreateDropdown() => new DropdownControl();

        protected new class DropdownControl : OsuEnumDropdown<T>
        {
            protected virtual int MenuMaxHeight => 200;

            public DropdownControl()
            {
                Margin = new MarginPadding { Top = 5 };
                RelativeSizeAxes = Axes.X;
            }

            protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = MenuMaxHeight);
        }
    }
}

Refactor the menu's max height to be a property


// Copyright (c) 2015 Bartlomiej Wolk (bartlomiejwolk@gmail.com)
//
// This file is part of the HealthBar extension for Unity. Licensed under the
// MIT license. See LICENSE file in the project root folder. Based on HealthBar
// component made by Zero3Growlithe (zero3growlithe@gmail.com).

using UnityEngine;

namespace HealthBarEx {

    [System.Serializable]
    // todo encapsulate fields
    public class HealthBarGUI {

        public Color addedHealth;

        [HideInInspector]
        public float alpha;

        public float animationSpeed = 3f;
        public Color availableHealth;
        public Color displayedValue;
        public bool displayValue = true;
        public Color drainedHealth;
        public int height = 30;
        public Vector2 offset = new Vector2(0, 30);
        public PositionModes positionMode;
        public GUIStyle textStyle;
        public Texture texture;
        public float transitionDelay = 3f;
        public float transitionSpeed = 5f;
        public Vector2 valueOffset = new Vector2(0, 30);
        public float visibility = 1;
        public int width = 100;

        public enum PositionModes {

            Fixed,
            Center

        };

    }

}

// Copyright (c) 2015 Bartlomiej Wolk (bartlomiejwolk@gmail.com)
//
// This file is part of the HealthBar extension for Unity. Licensed under the
// MIT license. See LICENSE file in the project root folder. Based on HealthBar
// component made by Zero3Growlithe (zero3growlithe@gmail.com).

using UnityEngine;

namespace HealthBarEx {

    [System.Serializable]
    // todo encapsulate fields
    public class HealthBarGUI {

        [HideInInspector]
        public float alpha;

        public bool displayValue = true;
        public PositionModes positionMode;
        public Texture texture;
        public Color addedHealth;
        public Color availableHealth;
        public Color displayedValue;
        public Color drainedHealth;
        public float animationSpeed = 3f;
        public float transitionSpeed = 5f;
        public float transitionDelay = 3f;
        public float visibility = 1;
        public int width = 100;
        public int height = 30;
        public Vector2 offset = new Vector2(0, 30);
        public Vector2 valueOffset = new Vector2(0, 30);
        public GUIStyle textStyle;

        public enum PositionModes {

            Fixed,
            Center

        };

    }

}

Reorder fields in the inspector

Reorder fields in the inspector


using System;

using FluentAssertions;

using Xunit;

namespace Grobid.PdfToXml.Test
{
    public class TokenBlockFactoryTest
    {
        [Fact]
        public void TestA()
        {
            var stub = new TextRenderInfoStub();
            var testSubject = new TokenBlockFactory(100, 100);

            Action test = () => testSubject.Create(stub);
            test.ShouldThrow<NullReferenceException>("I am still implementing the code.");
        }
    }
}

using System;

using FluentAssertions;

using iTextSharp.text.pdf.parser;

using Xunit;

namespace Grobid.PdfToXml.Test
{
    public class TokenBlockFactoryTest
    {
        [Fact]
        public void FactoryShouldNormalizeUnicodeStrings()
        {
            var stub = new TextRenderInfoStub
            {
                AscentLine = new LineSegment(new Vector(0, 0, 0), new Vector(1, 1, 1)),
                Baseline = new LineSegment(new Vector(0, 0, 0), new Vector(1, 1, 1)),
                DescentLine = new LineSegment(new Vector(0, 0, 0), new Vector(1, 1, 1)),
                PostscriptFontName = "CHUFSU+NimbusRomNo9L-Medi",
                Text = "abcd\u0065\u0301fgh",
            };

            var testSubject = new TokenBlockFactory(100, 100);
            var tokenBlock = testSubject.Create(stub);

            stub.Text.ToCharArray().Should().HaveCount(9);
            tokenBlock.Text.ToCharArray().Should().HaveCount(8);
        }
    }
}

Write test to ensure characters are normalized.


// Copyright(c) 2016 Google Inc.
//
// 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 System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;

namespace GoogleCloudSamples.Controllers
{
    // [START login]
    public class SessionController : Controller
    {
        public ActionResult Login()
        {
            // Redirect to the Google OAuth 2.0 user consent screen
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                "Google"
            );
            return new HttpUnauthorizedResult();
        }

        // ...
        // [END login]

        // [START logout]
        public ActionResult Logout()
        {
            Request.GetOwinContext().Authentication.SignOut();
            return Redirect("/");
        }
        // [END logout]
    }
}

// Copyright(c) 2016 Google Inc.
//
// 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 System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;

namespace GoogleCloudSamples.Controllers
{
    // [START login]
    public class SessionController : Controller
    {
        public void Login()
        {
            // Redirect to the Google OAuth 2.0 user consent screen
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                "Google"
            );
        }

        // ...
        // [END login]

        // [START logout]
        public ActionResult Logout()
        {
            Request.GetOwinContext().Authentication.SignOut();
            return Redirect("/");
        }
        // [END logout]
    }
}

Simplify Login() action - no explicit return necessary


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

using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Graphics.UserInterfaceV2;
using osu.Game.Skinning;
using osuTK.Graphics;

namespace osu.Game.Screens.Edit.Setup
{
    internal class ColoursSection : SetupSection
    {
        public override LocalisableString Title => "Colours";

        private LabelledColourPalette comboColours;

        [BackgroundDependencyLoader]
        private void load()
        {
            Children = new Drawable[]
            {
                comboColours = new LabelledColourPalette
                {
                    Label = "Hitcircle / Slider Combos",
                    FixedLabelWidth = LABEL_WIDTH,
                    ColourNamePrefix = "Combo"
                }
            };

            var colours = Beatmap.BeatmapSkin?.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value;
            if (colours != null)
                comboColours.Colours.AddRange(colours.Select(c => (Colour4)c));
        }
    }
}

// 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.Localisation;
using osu.Game.Graphics.UserInterfaceV2;

namespace osu.Game.Screens.Edit.Setup
{
    internal class ColoursSection : SetupSection
    {
        public override LocalisableString Title => "Colours";

        private LabelledColourPalette comboColours;

        [BackgroundDependencyLoader]
        private void load()
        {
            Children = new Drawable[]
            {
                comboColours = new LabelledColourPalette
                {
                    Label = "Hitcircle / Slider Combos",
                    FixedLabelWidth = LABEL_WIDTH,
                    ColourNamePrefix = "Combo"
                }
            };

            if (Beatmap.BeatmapSkin != null)
                comboColours.Colours.BindTo(Beatmap.BeatmapSkin.ComboColours);
        }
    }
}

Use editable skin structure in combo colour picker


using System.Collections.Generic;

using commercetools.Common;
using commercetools.CustomFields;

using Newtonsoft.Json;

namespace commercetools.Carts
{
    /// <summary>
    /// API representation for creating a new CustomLineItem.
    /// </summary>
    /// <see href="http://dev.commercetools.com/http-api-projects-carts.html#customlineitemdraft"/>
    public class CustomLineItemDraft
    {
        #region Properties

        [JsonProperty(PropertyName = "name")]
        public LocalizedString Name { get; set; }

        [JsonProperty(PropertyName = "quantity")]
        public int? Quantity { get; set; }

        [JsonProperty(PropertyName = "money")]
        public Money Money { get; set; }

        [JsonProperty(PropertyName = "slug")]
        public string Slug { get; set; }

        [JsonProperty(PropertyName = "taxCategory")]
        public Reference TaxCategory { get; set; }

        [JsonProperty(PropertyName = "custom")]
        public List<CustomFieldsDraft> Custom { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor.
        /// </summary>
        public CustomLineItemDraft(LocalizedString name)
        {
            this.Name = name;
        }

        #endregion
    }
}

using System.Collections.Generic;

using commercetools.Common;
using commercetools.CustomFields;

using Newtonsoft.Json;

namespace commercetools.Carts
{
    /// <summary>
    /// API representation for creating a new CustomLineItem.
    /// </summary>
    /// <see href="http://dev.commercetools.com/http-api-projects-carts.html#customlineitemdraft"/>
    public class CustomLineItemDraft
    {
        #region Properties

        [JsonProperty(PropertyName = "name")]
        public LocalizedString Name { get; set; }

        [JsonProperty(PropertyName = "quantity")]
        public int? Quantity { get; set; }

        [JsonProperty(PropertyName = "money")]
        public Money Money { get; set; }

        [JsonProperty(PropertyName = "slug")]
        public string Slug { get; set; }

        [JsonProperty(PropertyName = "taxCategory")]
        public Reference TaxCategory { get; set; }

        [JsonProperty(PropertyName = "custom")]
        public CustomFieldsDraft Custom { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor.
        /// </summary>
        public CustomLineItemDraft(LocalizedString name)
        {
            this.Name = name;
        }

        #endregion
    }
}

Update Custom field to the correct POCO representation


namespace Cronofy
{
    using System;

    /// <summary>
    /// Interface for a Cronofy client base that manages the
    /// access token and any shared client methods.
    /// </summary>
    public interface ICronofyUserInfoClient
    {
        /// <summary>
        /// Gets the user info belonging to the account.
        /// </summary>
        /// <returns>The account's user info.</returns>
        /// <exception cref="ArgumentException">
        /// Thrown if <paramref name="request"/> is null.
        /// </exception>
        /// <exception cref="CronofyException">
        /// Thrown if an error is encountered whilst making the request.
        /// </exception>
        UserInfo GetUserInfo();
    }
}

namespace Cronofy
{
    using System;

    /// <summary>
    /// Interface for a Cronofy client base that manages the
    /// access token and any shared client methods.
    /// </summary>
    public interface ICronofyUserInfoClient
    {
        /// <summary>
        /// Gets the user info belonging to the account.
        /// </summary>
        /// <returns>The account's user info.</returns>
        /// <exception cref="CronofyException">
        /// Thrown if an error is encountered whilst making the request.
        /// </exception>
        UserInfo GetUserInfo();
    }
}

Remove unnecessary argument exception documentation on user info


namespace MyParcelApi.Net.Models
{
    public enum Carrier
    {
        PostNl = 1,
        BPost = 2
    }
}

namespace MyParcelApi.Net.Models
{
    public enum Carrier
    {
        None = 0,
        PostNl = 1,
        BPost = 2
    }
}

Improve when there is no carrier

Improve when there is no carrier


using UnityEngine;
using System.Collections;

public class ShotControl : MonoBehaviour {

	public float speed = 0.2f;

	private bool inBlock;

	private int life = 3;

	void Start () {
	}

	void Update () {
		// Old position
		Vector3 position = transform.position;

		// Move
		transform.Translate(Vector3.up * speed);

		// Check for collision
		Collider2D collider = Physics2D.OverlapCircle(transform.position, 0.1f);
		if (collider) {
			if (collider.name == "ArenaBlock") {
				if (!inBlock) {
					// Reduce life
					if (--life == 0) {
						Destroy(gameObject);
						return;
					}
					// Find vector to block center (normalized for stretched blocks)
					Vector3 v = collider.transform.position - position;
					v.x /= collider.transform.localScale.x;
					v.y /= collider.transform.localScale.y;
					Vector3 forward = transform.up;
					if (Mathf.Abs(v.x) < Mathf.Abs(v.y)) {
						forward.y = -forward.y; // bounce vertically
					} else {
						forward.x = -forward.x; // bounce horizontally
					}
					transform.up = forward;
				}
				inBlock = true;
			}
		} else {
			inBlock = false;
		}
	}
}

using UnityEngine;
using System.Collections;

public class ShotControl : MonoBehaviour {

	public float speed = 0.2f;

	private bool inBlock;

	private int life = 3;

	void Start () {
	}

	void Update () {
		// Old position
		Vector3 position = transform.position;

		// Move
		transform.Translate(Vector3.up * speed);

		// Check for out of bounds
		if (100f <= Mathf.Abs(transform.position.magnitude)) {
			Destroy(gameObject);
			return;
		}

		// Check for collision
		Collider2D collider = Physics2D.OverlapCircle(transform.position, 0.15f);
		if (collider) {
			if (collider.name == "ArenaBlock") {
				if (!inBlock) {
					// Reduce life
					if (--life == 0) {
						Destroy(gameObject);
						return;
					}
					// Find vector to block center (normalized for stretched blocks)
					Vector3 v = collider.transform.position - position;
					v.x /= collider.transform.localScale.x;
					v.y /= collider.transform.localScale.y;
					Vector3 forward = transform.up;
					if (Mathf.Abs(v.x) < Mathf.Abs(v.y)) {
						forward.y = -forward.y; // bounce vertically
					} else {
						forward.x = -forward.x; // bounce horizontally
					}
					transform.up = forward;
				}
				inBlock = true;
			}
		} else {
			inBlock = false;
		}
	}
}

Check for shots going out of bounds and kill them


using WootzJs.Mvc.Views;
using WootzJs.Mvc.Views.Css;

namespace WootzJs.Mvc
{
    public static class StyleExtensions
    {
        public static T WithBold<T>(this T control) where T : Control
        {
            control.Style.Font.Weight = new CssFontWeight(CssFontWeightType.Bold);
            return control;
        }
    }
}

using WootzJs.Mvc.Views;
using WootzJs.Mvc.Views.Css;

namespace WootzJs.Mvc
{
    public static class StyleExtensions
    {
        public static T WithBold<T>(this T control) where T : Control
        {
            control.Style.Font.Weight = new CssFontWeight(CssFontWeightType.Bold);
            return control;
        }

        public static T WithPadding<T>(this T control, CssPadding padding) where T : Control
        {
            control.Style.Padding = padding;
            return control;
        }
    }
}

Add more style extension methods

Add more style extension methods


using System.Net;
using System.Web.Script.Serialization;

namespace MultiMiner.MobileMiner.Api
{
    public class ApiContext
    {
        static public void SubmitMiningStatistics(string url, MiningStatistics miningStatistics)
        {
            string fullUrl = url + "/api/MiningStatisticsInput";
            using (WebClient client = new WebClient())
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string jsonData = serializer.Serialize(miningStatistics);
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.UploadString(fullUrl, jsonData);
            }
        }
    }
}

using System.Net;
using System.Web.Script.Serialization;

namespace MultiMiner.MobileMiner.Api
{
    public class ApiContext
    {
        static public void SubmitMiningStatistics(string url, MiningStatistics miningStatistics)
        {
            if (!url.EndsWith("/"))
                url = url + "/";
            string fullUrl = url + "api/MiningStatisticsInput";
            using (WebClient client = new WebClient())
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string jsonData = serializer.Serialize(miningStatistics);
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.UploadString(fullUrl, jsonData);
            }
        }
    }
}

Handle URL's with or without a / suffix

Handle URL's with or without a / suffix


#load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease

Environment.SetVariableNames();

BuildParameters.SetParameters(context: Context,
                            buildSystem: BuildSystem,
                            sourceDirectoryPath: "./src",
                            title: "Cake.Hg",
                            repositoryOwner: "cake-contrib",
                            repositoryName: "Cake.Hg",
                            appVeyorAccountName: "cakecontrib",
                            solutionFilePath: "./src/Cake.Hg.sln",
                            shouldRunCodecov: false,
                            wyamSourceFiles: "../../src/**/{!bin,!obj,!packages,!*Tests,}/**/*.cs");

BuildParameters.PrintParameters(Context);

ToolSettings.SetToolSettings(context: Context,
                            dupFinderExcludePattern: new string[] {
                                BuildParameters.RootDirectoryPath + "/src/Cake.HgTests/**/*.cs",
                                BuildParameters.RootDirectoryPath + "/src/Cake.Hg/**/*.AssemblyInfo.cs"
                            });

Build.Run();

#load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease

Environment.SetVariableNames();

BuildParameters.SetParameters(context: Context,
    buildSystem: BuildSystem,
    sourceDirectoryPath: "./src",
    title: "Cake.Hg",
    repositoryOwner: "cake-contrib",
    repositoryName: "Cake.Hg",
    appVeyorAccountName: "cakecontrib",
    solutionFilePath: "./src/Cake.Hg.sln",
    shouldRunCodecov: false,
    shouldRunDupFinder: false,
    wyamSourceFiles: "../../src/**/{!bin,!obj,!packages,!*Tests,}/**/*.cs");

BuildParameters.PrintParameters(Context);

ToolSettings.SetToolSettings(context: Context,
    dupFinderExcludePattern: new string[] {
        BuildParameters.RootDirectoryPath + "/src/Cake.HgTests/**/*.cs",
        BuildParameters.RootDirectoryPath + "/src/Cake.Hg/**/*.AssemblyInfo.cs"
    });

Build.Run();

Disable dupfinder because of Hg.Net

Disable dupfinder because of Hg.Net


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MowChat")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MowChat")]
[assembly: AssemblyCopyright("Copyright ©  2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("17fb5df9-452a-423d-925e-7b98ab9a5b02")]

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

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MowChat")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MowChat")]
[assembly: AssemblyCopyright("Copyright ©  2013-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("17fb5df9-452a-423d-925e-7b98ab9a5b02")]

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

Increase version number & add 2014 copyright


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

[assembly: AssemblyTitle("Autofac.Extras.DomainServices")]
[assembly: AssemblyDescription("Autofac Integration for RIA Services")]
[assembly: ComVisible(false)]

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

[assembly: AssemblyTitle("Autofac.Extras.DomainServices")]
[assembly: ComVisible(false)]

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


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

using System.Linq;
using osu.Framework.Audio.Track;
using osu.Game.Rulesets.Objects.Types;

namespace osu.Game.Beatmaps
{
    public partial class WorkingBeatmap
    {
        /// <summary>
        /// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>.
        /// </summary>
        protected class VirtualBeatmapTrack : TrackVirtual
        {
            private readonly IBeatmap beatmap;

            public VirtualBeatmapTrack(IBeatmap beatmap)
            {
                this.beatmap = beatmap;
                updateVirtualLength();
            }

            protected override void UpdateState()
            {
                updateVirtualLength();
                base.UpdateState();
            }

            private void updateVirtualLength()
            {
                var lastObject = beatmap.HitObjects.LastOrDefault();

                switch (lastObject)
                {
                    case null:
                        Length = 1000;
                        break;
                    case IHasEndTime endTime:
                        Length = endTime.EndTime + 1000;
                        break;
                    default:
                        Length = lastObject.StartTime + 1000;
                        break;
                }
            }
        }
    }
}

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

using System.Linq;
using osu.Framework.Audio.Track;
using osu.Game.Rulesets.Objects.Types;

namespace osu.Game.Beatmaps
{
    public partial class WorkingBeatmap
    {
        /// <summary>
        /// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>.
        /// </summary>
        protected class VirtualBeatmapTrack : TrackVirtual
        {
            private const double excess_length = 1000;

            private readonly IBeatmap beatmap;

            public VirtualBeatmapTrack(IBeatmap beatmap)
            {
                this.beatmap = beatmap;
                updateVirtualLength();
            }

            protected override void UpdateState()
            {
                updateVirtualLength();
                base.UpdateState();
            }

            private void updateVirtualLength()
            {
                var lastObject = beatmap.HitObjects.LastOrDefault();

                switch (lastObject)
                {
                    case null:
                        Length = excess_length;
                        break;
                    case IHasEndTime endTime:
                        Length = endTime.EndTime + excess_length;
                        break;
                    default:
                        Length = lastObject.StartTime + excess_length;
                        break;
                }
            }
        }
    }
}

Use a const for excess length

Use a const for excess length


// Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Core.Utilities;

namespace Nuke.Core.Tooling
{
    [PublicAPI]
    [DebuggerStepThrough]
    [DebuggerNonUserCode]
    public static class ProcessExtensions
    {
        [AssertionMethod]
        public static void AssertWaitForExit ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process)
        {
            ControlFlow.Assert(process != null && process.WaitForExit(), "process != null && process.WaitForExit()");
        }

        [AssertionMethod]
        public static void AssertZeroExitCode ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process)
        {
            process.AssertWaitForExit();
            ControlFlow.Assert(process.ExitCode == 0,
                new[]
                {
                    $"Process '{Path.GetFileName(process.StartInfo.FileName)}' exited with code {process.ExitCode}. Please verify the invocation:",
                    $"> {process.StartInfo.FileName.DoubleQuoteIfNeeded()} {process.StartInfo.Arguments}"
                }.Join(EnvironmentInfo.NewLine));
        }

        public static IEnumerable<Output> EnsureOnlyStd (this IEnumerable<Output> output)
        {
            foreach (var o in output)
            {
                ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std");
                yield return o;
            }
        }
    }
}

// Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Core.Utilities;

namespace Nuke.Core.Tooling
{
    [PublicAPI]
    [DebuggerStepThrough]
    [DebuggerNonUserCode]
    public static class ProcessExtensions
    {
        [AssertionMethod]
        public static void AssertWaitForExit ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process)
        {
            ControlFlow.Assert(process != null && process.WaitForExit(), "process != null && process.WaitForExit()");
        }

        [AssertionMethod]
        public static void AssertZeroExitCode ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process)
        {
            process.AssertWaitForExit();
            ControlFlow.Assert(process.ExitCode == 0,
                $"Process '{Path.GetFileName(process.StartInfo.FileName)}' exited with code {process.ExitCode}. Please verify the invocation.");
        }

        public static IEnumerable<Output> EnsureOnlyStd (this IEnumerable<Output> output)
        {
            foreach (var o in output)
            {
                ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std");
                yield return o;
            }
        }
    }
}

Remove printing of invocation in case of non-zero exit code.


using System;
using System.Drawing.Imaging;
using System.IO;
using Tellurium.MvcPages.Utils;

namespace Tellurium.MvcPages.BrowserCamera.Storage
{
    public class FileSystemScreenshotStorage : IScreenshotStorage
    {
        private readonly string screenshotDirectoryPath;

        public FileSystemScreenshotStorage(string screenshotDirectoryPath)
        {
            this.screenshotDirectoryPath = screenshotDirectoryPath;
        }

        public virtual void Persist(byte[] image, string screenshotName)
        {
            var screenshotPath = GetScreenshotPath(screenshotName);
            image.ToBitmap().Save(screenshotPath, ImageFormat.Jpeg);
        }

        protected string GetScreenshotPath(string screenshotName)
        {
            if (string.IsNullOrWhiteSpace(screenshotDirectoryPath))
            {
                throw new ApplicationException("Screenshot directory path not defined");
            }

            if (string.IsNullOrWhiteSpace(screenshotName))
            {
                throw new ArgumentException("Screenshot name cannot be empty", nameof(screenshotName));
            }
            var fileName = $"{screenshotName}.jpg";
            return Path.Combine(screenshotDirectoryPath, fileName);
        }
    }
}

using System;
using System.Drawing.Imaging;
using System.IO;
using Tellurium.MvcPages.Utils;

namespace Tellurium.MvcPages.BrowserCamera.Storage
{
    public class FileSystemScreenshotStorage : IScreenshotStorage
    {
        private readonly string screenshotDirectoryPath;

        public FileSystemScreenshotStorage(string screenshotDirectoryPath)
        {
            this.screenshotDirectoryPath = screenshotDirectoryPath;
        }

        public virtual void Persist(byte[] image, string screenshotName)
        {
            var screenshotPath = GetScreenshotPath(screenshotName);
            image.ToBitmap().Save(screenshotPath, ImageFormat.Jpeg);
        }

        protected string GetScreenshotPath(string screenshotName)
        {
            if (string.IsNullOrWhiteSpace(screenshotDirectoryPath))
            {
                throw new ApplicationException("Screenshot directory path not defined");
            }

            if (string.IsNullOrWhiteSpace(screenshotName))
            {
                throw new ArgumentException("Screenshot name cannot be empty", nameof(screenshotName));
            }

            if (Directory.Exists(screenshotDirectoryPath) == false)
            {
                Directory.CreateDirectory(screenshotDirectoryPath);
            }

            var fileName = $"{screenshotName}.jpg";
            return Path.Combine(screenshotDirectoryPath, fileName);
        }
    }
}

Create directory for error screenshot if it does not exist


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

using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Mvc.Internal
{
    public static class TaskCache
    {
#if NET451
        static readonly Task _completedTask = Task.FromResult(0);
#endif

        /// <summary>Gets a task that's already been completed successfully.</summary>
        /// <remarks>May not always return the same instance.</remarks>
        public static Task CompletedTask
        {
            get
            {
#if NET451
                return _completedTask;
#else
                return Task.CompletedTask;
#endif
            }
        }
    }

}

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

using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Mvc.Internal
{
    public static class TaskCache
    {

        /// <summary>
        /// A <see cref="Task"/> that's already completed successfully.
        /// </summary>
        /// <remarks>
        /// We're caching this in a static readonly field to make it more inlinable and avoid the volatile lookup done
        /// by <c>Task.CompletedTask</c>.
        /// </remarks>
#if NET451
        public static readonly Task CompletedTask = Task.FromResult(0);
#else
        public static readonly Task CompletedTask = Task.CompletedTask;
#endif
    }
}

Change our cached task to a field

Change our cached task to a field

This makes it more inlinable and saves a volatile lookup on netstandard.


// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

using ImageMagick;
using Xunit;
using Xunit.Sdk;

namespace Magick.NET.Tests
{
    public partial class ResourceLimitsTests
    {
        [Collection(nameof(RunTestsSeparately))]
        public class TheMaxMemoryRequest
        {
            [Fact]
            public void ShouldHaveTheCorrectValue()
            {
                if (ResourceLimits.MaxMemoryRequest < 100000000U)
                    throw new XunitException("Invalid memory limit: " + ResourceLimits.MaxMemoryRequest);
            }

            [Fact]
            public void ShouldReturnTheCorrectValueWhenChanged()
            {
                var oldMemory = ResourceLimits.MaxMemoryRequest;
                var newMemory = (ulong)(ResourceLimits.MaxMemoryRequest * 0.9);

                ResourceLimits.MaxMemoryRequest = newMemory;
                Assert.Equal(newMemory, ResourceLimits.MaxMemoryRequest);
                ResourceLimits.MaxMemoryRequest = oldMemory;
            }
        }
    }
}

// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

using ImageMagick;
using Xunit;
using Xunit.Sdk;

namespace Magick.NET.Tests
{
    public partial class ResourceLimitsTests
    {
        [Collection(nameof(RunTestsSeparately))]
        public class TheMaxMemoryRequest
        {
            [Fact]
            public void ShouldHaveTheCorrectValue()
            {
                if (ResourceLimits.MaxMemoryRequest < 100000000U)
                    throw new XunitException("Invalid memory limit: " + ResourceLimits.MaxMemoryRequest);
            }

            [Fact]
            public void ShouldReturnTheCorrectValueWhenChanged()
            {
                var oldMemory = ResourceLimits.MaxMemoryRequest;
                var newMemory = (ulong)(ResourceLimits.MaxMemoryRequest * 0.8);

                ResourceLimits.MaxMemoryRequest = newMemory;
                Assert.Equal(newMemory, ResourceLimits.MaxMemoryRequest);
                ResourceLimits.MaxMemoryRequest = oldMemory;
            }
        }
    }
}

Use different percentage in the unit test.


using System.Collections.Generic;

namespace AttachToolbar
{
    internal static class State
    {
        public static string ProcessName = "";
        public static List<string> ProcessList = new List<string>();
        public static EngineType EngineType = EngineType.Native;
        public static bool IsAttached = false;

        public static void Clear()
        {
            ProcessList.Clear();
            EngineType = EngineType.Native;
            IsAttached = false;
            ProcessName = "";
        }
    }
}

using System.Collections.Generic;

namespace AttachToolbar
{
    internal static class State
    {
        public static int ProcessIndex = -1;
        public static List<string> ProcessList = new List<string>();
        public static EngineType EngineType = EngineType.Native;
        public static bool IsAttached = false;

        public static string ProcessName
        {
            get
            {
                string processName = ProcessIndex >= 0
                        ? ProcessList[ProcessIndex]
                        : "";
                return processName;
            }

            set
            {
                ProcessIndex = ProcessList.IndexOf(value);
            }
        }

        public static void Clear()
        {
            ProcessList.Clear();
            EngineType = EngineType.Native;
            IsAttached = false;
            ProcessIndex = -1;
        }
    }
}

Add process index to state as primary key. Use process name as property


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

namespace Bloom.Utils
{
	class MemoryUtils
	{
		/// <summary>
		/// A crude way of measuring when we might be short enough of memory to need a full reload.
		/// </summary>
		/// <returns></returns>
		public static bool SystemIsShortOfMemory()
		{
			// A rather arbitrary limit of 750M...a bit more than Bloom typically uses for a large book
			// before memory leaks start to mount up.
			return GetPrivateBytes() > 750000000;
		}

		/// <summary>
		/// Significance: This counter indicates the current number of bytes allocated to this process that cannot be shared with
		/// other processes. This counter has been useful for identifying memory leaks.
		/// </summary>
		/// <remarks>We've had other versions of this method which, confusingly, returned results in KB. This one actually answers bytes.</remarks>
		/// <returns></returns>
		public static long GetPrivateBytes()
		{
			using (var perfCounter = new PerformanceCounter("Process", "Private Bytes",
				Process.GetCurrentProcess().ProcessName))
			{
				return perfCounter.RawValue;
			}
		}
	}
}

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

namespace Bloom.Utils
{
	class MemoryUtils
	{
		/// <summary>
		/// A crude way of measuring when we might be short enough of memory to need a full reload.
		/// </summary>
		/// <returns></returns>
		public static bool SystemIsShortOfMemory()
		{
			// A rather arbitrary limit of 750M...a bit more than Bloom typically uses for a large book
			// before memory leaks start to mount up.  A larger value is wanted for 64-bit processes
			// since they can start out above the 750M level.
			var triggerLevel = Environment.Is64BitProcess ? 2000000000L : 750000000;
			return GetPrivateBytes() > triggerLevel;
		}

		/// <summary>
		/// Significance: This value indicates the current number of bytes allocated to this process that cannot be shared with
		/// other processes. This value has been useful for identifying memory leaks.
		/// </summary>
		/// <remarks>We've had other versions of this method which, confusingly, returned results in KB. This one actually answers bytes.</remarks>
		public static long GetPrivateBytes()
		{
			// Using a PerformanceCounter does not work on Linux and gains nothing on Windows.
			// After using the PerformanceCounter once on Windows, it always returns the same
			// value as getting it directly from the Process property.
			using (var process = Process.GetCurrentProcess())
			{
				return process.PrivateMemorySize64;
			}
		}
	}
}

Fix system memory check for Linux (20210323)


using System.Collections.Generic;
using Amazon.DynamoDBv2.Model;

namespace Narochno.Credstash.Internal
{
    public class CredstashItem
    {
        public const string DEFAULT_DIGEST = "SHA256";

        public string Name { get; set; }
        public string Version { get; set; }
        public string Contents { get; set; }
        public string Digest { get; set; }
        public string Hmac { get; set; }
        public string Key { get; set; }

        public static CredstashItem From(Dictionary<string, AttributeValue> item)
        {
            return new CredstashItem
            {
                Name = item["name"].S,
                Version = item["version"].S,
                Contents = item["contents"].S,
                Digest = item["digest"]?.S ?? DEFAULT_DIGEST,
                Hmac = item["hmac"].S,
                Key = item["key"].S,
            };
        }
    }
}

using System.Collections.Generic;
using Amazon.DynamoDBv2.Model;

namespace Narochno.Credstash.Internal
{
    public class CredstashItem
    {
        public const string DEFAULT_DIGEST = "SHA256";

        public string Name { get; set; }
        public string Version { get; set; }
        public string Contents { get; set; }
        public string Digest { get; set; }
        public string Hmac { get; set; }
        public string Key { get; set; }

        public static CredstashItem From(Dictionary<string, AttributeValue> item)
        {
            return new CredstashItem
            {
                Name = item["name"].S,
                Version = item["version"].S,
                Contents = item["contents"].S,
                Digest = (item.ContainsKey("digest") ? item["digest"]?.S : null) ?? DEFAULT_DIGEST,
                Hmac = item["hmac"].S,
                Key = item["key"].S,
            };
        }
    }
}

Update for Dict contains before null check


using System;
using System.Diagnostics;
using System.IO;

namespace PackageRunner
{
    /// <summary>
    /// </summary>
    internal class FileLogging
    {
        private readonly string _file;
        private static readonly object _lock = new object();

        public FileLogging(string file)
        {
            _file = file;
        }

        public void AddLine(string text)
        {
            lock (_lock)
            {
                File.AppendAllText(_file, DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " " + text);
                Debug.WriteLine(text);
            }
        }

        /// <summary>
        /// </summary>
        public void AddLine(string format, params object[] args)
        {
            var text = string.Format(format, args);
            this.AddLine(text);
        }
    }
}

using System;
using System.Diagnostics;
using System.IO;

namespace PackageRunner
{
    /// <summary>
    /// </summary>
    internal class FileLogging
    {
        private readonly string _file;
        private static readonly object _lock = new object();

        public FileLogging(string file)
        {
            _file = file;
        }

        public void AddLine(string text)
        {
            lock (_lock)
            {
                File.AppendAllText(_file, DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " " + text + Environment.NewLine);
                Debug.WriteLine(text);
            }
        }

        /// <summary>
        /// </summary>
        public void AddLine(string format, params object[] args)
        {
            var text = string.Format(format, args);
            this.AddLine(text);
        }
    }
}

Add new line for file logging

Add new line for file logging