using Azure.Core.Pipeline;
using Azure.Test.PerfStress;
using System;
using System.Net.Http;

namespace Azure.Storage.Blobs.PerfStress
{
    public abstract class StorageTest<TOptions> : PerfStressTest<TOptions> where TOptions: PerfStressOptions
    {
        private const string _containerName = "perfstress";

        protected BlobClient BlobClient { get; private set; }

        public StorageTest(string id, TOptions options) : base(id, options)
        {
            var blobName = this.GetType().Name.ToLowerInvariant() + id;
            var connectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING");

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new InvalidOperationException("Undefined environment variable STORAGE_CONNECTION_STRING");
            }

            var httpClientHandler = new HttpClientHandler();
            httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
            var httpClient = new HttpClient(httpClientHandler);

            var blobClientOptions = new BlobClientOptions();
            blobClientOptions.Transport = new HttpClientTransport(httpClient);

            var serviceClient = new BlobServiceClient(connectionString, blobClientOptions);
            try
            {
                serviceClient.CreateBlobContainer(_containerName);
            }
            catch (StorageRequestFailedException)
            {
            }

            BlobClient = new BlobClient(connectionString, _containerName, blobName, blobClientOptions);
        }
    }
}

using Azure.Core.Pipeline;
using Azure.Test.PerfStress;
using System;
using System.Net.Http;

namespace Azure.Storage.Blobs.PerfStress
{
    public abstract class StorageTest<TOptions> : PerfStressTest<TOptions> where TOptions: PerfStressOptions
    {
        private const string _containerName = "perfstress";

        protected BlobServiceClient BlobServiceClient { get; private set; }

        protected BlobContainerClient BlobContainerClient { get; private set; }

        protected BlobClient BlobClient { get; private set; }

        public StorageTest(string id, TOptions options) : base(id, options)
        {
            var blobName = this.GetType().Name.ToLowerInvariant() + id;
            var connectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING");

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new InvalidOperationException("Undefined environment variable STORAGE_CONNECTION_STRING");
            }

            var httpClientHandler = new HttpClientHandler();
            httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
            var httpClient = new HttpClient(httpClientHandler);

            var blobClientOptions = new BlobClientOptions();
            blobClientOptions.Transport = new HttpClientTransport(httpClient);

            BlobServiceClient = new BlobServiceClient(connectionString, blobClientOptions);
            try
            {
                BlobServiceClient.CreateBlobContainer(_containerName);
            }
            catch (StorageRequestFailedException)
            {
            }

            BlobContainerClient = BlobServiceClient.GetBlobContainerClient(_containerName);

            BlobClient = BlobContainerClient.GetBlobClient(blobName);
        }
    }
}

Add service and container clients

Add service and container clients


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

// ADDED FIRST LINE

namespace PracticeGit.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

// ADDED FIRST LINE

// ADDED SECOND LINE

namespace PracticeGit.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }
    }
}

Test Major/Minor versions - Commit 2

Test Major/Minor versions - Commit 2


using System;
using System.ComponentModel;
using DesktopWidgets.WidgetBase.Settings;

namespace DesktopWidgets.Widgets.PictureSlideshow
{
    public class Settings : WidgetSettingsBase
    {
        public Settings()
        {
            Width = 384;
            Height = 216;
        }

        [Category("General")]
        [DisplayName("Image Folder Path")]
        public string RootPath { get; set; }

        [Category("General")]
        [DisplayName("Maximum File Size (bytes)")]
        public double FileFilterSize { get; set; } = 1024000;

        [Category("General")]
        [DisplayName("Next Image Interval")]
        public TimeSpan ChangeInterval { get; set; } = TimeSpan.FromSeconds(15);

        [Category("General")]
        [DisplayName("Shuffle")]
        public bool Shuffle { get; set; } = true;

        [Category("General")]
        [DisplayName("Recursive")]
        public bool Recursive { get; set; } = false;

        [Category("General")]
        [DisplayName("Current Image Path")]
        public string ImageUrl { get; set; }

        [Category("General")]
        [DisplayName("Allow Dropping Images")]
        public bool AllowDropFiles { get; set; } = true;

        [Category("General")]
        [DisplayName("Freeze")]
        public bool Freeze { get; set; }
    }
}

using System;
using System.ComponentModel;
using DesktopWidgets.WidgetBase.Settings;

namespace DesktopWidgets.Widgets.PictureSlideshow
{
    public class Settings : WidgetSettingsBase
    {
        public Settings()
        {
            Width = 384;
            Height = 216;
        }

        [Category("General")]
        [DisplayName("Image Folder Path")]
        public string RootPath { get; set; }

        [Category("General")]
        [DisplayName("Maximum File Size (bytes)")]
        public double FileFilterSize { get; set; } = 1048576;

        [Category("General")]
        [DisplayName("Next Image Interval")]
        public TimeSpan ChangeInterval { get; set; } = TimeSpan.FromSeconds(15);

        [Category("General")]
        [DisplayName("Shuffle")]
        public bool Shuffle { get; set; } = true;

        [Category("General")]
        [DisplayName("Recursive")]
        public bool Recursive { get; set; } = false;

        [Category("General")]
        [DisplayName("Current Image Path")]
        public string ImageUrl { get; set; }

        [Category("General")]
        [DisplayName("Allow Dropping Images")]
        public bool AllowDropFiles { get; set; } = true;

        [Category("General")]
        [DisplayName("Freeze")]
        public bool Freeze { get; set; }
    }
}

Fix "Picture Slideshow" "Maximum File Size" default value


using System.Linq;
using AutoMapper;
using Abp.Authorization;
using Abp.Authorization.Roles;
using AbpCompanyName.AbpProjectName.Authorization.Roles;

namespace AbpCompanyName.AbpProjectName.Roles.Dto
{
    public class RoleMapProfile : Profile
    {
        public RoleMapProfile()
        {
            // Role and permission
            CreateMap<Permission, string>().ConvertUsing(r => r.Name);
            CreateMap<RolePermissionSetting, string>().ConvertUsing(r => r.Name);

            CreateMap<CreateRoleDto, Role>();

            CreateMap<RoleDto, Role>();

            CreateMap<Role, RoleDto>().ForMember(x => x.GrantedPermissions,
                opt => opt.MapFrom(x => x.Permissions.Where(p => p.IsGranted)));
        }
    }
}

using System.Linq;
using AutoMapper;
using Abp.Authorization;
using Abp.Authorization.Roles;
using AbpCompanyName.AbpProjectName.Authorization.Roles;

namespace AbpCompanyName.AbpProjectName.Roles.Dto
{
    public class RoleMapProfile : Profile
    {
        public RoleMapProfile()
        {
            // Role and permission
            CreateMap<Permission, string>().ConvertUsing(r => r.Name);
            CreateMap<RolePermissionSetting, string>().ConvertUsing(r => r.Name);

            CreateMap<CreateRoleDto, Role>();

            CreateMap<RoleDto, Role>();

            CreateMap<Role, RoleDto>().ForMember(x => x.GrantedPermissions,
                opt => opt.MapFrom(x => x.Permissions.Where(p => p.IsGranted)));

            CreateMap<Role, RoleListDto>();
            CreateMap<Role, RoleEditDto>();
            CreateMap<Permission, FlatPermissionDto>();
        }
    }
}

Add missing object mapping configuration.


#if !NO_UNITY
using System;
using System.Collections.Generic;
using UnityEngine;

namespace FullSerializer {
	public class fsAotConfiguration : ScriptableObject {
        public enum AotState {
            Default, Enabled, Disabled
        }

        [Serializable]
        public struct Entry {
            public AotState State;
            public string FullTypeName;

            public Entry(Type type) {
                FullTypeName = type.FullName;
                State = AotState.Default;
            }

            public Entry(Type type, AotState state) {
                FullTypeName = type.FullName;
                State = state;
            }
        }
		public List<Entry> aotTypes = new List<Entry>();
        public string outputDirectory = "Assets/AotModels";

        public bool TryFindEntry(Type type, out Entry result) {
            string searchFor = type.FullName;
            foreach (Entry entry in aotTypes) {
                if (entry.FullTypeName == searchFor) {
                    result = entry;
                    return true;
                }
            }

            result = default(Entry);
            return false;
        }

        public void UpdateOrAddEntry(Entry entry) {
            for (int i = 0; i < aotTypes.Count; ++i) {
                if (aotTypes[i].FullTypeName == entry.FullTypeName) {
                    aotTypes[i] = entry;
                    return;
                }
            }

            aotTypes.Add(entry);
        }
	}
}
#endif

#if !NO_UNITY
using System;
using System.Collections.Generic;
using UnityEngine;

namespace FullSerializer {
    [CreateAssetMenu(menuName = "Full Serializer AOT Configuration")]
    public class fsAotConfiguration : ScriptableObject {
        public enum AotState {
            Default, Enabled, Disabled
        }

        [Serializable]
        public struct Entry {
            public AotState State;
            public string FullTypeName;

            public Entry(Type type) {
                FullTypeName = type.FullName;
                State = AotState.Default;
            }

            public Entry(Type type, AotState state) {
                FullTypeName = type.FullName;
                State = state;
            }
        }
		public List<Entry> aotTypes = new List<Entry>();
        public string outputDirectory = "Assets/AotModels";

        public bool TryFindEntry(Type type, out Entry result) {
            string searchFor = type.FullName;
            foreach (Entry entry in aotTypes) {
                if (entry.FullTypeName == searchFor) {
                    result = entry;
                    return true;
                }
            }

            result = default(Entry);
            return false;
        }

        public void UpdateOrAddEntry(Entry entry) {
            for (int i = 0; i < aotTypes.Count; ++i) {
                if (aotTypes[i].FullTypeName == entry.FullTypeName) {
                    aotTypes[i] = entry;
                    return;
                }
            }

            aotTypes.Add(entry);
        }
	}
}
#endif

Add menu item to create AOT configuration


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

namespace Toolhouse.Monitoring.Dependencies
{
    public class SmtpDependency : IDependency
    {
        public SmtpDependency(string name)
        {
            this.Name = name;
        }

        public string Name
        {
            get;
            private set;
        }

        public DependencyStatus Check()
        {
            // TODO: A more sophisticated test here would be opening up a socket and actually attempting to speak SMTP.
            using (var client = new System.Net.Mail.SmtpClient())
            {
                var message = new MailMessage("test@example.org", "smtpdependencycheck@toolhouse.com", "SMTP test", "");
                client.Send(message);
            }

            return new DependencyStatus(this, true, "");
        }
    }
}

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

namespace Toolhouse.Monitoring.Dependencies
{
    public class SmtpDependency : IDependency
    {
        public SmtpDependency(string name)
        {
            this.Name = name;
        }

        public string Name
        {
            get;
            private set;
        }

        public DependencyStatus Check()
        {
            // TODO: A more sophisticated test here would be opening up a socket and actually attempting to speak SMTP.
            using (var client = new System.Net.Mail.SmtpClient())
            {
                var message = new MailMessage("test@example.org", "smtpdependencycheck@example.org", "SMTP test", "");
                client.Send(message);
            }

            return new DependencyStatus(this, true, "");
        }
    }
}

Tweak SMTP test "From" address.

Tweak SMTP test "From" address.

Just always use example.org


using System;
using System.Reflection;
//using System.IO;
//using System.Reflection;
using LASI.Utilities;

namespace LASI.WebApp.Tests.TestAttributes
{
    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class PreconfigureLASIAttribute : Xunit.Sdk.BeforeAfterTestAttribute
    {
        private const string ConfigFileName = "config.json";
        private const string LASIComponentConfigSubkey = "Resources";

        public override void Before(MethodInfo methodUnderTest)
        {
            base.Before(methodUnderTest);
            ConfigureLASIComponents(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), ConfigFileName), LASIComponentConfigSubkey);
        }
        private static void ConfigureLASIComponents(string fileName, string subkey)
        {
            Interop.ResourceUsageManager.SetPerformanceLevel(Interop.PerformanceProfile.High);
            try
            {
                Interop.Configuration.Initialize(fileName, Interop.ConfigFormat.Json, subkey);
            }
            catch (Interop.SystemAlreadyConfiguredException)
            {
                //Console.WriteLine("LASI was already setup by a previous test; continuing");
            }
            Logger.SetToSilent();
        }
    }
}

using System;
using System.Reflection;
//using System.IO;
//using System.Reflection;
using LASI.Utilities;

namespace LASI.WebApp.Tests.TestAttributes
{
    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class PreconfigureLASIAttribute : Xunit.Sdk.BeforeAfterTestAttribute
    {
        private const string ConfigFileName = "config.json";
        private const string LASIComponentConfigSubkey = "Resources";

        public override void Before(MethodInfo methodUnderTest)
        {
            base.Before(methodUnderTest);
            ConfigureLASIComponents(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), ConfigFileName), LASIComponentConfigSubkey);
        }
        private static void ConfigureLASIComponents(string fileName, string subkey)
        {
            Interop.ResourceUsageManager.SetPerformanceLevel(Interop.PerformanceProfile.High);
            try
            {
                Interop.Configuration.Initialize(fileName, Interop.ConfigFormat.Json, subkey);
            }
            catch (Interop.AlreadyConfiguredException)
            {
                //Console.WriteLine("LASI was already setup by a previous test; continuing");
            }
            Logger.SetToSilent();
        }
    }
}

Fix type name error due to temporarily excluded project


using System;
using Agiil.Domain.Validation;
using CSF.Validation;
using CSF.Validation.Manifest.Fluent;
using CSF.Validation.StockRules;

namespace Agiil.Domain.Sprints
{
  public class CreateSprintValidatorFactory : ValidatorFactoryBase<CreateSprintRequest>
  {
    protected override void ConfigureManifest(IManifestBuilder<CreateSprintRequest> builder)
    {
      builder.AddRule<NotNullRule>();
      builder.AddMemberRule<RegexMatchValueRule>(x => x.Name, c => {
        c.Configure(r => r.Pattern = @"^\S+");
      });
      builder.AddRule<EndDateMustNotBeBeforeStartDateRule>();
    }

    public CreateSprintValidatorFactory(IValidatorFactory validatorFactory) : base(validatorFactory) {}
  }
}

using System;
using Agiil.Domain.Validation;
using CSF.Validation;
using CSF.Validation.Manifest.Fluent;
using CSF.Validation.StockRules;

namespace Agiil.Domain.Sprints
{
  public class CreateSprintValidatorFactory : ValidatorFactoryBase<CreateSprintRequest>
  {
    protected override void ConfigureManifest(IManifestBuilder<CreateSprintRequest> builder)
    {
      builder.AddRule<NotNullRule>();
      builder.AddMemberRule<NotNullValueRule>(x => x.Name);
      builder.AddMemberRule<RegexMatchValueRule>(x => x.Name, c => {
        c.Configure(r => r.Pattern = @"^\S+");
      });
      builder.AddRule<EndDateMustNotBeBeforeStartDateRule>();
    }

    public CreateSprintValidatorFactory(IValidatorFactory validatorFactory) : base(validatorFactory) {}
  }
}

Fix mistake in create sprint validator - was allowing null Name


using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SupportManager.DAL;

namespace SupportManager.Web.Areas.Teams
{
    [Area("Teams")]
    [Authorize]
    public abstract class BaseController : Controller
    {
        protected int TeamId => int.Parse((string) ControllerContext.RouteData.Values["teamId"]);

        protected SupportTeam Team { get; private set; }

        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var db = (SupportManagerContext) context.HttpContext.RequestServices.GetService(typeof(SupportManagerContext));
            Team = await db.Teams.FindAsync(TeamId);

            if (Team == null)
            {
                context.Result = NotFound();
                return;
            }

            ViewData["TeamName"] = Team.Name;

            await base.OnActionExecutionAsync(context, next);
        }
    }
}

using System.Data.Entity;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SupportManager.DAL;

namespace SupportManager.Web.Areas.Teams
{
    [Area("Teams")]
    [Authorize]
    public abstract class BaseController : Controller
    {
        protected int TeamId => int.Parse((string) ControllerContext.RouteData.Values["teamId"]);

        protected SupportTeam Team { get; private set; }

        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var db = (SupportManagerContext) context.HttpContext.RequestServices.GetService(typeof(SupportManagerContext));
            Team = await db.Teams.FindAsync(TeamId);

            if (Team == null)
            {
                context.Result = NotFound();
                return;
            }

            var userName = context.HttpContext.User.Identity.Name;
            if (!await db.TeamMembers.AnyAsync(x => x.TeamId == Team.Id && x.User.Login == userName))
            {
                context.Result = NotFound();
                return;
            }

            ViewData["TeamName"] = Team.Name;

            await base.OnActionExecutionAsync(context, next);
        }
    }
}

web: Return NotFound on teams user is not a member of


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

using System.Globalization;
using Microsoft.Common.Core;
using Microsoft.Common.Core.Shell;
using Microsoft.R.Host.Client;
using Microsoft.VisualStudio.R.Package.Commands;
using Microsoft.VisualStudio.R.Package.Shell;
using Microsoft.VisualStudio.R.Packages.R;
using Microsoft.VisualStudio.R.Package.Utilities;

namespace Microsoft.VisualStudio.R.Package.DataInspect.Commands {
    internal sealed class DeleteAllVariablesCommand : SessionCommand {
        public DeleteAllVariablesCommand(IRSession session) :
            base(session, RGuidList.RCmdSetGuid, RPackageCommandId.icmdDeleteAllVariables) {
        }

        protected override void SetStatus() {
            var variableWindowPane = ToolWindowUtilities.FindWindowPane<VariableWindowPane>(0);
            Enabled = (variableWindowPane?.IsGlobalREnvironment()) ?? true;
        }

        protected override void Handle() {
            if(MessageButtons.No == VsAppShell.Current.ShowMessage(Resources.Warning_DeleteAllVariables, MessageButtons.YesNo)) {
                return;
            }
            try {
                RSession.ExecuteAsync("rm(list = ls(all = TRUE))").DoNotWait();
            } catch(RException ex) {
                VsAppShell.Current.ShowErrorMessage(
                    string.Format(CultureInfo.InvariantCulture, Resources.Error_UnableToDeleteVariable, ex.Message));
            } catch(MessageTransportException) { }
        }
    }
}

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

using System.Globalization;
using Microsoft.Common.Core;
using Microsoft.Common.Core.Shell;
using Microsoft.R.Host.Client;
using Microsoft.VisualStudio.R.Package.Commands;
using Microsoft.VisualStudio.R.Package.Shell;
using Microsoft.VisualStudio.R.Packages.R;
using Microsoft.VisualStudio.R.Package.Utilities;

namespace Microsoft.VisualStudio.R.Package.DataInspect.Commands {
    internal sealed class DeleteAllVariablesCommand : SessionCommand {
        public DeleteAllVariablesCommand(IRSession session) :
            base(session, RGuidList.RCmdSetGuid, RPackageCommandId.icmdDeleteAllVariables) {
        }

        protected override void SetStatus() {
            var variableWindowPane = ToolWindowUtilities.FindWindowPane<VariableWindowPane>(0);
            // 'Delete all variables' button should be enabled only when the Global environment
            // is selected in Variable Explorer.
            Enabled = (variableWindowPane?.IsGlobalREnvironment()) ?? false;
        }

        protected override void Handle() {
            if(MessageButtons.No == VsAppShell.Current.ShowMessage(Resources.Warning_DeleteAllVariables, MessageButtons.YesNo)) {
                return;
            }
            try {
                RSession.ExecuteAsync("rm(list = ls(all = TRUE))").DoNotWait();
            } catch(RException ex) {
                VsAppShell.Current.ShowErrorMessage(
                    string.Format(CultureInfo.InvariantCulture, Resources.Error_UnableToDeleteVariable, ex.Message));
            } catch(MessageTransportException) { }
        }
    }
}

Disable 'Delete all variables' when no environment is selected.


using System;
using System.IO;
using System.Security.Cryptography;

namespace Nuterra.Installer
{
	public static class InstallerUtil
	{
		public static string GetFileHash(string filePath)
		{
			if (!File.Exists(filePath))
			{
				return null;
			}
			using (var md5 = MD5.Create())
			using (var stream = File.OpenRead(filePath))
			{
				return Convert.ToBase64String(md5.ComputeHash(stream));
			}
		}

		public static string CreateAssemblyBackup(string sourceAssembly, string assemblyBackupDir, string hash)
		{
			string targetFile = Path.Combine(assemblyBackupDir, $"{hash}.dll");
			if (Directory.Exists(assemblyBackupDir))
			{
				Directory.CreateDirectory(assemblyBackupDir);
			}
			if (!File.Exists(targetFile))
			{
				File.Copy(sourceAssembly, targetFile);
			}
			return targetFile;
		}

		public static string FormatBackupPath(string assemblyBackupDir, string hash)
		{
			return Path.Combine(assemblyBackupDir, $"{hash}.dll");
		}
	}
}

using System;
using System.IO;
using System.Security.Cryptography;

namespace Nuterra.Installer
{
	public static class InstallerUtil
	{
		public static string GetFileHash(string filePath)
		{
			if (!File.Exists(filePath))
			{
				return null;
			}
			using (var md5 = MD5.Create())
			using (var stream = File.OpenRead(filePath))
			{
				return Convert.ToBase64String(md5.ComputeHash(stream));
			}
		}

		public static string CreateAssemblyBackup(string sourceAssembly, string assemblyBackupDir, string hash)
		{
			string targetFile = Path.Combine(assemblyBackupDir, $"{hash}.dll");
			if (!Directory.Exists(assemblyBackupDir))
			{
				Directory.CreateDirectory(assemblyBackupDir);
			}
			if (!File.Exists(targetFile))
			{
				File.Copy(sourceAssembly, targetFile);
			}
			return targetFile;
		}

		public static string FormatBackupPath(string assemblyBackupDir, string hash)
		{
			return Path.Combine(assemblyBackupDir, $"{hash}.dll");
		}
	}
}

Create backup directory if missing

Create backup directory if missing

Just embarassing that I managed to write this


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

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

namespace Roslyn.Test.Utilities
{
    public struct TestInfo
    {
        public decimal Time { get; }

        public TestInfo(decimal time)
        {
            Time = time;
        }

        public static IDictionary<string, TestInfo> GetPassedTestsInfo()
        {
            var result = new Dictionary<string, TestInfo>();
            var filePath = System.Environment.GetEnvironmentVariable("OutputXmlFilePath");
            if (filePath != null)
            {
                if (File.Exists(filePath))
                {
                    var doc = new XmlDocument();
                    doc.Load(filePath);
                    foreach (XmlNode assemblies in doc.SelectNodes("assemblies"))
                    {
                        foreach (XmlNode assembly in assemblies.SelectNodes("assembly"))
                        {
                            foreach (XmlNode collection in assembly.SelectNodes("collection"))
                            {
                                foreach (XmlNode test in assembly.SelectNodes("test"))
                                {
                                    if (test.SelectNodes("failure").Count == 0)
                                    {
                                        if (decimal.TryParse(test.Attributes["time"].InnerText, out var time))
                                        {
                                            result.Add(test.Name, new TestInfo(time));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }
    }
}

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

using System.Collections.Immutable;
using System.IO;
using System.Xml.Linq;
using System.Xml.XPath;

namespace Roslyn.Test.Utilities
{
    public readonly struct TestInfo
    {
        public decimal Time { get; }

        public TestInfo(decimal time)
        {
            Time = time;
        }

        public static ImmutableDictionary<string, TestInfo> GetPassedTestsInfo()
        {
            var result = ImmutableDictionary.CreateBuilder<string, TestInfo>();
            var filePath = System.Environment.GetEnvironmentVariable("OutputXmlFilePath");
            if (filePath != null)
            {
                if (File.Exists(filePath))
                {
                    var doc = XDocument.Load(filePath);
                    foreach (var test in doc.XPathSelectElements("/assemblies/assembly/collection/test[@result='Pass']"))
                    {
                        if (decimal.TryParse(test.Attribute("time").Value, out var time))
                        {
                            result.Add(test.Attribute("name").Value, new TestInfo(time));
                        }
                    }
                }
            }

            return result.ToImmutable();
        }
    }
}

Simplify GetPassedTestsInfo with XDocument and XPath


// NoteSorter.cs
// <copyright file="NoteSorter.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
using System.Linq;

namespace Todo_List
{
    /// <summary>
    /// A static class containing a list of notes and methods for sorting them.
    /// </summary>
    public static class NoteSorter
    {
        /// <summary>
        /// Initializes static members of the <see cref="NoteSorter" /> class.
        /// </summary>
        public static NoteSorter()
        {
            Notes = new List<Note>();
        }

        /// <summary>
        /// Gets or sets the list of notes currently stored in the program.
        /// </summary>
        public static List<Note> Notes { get; set; }

        /// <summary>
        /// Gets all the notes with certain category tags.
        /// </summary>
        /// <param name="categoryNames"> The list of categories. </param>
        /// <returns> The list of notes under the category. </returns>
        /// <remarks> Null categories means all categories.</remarks>
        public static List<Note> GetNotesByCatagory(List<string> categoryNames = null)
        {
            IEnumerable<Note> notesUnderCategories = Notes;
            foreach (string catergory in categoryNames)
            {
                notesUnderCategories = notesUnderCategories.Where(n => n.Categories.Contains(catergory.ToUpper()));
            }

            return notesUnderCategories.ToList();
        }
    }
}

// NoteSorter.cs
// <copyright file="NoteSorter.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
using System.Linq;

namespace Todo_List
{
    /// <summary>
    /// A static class containing a list of notes and methods for sorting them.
    /// </summary>
    public static class NoteSorter
    {
        /// <summary>
        /// Initializes static members of the <see cref="NoteSorter" /> class.
        /// </summary>
        public static NoteSorter()
        {
            Notes = new List<Note>();
        }

        /// <summary>
        /// Gets or sets the list of notes currently stored in the program.
        /// </summary>
        public static List<Note> Notes { get; set; }

        /// <summary>
        /// Gets all the notes with certain category tags.
        /// </summary>
        /// <param name="categoryNames"> The list of categories. </param>
        /// <returns> The list of notes under the category. </returns>
        /// <remarks> No category names in the list means all categories. </remarks>
        public static List<Note> GetNotesByCatagory(List<string> categoryNames)
        {
            IEnumerable<Note> notesUnderCategories = Notes;
            foreach (string catergory in categoryNames)
            {
                notesUnderCategories = notesUnderCategories.Where(n => n.Categories.Contains(catergory.ToUpper()));
            }

            return notesUnderCategories.ToList();
        }
    }
}

Fix null category search bug

Fix null category search bug

Fix the default variable being null, which will cause an error at runtime
when trying to itterate over the null list.


using System;
using Elastic.Xunit.Sdk;
using Elastic.Xunit.XunitPlumbing;
using Elasticsearch.Net;
using FluentAssertions;
using Tests.Framework.ManagedElasticsearch.Clusters;

namespace Tests.Reproduce
{
	public class GithubIssue2985 : IClusterFixture<WritableCluster>
	{
		private readonly WritableCluster _cluster;

		public GithubIssue2985(WritableCluster cluster) => _cluster = cluster;

		protected static string RandomString() => Guid.NewGuid().ToString("N").Substring(0, 8);

		[I]
		public void CanReadSingleOrMultipleCommonGramsCommonWordsItem()
		{
			var client = _cluster.Client;
			var index = $"gh2985-{RandomString()}";
			var response = client.CreateIndex(index, i=> i
				.Settings(s=>s
					.Analysis(a=>a
						.Analyzers(an=>an
							.Custom("custom", c=>c.Filters("ascii_folding").Tokenizer("standard"))
						)
					)
				)
			);
			response.OriginalException.Should().NotBeNull().And.BeOfType<ElasticsearchClientException>();
			response.OriginalException.Message.Should()
				.StartWith("Request failed to execute")
				.And.EndWith(
					"Type: illegal_argument_exception Reason: \"Custom Analyzer [custom] failed to find filter under name [ascii_folding]\""
				);

			client.DeleteIndex(index);
		}
	}
}

using System;
using Elastic.Xunit.Sdk;
using Elastic.Xunit.XunitPlumbing;
using Elasticsearch.Net;
using FluentAssertions;
using Tests.Framework.ManagedElasticsearch.Clusters;

namespace Tests.Reproduce
{
	public class GithubIssue2985 : IClusterFixture<WritableCluster>
	{
		private readonly WritableCluster _cluster;

		public GithubIssue2985(WritableCluster cluster) => _cluster = cluster;

		protected static string RandomString() => Guid.NewGuid().ToString("N").Substring(0, 8);

		[I]
		public void BadRequestErrorShouldBeWrappedInElasticsearchClientException()
		{
			var client = _cluster.Client;
			var index = $"gh2985-{RandomString()}";
			var response = client.CreateIndex(index, i=> i
				.Settings(s=>s
					.Analysis(a=>a
						.Analyzers(an=>an
							.Custom("custom", c=>c.Filters("ascii_folding").Tokenizer("standard"))
						)
					)
				)
			);
			response.OriginalException.Should().NotBeNull().And.BeOfType<ElasticsearchClientException>();
			response.OriginalException.Message.Should()
				.Contain(
					"Type: illegal_argument_exception Reason: \"Custom Analyzer [custom] failed to find filter under name [ascii_folding]\""
				);

			client.DeleteIndex(index);
		}
	}
}

Fix test name and assertion.

Fix test name and assertion.


using System;

namespace Table {
  public class Table {
    public int Width;
    public int Spacing;

    public Table(int width, int spacing) {
      Width = width;
      Spacing = spacing;
    }
  }
}

using System;

namespace Hangman {
  public class Table {
    public int Width;
    public int Spacing;

    public Table(int width, int spacing) {
      Width = width;
      Spacing = spacing;
    }
  }
}

Make the namespace uniform accross the project


using System;
using Structurizer.Extensions;

namespace Structurizer.Schemas
{
    public class StructureProperty : IStructureProperty
    {
        private readonly DynamicGetter _getter;

        public string Name { get; }
        public string Path { get; }
        public Type DataType { get; }
        public IStructureProperty Parent { get; }
        public bool IsRootMember { get; }
        public bool IsEnumerable { get; }
        public bool IsElement { get; }
        public Type ElementDataType { get; }

        public StructureProperty(StructurePropertyInfo info, DynamicGetter getter)
        {
            _getter = getter;

            Parent = info.Parent;
            Name = info.Name;
            DataType = info.DataType;
            IsRootMember = info.Parent == null;

            var isSimpleOrValueType = DataType.IsSimpleType() || DataType.IsValueType;
            IsEnumerable = !isSimpleOrValueType && DataType.IsEnumerableType();
            IsElement = Parent != null && (Parent.IsElement || Parent.IsEnumerable);
            ElementDataType = IsEnumerable ? DataType.GetEnumerableElementType() : null;
            Path = PropertyPathBuilder.BuildPath(this);
        }

        public virtual object GetValue(object item) => _getter.GetValue(item);
    }
}

using System;
using Structurizer.Extensions;

namespace Structurizer.Schemas
{
    public class StructureProperty : IStructureProperty
    {
        private readonly DynamicGetter _getter;

        public string Name { get; }
        public string Path { get; }
        public Type DataType { get; }
        public IStructureProperty Parent { get; }
        public bool IsRootMember { get; }
        public bool IsEnumerable { get; }
        public bool IsElement { get; }
        public Type ElementDataType { get; }

        public StructureProperty(StructurePropertyInfo info, DynamicGetter getter)
        {
            _getter = getter;

            Parent = info.Parent;
            Name = info.Name;
            DataType = info.DataType;
            IsRootMember = info.Parent == null;

            IsEnumerable = !DataType.IsSimpleType() && DataType.IsEnumerableType();
            IsElement = Parent != null && (Parent.IsElement || Parent.IsEnumerable);
            ElementDataType = IsEnumerable ? DataType.GetEnumerableElementType() : null;
            Path = PropertyPathBuilder.BuildPath(this);
        }

        public object GetValue(object item) => _getter(item);
    }
}

Simplify check and fix for new DynamicGetter


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

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

namespace Concordion.Internal.Util
{
    public class Check
    {
        public static void IsTrue(bool expression, string message, params object[] args)
        {
            if (!expression)
            {
                throw new Exception(String.Format(message, args));
            }
        }

        public static void IsFalse(bool expression, string message, params object[] args)
        {
            IsTrue(!expression, message, args);
        }

        public static void NotNull(object obj, string message, params object[] args)
        {
            IsTrue(obj != null, message, args);
        }

        public static void NotEmpty(string str, string message, params object[] args)
        {
            IsTrue(String.IsNullOrEmpty(str), message, args);
        }
    }
}

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

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

namespace Concordion.Internal.Util
{
    public class Check
    {
        public static void IsTrue(bool expression, string message, params object[] args)
        {
            if (!expression)
            {
                throw new Exception(String.Format(message, args));
            }
        }

        public static void IsFalse(bool expression, string message, params object[] args)
        {
            IsTrue(!expression, message, args);
        }

        public static void NotNull(object obj, string message, params object[] args)
        {
            IsTrue(obj != null, message, args);
        }

        public static void NotEmpty(string str, string message, params object[] args)
        {
            IsTrue(!String.IsNullOrEmpty(str), message, args);
        }
    }
}

Fix for the NotEmpty method.

Fix for the NotEmpty method.


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

namespace Microsoft.Bot.Connector
{
    public class ActionTypes
    {
        /// <summary>
        /// Client will open given url in the built-in browser.
        /// </summary>
        public const string OpenUrl = "openUrl";

        /// <summary>
        /// Client will post message to bot, so all other participants will see that was posted to the bot and who posted this.
        /// </summary>
        public const string ImBack = "imBack";

        /// <summary>
        /// Client will post message to bot privately, so other participants inside conversation will not see that was posted.
        /// </summary>
        public const string PostBack = "postBack";

        /// <summary>
        /// playback audio container referenced by url
        /// </summary>
        public const string PlayAudio = "playAudio";

        /// <summary>
        /// playback video container referenced by url
        /// </summary>
        public const string PlayVideo = "playVideo";

        /// <summary>
        /// show image referenced by url
        /// </summary>
        public const string ShowImage = "showImage";

        /// <summary>
        /// download file referenced by url
        /// </summary>
        public const string DownloadFile = "downloadFile";

        /// <summary>
        /// Signin button
        /// </summary>
        public const string Signin = "signin";
    }
}

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

namespace Microsoft.Bot.Connector
{
    public class ActionTypes
    {
        /// <summary>
        /// Client will open given url in the built-in browser.
        /// </summary>
        public const string OpenUrl = "openUrl";

        /// <summary>
        /// Client will post message to bot, so all other participants will see that was posted to the bot and who posted this.
        /// </summary>
        public const string ImBack = "imBack";

        /// <summary>
        /// Client will post message to bot privately, so other participants inside conversation will not see that was posted.
        /// </summary>
        public const string PostBack = "postBack";

        /// <summary>
        /// playback audio container referenced by url
        /// </summary>
        public const string PlayAudio = "playAudio";

        /// <summary>
        /// playback video container referenced by url
        /// </summary>
        public const string PlayVideo = "playVideo";

        /// <summary>
        /// show image referenced by url
        /// </summary>
        public const string ShowImage = "showImage";

        /// <summary>
        /// download file referenced by url
        /// </summary>
        public const string DownloadFile = "downloadFile";

        /// <summary>
        /// Signin button
        /// </summary>
        public const string Signin = "signin";

        /// <summary>
        /// Post message to bot
        /// </summary>
        public const string MessageBack = "messageBack";
    }
}

Add messageBack to action types.

Add messageBack to action types.


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

using System;
using System.IO;

namespace osu.Framework.Audio.Callbacks
{
    /// <summary>
    /// Implementation of <see cref="IFileProcedures"/> that supports reading from a <see cref="Stream"/>.
    /// </summary>
    public class DataStreamFileProcedures : IFileProcedures
    {
        private readonly Stream dataStream;

        public DataStreamFileProcedures(Stream data)
        {
            dataStream = data;
        }

        public void Close(IntPtr user)
        {
        }

        public long Length(IntPtr user)
        {
            if (dataStream?.CanSeek != true) return 0;

            try
            {
                return dataStream.Length;
            }
            catch
            {
                return 0;
            }
        }

        public unsafe int Read(IntPtr buffer, int length, IntPtr user)
        {
            if (dataStream?.CanRead != true) return 0;

            try
            {
                return dataStream.Read(new Span<byte>((void*)buffer, length));
            }
            catch
            {
                return 0;
            }
        }

        public bool Seek(long offset, IntPtr user)
        {
            if (dataStream?.CanSeek != true) return false;

            try
            {
                return dataStream.Seek(offset, SeekOrigin.Begin) == offset;
            }
            catch
            {
                return false;
            }
        }
    }
}

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

using System;
using System.IO;

#nullable enable

namespace osu.Framework.Audio.Callbacks
{
    /// <summary>
    /// Implementation of <see cref="IFileProcedures"/> that supports reading from a <see cref="Stream"/>.
    /// </summary>
    public class DataStreamFileProcedures : IFileProcedures
    {
        private readonly Stream dataStream;

        public DataStreamFileProcedures(Stream data)
        {
            dataStream = data;
        }

        public void Close(IntPtr user)
        {
        }

        public long Length(IntPtr user)
        {
            if (!dataStream.CanSeek) return 0;

            try
            {
                return dataStream.Length;
            }
            catch
            {
                return 0;
            }
        }

        public unsafe int Read(IntPtr buffer, int length, IntPtr user)
        {
            if (!dataStream.CanRead) return 0;

            try
            {
                return dataStream.Read(new Span<byte>((void*)buffer, length));
            }
            catch
            {
                return 0;
            }
        }

        public bool Seek(long offset, IntPtr user)
        {
            if (!dataStream.CanSeek) return false;

            try
            {
                return dataStream.Seek(offset, SeekOrigin.Begin) == offset;
            }
            catch
            {
                return false;
            }
        }
    }
}

Enable nullable and don't bother null checking at every read.


using System.Diagnostics;

namespace Microsoft.Build.Logging.StructuredLogger
{
    public class BinaryLog
    {
        public static Build ReadBuild(string filePath)
        {
            var eventSource = new BinaryLogReplayEventSource();

            byte[] sourceArchive = null;

            eventSource.OnBlobRead += (kind, bytes) =>
            {
                if (kind == BinaryLogRecordKind.SourceArchive)
                {
                    sourceArchive = bytes;
                }
            };

            StructuredLogger.SaveLogToDisk = false;
            StructuredLogger.CurrentBuild = null;
            var structuredLogger = new StructuredLogger();
            structuredLogger.Parameters = "build.buildlog";
            structuredLogger.Initialize(eventSource);

            var sw = Stopwatch.StartNew();
            eventSource.Replay(filePath);
            var elapsed = sw.Elapsed;

            var build = StructuredLogger.CurrentBuild;
            StructuredLogger.CurrentBuild = null;

            build.SourceFilesArchive = sourceArchive;
            // build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });

            return build;
        }
    }
}

using System.Diagnostics;

namespace Microsoft.Build.Logging.StructuredLogger
{
    public class BinaryLog
    {
        public static Build ReadBuild(string filePath)
        {
            var eventSource = new BinaryLogReplayEventSource();

            byte[] sourceArchive = null;

            eventSource.OnBlobRead += (kind, bytes) =>
            {
                if (kind == BinaryLogRecordKind.SourceArchive)
                {
                    sourceArchive = bytes;
                }
            };

            StructuredLogger.SaveLogToDisk = false;
            StructuredLogger.CurrentBuild = null;
            var structuredLogger = new StructuredLogger();
            structuredLogger.Parameters = "build.buildlog";
            structuredLogger.Initialize(eventSource);

            var sw = Stopwatch.StartNew();
            eventSource.Replay(filePath);
            var elapsed = sw.Elapsed;

            var build = StructuredLogger.CurrentBuild;
            StructuredLogger.CurrentBuild = null;

            if (build == null)
            {
                build = new Build() { Succeeded = false };
                build.AddChild(new Error() { Text = "Error when opening the file: " + filePath });
            }

            build.SourceFilesArchive = sourceArchive;
            // build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });

            return build;
        }
    }
}

Add an error message if opening the log file fails.


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

namespace Zermelo.App.UWP.Helpers
{
    static class ObservableCollectionExtensions
    {
        public static void MorphInto<TSource>(this ObservableCollection<TSource> first, IReadOnlyList<TSource> second)
        {
            var add = second.Except(first);
            var remove = first.Except(second);

            foreach (var i in remove)
                first.Remove(i);

            foreach (var i in add)
                first.Add(i);

            // If there are any changes to first, make sure it's in
            // the same order as second.
            if (add.Count() > 0 || remove.Count() > 0)
                for (int i = 0; i < second.Count(); i++)
                    first.Move(first.IndexOf(second.ElementAt(i)), i);
        }
    }
}

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

namespace Zermelo.App.UWP.Helpers
{
    static class ObservableCollectionExtensions
    {
        public static void MorphInto<TSource>(this ObservableCollection<TSource> first, IReadOnlyList<TSource> second)
        {
            var add = second.Except(first);
            var remove = first.Except(second);

            // TODO: Remove the diagnostic try-catch blocks, when #12 is fixed
            try
            {
                foreach (var i in remove)
                    first.Remove(i);
            }
            catch (InvalidOperationException ex)
            {
                throw new Exception("Exception in the Remove loop.", ex);
            }

            try
            {
                foreach (var i in add)
                    first.Add(i);
            }
            catch (InvalidOperationException ex)
            {
                throw new Exception("Exception in the Add loop.", ex);
            }

            try
            {
                // If there are any changes to first, make sure it's in
                // the same order as second.
                if (add.Count() > 0 || remove.Count() > 0)
                    for (int i = 0; i < second.Count(); i++)
                        first.Move(first.IndexOf(second.ElementAt(i)), i);
            }
            catch (InvalidOperationException ex)
            {
                throw new Exception("Exception in the reordering loop.", ex);
            }
        }
    }
}

Add diagnostic try-catch blocks to MorphInto()

Hopefully this will give some more insights into #12


namespace Mollie.Api.Models
{
    /// <summary>
    /// Payment method
    /// </summary>
    public enum Method
    {
        ideal,
        creditcard,
        mistercash,
        sofort,
        banktransfer,
        directdebit,
        belfius,
        kbc,
        bitcoin,
        paypal,
        paysafecard,
    }
}

namespace Mollie.Api.Models
{
    /// <summary>
    /// Payment method
    /// </summary>
    public enum Method
    {
        ideal,
        creditcard,
        mistercash,
        sofort,
        banktransfer,
        directdebit,
        belfius,
        kbc,
        bitcoin,
        paypal,
        paysafecard,
        giftcard,
    }
}

Add giftcard method to list of methods

Add giftcard method to list of methods

Mollie will be launching support for gift cards soon.


using System;
using System.Collections.ObjectModel;
using ReactiveUI;

namespace BindingTest.ViewModels
{
    public class MainWindowViewModel : ReactiveObject
    {
        private string _simpleBinding = "Simple Binding";

        public MainWindowViewModel()
        {
            Items = new ObservableCollection<TestItem>
            {
                new TestItem { StringValue = "Foo" },
                new TestItem { StringValue = "Bar" },
                new TestItem { StringValue = "Baz" },
            };

            ShuffleItems = ReactiveCommand.Create();
            ShuffleItems.Subscribe(_ =>
            {
                var r = new Random();
                Items[r.Next(Items.Count)] = Items[r.Next(Items.Count)];
            });
        }

        public ObservableCollection<TestItem> Items { get; }
        public ReactiveCommand<object> ShuffleItems { get; }

        public string SimpleBinding
        {
            get { return _simpleBinding; }
            set { this.RaiseAndSetIfChanged(ref _simpleBinding, value); }
        }
    }
}

using System;
using System.Collections.ObjectModel;
using ReactiveUI;

namespace BindingTest.ViewModels
{
    public class MainWindowViewModel : ReactiveObject
    {
        private string _simpleBinding = "Simple Binding";

        public MainWindowViewModel()
        {
            Items = new ObservableCollection<TestItem>
            {
                new TestItem { StringValue = "Foo" },
                new TestItem { StringValue = "Bar" },
                new TestItem { StringValue = "Baz" },
            };

            ShuffleItems = ReactiveCommand.Create();
            ShuffleItems.Subscribe(_ =>
            {
                var r = new Random();
                Items[1] = Items[r.Next(Items.Count)];
            });
        }

        public ObservableCollection<TestItem> Items { get; }
        public ReactiveCommand<object> ShuffleItems { get; }

        public string SimpleBinding
        {
            get { return _simpleBinding; }
            set { this.RaiseAndSetIfChanged(ref _simpleBinding, value); }
        }
    }
}

Make the shuffle more noticable.

Make the shuffle more noticable.


using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json.Linq;

namespace CmsEngine.Application.Helpers.Email
{
    public class ContactForm
    {
        [Required]
        [DataType(DataType.EmailAddress)]
        public string From { get; set; }
        [DataType(DataType.EmailAddress)]
        public string To { get; set; }
        [Required]
        public string Subject { get; set; }
        [Required]
        public string Message { get; set; }

        public ContactForm()
        {

        }

        public ContactForm(string to, string subject, string message)
        {
            To = to;
            Subject = subject;
            Message = message;
        }

        public override string ToString()
        {
            var jsonResult = new JObject(
                                        new JProperty("From", From),
                                        new JProperty("To", To),
                                        new JProperty("Subject", Subject),
                                        new JProperty("Message", Message)
                                    );
            return jsonResult.ToString();
        }
    }
}

using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json.Linq;

namespace CmsEngine.Application.Helpers.Email
{
    public class ContactForm
    {
        [Required]
        [DataType(DataType.EmailAddress)]
        public string From { get; set; }
        [DataType(DataType.EmailAddress)]
        public string To { get; set; }
        [Required]
        [MaxLength(150)]
        public string Subject { get; set; }
        [Required]
        [MaxLength(500)]
        public string Message { get; set; }

        public ContactForm()
        {

        }

        public ContactForm(string to, string subject, string message)
        {
            To = to;
            Subject = subject;
            Message = message;
        }

        public override string ToString()
        {
            var jsonResult = new JObject(
                                        new JProperty("From", From),
                                        new JProperty("To", To),
                                        new JProperty("Subject", Subject),
                                        new JProperty("Message", Message)
                                    );
            return jsonResult.ToString();
        }
    }
}

Set size for the fields on contact form

Set size for the fields on contact form


using System;

namespace ClosedXML_Sandbox
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Running {0}", nameof(PerformanceRunner.OpenTestFile));
            PerformanceRunner.TimeAction(PerformanceRunner.OpenTestFile);
            Console.WriteLine();

            Console.WriteLine("Running {0}", nameof(PerformanceRunner.RunInsertTable));
            PerformanceRunner.TimeAction(PerformanceRunner.RunInsertTable);
            Console.WriteLine();

            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
        }
    }
}

using System;

namespace ClosedXML_Sandbox
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Running {0}", nameof(PerformanceRunner.OpenTestFile));
            PerformanceRunner.TimeAction(PerformanceRunner.OpenTestFile);
            Console.WriteLine();

            // Disable this block by default - I don't use it often
#if false

            Console.WriteLine("Running {0}", nameof(PerformanceRunner.RunInsertTable));
            PerformanceRunner.TimeAction(PerformanceRunner.RunInsertTable);
            Console.WriteLine();
#endif

            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
        }
    }
}

Disable 2nd sandbox test by default

Disable 2nd sandbox test by default


namespace formulate.meta
{

    /// <summary>
    /// Constants relating to Formulate itself (i.e., does not
    /// include constants used by Formulate).
    /// </summary>
    public class Constants
    {

        /// <summary>
        /// This is the version of Formulate. It is used on
        /// assemblies and during the creation of the
        /// installer package.
        /// </summary>
        /// <remarks>
        /// Do not reformat this code. A grunt task reads this
        /// version number with a regular expression.
        /// </remarks>
        public const string Version = "1.3.4.0";

        /// <summary>
        /// The name of the Formulate package.
        /// </summary>
        public const string PackageName = "Formulate";

        /// <summary>
        /// The name of the Formulate package, in camel case.
        /// </summary>
        public const string PackageNameCamelCase = "formulate";

    }

}

namespace formulate.meta
{

    /// <summary>
    /// Constants relating to Formulate itself (i.e., does not
    /// include constants used by Formulate).
    /// </summary>
    public class Constants
    {

        /// <summary>
        /// This is the version of Formulate. It is used on
        /// assemblies and during the creation of the
        /// installer package.
        /// </summary>
        /// <remarks>
        /// Do not reformat this code. A grunt task reads this
        /// version number with a regular expression.
        /// </remarks>
        public const string Version = "1.3.5.0";

        /// <summary>
        /// The name of the Formulate package.
        /// </summary>
        public const string PackageName = "Formulate";

        /// <summary>
        /// The name of the Formulate package, in camel case.
        /// </summary>
        public const string PackageNameCamelCase = "formulate";

    }

}

Increment version number to 1.3.5.0

Increment version number to 1.3.5.0


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

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

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

        public TdfNode RootNode { get; private set; }

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

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

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

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

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

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

        public TdfNode RootNode { get; private set; }

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

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

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

Revert "Make all strings in loaded TdfNodes lowercase"

This reverts commit 652439451f8357ab4a323aaeb783daef5e5a5106.


using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;

namespace tweetz5.Utilities.Translate
{
    public class TranslationService
    {
        public readonly static TranslationService Instance = new TranslationService();
        public ITranslationProvider TranslationProvider { get; set; }
        public event EventHandler LanguageChanged;

        public CultureInfo CurrentLanguage
        {
            get { return Thread.CurrentThread.CurrentUICulture; }
            set
            {
                if (value.Equals(Thread.CurrentThread.CurrentUICulture) == false)
                {
                    Thread.CurrentThread.CurrentUICulture = value;
                    OnLanguageChanged();
                }
            }
        }

        private void OnLanguageChanged()
        {
            if (LanguageChanged != null)
            {
                LanguageChanged(this, EventArgs.Empty);
            }
        }

        public IEnumerable<CultureInfo> Languages
        {
            get { return (TranslationProvider != null) ? TranslationProvider.Languages : Enumerable.Empty<CultureInfo>(); }
        }

        public object Translate(string key)
        {
            if (TranslationProvider != null)
            {
                var translatedValue = TranslationProvider.Translate(key);
                if (translatedValue != null)
                {
                    return translatedValue;
                }
            }
            return string.Format("!{0}!", key);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;

namespace tweetz5.Utilities.Translate
{
    public class TranslationService
    {
        public readonly static TranslationService Instance = new TranslationService();
        public ITranslationProvider TranslationProvider { get; set; }
        public event EventHandler LanguageChanged;

        private TranslationService()
        {
        }

        public CultureInfo CurrentLanguage
        {
            get { return Thread.CurrentThread.CurrentUICulture; }
            set
            {
                if (value.Equals(Thread.CurrentThread.CurrentUICulture) == false)
                {
                    Thread.CurrentThread.CurrentUICulture = value;
                    OnLanguageChanged();
                }
            }
        }

        private void OnLanguageChanged()
        {
            if (LanguageChanged != null)
            {
                LanguageChanged(this, EventArgs.Empty);
            }
        }

        public IEnumerable<CultureInfo> Languages
        {
            get { return (TranslationProvider != null) ? TranslationProvider.Languages : Enumerable.Empty<CultureInfo>(); }
        }

        public object Translate(string key)
        {
            if (TranslationProvider != null)
            {
                var translatedValue = TranslationProvider.Translate(key);
                if (translatedValue != null)
                {
                    return translatedValue;
                }
            }
            return string.Format("!{0}!", key);
        }
    }
}

Add private constructor to singleton class

git-tfs-id: [https://mikeward.visualstudio.com/DefaultCollection]$/tweetz5;C1805


using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

namespace Harmony
{
	public static class Transpilers
	{
		public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null)
		{
			foreach (var instruction in instructions)
			{
				var method = instruction.operand as MethodBase;
				if (method == from)
				{
					instruction.opcode = callOpcode ?? OpCodes.Call;
					instruction.operand = to;
				}
				yield return instruction;
			}
		}

		public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
		{
			yield return new CodeInstruction(OpCodes.Ldstr, text);
			yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
			foreach (var instruction in instructions) yield return instruction;
		}

		// more added soon
	}
}

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

namespace Harmony
{
	public static class Transpilers
	{
		public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null)
		{
			if (from == null)
				throw new ArgumentException("Unexpected null argument", nameof(from));
			if (to == null)
				throw new ArgumentException("Unexpected null argument", nameof(to));

			foreach (var instruction in instructions)
			{
				var method = instruction.operand as MethodBase;
				if (method == from)
				{
					instruction.opcode = callOpcode ?? OpCodes.Call;
					instruction.operand = to;
				}
				yield return instruction;
			}
		}

		public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
		{
			yield return new CodeInstruction(OpCodes.Ldstr, text);
			yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
			foreach (var instruction in instructions) yield return instruction;
		}

		// more added soon
	}
}

Add null checks for MethodReplacer

Add null checks for MethodReplacer


using System.Web.Security;

using Oogstplanner.Models;

namespace Oogstplanner.Services
{
    public interface IMembershipService
    {
        bool ValidateUser(string userNameOrEmail, string password);
        void SetAuthCookie(string userNameOrEmail, bool createPersistentCookie);
        MembershipUser GetMembershipUserByEmail(string email);
        bool TryCreateUser(string username, string password, string email, out ModelError modelError);
        void AddUserToRole(string userName, string role);
        void SignOut();
        void RemoveUser(string userName);
    }
}

using System.Web.Security;

using Oogstplanner.Models;

namespace Oogstplanner.Services
{
    public interface IMembershipService
    {
        bool ValidateUser(string userNameOrEmail, string password);
        MembershipUser GetMembershipUserByEmail(string email);
        bool TryCreateUser(string username, string password, string email, out ModelError modelError);
        void SetAuthCookie(string userNameOrEmail, bool createPersistentCookie);
        void AddUserToRole(string userName, string role);
        void SignOut();
        void RemoveUser(string userName);
    }
}

Order methods in membership service interface by type


using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.BEncoding;
using System.Net;

namespace MonoTorrent.Tracker.Listeners
{
	public class ManualListener : ListenerBase
	{
		private bool running;

		public override bool Running
		{
			get { return running; }
		}

		public override void Start()
		{
			running = true;
		}

		public override void Stop()
		{
			running = false;
		}

		public BEncodedValue Handle(string rawUrl, IPAddress remoteAddress)
		{
			if (rawUrl == null)
				throw new ArgumentNullException("rawUrl");
			if (remoteAddress == null)
				throw new ArgumentOutOfRangeException("remoteAddress");

			bool isScrape = rawUrl.StartsWith("/scrape", StringComparison.OrdinalIgnoreCase);
			return Handle(rawUrl, remoteAddress, isScrape);
		}
	}
}

using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.BEncoding;
using System.Net;

namespace MonoTorrent.Tracker.Listeners
{
	public class ManualListener : ListenerBase
	{
		private bool running;

		public override bool Running
		{
			get { return running; }
		}

		public override void Start()
		{
			running = true;
		}

		public override void Stop()
		{
			running = false;
		}

		public BEncodedValue Handle(string rawUrl, IPAddress remoteAddress)
		{
			if (rawUrl == null)
				throw new ArgumentNullException("rawUrl");
			if (remoteAddress == null)
				throw new ArgumentOutOfRangeException("remoteAddress");

            rawUrl = rawUrl.Substring(rawUrl.LastIndexOf('/'));
			bool isScrape = rawUrl.StartsWith("/scrape", StringComparison.OrdinalIgnoreCase);
			return Handle(rawUrl, remoteAddress, isScrape);
		}
	}
}

Correct detection of scrape requests

Correct detection of scrape requests

svn path=/trunk/bitsharp/; revision=98390


using UnityEngine;
using System.Collections;

namespace Assets.BeMoBI.Paradigms.SearchAndFind {

	/// <summary>
	/// Represents all possible interactions for subject regarding the paradigm or trial behaviour
	/// </summary>
	public class SubjectInteractions : MonoBehaviour {

		private const string SUBMIT_INPUT = "Subject_Submit";
		private const string REQUIRE_PAUSE = "Subject_Requires_Break";

		ParadigmController controller;

		public bool TestMode = false;

		private bool homeButtonIsDown = false;

		void Awake()
		{
			controller = FindObjectOfType<ParadigmController>();
		}

		// Update is called once per frame
		void Update () {

			if (Input.GetAxis(SUBMIT_INPUT) > 0)
			{
				controller.SubjectTriesToSubmit();
			}

			if (Input.GetAxis(REQUIRE_PAUSE) > 0)
			{
				controller.ForceABreakInstantly();
			}
		}
	}
}

using UnityEngine;
using System.Collections;

namespace Assets.BeMoBI.Paradigms.SearchAndFind {

	/// <summary>
	/// Represents all possible interactions for subject regarding the paradigm or trial behaviour
	/// </summary>
	public class SubjectInteractions : MonoBehaviour {

		private const string SUBMIT_INPUT = "Subject_Submit";
		private const string REQUIRE_PAUSE = "Subject_Requires_Break";

		ParadigmController paradigm;

		void Awake()
		{
			paradigm = FindObjectOfType<ParadigmController>();
		}

		// Update is called once per frame
		void Update () {

			if (Input.GetAxis(SUBMIT_INPUT) > 0)
			{
				paradigm.SubjectTriesToSubmit();
			}

			if (Input.GetAxis(REQUIRE_PAUSE) > 0)
			{
				paradigm.ForceABreakInstantly();
			}
		}
	}
}

[REFAC] Change variable to paradigm instead of controller to improve naming consistency


using NUnit.Framework;

namespace Algorithms.Collections.Tests
{
	[TestFixture]
	public class SquareMatrixTests
	{
	}
}

using System.Collections.Generic;
using System.Globalization;
using System.Text;
using NUnit.Framework;

namespace Algorithms.Collections.Tests
{
	[TestFixture]
	public class SquareMatrixTests
	{
		[TestCaseSource("GetTestCases")]
		public void Multiply(TestCase testCase)
		{
			int[,] result = SquareMatrix.Multiply(testCase.Left, testCase.Right, (x, y) => x + y, (x, y) => x * y);
			CollectionAssert.AreEqual(result, testCase.Product);
		}

		public IEnumerable<TestCase> GetTestCases()
		{
			return new[]
				{
					new TestCase
						{
							Left = new[,] {{1, 2}, {3, 4}},
							Right = new[,] {{4, 3}, {2, 1}},
							Product = new[,] {{8, 5}, {20, 13}},
						},
				};
		}

		public class TestCase
		{
			public int[,] Left { get; set; }
			public int[,] Right { get; set; }
			public int[,] Product { get; set; }

			public override string ToString()
			{
				return string.Format("{{Left={0}, Right={1}, Product={2}}}", RenderMatrix(Left), RenderMatrix(Right), RenderMatrix(Product));
			}

			private static string RenderMatrix(int[,] matrix)
			{
				var builder = new StringBuilder();
				builder.Append("{");
				for (int row = 0; row < matrix.GetLength(0); row++)
				{
					if (row != 0)
						builder.Append(",");
					builder.Append("{");
					for (int column = 0; column < matrix.GetLength(1); column++)
					{
						if (column != 0)
							builder.Append(",");
						builder.Append(matrix[row, column]);
					}
					builder.Append("}");
				}
				builder.Append("}");
				return builder.ToString();
			}

			private static string RenderRow(int row, int[,] matrix, int padding)
			{
				var builder = new StringBuilder();
				if (row < matrix.GetLength(row))
				{
					for (int column = 0; column < matrix.GetLength(1); column++)
						builder.Append(matrix[row, column].ToString(CultureInfo.InvariantCulture).PadLeft(padding));
				}
				return builder.ToString();
			}
		}
	}
}

Add square matrix multiplication test case.


using UnityEngine;
using UnityEngine.UI;

public class LeaderboardEntry : MonoBehaviour
{

    [SerializeField] private Text _name;
    [SerializeField] private Text _time;
    [SerializeField] private Text _penality;

    public void SetInfo(Score score)
    {
        _name.text = score.Name;
        _time.text = score.Time.ToString();
        _penality.text = score.Penality.ToString();
    }
}

using UnityEngine;
using UnityEngine.UI;

public class LeaderboardEntry : MonoBehaviour
{

    [SerializeField] private Text _name;
    [SerializeField] private Text _time;
    [SerializeField] private Text _penality;

    public void SetInfo(Score score)
    {
        _name.text = score.Name;
        var time = score.Time;
        _time.text = string.Format("{0}:{1:00}", time / 60, time % 60);
        _penality.text = score.Penality.ToString();
    }
}

Convert seconds to actual minutes (works up to an hour...)


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

namespace TestingApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World\nPress any key to close...");

            Console.WriteLine("Added some text");

	    Console.WriteLine("Something new from Peter");

            Console.ReadKey();
        }
    }
}

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

namespace TestingApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World\nPress any key to close...");

            Console.WriteLine("Added some text");

            Console.ReadKey();
        }
    }
}

Revert "Something new from Peter"

Revert "Something new from Peter"

This reverts commit 0f0feb65c4743741b9cf5e8ba22cdcf115a8da7c.

This commit was not meant for master.


namespace Stripe
{
    using Newtonsoft.Json;

    public class InvoiceItemListOptions : ListOptionsWithCreated
    {
        [JsonProperty("customer")]
        public string CustomerId { get; set; }
    }
}

namespace Stripe
{
    using Newtonsoft.Json;

    public class InvoiceItemListOptions : ListOptionsWithCreated
    {
        [JsonProperty("customer")]
        public string CustomerId { get; set; }

        [JsonProperty("invoice")]
        public string InvoiceId { get; set; }

        [JsonProperty("pending")]
        public bool? Pending { get; set; }
    }
}

Add support for listing invoice items via invoice and pending


namespace Boxed.Templates.Test
{
    using System;
    using System.Threading;

    public static class CancellationTokenFactory
    {
        public static CancellationToken GetCancellationToken(TimeSpan? timeout) =>
            GetCancellationToken(timeout ?? TimeSpan.FromSeconds(30));

        public static CancellationToken GetCancellationToken(TimeSpan timeout) =>
            new CancellationTokenSource(timeout).Token;
    }
}

namespace Boxed.Templates.Test
{
    using System;
    using System.Threading;

    public static class CancellationTokenFactory
    {
        public static CancellationToken GetCancellationToken(TimeSpan? timeout) =>
            GetCancellationToken(timeout ?? TimeSpan.FromMinutes(1));

        public static CancellationToken GetCancellationToken(TimeSpan timeout) =>
            new CancellationTokenSource(timeout).Token;
    }
}

Increase default timeout time to one minute


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

public class AdminModeTriggerer : MonoBehaviour {
    private const float WAIT_TIME = 10f;
    public ActionBase AdminModeAction;

    public void Initialize() {
        StartCoroutine(WaitThenEnterAdminMode());
    }

    public IEnumerator WaitThenEnterAdminMode() {
        yield return new WaitForSeconds(WAIT_TIME);
        AdminModeAction.Act();
    }
}

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

public class AdminModeTriggerer : MonoBehaviour {
    private const float WAIT_TIME = 180f;
    public ActionBase AdminModeAction;

    public void Initialize() {
        StartCoroutine(WaitThenEnterAdminMode());
    }

    public IEnumerator WaitThenEnterAdminMode() {
        yield return new WaitForSeconds(WAIT_TIME);
        AdminModeAction.Act();
    }
}

Set adminModeTriggerer back to 180 seconds


        Your number is...

        @(Model)!!!

        Click this pink square to record a three second video of you saying
        @Model in your language of choice.

        Make yourself comfortable and get ready to join A Thousand Counts.

        3, 2, 1, COUNT!

        Your number is...

        @(Model)!!!

        Click this pink square to record a three second video of you saying
        @Model in your language of choice.

        If you don't like your number please hit refresh.

        Make yourself comfortable and get ready to join A Thousand Counts.

        3, 2, 1, COUNT!

Save ip after recording, check ip on index, version 1.0


using System.Collections.ObjectModel;
using System.ComponentModel;

namespace ProjectCDA.Data
{
    public class DataSource : INotifyPropertyChanged
    {
        private ObservableCollection<TwoPages> _Schedule;

        public DataSource()
        {
            AddSomeDummyData();
        }

        public ObservableCollection<TwoPages> Schedule
        {
            get
            {
                return _Schedule;
            }
            set
            {
                if (value != _Schedule)
                {
                    _Schedule = value;
                    PropertyChanged(this, new PropertyChangedEventArgs("Schedule"));
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void AddSomeDummyData()
        {
            ObservableCollection<TwoPages> TmpSchedule = new ObservableCollection<TwoPages>();

            for(int i=0; i<20; i++)
            {
                TwoPages pages = new TwoPages();
                pages.ID = i.ToString();
                pages.RightPage = i % 5 != 3;
                TmpSchedule.Add(new TwoPages());
            }

            Schedule = TmpSchedule;
        }
    }
}

using System.Collections.ObjectModel;
using System.ComponentModel;

namespace ProjectCDA.Data
{
    public class DataSource : INotifyPropertyChanged
    {
        private ObservableCollection<TwoPages> _Schedule;

        public DataSource()
        {
            AddSomeDummyData();
        }

        public ObservableCollection<TwoPages> Schedule
        {
            get
            {
                return _Schedule;
            }
            set
            {
                if (value != _Schedule)
                {
                    _Schedule = value;
                    PropertyChanged(this, new PropertyChangedEventArgs("Schedule"));
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void AddSomeDummyData()
        {
            ObservableCollection<TwoPages> TmpSchedule = new ObservableCollection<TwoPages>();

            for(int i=0; i<20; i++)
            {
                TwoPages pages = new TwoPages();
                pages.ID = i.ToString();
                pages.RightPage = i % 5 != 3;
                TmpSchedule.Add(pages);
            }

            Schedule = TmpSchedule;
        }
    }
}

Fix new object was added into collection instead of the one we made just above.


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

using Microsoft.CodeAnalysis.Options;

namespace Microsoft.CodeAnalysis.SymbolSearch
{
    internal static class SymbolSearchOptions
    {
        private const string LocalRegistryPath = @"Roslyn\Features\SymbolSearch\";

        public static readonly Option<bool> Enabled = new Option<bool>(
            nameof(SymbolSearchOptions), nameof(Enabled), defaultValue: true,
            storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(Enabled)));

        public static PerLanguageOption<bool> SuggestForTypesInReferenceAssemblies =
            new PerLanguageOption<bool>(nameof(SymbolSearchOptions), nameof(SuggestForTypesInReferenceAssemblies), defaultValue: false,
                storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SuggestForTypesInReferenceAssemblies"));

        public static PerLanguageOption<bool> SuggestForTypesInNuGetPackages =
            new PerLanguageOption<bool>(nameof(SymbolSearchOptions), nameof(SuggestForTypesInNuGetPackages), defaultValue: false,
                storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SuggestForTypesInNuGetPackages"));
    }
}

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

using Microsoft.CodeAnalysis.Options;

namespace Microsoft.CodeAnalysis.SymbolSearch
{
    internal static class SymbolSearchOptions
    {
        private const string LocalRegistryPath = @"Roslyn\Features\SymbolSearch\";

        public static readonly Option<bool> Enabled = new Option<bool>(
            nameof(SymbolSearchOptions), nameof(Enabled), defaultValue: true,
            storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(Enabled)));

        public static PerLanguageOption<bool> SuggestForTypesInReferenceAssemblies =
            new PerLanguageOption<bool>(nameof(SymbolSearchOptions), nameof(SuggestForTypesInReferenceAssemblies), defaultValue: true,
                storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SuggestForTypesInReferenceAssemblies"));

        public static PerLanguageOption<bool> SuggestForTypesInNuGetPackages =
            new PerLanguageOption<bool>(nameof(SymbolSearchOptions), nameof(SuggestForTypesInNuGetPackages), defaultValue: false,
                storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SuggestForTypesInNuGetPackages"));
    }
}

Enable suggestions for types in reference assemblies by default

See #20255


@model SFA.DAS.EmployerUsers.Web.Models.AccessCodeViewModel

Register

@if (!Model.Valid)
{

            Invalid Code

}

<form method="post">
    <fieldset>
        <legend class="visuallyhidden">Access code for user registration</legend>

            Access Code
            <input class="form-control" id="AccessCode" name="AccessCode">

    </fieldset>
    <button type="submit" class="button">Activate Account</button>
</form>

@model SFA.DAS.EmployerUsers.Web.Models.AccessCodeViewModel

@{
    var invalidAttributes = Model.Valid ? "aria-invalid=\"true\" aria-labeledby=\"invalidMessage\"" : "";
}

Register

@if (!Model.Valid)
{

            Invalid Code

}

<form method="post">
    <fieldset>
        <legend class="visuallyhidden">Access code for user registration</legend>

            Access Code
            <input @invalidAttributes autofocus="autofocus" aria-required="true" class="form-control" id="AccessCode" name="AccessCode">

    </fieldset>
    <button type="submit" class="button">Activate Account</button>
</form>

Add autofocus to AccessCode entry so invalid entry will force focus onto the input field


using Infra.Authentications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Security.Claims;
using System.Threading;
using Infra.Events;

namespace Infra.Authentications.Identity.Services
{
    public class Authenticator : IAuthenticator
    {

        public Authenticator(IEnumerable<IAuthenticationObserver> monitors)
        {
            Monitors = monitors;
        }

        IEnumerable<IAuthenticationObserver> Monitors { get; }

        public IPAddress ClientIP {
            get
            {
                IPAddress address;
                if (IPAddress.TryParse(HttpContext.Current.Request.UserHostAddress, out address))
                    return address;

                return IPAddress.None;
            }
        }

        public string ImpersonatorId
        {
            get
            {
                if (!IsAuthenticated)
                    return null;

                return Identity.GetImpersonatorId();
            }
        }

        public string UserId
        {
            get
            {
                if (!IsAuthenticated)
                    return null;

                foreach (var monitor in Monitors)
                    monitor.Observe(this);

                return Identity.Name;
            }
        }

        ClaimsPrincipal Principal => Thread.CurrentPrincipal as ClaimsPrincipal;
        ClaimsIdentity Identity => Principal?.Identity as ClaimsIdentity;
        bool IsAuthenticated => Identity?.IsAuthenticated ?? false;

    }
}

using Infra.Authentications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Security.Claims;
using System.Threading;
using Infra.Events;

namespace Infra.Authentications.Identity.Services
{
    public class Authenticator : IAuthenticator
    {

        public Authenticator(IEnumerable<IAuthenticationObserver> monitors)
        {
            Monitors = monitors;
        }

        IEnumerable<IAuthenticationObserver> Monitors { get; }

        public IPAddress ClientIP {
            get
            {
                IPAddress address;
                if (IPAddress.TryParse(HttpContext.Current.Request.Headers.GetValues("CF-Connecting-IP").FirstOrDefault(), out address))
                    return address;

                return IPAddress.None;
            }
        }

        public string ImpersonatorId
        {
            get
            {
                if (!IsAuthenticated)
                    return null;

                return Identity.GetImpersonatorId();
            }
        }

        public string UserId
        {
            get
            {
                if (!IsAuthenticated)
                    return null;

                foreach (var monitor in Monitors)
                    monitor.Observe(this);

                return Identity.Name;
            }
        }

        ClaimsPrincipal Principal => Thread.CurrentPrincipal as ClaimsPrincipal;
        ClaimsIdentity Identity => Principal?.Identity as ClaimsIdentity;
        bool IsAuthenticated => Identity?.IsAuthenticated ?? false;

    }
}

Use CloudFlare CF-Connecting-IP to access user ip address


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

namespace MetroTrilithon.Lifetime
{
	public static class DisposableExtensions
	{
		/// <summary>
		/// <see cref="IDisposable"/> オブジェクトを、指定した <see cref="IDisposableHolder.CompositeDisposable"/> に追加します。
		/// </summary>
		public static T AddTo<T>(this T disposable, IDisposableHolder obj) where T : IDisposable
		{
			if (obj == null)
			{
				disposable.Dispose();
				return disposable;
			}

			obj.CompositeDisposable.Add(disposable);
			return disposable;
		}
	}
}

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

namespace MetroTrilithon.Lifetime
{
	public static class DisposableExtensions
	{
		/// <summary>
		/// <see cref="IDisposable"/> オブジェクトを、指定した <see cref="IDisposableHolder.CompositeDisposable"/> に追加します。
		/// </summary>
		public static T AddTo<T>(this T disposable, IDisposableHolder obj) where T : IDisposable
		{
			if (obj == null)
			{
				disposable.Dispose();
			}
			else
			{
				obj.CompositeDisposable.Add(disposable);
			}

			return disposable;
		}

		public static T AddTo<T>(this T disposable, MultipleDisposable obj) where T : IDisposable
		{
			if (obj == null)
			{
				disposable.Dispose();
			}
			else
			{
				obj.Add(disposable);
			}

			return disposable;
		}
	}
}

Add extension method for StatefulModel.MultipleDisposable.


using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;

namespace Promact.Trappist.Core.Controllers
{
    [Route("api/question")]
    public class QuestionsController : Controller
    {
        private readonly IQuestionRepository _questionsRepository;
        public QuestionsController(IQuestionRepository questionsRepository)
        {
            _questionsRepository = questionsRepository;
        }

        [HttpGet]
        /// <summary>
        /// Gets all questions
        /// </summary>
        /// <returns>Questions list</returns>
        public IActionResult GetQuestions()
        {
            var questions = _questionsRepository.GetAllQuestions();
            return Json(questions);
        }
        [HttpPost]
        /// <summary>
        ///
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
            return Ok();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
            return Ok();
        }
    }
}

using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;

namespace Promact.Trappist.Core.Controllers
{
    [Route("api/question")]
    public class QuestionsController : Controller
    {
        private readonly IQuestionRepository _questionsRepository;
        public QuestionsController(IQuestionRepository questionsRepository)
        {
            _questionsRepository = questionsRepository;
        }

        [HttpGet]
        /// <summary>
        /// Gets all questions
        /// </summary>
        /// <returns>Questions list</returns>
        public IActionResult GetQuestions()
        {
            var questions = _questionsRepository.GetAllQuestions();
            return Json(questions);
        }

        [HttpPost]
        /// <summary>
        /// Add single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
            return Ok();
        }

        /// <summary>
        /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestionOption"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
            return Ok();
        }
    }
}

Update server side API for single multiple answer question


using System.Globalization;

namespace Agens.Stickers
{
    public static class StickerEditorUtility
    {
        /// <summary>
        /// Checks the file extension of a filename
        /// </summary>
        /// <param name="fileName">filename with extension or full path of a file</param>
        /// <returns>True if the file type is supported for stickers</returns>
        public static bool HasValidFileExtension(string fileName)
        {
            var s = fileName.ToLower(CultureInfo.InvariantCulture);
            return s.EndsWith(".png") || s.EndsWith(".gif") || s.EndsWith(".jpg") || s.EndsWith(".jpeg");
        }

        /// <summary>
        /// Creates a readable string in Bytes or KiloBytes of a file
        /// 1 kB is 1000B in this case
        /// </summary>
        /// <param name="size">File size in byte</param>
        /// <returns>File size with fitting units</returns>
        public static string GetFileSizeString(long size)
        {
            if (size < 1000)
            {
                return size.ToString() + "B";
            }
            else
            {
                return (size / 1000L).ToString() + " kB";
            }
        }
    }
}

using System.Globalization;

namespace Agens.Stickers
{
    public static class StickerEditorUtility
    {
        /// <summary>
        /// Checks the file extension of a filename
        /// </summary>
        /// <param name="fileName">filename with extension or full path of a file</param>
        /// <returns>True if the file type is supported for stickers</returns>
        public static bool HasValidFileExtension(string fileName)
        {
            var s = fileName.ToLower(CultureInfo.InvariantCulture);
            return s.EndsWith(".png") || s.EndsWith(".gif") || s.EndsWith(".jpg") || s.EndsWith(".jpeg");
        }

        /// <summary>
        /// Creates a readable string in Bytes or KiloBytes of a file
        /// 1 kB is 1000B in this case
        /// </summary>
        /// <param name="size">File size in byte</param>
        /// <returns>File size with fitting units</returns>
        public static string GetFileSizeString(long size)
        {
            if (size < 1000)
            {
                return size.ToString() + "B";
            }
            else
            {
                return (size / 1000L).ToString() + " kB";
            }
        }

        /// <summary>
        /// Checks if the filetype is an animated file or not.
        /// Supported file checks: .gif
        /// </summary>
        /// <param name="filePath">Path to the file or filename</param>
        /// <returns>True if the file type supports animations</returns>
        public static bool IsAnimatedTexture(string filePath)
        {
            var s = filePath.ToLower(CultureInfo.InvariantCulture);
            return s.EndsWith(".gif");
        }
    }
}

Add check if a file supports animations

Add check if a file supports animations

Right now it only checks for gifs, this method could include a check a png is an apng