using System;
using System.Net;
using CVaS.Shared.Exceptions;
using CVaS.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace CVaS.Web.Filters
{
    /// <summary>
    /// Exception filter that catch exception of known type
    /// and transform them into specific HTTP status code with
    /// error message
    /// </summary>
    public class HttpExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            switch (context.Exception)
            {
                case ApiException apiException:
                    var apiError = new ApiError(apiException.Message);
                    context.ExceptionHandled = true;
                    context.HttpContext.Response.StatusCode = apiException.StatusCode;
                    context.Result = new ObjectResult(apiError);
                    break;

                case NotImplementedException _:
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                    context.ExceptionHandled = true;
                    break;

                case UnauthorizedAccessException _:
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    context.ExceptionHandled = true;
                    break;
            }

            base.OnException(context);
        }
    }
}

using System;
using System.Net;
using CVaS.Shared.Exceptions;
using CVaS.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace CVaS.Web.Filters
{
    /// <summary>
    /// Exception filter that catch exception of known type
    /// and transform them into specific HTTP status code with
    /// error message
    /// </summary>
    public class HttpExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            switch (context.Exception)
            {
                case ApiException apiException:
                    var apiError = new ApiError(apiException.Message);
                    context.ExceptionHandled = true;
                    context.HttpContext.Response.StatusCode = apiException.StatusCode;
                    context.Result = new ObjectResult(apiError);
                    break;

                case NotImplementedException _:
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                    context.ExceptionHandled = true;
                    break;

                case UnauthorizedAccessException _:
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    context.ExceptionHandled = true;
                    break;
            }

            base.OnException(context);
        }
    }
}

Return 403 instead of 401

Return 403 instead of 401


using System.Configuration;
using System.IdentityModel.Tokens;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Web.Hosting;

namespace Dragon.SecurityServer.Common
{
    public class SecurityHelper
    {
        public static X509SigningCredentials CreateSignupCredentialsFromConfig()
        {
            return new X509SigningCredentials(new X509Certificate2(X509Certificate.CreateFromCertFile(
                    Path.Combine(HostingEnvironment.ApplicationPhysicalPath, ConfigurationManager.AppSettings["SigningCertificateName"]))));
        }
    }
}

using System.Configuration;
using System.IdentityModel.Tokens;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Web.Hosting;

namespace Dragon.SecurityServer.Common
{
    public class SecurityHelper
    {
        public static X509SigningCredentials CreateSignupCredentialsFromConfig()
        {
            var certificateFilePath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, ConfigurationManager.AppSettings["SigningCertificateName"]);
            var data = File.ReadAllBytes(certificateFilePath);
            var certificate = new X509Certificate2(data, string.Empty, X509KeyStorageFlags.MachineKeySet);
            return new X509SigningCredentials(certificate);
        }
    }
}

Allow reading certificates from local files


using compiler.middleend.ir;
using NUnit.Framework;

namespace NUnit.Tests.MiddleEnd
{
    [TestFixture]
    public class InstructionTests
    {
        [Test]
        public void ToStringTest()
        {
            var inst1 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 10),
                new Operand(Operand.OpType.Identifier, 10));

            var inst2 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 05),
                new Operand(inst1));

            Assert.AreEqual( inst2.Num.ToString() + " Add #5 (" + inst1.Num.ToString() + ")",inst2.ToString());

        }
    }
}

using compiler.middleend.ir;
using NUnit.Framework;

namespace NUnit.Tests.MiddleEnd
{
    [TestFixture]
    public class InstructionTests
    {
        [Test]
        public void ToStringTest()
        {
            var inst1 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 10),
                new Operand(Operand.OpType.Identifier, 10));

            var inst2 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 05),
                new Operand(inst1));

            Assert.AreEqual( inst2.Num.ToString() + ": Add #5 (" + inst1.Num.ToString() + ")",inst2.ToString());

        }
    }
}

Fix error in unit test from changing the ToString


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("Tomato")]
[assembly: AssemblyDescription("Pomodoro Timer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Software Punt")]
[assembly: AssemblyProduct("Tomato")]
[assembly: AssemblyCopyright("Copyright © Software Punt 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("e5f59157-7a01-4616-86e3-c9a924d8a218")]

// 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("Tomato")]
[assembly: AssemblyDescription("Pomodoro Timer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Software Punt")]
[assembly: AssemblyProduct("Tomato")]
[assembly: AssemblyCopyright("Copyright © Software Punt 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("e5f59157-7a01-4616-86e3-c9a924d8a218")]

// 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")]

Update copyright statement to 2014

Update copyright statement to 2014


using System.Reflection;

[assembly: AssemblyTitle("Autofac.Tests.Integration.Mef")]
[assembly: AssemblyDescription("")]

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


using System;
using EntityNetwork;
using EntityNetwork.Unity3D;
using UnityEngine;

public class ClientEntityFactory : IClientEntityFactory
{
    private static ClientEntityFactory _default;

    public static ClientEntityFactory Default
    {
        get { return _default ?? (_default = new ClientEntityFactory()); }
    }

    public Transform RootTransform { get; set; }

    IClientEntity IClientEntityFactory.Create(Type protoTypeType)
    {
        var resource = Resources.Load("Client" + protoTypeType.Name.Substring(1));
        var go = (GameObject)GameObject.Instantiate(resource);
        if (RootTransform != null)
            go.transform.SetParent(RootTransform, false);

        return go.GetComponent<IClientEntity>();
    }

    void IClientEntityFactory.Delete(IClientEntity entity)
    {
        var enb = ((EntityNetworkBehaviour)entity);
        GameObject.Destroy(enb.gameObject);
    }
}

using System;
using System.Collections.Concurrent;
using EntityNetwork;
using EntityNetwork.Unity3D;
using UnityEngine;

public class ClientEntityFactory : IClientEntityFactory
{
    private static ClientEntityFactory _default;

    public static ClientEntityFactory Default
    {
        get { return _default ?? (_default = new ClientEntityFactory()); }
    }

    public Transform RootTransform { get; set; }

    private readonly ConcurrentDictionary<Type, Type> _clientEntityToProtoTypeMap =
        new ConcurrentDictionary<Type, Type>();

    Type IClientEntityFactory.GetProtoType(Type entityType)
    {
        return _clientEntityToProtoTypeMap.GetOrAdd(entityType, t =>
        {
            var type = entityType;
            while (type != null && type != typeof(object))
            {
                if (type.Name.EndsWith("ClientBase"))
                {
                    var typePrefix = type.Namespace.Length > 0 ? type.Namespace + "." : "";
                    var protoType = type.Assembly.GetType(typePrefix + "I" +
                                                          type.Name.Substring(0, type.Name.Length - 10));
                    if (protoType != null && typeof(IEntityPrototype).IsAssignableFrom(protoType))
                    {
                        return protoType;
                    }
                }
                type = type.BaseType;
            }
            return null;
        });
    }

    IClientEntity IClientEntityFactory.Create(Type protoType)
    {
        var resourceName = "Client" + protoType.Name.Substring(1);
        var resource = Resources.Load(resourceName);
        if (resource == null)
            throw new InvalidOperationException("Failed to load resource(" + resourceName + ")");

        var go = (GameObject)GameObject.Instantiate(resource);
        if (go == null)
            throw new InvalidOperationException("Failed to instantiate resource(" + resourceName + ")");

        if (RootTransform != null)
            go.transform.SetParent(RootTransform, false);

        return go.GetComponent<IClientEntity>();
    }

    void IClientEntityFactory.Delete(IClientEntity entity)
    {
        var enb = ((EntityNetworkBehaviour)entity);
        GameObject.Destroy(enb.gameObject);
    }
}

Fix a build error of UnityPackage

Fix a build error of UnityPackage


namespace Moq
{
    using System;
    using System.CodeDom.Compiler;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using Moq.Sdk;

    /// <summary>
    /// Instantiates mocks for the specified types.
    /// </summary>
    [GeneratedCode("Moq", "5.0")]
    [CompilerGenerated]
    partial class Mock
    {
        /// <summary>
        /// Creates the mock instance by using the specified types to
        /// lookup the mock type in the assembly defining this class.
        /// </summary>
        private static T Create<T>(MockBehavior behavior, object[] constructorArgs, params Type[] interfaces)
        {
            var mocked = (IMocked)MockFactory.Default.CreateMock(typeof(Mock).GetTypeInfo().Assembly, typeof(T), interfaces, constructorArgs);

            mocked.Initialize(behavior);

            return (T)mocked;
        }
   }
}

using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Runtime.CompilerServices;
using Moq.Sdk;

namespace Moq
{
    /// <summary>
    /// Instantiates mocks for the specified types.
    /// </summary>
    [GeneratedCode("Moq", "5.0")]
    [CompilerGenerated]
    partial class Mock
    {
        /// <summary>
        /// Creates the mock instance by using the specified types to
        /// lookup the mock type in the assembly defining this class.
        /// </summary>
        private static T Create<T>(MockBehavior behavior, object[] constructorArgs, params Type[] interfaces)
        {
            var mocked = (IMocked)MockFactory.Default.CreateMock(typeof(Mock).GetTypeInfo().Assembly, typeof(T), interfaces, constructorArgs);

            mocked.Initialize(behavior);

            return (T)mocked;
        }
   }
}

Unify namespace placement with the .Overloads partial class


using System;
using System.Linq;

namespace Smartrak.Collections.Paging
{
	public static class PagingHelpers
	{
		/// <summary>
		/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
		/// </summary>
		/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
		/// <param name="entities">A queryable of entities</param>
		/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
		/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
		/// <returns>A queryable of the page of entities with counts appended.</returns>
		public static IQueryable<EntityWithCount<T>> GetPageWithTotal<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
		{
			if (entities == null)
			{
				throw new ArgumentNullException("entities");
			}
			if (page < 1)
			{
				throw new ArgumentException("Must be positive", "page");
			}
			if (pageSize < 1)
			{
				throw new ArgumentException("Must be positive", "pageSize");
			}

			return entities
				.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
				.Skip(page - 1 * pageSize)
				.Take(pageSize);
		}
	}
}

using System;
using System.Linq;

namespace Smartrak.Collections.Paging
{
	public static class PagingHelpers
	{
		/// <summary>
		/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
		/// </summary>
		/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
		/// <param name="entities">A queryable of entities</param>
		/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
		/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
		/// <returns>A queryable of the page of entities with counts appended.</returns>
		public static IQueryable<EntityWithCount<T>> GetPageWithTotalzzz<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
		{
			if (entities == null)
			{
				throw new ArgumentNullException("entities");
			}
			if (page < 1)
			{
				throw new ArgumentException("Must be positive", "page");
			}
			if (pageSize < 1)
			{
				throw new ArgumentException("Must be positive", "pageSize");
			}

			return entities
				.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
				.Skip(page - 1 * pageSize)
				.Take(pageSize);
		}
	}
}

Revert "Removing 'zzz' from method name"

This reverts commit 05e1115699ce4f4550dd112b06bb8ba107daacd0.


// 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.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using osu.Framework.Allocation;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Ladder.Components;

namespace osu.Game.Tournament.Tests
{
    public class TestCaseLadderManager : OsuTestCase
    {
        [Cached]
        private readonly LadderManager manager;

        public TestCaseLadderManager()
        {
            var teams = JsonConvert.DeserializeObject<List<TournamentTeam>>(File.ReadAllText(@"teams.json"));
            var ladder = JsonConvert.DeserializeObject<LadderInfo>(File.ReadAllText(@"bracket.json")) ?? new LadderInfo();

            Child = manager = new LadderManager(ladder, teams);
        }

        protected override void Dispose(bool isDisposing)
        {
            base.Dispose(isDisposing);

            File.WriteAllText(@"bracket.json", JsonConvert.SerializeObject(manager.Info));
        }
    }
}

// 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.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using osu.Framework.Allocation;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Ladder.Components;

namespace osu.Game.Tournament.Tests
{
    public class TestCaseLadderManager : OsuTestCase
    {
        [Cached]
        private readonly LadderManager manager;

        public TestCaseLadderManager()
        {
            var teams = JsonConvert.DeserializeObject<List<TournamentTeam>>(File.ReadAllText(@"teams.json"));
            var ladder = File.Exists(@"bracket.json") ? JsonConvert.DeserializeObject<LadderInfo>(File.ReadAllText(@"bracket.json")) : new LadderInfo();

            Child = manager = new LadderManager(ladder, teams);
        }

        protected override void Dispose(bool isDisposing)
        {
            base.Dispose(isDisposing);

            File.WriteAllText(@"bracket.json", JsonConvert.SerializeObject(manager.Info,
                new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    DefaultValueHandling = DefaultValueHandling.Ignore
                }));
        }
    }
}

Reduce noise in json output and handle the case the file doesn't exist


using MoviesSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfMovieSystem.Views
{
    /// <summary>
    /// Interaction logic for InsertWindowView.xaml
    /// </summary>
    public partial class InsertWindowView : Window
    {
        public InsertWindowView()
        {
            InitializeComponent();
        }

        private void CreateButton_Click(object sender, RoutedEventArgs e)
        {
            using (MoviesSystemDbContext context = new MoviesSystemDbContext())
            {
                var firstName = FirstNameTextBox.Text;
                var lastName = LastNameTextBox.Text;
                var movies = MoviesTextBox.Text.Split(',');

                var newActor = new Actor
                {
                    FirstName = firstName,
                    LastName = lastName,
                    Movies = new List<Movie>()
                };
                foreach (var movie in movies)
                {
                    newActor.Movies.Add(new Movie { Title = movie });
                }

                context.Actors.Add(newActor);
                context.SaveChanges();
            }
            FirstNameTextBox.Text = "";
            LastNameTextBox.Text = "";
            MoviesTextBox.Text = "";
        }
    }
}

using MoviesSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfMovieSystem.Views
{
    /// <summary>
    /// Interaction logic for InsertWindowView.xaml
    /// </summary>
    public partial class InsertWindowView : Window
    {
        public InsertWindowView()
        {
            InitializeComponent();
        }

        private void CreateButton_Click(object sender, RoutedEventArgs e)
        {
            using (MoviesSystemDbContext context = new MoviesSystemDbContext())
            {
                var firstName = FirstNameTextBox.Text;
                var lastName = LastNameTextBox.Text;
                var movies = MoviesTextBox.Text.Split(',');

                var newActor = new Actor
                {
                    FirstName = firstName,
                    LastName = lastName,
                    Movies = new List<Movie>()
                };
                foreach (var movie in movies)
                {
                    newActor.Movies.Add(LoadOrCreateMovie(context, movie));
                }

                context.Actors.Add(newActor);
                context.SaveChanges();
            }
            FirstNameTextBox.Text = "";
            LastNameTextBox.Text = "";
            MoviesTextBox.Text = "";
        }

        private static Movie LoadOrCreateMovie(MoviesSystemDbContext context, string movieTitle)
        {
            var movie = context.Movies
                            .FirstOrDefault(m => m.Title.ToLower() == movieTitle.ToLower());

            if (movie == null)
            {
                movie = new Movie
                {
                    Title = movieTitle
                };
            }

            return movie;
        }
    }
}

Add restrictions when creating the movie collection


namespace TraktApiSharp.Objects.Get.Shows
{
    using Basic;

    public class TraktShowIds : TraktIds
    {

    }
}

namespace TraktApiSharp.Objects.Get.Shows
{
    using Basic;

    /// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt show.</summary>
    public class TraktShowIds : TraktIds
    {

    }
}

Add documentation for show ids.

Add documentation for show ids.


using System;
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace DiplomContentSystem.Requests
{
    public class RequestService
    {
        public async Task<Stream> SendRequest(object data)
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var content = new StringContent(JsonConvert.SerializeObject(data)
                    );
                    client.BaseAddress = new Uri("http://localhost:1337");

                    var response = await client.PostAsync("api/docx", content);
                    response.EnsureSuccessStatusCode(); // Throw in not success

                    return await response.Content.ReadAsStreamAsync();
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine($"Request exception: {e.Message}");
                    throw (e);
                }
            }
        }
    }
}

using System;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace DiplomContentSystem.Requests
{
    public class RequestService
    {
        public async Task<Stream> SendRequest(object data)
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var content = new StringContent(JsonConvert.SerializeObject(data,
                    new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    }), System.Text.Encoding.UTF8, "application/json");
                    client.BaseAddress = new Uri("http://localhost:1337");

                    var response = await client.PostAsync("api/docx",content);
                    response.EnsureSuccessStatusCode(); // Throw in not success

                    return await response.Content.ReadAsStreamAsync();
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine($"Request exception: {e.Message}");
                    throw (e);
                }
            }
        }
    }
}

DCS-30: Update json.net to use new MIME, encoding and camelCase formatting


using System.Collections.Generic;

namespace Dapper.FluentMap.Utils
{
    internal static class DictionaryExtensions
    {
        internal static void AddOrUpdate<TKey, TValue>(this IDictionary<TKey, IList<TValue>> dict, TKey key, TValue value)
        {
            if (dict.ContainsKey(key))
            {
                dict[key].Add(value);
            }
            else
            {
                dict.Add(key, new[] { value });
            }
        }
    }
}

using System.Collections.Generic;

namespace Dapper.FluentMap.Utils
{
    internal static class DictionaryExtensions
    {
        internal static void AddOrUpdate<TKey, TValue>(this IDictionary<TKey, IList<TValue>> dict, TKey key, TValue value)
        {
            if (dict.ContainsKey(key))
            {
                dict[key].Add(value);
            }
            else
            {
                dict.Add(key, new List<TValue> { value });
            }
        }
    }
}

Use a list rather than a fixed-size array.


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

namespace Edulinq
{
    public static partial class Enumerable
    {
        public static IEnumerable<TResult> Repeat<TResult>(this TResult element, int count)
        {
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count");
            }
            return RepeatImpl(element, count);
        }

        public static IEnumerable<TResult> RepeatImpl<TResult>(TResult element, int count)
        {
            for (int i = 0; i < count; i++)
            {
                yield return element;
            }
        }
    }
}

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

namespace Edulinq
{
    public static partial class Enumerable
    {
        public static IEnumerable<TResult> Repeat<TResult>(this TResult element, int count)
        {
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count");
            }
            return RepeatImpl(element, count);
        }

        private static IEnumerable<TResult> RepeatImpl<TResult>(TResult element, int count)
        {
            for (int i = 0; i < count; i++)
            {
                yield return element;
            }
        }
    }
}

Make the implementation method private.

Make the implementation method private.


using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mycroft;
using System.IO;
using System.Diagnostics;

namespace Mycroft.Tests
{
    [TestClass]
    public class TestCommandConnection
    {
        [TestMethod]
        public async Task TestBodylessMessage(){
            var s = new MemoryStream(Encoding.UTF8.GetBytes("6\nAPP_UP"));
            var cmd = new CommandConnection(s);
            var msg = await cmd.getCommandAsync();
            Trace.WriteLine(msg);
            if (msg != "APP_UP")
                throw new Exception("Incorrect message!");
        }

        [TestMethod]
        public async Task TestBodaciousMessage()
        {
            var input = "30\nMSG_BROADCAST {\"key\": \"value\"}";
            var s = new MemoryStream(Encoding.UTF8.GetBytes(input));
            var cmd = new CommandConnection(s);
            var msg = await cmd.getCommandAsync();
            Trace.WriteLine(msg);
            Trace.WriteLine(input.Substring(3));
            if (msg != input.Substring(3))
                throw new Exception("Incorrect message!");
        }

    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mycroft;
using System.IO;
using System.Diagnostics;

namespace Mycroft.Tests
{
    [TestClass]
    public class TestCommandConnection
    {
        [TestMethod]
        public async Task TestBodylessMessage(){
            var s = new MemoryStream(Encoding.UTF8.GetBytes("6\nAPP_UP"));
            var cmd = new CommandConnection(s);
            var msg = await cmd.GetCommandAsync();
            Trace.WriteLine(msg);
            if (msg != "APP_UP")
                throw new Exception("Incorrect message!");
        }

        [TestMethod]
        public async Task TestBodaciousMessage()
        {
            var input = "30\nMSG_BROADCAST {\"key\": \"value\"}";
            var s = new MemoryStream(Encoding.UTF8.GetBytes(input));
            var cmd = new CommandConnection(s);
            var msg = await cmd.GetCommandAsync();
            Trace.WriteLine(msg);
            Trace.WriteLine(input.Substring(3));
            if (msg != input.Substring(3))
                throw new Exception("Incorrect message!");
        }

    }
}

Fix CommandConnection methods in Test

Fix CommandConnection methods in Test


using System;
using Newtonsoft.Json;

namespace Archetype.Models
{
    public class ArchetypePreValueProperty
    {
        [JsonProperty("alias")]
        public string Alias { get; set; }

        [JsonProperty("remove")]
        public bool Remove { get; set; }

        [JsonProperty("collapse")]
        public bool Collapse { get; set; }

        [JsonProperty("label")]
        public string Label { get; set; }

        [JsonProperty("helpText")]
        public string HelpText { get; set; }

        [JsonProperty("dataTypeGuid")]
        public Guid DataTypeGuid { get; set; }

        [JsonProperty("propertyEditorAlias")]
        public string PropertyEditorAlias { get; set; }

        [JsonProperty("value")]
        public string Value { get; set; }

        [JsonProperty("required")]
        public bool Required { get; set; }

        [JsonProperty("regEx")]
        public bool RegEx { get; set; }
    }
}

using System;
using Newtonsoft.Json;

namespace Archetype.Models
{
    public class ArchetypePreValueProperty
    {
        [JsonProperty("alias")]
        public string Alias { get; set; }

        [JsonProperty("remove")]
        public bool Remove { get; set; }

        [JsonProperty("collapse")]
        public bool Collapse { get; set; }

        [JsonProperty("label")]
        public string Label { get; set; }

        [JsonProperty("helpText")]
        public string HelpText { get; set; }

        [JsonProperty("dataTypeGuid")]
        public Guid DataTypeGuid { get; set; }

        [JsonProperty("propertyEditorAlias")]
        public string PropertyEditorAlias { get; set; }

        [JsonProperty("value")]
        public string Value { get; set; }

        [JsonProperty("required")]
        public bool Required { get; set; }

        [JsonProperty("regEx")]
        public string RegEx { get; set; }
    }
}

Fix deserialization of RegEx enabled properties

Fix type mismatch for RegEx (introduced in 6e50301 - my bad, sorry)


namespace FunctionalTestUtils
{
    using System;
    using System.Collections.Generic;
    using Microsoft.ApplicationInsights.Channel;

    public class BackTelemetryChannel : ITelemetryChannel
    {
        private IList<ITelemetry> buffer;

        public BackTelemetryChannel()
        {
            this.buffer = new List<ITelemetry>();
        }

        public IList<ITelemetry> Buffer
        {
            get
            {
                return this.buffer;
            }
        }

        public bool? DeveloperMode
        {
            get
            {
                return true;
            }
            set
            {
            }
        }

        public string EndpointAddress
        {
            get
            {
                return "https://dc.services.visualstudio.com/v2/track";
            }

            set
            {
            }
        }

        public void Dispose()
        {
        }

        public void Flush()
        {
            throw new NotImplementedException();
        }

        public void Send(ITelemetry item)
        {
            this.buffer.Add(item);
        }
    }
}

namespace FunctionalTestUtils
{
    using System;
    using System.Collections.Generic;
    using Microsoft.ApplicationInsights.Channel;

    public class BackTelemetryChannel : ITelemetryChannel
    {
        private IList<ITelemetry> buffer;

        public BackTelemetryChannel()
        {
            this.buffer = new List<ITelemetry>();
        }

        public IList<ITelemetry> Buffer
        {
            get
            {
                return this.buffer;
            }
        }

        public bool? DeveloperMode
        {
            get
            {
                return true;
            }
            set
            {
            }
        }

        public string EndpointAddress
        {
            get
            {
                return "https://dc.services.visualstudio.com/v2/track";
            }

            set
            {
            }
        }

        public void Dispose()
        {
        }

        public void Flush()
        {
        }

        public void Send(ITelemetry item)
        {
            this.buffer.Add(item);
        }
    }
}

Add flush for mock channel

Add flush for mock channel


using System.Reflection;

[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © 2011 Andrew Davey")]

// NOTE: When changing this version, also update Cassette.MSBuild\Cassette.targets to match.
[assembly: AssemblyInformationalVersion("2.0.0")]

[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyFileVersion("2.0.0.0")]

using System.Reflection;

[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © 2011 Andrew Davey")]

[assembly: AssemblyInformationalVersion("2.0.0-beta1")]

[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyFileVersion("2.0.0.0")]

Set nuget package version to 2.0.0-beta1


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

namespace DotVVM.Framework.Diagnostics
{

    public class DotvvmDiagnosticsConfiguration
    {
        public DotvvmDiagnosticsConfiguration()
        {
            LoadConfiguration();
        }

        private DiagnosticsServerConfiguration configuration;

        public string DiagnosticsServerHostname
        {
            get
            {
                if (configuration == null)
                    LoadConfiguration();
                return configuration.HostName;
            }
        }

        public int? DiagnosticsServerPort
        {
            get
            {
                if (configuration == null)
                    LoadConfiguration();
                return configuration?.Port;
            }
        }

        private void LoadConfiguration()
        {
            try
            {
                var diagnosticsJson = File.ReadAllText(DiagnosticsServerConfiguration.DiagnosticsFilePath);
                configuration = JsonConvert.DeserializeObject<DiagnosticsServerConfiguration>(diagnosticsJson);
            }
            catch
            {
                // ignored
            }
        }
    }
}

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

namespace DotVVM.Framework.Diagnostics
{

    public class DotvvmDiagnosticsConfiguration
    {
        public DotvvmDiagnosticsConfiguration()
        {
            LoadConfiguration();
        }

        private DiagnosticsServerConfiguration configuration;

        public string DiagnosticsServerHostname => configuration.HostName;

        public int? DiagnosticsServerPort => configuration?.Port;

        private void LoadConfiguration()
        {
            try
            {
                var diagnosticsJson = File.ReadAllText(DiagnosticsServerConfiguration.DiagnosticsFilePath);
                configuration = JsonConvert.DeserializeObject<DiagnosticsServerConfiguration>(diagnosticsJson);
            }
            catch
            {
                // ignored
            }
        }
    }
}

Remove redundant configuration loading of diagnostics configuration


using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using OmniSharp.Models;

namespace OmniSharp.Helpers
{
    public static class LocationExtensions
    {
        public static QuickFix GetQuickFix(this Location location, OmniSharpWorkspace workspace)
        {
            if (!location.IsInSource)
                throw new Exception("Location is not in the source tree");

            var lineSpan = location.GetMappedLineSpan();
            var path = lineSpan.Path;
            var documents = workspace.GetDocuments(path);

            var line = lineSpan.StartLinePosition.Line;
            var text = location.SourceTree.GetText().Lines[line].ToString();

            return new QuickFix
            {
                Text = text.Trim(),
                FileName = path,
                Line = line,
                Column = lineSpan.HasMappedPath ? 0 : lineSpan.StartLinePosition.Character, // when a #line directive maps into a separate file, assume columns (0,0)
                EndLine = lineSpan.EndLinePosition.Line,
                EndColumn = lineSpan.HasMappedPath ? 0 : lineSpan.EndLinePosition.Character,
                Projects = documents.Select(document => document.Project.Name).ToArray()
            };
        }
    }
}

using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using OmniSharp.Models;

namespace OmniSharp.Helpers
{
    public static class LocationExtensions
    {
        public static QuickFix GetQuickFix(this Location location, OmniSharpWorkspace workspace)
        {
            if (!location.IsInSource)
                throw new Exception("Location is not in the source tree");

            var lineSpan = Path.GetExtension(location.SourceTree.FilePath).Equals(".cake", StringComparison.OrdinalIgnoreCase)
                ? location.GetLineSpan()
                : location.GetMappedLineSpan();
            var path = lineSpan.Path;
            var documents = workspace.GetDocuments(path);

            var line = lineSpan.StartLinePosition.Line;
            var text = location.SourceTree.GetText().Lines[line].ToString();

            return new QuickFix
            {
                Text = text.Trim(),
                FileName = path,
                Line = line,
                Column = lineSpan.HasMappedPath ? 0 : lineSpan.StartLinePosition.Character, // when a #line directive maps into a separate file, assume columns (0,0)
                EndLine = lineSpan.EndLinePosition.Line,
                EndColumn = lineSpan.HasMappedPath ? 0 : lineSpan.EndLinePosition.Character,
                Projects = documents.Select(document => document.Project.Name).ToArray()
            };
        }
    }
}

Exclude Cake files from line span mapping


using System.Linq;
using Microsoft.Extensions.Configuration;
using Slp.Evi.Storage.Database;
using Slp.Evi.Storage.Database.Vendor.MsSql;
using Xunit;

namespace Slp.Evi.Test.System.Sparql.Vendor
{
    public sealed class MsSqlSparqlFixture
        : SparqlFixture
    {
        public MsSqlSparqlFixture()
        {
            // Prepare all databases beforehand
            var bootUp = SparqlTestSuite.TestData.Select(x => x[0]).Cast<string>().Distinct()
                .Select(x => base.GetStorage(x));
        }

        protected override ISqlDatabase GetSqlDb()
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile("database.json")
                .AddEnvironmentVariables();

            var config = builder.Build();
            var connectionString = config.GetConnectionString("mssql");

            return (new MsSqlDbFactory()).CreateSqlDb(connectionString, 30);
        }
    }

    public class MsSqlSparqlTestSuite
        : SparqlTestSuite, IClassFixture<MsSqlSparqlFixture>
    {
        public MsSqlSparqlTestSuite(MsSqlSparqlFixture fixture)
            : base(fixture)
        {
        }
    }
}

using System.Linq;
using Microsoft.Extensions.Configuration;
using Slp.Evi.Storage.Database;
using Slp.Evi.Storage.Database.Vendor.MsSql;
using Xunit;

namespace Slp.Evi.Test.System.Sparql.Vendor
{
    public sealed class MsSqlSparqlFixture
        : SparqlFixture
    {
        public MsSqlSparqlFixture()
        {
            // Prepare all databases beforehand
            var datasetsToBootup = SparqlTestSuite.TestData.Select(x => x[0]).Cast<string>().Distinct();
            foreach (var dataset in datasetsToBootup)
            {
                GetStorage(dataset);
            }
        }

        protected override ISqlDatabase GetSqlDb()
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile("database.json")
                .AddEnvironmentVariables();

            var config = builder.Build();
            var connectionString = config.GetConnectionString("mssql");

            return (new MsSqlDbFactory()).CreateSqlDb(connectionString, 30);
        }
    }

    public class MsSqlSparqlTestSuite
        : SparqlTestSuite, IClassFixture<MsSqlSparqlFixture>
    {
        public MsSqlSparqlTestSuite(MsSqlSparqlFixture fixture)
            : base(fixture)
        {
        }
    }
}

Improve way how fixture is bootup.

Improve way how fixture is bootup.


using System;
using UnityEngine;

namespace Alensia.Core.UI.Legacy
{
    [Serializable]
    public class CursorDefinition
    {
        public bool Visible;

        public CursorLockMode LockMode;

        public Vector2 Hotspot;

        public Texture2D Image;

        public void Apply()
        {
            Cursor.visible = Visible;
            Cursor.lockState = LockMode;

            Cursor.SetCursor(Image, Hotspot, CursorMode.Auto);
        }

        public static CursorDefinition Hidden = new CursorDefinition
        {
            Visible = false,
            LockMode = CursorLockMode.Locked
        };

        public static CursorDefinition Default = new CursorDefinition
        {
            Visible = true,
            LockMode = CursorLockMode.None
        };
    }
}

using System;
using UnityEngine;

namespace Alensia.Core.UI.Legacy
{
    [Serializable]
    public class CursorDefinition
    {
        public bool Visible;

        public CursorLockMode LockMode;

        public Vector2 Hotspot;

        public Texture2D Image;

        public void Apply()
        {
            UnityEngine.Cursor.visible = Visible;
            UnityEngine.Cursor.lockState = LockMode;

            UnityEngine.Cursor.SetCursor(Image, Hotspot, CursorMode.Auto);
        }

        public static CursorDefinition Hidden = new CursorDefinition
        {
            Visible = false,
            LockMode = CursorLockMode.Locked
        };

        public static CursorDefinition Default = new CursorDefinition
        {
            Visible = true,
            LockMode = CursorLockMode.None
        };
    }
}

Fix compile error with namespace conflict


using AsmResolver.PE.Debug.CodeView;

namespace AsmResolver.PE.Debug
{
    /// <summary>
    /// Provides a default implementation of the <see cref="IDebugDataReader"/> interface.
    /// </summary>
    public class DefaultDebugDataReader : IDebugDataReader
    {
        /// <inheritdoc />
        public IDebugDataSegment ReadDebugData(PEReaderContext context, DebugDataType type,
            IBinaryStreamReader reader)
        {
            if (type == DebugDataType.CodeView)
                return CodeViewDataSegment.FromReader(reader);

            return new CustomDebugDataSegment(type, DataSegment.FromReader(reader));
        }
    }
}

using AsmResolver.PE.Debug.CodeView;

namespace AsmResolver.PE.Debug
{
    /// <summary>
    /// Provides a default implementation of the <see cref="IDebugDataReader"/> interface.
    /// </summary>
    public class DefaultDebugDataReader : IDebugDataReader
    {
        /// <inheritdoc />
        public IDebugDataSegment ReadDebugData(PEReaderContext context, DebugDataType type,
            IBinaryStreamReader reader)
        {
            return type switch
            {
                DebugDataType.CodeView => CodeViewDataSegment.FromReader(reader, context),
                _ => new CustomDebugDataSegment(type, DataSegment.FromReader(reader))
            };
        }
    }
}

Change if to switch expression

Change if to switch expression


using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace SimpSim.NET
{
    public class StateSaver
    {
        public virtual void SaveMemory(Memory memory, FileInfo file)
        {
            Save(memory, file);
        }

        public virtual Memory LoadMemory(FileInfo file)
        {
            return Load<Memory>(file);
        }

        public virtual void SaveRegisters(Registers registers, FileInfo file)
        {
            Save(registers, file);
        }

        public virtual Registers LoadRegisters(FileInfo file)
        {
            return Load<Registers>(file);
        }

        public virtual void SaveMachine(Machine machine, FileInfo file)
        {
            Save(machine, file);
        }

        public virtual Machine LoadMachine(FileInfo file)
        {
            return Load<Machine>(file);
        }

        private void Save(object @object, FileInfo file)
        {
            using (var fileStream = file.Create())
                new BinaryFormatter().Serialize(fileStream, @object);
        }

        private T Load<T>(FileInfo file)
        {
            using (var fileStream = file.OpenRead())
                return (T)new BinaryFormatter().Deserialize(fileStream);
        }
    }
}

using System.IO;
using System.Text.Json;

namespace SimpSim.NET
{
    public class StateSaver
    {
        public virtual void SaveMemory(Memory memory, FileInfo file)
        {
            Save(memory, file);
        }

        public virtual Memory LoadMemory(FileInfo file)
        {
            return Load<Memory>(file);
        }

        public virtual void SaveRegisters(Registers registers, FileInfo file)
        {
            Save(registers, file);
        }

        public virtual Registers LoadRegisters(FileInfo file)
        {
            return Load<Registers>(file);
        }

        public virtual void SaveMachine(Machine machine, FileInfo file)
        {
            Save(machine, file);
        }

        public virtual Machine LoadMachine(FileInfo file)
        {
            return Load<Machine>(file);
        }

        private void Save(object @object, FileInfo file)
        {
            using (var streamWriter = file.CreateText())
                streamWriter.Write(JsonSerializer.Serialize(@object));
        }

        private T Load<T>(FileInfo file)
        {
            using (var streamReader = file.OpenText())
                return JsonSerializer.Deserialize<T>(streamReader.ReadToEnd());
        }
    }
}

Replace BinaryFormatter with JsonSerializer due to the former being obsoleted. Tests still fail.


using UnityEngine;
using System.Collections;

public class DeskLampPuzzle : Puzzle
{
	private bool isLampOn = false;
	private bool hasLampBeenTurnedOn = false;
	private InteractableSwitch lampSwitch;

	// Use this for initialization
	public override void Start ()
	{
		base.Start();
		lampSwitch = GetComponent<InteractableSwitch>();
	}

	// Update is called once per frame
	void Update () {
		if (isLampOn != lampSwitch.turnedOn) {
			isLampOn = lampSwitch.turnedOn;
			hasLampBeenTurnedOn = true;
			base.CompletePuzzle();
		}
	}

}

using UnityEngine;
using System.Collections;

public class DeskLampPuzzle : Puzzle
{
	private bool isLampOn = false;
	private bool hasLampBeenTurnedOn = false;
	private InteractableSwitch lampSwitch;

	// Use this for initialization
	public override void Start ()
	{
		base.Start();
		lampSwitch = GetComponent<InteractableSwitch>();
	}

	// Update is called once per frame
	void Update () {
		if (isLampOn != lampSwitch.turnedOn) {
			isLampOn = lampSwitch.turnedOn;

			if (!hasLampBeenTurnedOn) {
				base.CompletePuzzle();
			}
			hasLampBeenTurnedOn = true;
		}
	}

}

Check that the puzzle has not already been solved.


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

namespace EloWeb.Models
{
    public class Games
    {
        public enum GamesSortOrder
        {
            MostRecentFirst = 1,
            MostRecentLast = 2
        }

        private static List<Game> _games = new List<Game>();

        public static void Initialise(IEnumerable<Game> gameEntities)
        {
            _games = gameEntities.ToList();

            foreach(var game in _games)
                Players.UpdateRatings(game);
        }

        public static void Add(Game game)
        {
            _games.Add(game);
        }

        public static IEnumerable<Game> All()
        {
            return _games.AsEnumerable();
        }

        public static IEnumerable<Game> MostRecent(int howMany, GamesSortOrder sortOrder)
        {
            var games = _games.AsEnumerable()
                .OrderBy(g => g.WhenPlayed)
                .Reverse()
                .Take(howMany);

            if (sortOrder == GamesSortOrder.MostRecentLast)
                return games.Reverse();

            return games;
        }

        public static IEnumerable<Game> GamesByPlayer(string name)
        {
            return _games.Where(game => game.Winner == name || game.Loser == name);
        }
    }
}

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

namespace EloWeb.Models
{
    public class Games
    {
        public enum GamesSortOrder
        {
            MostRecentFirst = 1,
            MostRecentLast = 2
        }

        private static List<Game> _games = new List<Game>();

        public static void Initialise(IEnumerable<Game> gameEntities)
        {
            _games = gameEntities
                        .OrderBy(g => g.WhenPlayed)
                        .ToList();

            foreach(var game in _games)
                Players.UpdateRatings(game);
        }

        public static void Add(Game game)
        {
            _games.Add(game);
        }

        public static IEnumerable<Game> All()
        {
            return _games.AsEnumerable();
        }

        public static IEnumerable<Game> MostRecent(int howMany, GamesSortOrder sortOrder)
        {
            var games = _games.AsEnumerable()
                .OrderBy(g => g.WhenPlayed)
                .Reverse()
                .Take(howMany);

            if (sortOrder == GamesSortOrder.MostRecentLast)
                return games.Reverse();

            return games;
        }

        public static IEnumerable<Game> GamesByPlayer(string name)
        {
            return _games.Where(game => game.Winner == name || game.Loser == name);
        }
    }
}

Fix order of games when calculating ratings


@using System.Globalization
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Localization
@using Microsoft.Extensions.Options

@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var cultureItems = new SelectList(LocOptions.Value.SupportedUICultures, nameof(CultureInfo.Name), nameof(CultureInfo.DisplayName));
}

<div>
    <form id="selectLanguage" asp-area="" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path" method="post" class="form-horizontal" role="form">
        @Localizer["Language:"]
        <select name="culture" asp-for="@Context.GetCurrentCulture()" asp-items="cultureItems"></select>
        <button>OK</button>
    </form>
</div>

@using System.Globalization
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Localization
@using Microsoft.Extensions.Options

@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var cultureItems = new SelectList(LocOptions.Value.SupportedUICultures, nameof(CultureInfo.Name), nameof(CultureInfo.DisplayName));
    var currentCulture = Context.GetCurrentCulture();
}

<div>
    <form id="selectLanguage" asp-area="" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path" method="post" class="form-horizontal" role="form">
        @Localizer["Language:"]
        <select name="culture" asp-for="@currentCulture" asp-items="cultureItems"></select>
        <button>OK</button>
    </form>
</div>

Fix issue with tagHelper that requries field or property to target for


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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Security")]
[assembly: AssemblyTrademark("")]

// 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("ea66be4b-3391-49c4-96e8-b1b9044397b9")]

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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Credentials")]
[assembly: AssemblyTrademark("")]

// 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("ea66be4b-3391-49c4-96e8-b1b9044397b9")]

Correct AssemblyProduct name from Security to Credentials


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("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[assembly: AssemblyCopyright("Copyright © Xamarin Inc. 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("9453e5ef-4541-4491-941f-d20f4e39c967")]

// 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("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[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("9453e5ef-4541-4491-941f-d20f4e39c967")]

// 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")]

Drop the Xamarin copyright after the CLA has been signed to contribute this back to Microsoft


using Arkivverket.Arkade.Core.Base.Addml.Processes;
using Arkivverket.Arkade.Core.Resources;
using Arkivverket.Arkade.Core.Util;

namespace Arkivverket.Arkade.Core.Base
{
    public static class ArkadeTestNameProvider
    {
        public static string GetDisplayName(IArkadeTest arkadeTest)
        {
            TestId testId = arkadeTest.GetId();

            string testName = GetTestName(testId);

            string displayName = testName != null
                ? string.Format(ArkadeTestDisplayNames.DisplayNameFormat, testId, testName)
                : GetFallBackDisplayName(arkadeTest);

            return displayName;
        }

        private static string GetTestName(TestId testId)
        {
            string resourceDisplayNameKey = testId.ToString().Replace('.', '_');

            if (testId.Version.Equals("5.5"))
                resourceDisplayNameKey = $"{resourceDisplayNameKey}v5_5";

            return ArkadeTestDisplayNames.ResourceManager.GetString(resourceDisplayNameKey);
        }

        private static string GetFallBackDisplayName(IArkadeTest arkadeTest)
        {
            try
            {
                return ((AddmlProcess) arkadeTest).GetName(); // Process name
            }
            catch
            {
                return arkadeTest.GetType().Name; // Class name
            }
        }
    }
}

using Arkivverket.Arkade.Core.Resources;
using Arkivverket.Arkade.Core.Util;

namespace Arkivverket.Arkade.Core.Base
{
    public static class ArkadeTestNameProvider
    {
        public static string GetDisplayName(IArkadeTest arkadeTest)
        {
            TestId testId = arkadeTest.GetId();

            string testName = GetTestName(testId);

            return string.Format(ArkadeTestDisplayNames.DisplayNameFormat, testId, testName);
        }

        private static string GetTestName(TestId testId)
        {
            string resourceDisplayNameKey = testId.ToString().Replace('.', '_');

            if (testId.Version.Equals("5.5"))
                resourceDisplayNameKey = $"{resourceDisplayNameKey}v5_5";

            return ArkadeTestDisplayNames.ResourceManager.GetString(resourceDisplayNameKey);
        }
    }
}

Remove no longer needed display name fallback


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>@ViewBag.Title</title>
    </head>
    <body>
        <div>
            @RenderBody()
        </div>
    </body>
</html>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>@ViewBag.Title</title>
		@Styles.Render("~/Content/bootstrap.min.css")
	</head>
    <body>
        <div>
            @RenderBody()
        </div>
		@RenderSection("Scripts", false)
	</body>
</html>

Add Scripts section and Bootstrap styling.


using System;
using System.IO;

using Mango;

//
//  This the default StaticContentModule that comes with all Mango apps
//  if you do not wish to serve any static content with Mango you can
//  remove its route handler from <YourApp>.cs's constructor and delete
//  this file.
//
//  All Content placed on the Content/ folder should be handled by this
//  module.
//

namespace AppNameFoo {

	public class StaticContentModule : MangoModule {

		public StaticContentModule ()
		{
			Get ("*", Content);

		}

		public static void Content (IMangoContext ctx)
		{
			string path = ctx.Request.LocalPath;

			if (path.StartsWith ("/"))
				path = path.Substring (1);

			if (File.Exists (path)) {
				ctx.Response.SendFile (path);
			} else
				ctx.Response.StatusCode = 404;
		}
	}
}

using System;
using System.IO;

using Mango;

//
//  This the default StaticContentModule that comes with all Mango apps
//  if you do not wish to serve any static content with Mango you can
//  remove its route handler from <YourApp>.cs's constructor and delete
//  this file.
//
//  All Content placed on the Content/ folder should be handled by this
//  module.
//

namespace $APPNAME {

	public class StaticContentModule : MangoModule {

		public StaticContentModule ()
		{
			Get ("*", Content);

		}

		public static void Content (IMangoContext ctx)
		{
			string path = ctx.Request.LocalPath;

			if (path.StartsWith ("/"))
				path = path.Substring (1);

			if (File.Exists (path)) {
				ctx.Response.SendFile (path);
			} else
				ctx.Response.StatusCode = 404;
		}
	}
}

Use the correct namespace on the static content module.


using System;
using System.Collections.Generic;

namespace GridDomain.CQRS.Messaging.MessageRouting
{
    public class ProjectionGroup: IProjectionGroup
    {
        private readonly IServiceLocator _locator;
        readonly Dictionary<Type, List<Action<object>>> _handlers = new Dictionary<Type, List<Action<object>>>();

        public ProjectionGroup(IServiceLocator locator)
        {
            _locator = locator;
        }

        public void Add<TMessage, THandler>(string correlationPropertyName ) where THandler : IHandler<TMessage>
        {
            var handler = _locator.Resolve<THandler>();

            List<Action<object>> builderList;

            if (!_handlers.TryGetValue(typeof (TMessage), out builderList))
            {
                builderList = new List<Action<object>>();
                _handlers[typeof (TMessage)] = builderList;
            }
            builderList.Add(o => handler.Handle((TMessage) o));

            _acceptMessages.Add(new MessageRoute(typeof(TMessage), correlationPropertyName));
        }

        public void Project(object message)
        {
            var msgType = message.GetType();
            foreach(var handler in _handlers[msgType])
                        handler(message);
        }
        private readonly List<MessageRoute> _acceptMessages = new List<MessageRoute>();
        public IReadOnlyCollection<MessageRoute> AcceptMessages => _acceptMessages;
    }
}

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

namespace GridDomain.CQRS.Messaging.MessageRouting
{
    public class ProjectionGroup: IProjectionGroup
    {
        private readonly IServiceLocator _locator;
        readonly Dictionary<Type, List<Action<object>>> _handlers = new Dictionary<Type, List<Action<object>>>();

        public ProjectionGroup(IServiceLocator locator)
        {
            _locator = locator;
        }

        public void Add<TMessage, THandler>(string correlationPropertyName ) where THandler : IHandler<TMessage>
        {
            var handler = _locator.Resolve<THandler>();

            List<Action<object>> builderList;

            if (!_handlers.TryGetValue(typeof (TMessage), out builderList))
            {
                builderList = new List<Action<object>>();
                _handlers[typeof (TMessage)] = builderList;
            }
            builderList.Add(o => handler.Handle((TMessage) o));

            if(_acceptMessages.All(m => m.MessageType != typeof (TMessage)))
                _acceptMessages.Add(new MessageRoute(typeof(TMessage), correlationPropertyName));
        }

        public void Project(object message)
        {
            var msgType = message.GetType();
            foreach(var handler in _handlers[msgType])
                handler(message);
        }
        private readonly List<MessageRoute> _acceptMessages = new List<MessageRoute>();
        public IReadOnlyCollection<MessageRoute> AcceptMessages => _acceptMessages;
    }
}

Fix for several handlers for one message in projection group


using Lime.Protocol;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Takenet.MessagingHub.Client.Test
{
    [TestFixture]
    internal class MessagingHubClientTests_SendCommand : MessagingHubClientTestBase
    {
        [SetUp]
        protected override void Setup()
        {
            base.Setup();
        }

        [TearDown]
        protected override void TearDown()
        {
            base.TearDown();
        }

        [Test]
        public async Task Send_Command_And_Receive_Response_With_Success()
        {
            //Arrange
            var commandId = Guid.NewGuid();
            var commandResponse = new Command
            {
                Id = commandId,
                Status = CommandStatus.Success,
            };

            ClientChannel.ProcessCommandAsync(null, CancellationToken.None).ReturnsForAnyArgs(commandResponse);
            await MessagingHubClient.StartAsync();

            //Act
            var result = MessagingHubClient.SendCommandAsync(new Command { Id = commandId }).Result;

            //Assert
            ClientChannel.ReceivedWithAnyArgs().ReceiveCommandAsync(CancellationToken.None);
            result.ShouldNotBeNull();
            result.Status.ShouldBe(CommandStatus.Success);
            result.Id.ShouldBe(commandId);
        }

        [Test]
        public void Send_Command_Without_Start_Should_Throw_Exception()
        {
            //Act / Assert
            Should.ThrowAsync<InvalidOperationException>(async () => await MessagingHubClient.SendCommandAsync(Arg.Any<Command>()).ConfigureAwait(false)).Wait();
        }
    }
}

using Lime.Protocol;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Takenet.MessagingHub.Client.Test
{
    [TestFixture]
    internal class MessagingHubClientTests_SendCommand : MessagingHubClientTestBase
    {
        [SetUp]
        protected override void Setup()
        {
            base.Setup();
        }

        [TearDown]
        protected override void TearDown()
        {
            base.TearDown();
        }

        [Test]
        public async Task Send_Command_And_Receive_Response_With_Success()
        {
            //Arrange
            var commandId = Guid.NewGuid();
            var commandResponse = new Command
            {
                Id = commandId,
                Status = CommandStatus.Success,
            };

            ClientChannel.ProcessCommandAsync(null, CancellationToken.None).ReturnsForAnyArgs(commandResponse);
            await MessagingHubClient.StartAsync();

            //Act
            var result = await MessagingHubClient.SendCommandAsync(new Command { Id = commandId });
            await Task.Delay(TIME_OUT);

            //Assert
            ClientChannel.ReceivedWithAnyArgs().ReceiveCommandAsync(CancellationToken.None);
            result.ShouldNotBeNull();
            result.Status.ShouldBe(CommandStatus.Success);
            result.Id.ShouldBe(commandId);
        }

        [Test]
        public void Send_Command_Without_Start_Should_Throw_Exception()
        {
            //Act / Assert
            Should.ThrowAsync<InvalidOperationException>(async () => await MessagingHubClient.SendCommandAsync(Arg.Any<Command>()).ConfigureAwait(false)).Wait();
        }
    }
}

Use await um command tests

Use await um command 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Timing;

namespace osu.Game.Tests.Visual.Editing
{
    [TestFixture]
    public class TestSceneTimingScreen : EditorClockTestScene
    {
        [Cached(typeof(EditorBeatmap))]
        [Cached(typeof(IBeatSnapProvider))]
        private readonly EditorBeatmap editorBeatmap;

        public TestSceneTimingScreen()
        {
            editorBeatmap = new EditorBeatmap(CreateBeatmap(new OsuRuleset().RulesetInfo));
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
            Child = new TimingScreen();
        }
    }
}

// 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Timing;

namespace osu.Game.Tests.Visual.Editing
{
    [TestFixture]
    public class TestSceneTimingScreen : EditorClockTestScene
    {
        [Cached(typeof(EditorBeatmap))]
        [Cached(typeof(IBeatSnapProvider))]
        private readonly EditorBeatmap editorBeatmap;

        public TestSceneTimingScreen()
        {
            editorBeatmap = new EditorBeatmap(CreateBeatmap(new OsuRuleset().RulesetInfo));
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
            Beatmap.Disabled = true;

            Child = new TimingScreen();
        }

        protected override void Dispose(bool isDisposing)
        {
            Beatmap.Disabled = false;
            base.Dispose(isDisposing);
        }
    }
}

Fix beatmap potentially changing in test scene


using BatteryCommander.Web.Controllers;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Models
{
    public class NavigationViewComponent : ViewComponent
    {
        private readonly Database db;

        public Soldier Soldier { get; private set; }

        public Boolean ShowNavigation => !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]);

        public IEnumerable<Embed> NavItems
        {
            get
            {
                // TODO Only for nav items
                // TODO Only for the logged in unit

                yield return new Embed { Name = "PO Tracker" };

                yield return new Embed { Name = "SUTA" };

                //return
                //    db
                //    .Embeds
                //    .ToList();
            }
        }

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

        public async Task<IViewComponentResult> InvokeAsync()
        {
            Soldier = await UserService.FindAsync(db, UserClaimsPrincipal);

            return View(this);
        }
    }
}

using BatteryCommander.Web.Controllers;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Models
{
    public class NavigationViewComponent : ViewComponent
    {
        private readonly Database db;

        public Soldier Soldier { get; private set; }

        public Boolean ShowNavigation => !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]);

        public IEnumerable<Embed> NavItems
        {
            get
            {
                // TODO Only for nav items
                // TODO Only for the logged in uni

                return
                    db
                    .Embeds
                    .ToList();
            }
        }

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

        public async Task<IViewComponentResult> InvokeAsync()
        {
            Soldier = await UserService.FindAsync(db, UserClaimsPrincipal);

            return View(this);
        }
    }
}

Use the actual db data

Use the actual db data


using System.Text;
using Confluent.Kafka;
using Jasper.Transports;

namespace Jasper.ConfluentKafka
{
    public class KafkaTransportProtocol<TKey, TVal> : ITransportProtocol<Message<TKey, TVal>>
    {
        public Message<TKey, TVal> WriteFromEnvelope(Envelope envelope) =>
            new Message<TKey, TVal>
            {
                Headers = new Headers(),
                Value = (TVal) envelope.Message
            };

        public Envelope ReadEnvelope(Message<TKey, TVal> message)
        {
            var env = new Envelope();

            foreach (var header in message.Headers)
            {
                env.Headers.Add(header.Key, Encoding.UTF8.GetString(header.GetValueBytes()));
            }

            env.Message = message.Value;

            return env;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Confluent.Kafka;
using Jasper.Transports;

namespace Jasper.ConfluentKafka
{
    public class KafkaTransportProtocol<TKey, TVal> : ITransportProtocol<Message<TKey, TVal>>
    {
        private const string JasperMessageIdHeader = "Jasper_MessageId";
        public Message<TKey, TVal> WriteFromEnvelope(Envelope envelope)
        {
            var message = new Message<TKey, TVal>
            {
                Headers = new Headers(),
                Value = (TVal) envelope.Message
            };

            foreach (KeyValuePair<string, string> h in envelope.Headers)
            {
                Header header = new Header(h.Key, Encoding.UTF8.GetBytes(h.Value));
                message.Headers.Add(header);
            }

            message.Headers.Add(JasperMessageIdHeader, Encoding.UTF8.GetBytes(envelope.Id.ToString()));

            return message;
        }

        public Envelope ReadEnvelope(Message<TKey, TVal> message)
        {
            var env = new Envelope();

            foreach (var header in message.Headers.Where(h => !h.Key.StartsWith("Jasper")))
            {
                env.Headers.Add(header.Key, Encoding.UTF8.GetString(header.GetValueBytes()));
            }

            var messageIdHeader = message.Headers.Single(h => h.Key.Equals(JasperMessageIdHeader));
            env.Id = Guid.Parse(Encoding.UTF8.GetString(messageIdHeader.GetValueBytes()));
            env.Message = message.Value;

            return env;
        }
    }
}

Make sure Jasper MessageId goes across the wire


// 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.Graphics.Sprites;
using osu.Game.Online.API.Requests.Responses;

namespace osu.Game.Beatmaps.Drawables.Cards.Buttons
{
    public class DownloadButton : BeatmapCardIconButton
    {
        private readonly APIBeatmapSet beatmapSet;

        public DownloadButton(APIBeatmapSet beatmapSet)
        {
            this.beatmapSet = beatmapSet;

            Icon.Icon = FontAwesome.Solid.FileDownload;
        }

        // TODO: implement behaviour
    }
}

// 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.Graphics.Sprites;
using osu.Game.Online.API.Requests.Responses;

namespace osu.Game.Beatmaps.Drawables.Cards.Buttons
{
    public class DownloadButton : BeatmapCardIconButton
    {
        public DownloadButton(APIBeatmapSet beatmapSet)
        {
            Icon.Icon = FontAwesome.Solid.FileDownload;
        }

        // TODO: implement behaviour
    }
}

Remove unused field for now to appease inspectcode


using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;

namespace Orchard.Lists {
    public class Migrations : DataMigrationImpl {
        public int Create() {
            ContentDefinitionManager.AlterTypeDefinition("List",
                cfg=>cfg
                    .WithPart("CommonPart")
                    .WithPart("RoutePart")
                    .WithPart("ContainerPart")
                    .WithPart("MenuPart")
                    .WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2"))
                    .Creatable());

            return 3;
        }

        public int UpdateFrom1() {
            ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
            return 3;
        }

        public int UpdateFrom2() {
            ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
            return 3;
        }

    }
}

using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;

namespace Orchard.Lists {
    public class Migrations : DataMigrationImpl {
        public int Create() {
            ContentDefinitionManager.AlterTypeDefinition("List",
                cfg=>cfg
                    .WithPart("CommonPart")
                    .WithPart("TitlePart")
                    .WithPart("AutoroutePart")
                    .WithPart("ContainerPart")
                    .WithPart("MenuPart")
                    .WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2"))
                    .Creatable());

            return 4;
        }

        public int UpdateFrom1() {
            ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
            return 3;
        }

        public int UpdateFrom2() {
            ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
            return 3;
        }

        public int UpdateFrom3() {

            // TODO: (PH:Autoroute) Copy paths, routes, etc.

            ContentDefinitionManager.AlterTypeDefinition("List",
                cfg => cfg
                    .RemovePart("RoutePart")
                    .WithPart("TitlePart")
                    .WithPart("AutoroutePart"));

            return 4;
        }

    }
}

Update Lists migrations for Autoroute

Update Lists migrations for Autoroute

--HG--
branch : autoroute


using HalKit.Json;
using HalKit.Models.Response;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace GogoKit.Models.Response
{
    /// <summary>
    /// A carrier (e.g. UPS) that will collect tickets that are to be delivered.
    /// </summary>
    /// <remarks>See http://developer.viagogo.net/#carrier</remarks>
    [DataContract(Name = "carrier")]
    public class Carrier
    {
        /// <summary>
        /// The carrier identifier.
        /// </summary>
        [DataMember(Name = "id")]
        public int? Id { get; set; }

        /// <summary>
        /// The name of the carrier.
        /// </summary>
        [DataMember(Name = "name")]
        public string Name { get; set; }

        /// <summary>
        /// The windows available for ticket collection.
        /// </summary>
        [DataMember(Name = "pickup_windows")]
        public IList<PickupWindow> PickupWindows { get; set; }

        /// <summary>
        /// Creates a new pickup for the ticket(s).
        /// </summary>
        /// <remarks>See http://developer.viagogo.net/#carriercreatepickup</remarks>
        [Rel("carrier:createpickup")]
        public Link CreatePickupLink { get; set; }
    }
}

using HalKit.Json;
using HalKit.Models.Response;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace GogoKit.Models.Response
{
    /// <summary>
    /// A carrier (e.g. UPS) that will collect tickets that are to be delivered.
    /// </summary>
    /// <remarks>See http://developer.viagogo.net/#carrier</remarks>
    [DataContract(Name = "carrier")]
    public class Carrier : Resource
    {
        /// <summary>
        /// The carrier identifier.
        /// </summary>
        [DataMember(Name = "id")]
        public int? Id { get; set; }

        /// <summary>
        /// The name of the carrier.
        /// </summary>
        [DataMember(Name = "name")]
        public string Name { get; set; }

        /// <summary>
        /// The windows available for ticket collection.
        /// </summary>
        [DataMember(Name = "pickup_windows")]
        public IList<PickupWindow> PickupWindows { get; set; }

        /// <summary>
        /// Creates a new pickup for the ticket(s).
        /// </summary>
        /// <remarks>See http://developer.viagogo.net/#carriercreatepickup</remarks>
        [Rel("carrier:createpickup")]
        public Link CreatePickupLink { get; set; }
    }
}

Add missing resource base class

Add missing resource base class


using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;

namespace Promact.Trappist.Repository.Questions
{
    public class QuestionRepository : IQuestionRepository
    {
        private readonly TrappistDbContext _dbContext;

        public QuestionRepository(TrappistDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// Get all questions
        /// </summary>
        /// <returns>Question list</returns>
        public List<SingleMultipleAnswerQuestion> GetAllQuestions()
        {
            var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
            return questions;
        }

        /// <summary>
        /// Add single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
            _dbContext.SaveChanges();
        }
        /// <summary>
        /// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
            _dbContext.SaveChanges();
        }

    }
}

using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;

namespace Promact.Trappist.Repository.Questions
{
    public class QuestionRepository : IQuestionRepository
    {
        private readonly TrappistDbContext _dbContext;

        public QuestionRepository(TrappistDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// Get all questions
        /// </summary>
        /// <returns>Question list</returns>
        public List<SingleMultipleAnswerQuestion> GetAllQuestions()
        {
            var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
            return question;
        }

        /// <summary>
        /// Add single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
            _dbContext.SaveChanges();
        }
        /// <summary>
        /// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
            _dbContext.SaveChanges();
        }

    }
}

Create server side API for single multiple answer question


namespace Line.Messaging
{
    /// <summary>
    /// Rich menu response object.
    /// https://developers.line.me/en/docs/messaging-api/reference/#rich-menu-response-object
    /// </summary>
    public class ResponseRichMenu : RichMenu
    {
        /// <summary>
        /// Rich menu ID
        /// </summary>
        public string RichMenuId { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="richMenuId">
        /// Rich menu ID
        /// </param>
        /// <param name="source">
        /// Rich menu object
        /// </param>
        public ResponseRichMenu(string richMenuId, RichMenu source)
        {
            RichMenuId = richMenuId;
            Size = source.Size;
            Selected = source.Selected;
            Name = source.Name;
            ChatBarText = source.ChatBarText;
            Areas = source.Areas;
        }

        internal static ResponseRichMenu CreateFrom(dynamic dynamicObject)
        {
            var menu = new RichMenu()
            {
                Name = (string)dynamicObject?.name,
                Size = new ImagemapSize((int)(dynamicObject?.size?.width ?? 0), (int)(dynamicObject?.size?.height ?? 0)),
                Selected = (bool)(dynamicObject?.selected ?? false),
                ChatBarText = (string)dynamicObject?.chatBarText
            };
            return new ResponseRichMenu((string)dynamicObject?.richMenuId, menu);
        }
    }
}

namespace Line.Messaging
{
    /// <summary>
    /// Rich menu response object.
    /// https://developers.line.me/en/docs/messaging-api/reference/#rich-menu-response-object
    /// </summary>
    public class ResponseRichMenu : RichMenu
    {
        /// <summary>
        /// Rich menu ID
        /// </summary>
        public string RichMenuId { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="richMenuId">
        /// Rich menu ID
        /// </param>
        /// <param name="source">
        /// Rich menu object
        /// </param>
        public ResponseRichMenu(string richMenuId, RichMenu source)
        {
            RichMenuId = richMenuId;
            Size = source.Size;
            Selected = source.Selected;
            Name = source.Name;
            ChatBarText = source.ChatBarText;
            Areas = source.Areas;
        }

        internal static ResponseRichMenu CreateFrom(dynamic dynamicObject)
        {
            var menu = new RichMenu()
            {
                Name = (string)dynamicObject?.name,
                Size = new ImagemapSize((int)(dynamicObject?.size?.width ?? 0), (int)(dynamicObject?.size?.height ?? 0)),
                Selected = (bool)(dynamicObject?.selected ?? false),
                ChatBarText = (string)dynamicObject?.chatBarText,
                Areas = ActionArea.CreateFrom(dynamicObject?.areas)
            };
            return new ResponseRichMenu((string)dynamicObject?.richMenuId, menu);
        }
    }
}

Fix Areas property is not deserialized, In the return value of the GetRichMenuListAsync method.


using System;

namespace Staxel.Trace {
    public struct TraceScope : IDisposable {
        public TraceKey Key;

        public TraceScope(TraceKey key) {
            Key = key;
            TraceRecorder.Enter(Key);
        }

        public void Dispose() {
            TraceRecorder.Leave(Key);
        }
    }
}

using System;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;

namespace Staxel.Trace {
    public struct TraceScope : IDisposable {
        public TraceKey Key;

        [TargetedPatchingOptOut("")]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public TraceScope(TraceKey key) {
            Key = key;
            TraceRecorder.Enter(Key);
        }

        [Conditional("TRACE")]
        [TargetedPatchingOptOut("")]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Dispose() {
            TraceRecorder.Leave(Key);
        }
    }
}

Patch out the Tracescope for as far as possible when applicable.


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

#nullable disable

using System;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;

namespace osu.Framework.Tests.Visual.Containers
{
    public class TestSceneEnumerator : FrameworkTestScene
    {
        private Container parent;

        [Test]
        public void TestAddChildDuringEnumerationFails()
        {
            AddStep("create hierarchy", () => Child = parent = new Container
            {
                Child = new Container
                {
                }
            });

            AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
            {
                foreach (var child in parent)
                {
                }
            }));

            AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
            {
                foreach (var child in parent)
                {
                    parent.Add(new Container());
                }
            }));
        }

        [Test]
        public void TestRemoveChildDuringEnumerationFails()
        {
            AddStep("create hierarchy", () => Child = parent = new Container
            {
                Child = new Container
                {
                }
            });

            AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
            {
                foreach (var child in parent)
                {
                }
            }));

            AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
            {
                foreach (var child in parent)
                {
                    parent.Remove(child, true);
                }
            }));
        }
    }
}

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

#nullable disable

using System;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;

namespace osu.Framework.Tests.Visual.Containers
{
    public class TestSceneEnumerator : FrameworkTestScene
    {
        private Container parent;

        [SetUp]
        public void SetUp()
        {
            Child = parent = new Container
            {
                Child = new Container
                {
                }
            };
        }

        [Test]
        public void TestEnumeratingNormally()
        {
            AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
            {
                foreach (var child in parent)
                {
                }
            }));
        }

        [Test]
        public void TestAddChildDuringEnumerationFails()
        {
            AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
            {
                foreach (var child in parent)
                {
                    parent.Add(new Container());
                }
            }));
        }

        [Test]
        public void TestRemoveChildDuringEnumerationFails()
        {
            AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
            {
                foreach (var child in parent)
                {
                    parent.Remove(child, true);
                }
            }));
        }

        [Test]
        public void TestClearDuringEnumerationFails()
        {
            AddStep("clearing children during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
            {
                foreach (var child in parent)
                {
                    parent.Clear();
                }
            }));
        }
    }
}

Use SetUp for tests, add test for clearing children