namespace EFRepository
{
    /// <summary>
    /// IRepository
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    public interface IRepository<TEntity> where TEntity : class
    {
        /// <summary>
        /// Adds the specified data.
        /// </summary>
        /// <param name="data">The data.</param>
        void Add(TEntity data);

        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <returns></returns>
        int SaveChanges();
    }
}

using System.Collections.Generic;

namespace EFRepository
{
    /// <summary>
    /// IRepository
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    public interface IRepository<TEntity> where TEntity : class
    {
        /// <summary>
        /// Adds the specified data.
        /// </summary>
        /// <param name="data">The data.</param>
        void Add(TEntity data);

        /// <summary>
        /// Adds the range.
        /// </summary>
        /// <param name="datalist">The datalist.</param>
        void AddRange(IEnumerable<TEntity> datalist);

        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <returns></returns>
        int SaveChanges();
    }
}

Add add range funciton to interface

feat(repository): Add add range funciton to interface

Add add range function to IRepository interface


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

public class ReturnToBounds : MonoBehaviour
{
    [SerializeField]
    Transform frontBounds = null;

    [SerializeField]
    Transform backBounds = null;

    [SerializeField]
    Transform leftBounds = null;

    [SerializeField]
    Transform rightBounds = null;

    [SerializeField]
    Transform bottomBounds = null;

    [SerializeField]
    Transform topBounds = null;

    Vector3 positionAtStart;

    // Start is called before the first frame update
    void Start()
    {
        positionAtStart = transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        if (transform.position.x > rightBounds.position.x || transform.position.x < leftBounds.position.x ||
            transform.position.y > topBounds.position.y || transform.position.y < bottomBounds.position.y ||
            transform.position.z > backBounds.position.z || transform.position.z < frontBounds.position.z)
        {
            transform.position = positionAtStart;
        }
    }
}

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

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

namespace Microsoft.MixedReality.Toolkit.Examples.Experimental.Demos
{
    public class ReturnToBounds : MonoBehaviour
    {
        [SerializeField]
        private Transform frontBounds = null;

        public Transform FrontBounds
        {
            get => frontBounds;
            set => frontBounds = value;
        }

        [SerializeField]
        private Transform backBounds = null;

        public Transform BackBounds
        {
            get => backBounds;
            set => backBounds = value;
        }

        [SerializeField]
        private Transform leftBounds = null;

        public Transform LeftBounds
        {
            get => leftBounds;
            set => leftBounds = value;
        }

        [SerializeField]
        private Transform rightBounds = null;

        public Transform RightBounds
        {
            get => rightBounds;
            set => rightBounds = value;
        }

        [SerializeField]
        private Transform bottomBounds = null;

        public Transform BottomBounds
        {
            get => bottomBounds;
            set => bottomBounds = value;
        }

        [SerializeField]
        private Transform topBounds = null;

        public Transform TopBounds
        {
            get => topBounds;
            set => topBounds = value;
        }

        private Vector3 positionAtStart;

        // Start is called before the first frame update
        void Start()
        {
            positionAtStart = transform.position;
        }

        // Update is called once per frame
        void Update()
        {
            if (transform.position.x > rightBounds.position.x || transform.position.x < leftBounds.position.x ||
                transform.position.y > topBounds.position.y || transform.position.y < bottomBounds.position.y ||
                transform.position.z > backBounds.position.z || transform.position.z < frontBounds.position.z)
            {
                transform.position = positionAtStart;
            }
        }
    }
}

Make demo script comply with guidelines

Make demo script comply with guidelines


using System;
using System.Linq;
using System.Net;

namespace BmpListener.Bgp
{
    public class IPAddrPrefix
    {
        public IPAddrPrefix(ArraySegment<byte> data, AddressFamily afi = AddressFamily.IP)
        {
            DecodeFromBytes(data, afi);
        }

        public byte Length { get; private set; }
        public IPAddress Prefix { get; private set; }

        public override string ToString()
        {
            return ($"{Prefix}/{Length}");
        }

        public int GetByteLength()
        {
            return 1 + (Length + 7) / 8;
        }

        public void DecodeFromBytes(ArraySegment<byte> data, Bgp.AddressFamily afi)
        {
            Length = data.ElementAt(0);
            if (Length <= 0) return;
            var byteLength = (Length + 7) / 8;
            var ipBytes = afi == AddressFamily.IP
                ? new byte[4]
                : new byte[16];
            Buffer.BlockCopy(data.ToArray(), 1, ipBytes, 0, byteLength);
            Prefix = new IPAddress(ipBytes);
        }
    }
}

using System;
using System.Net;

namespace BmpListener.Bgp
{
    public class IPAddrPrefix
    {
        public IPAddrPrefix(byte[] data, AddressFamily afi = AddressFamily.IP)
        {
            DecodeFromBytes(data, afi);
        }

        public byte Length { get; private set; }
        public IPAddress Prefix { get; private set; }

        public override string ToString()
        {
            return ($"{Prefix}/{Length}");
        }

        public int GetByteLength()
        {
            return 1 + (Length + 7) / 8;
        }

        public void DecodeFromBytes(byte[] data, AddressFamily afi)
        {
            Length = data.ElementAt(0);
            if (Length <= 0) return;
            var byteLength = (Length + 7) / 8;
            var ipBytes = afi == AddressFamily.IP
                ? new byte[4]
                : new byte[16];
            Buffer.BlockCopy(data, 1, ipBytes, 0, byteLength);
            Prefix = new IPAddress(ipBytes);
        }
    }
}

Change ctor parameter to byte array

Change ctor parameter to byte array


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

namespace Archon.WebApi
{
	public abstract class Link
	{
		public Authorization Authorization { get; set; }

		public HttpRequestMessage CreateRequest()
		{
			var req = CreateRequestInternal();

			if (Authorization != null)
				req.Headers.Authorization = Authorization.AsHeader();

			return req;
		}

		protected abstract HttpRequestMessage CreateRequestInternal();
	}

	public abstract class Link<TResponse> : Link
	{
		public Task<TResponse> ParseResponseAsync(HttpResponseMessage response)
		{
			if (response == null)
				throw new ArgumentNullException("response");

			return ParseResponseInternal(response);
		}

		protected abstract Task<TResponse> ParseResponseInternal(HttpResponseMessage response);
	}
}

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

namespace Archon.WebApi
{
	public abstract class Link
	{
		public Authorization Authorization { get; set; }

		public HttpRequestMessage CreateRequest()
		{
			var req = CreateRequestInternal();

			var authToken = GetAuthToken();
			if (authToken != null)
				req.Headers.Authorization = authToken.AsHeader();

			return req;
		}

		Authorization GetAuthToken()
		{
			if (Authorization != null)
				return Authorization;

			var token = Thread.CurrentPrincipal as AuthToken;
			if (token != null)
				return Authorization.Bearer(token.Token);

			return null;
		}

		protected abstract HttpRequestMessage CreateRequestInternal();
	}

	public abstract class Link<TResponse> : Link
	{
		public Task<TResponse> ParseResponseAsync(HttpResponseMessage response)
		{
			if (response == null)
				throw new ArgumentNullException("response");

			return ParseResponseInternal(response);
		}

		protected abstract Task<TResponse> ParseResponseInternal(HttpResponseMessage response);
	}
}

Use current principal if provided for auth


<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewBag.Title - Atata.Bootstrap.TestApp v5</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    @RenderSection("styles", false)

@ViewBag.Title

        @RenderBody()

    @RenderSection("scripts", false)

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewBag.Title - Atata.Bootstrap.TestApp v5</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet">
    @RenderSection("styles", false)

@ViewBag.Title

        @RenderBody()

    @RenderSection("scripts", false)

Update Bootstrap package in v5 test pages to v5.2.2


using System;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AdmoInstallerCustomAction;
using System.Windows;

namespace AdmoTests.CustomActionTests
{
    [TestClass]
    public class CustomActionTests
    {

        [TestMethod]
        public void TestMethod1()
        {
          //Will have to use gui testing tools here

            //ManualResetEvent syncEvent = new ManualResetEvent(false);
            //Thread t = new Thread(() =>
            //{
            //    var app = new Application();
            //    app.Run(new DownloadRuntimeWPF());
            // //   syncEvent.Set();
            //});
            //t.SetApartmentState(ApartmentState.STA);

            //t.Start();
            //t.Join();

        }
    }
}

using System;
using System.Threading;
using Admo;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AdmoInstallerCustomAction;
using System.Windows;

namespace AdmoTests.CustomActionTests
{
    [TestClass]
    public class CustomActionTests
    {

        [TestMethod]
        public void TestRunWPFOnSTAThread()
        {
          //Will have to use gui testing tools here

            Thread t = new Thread(() =>
            {
                var app = new Application();
                app.Run(new DownloadRuntimeWPF());
            });
            t.SetApartmentState(ApartmentState.STA);

            t.Start();
           t.Abort();

        }
    }
}

Test to run gui on STA thread

Test to run gui on STA thread


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

namespace FizzBuzz.Specification.AutomationLayer
{
  [Binding]
  public class StepDefinitions
  {
    [Given(@"the current number is '(.*)'")]
    public void GivenTheCurrentNumberIs(int p0)
    {
      ScenarioContext.Current.Pending();
    }

    [When(@"I print the number")]
    public void WhenIPrintTheNumber()
    {
      ScenarioContext.Current.Pending();
    }

    [Then(@"the result is '(.*)'")]
    public void ThenTheResultIs(int p0)
    {
      ScenarioContext.Current.Pending();
    }
  }
}

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

namespace FizzBuzz.Specification.AutomationLayer
{
  [Binding]
  public class StepDefinitions
  {
    private int currentNumber;

    [Given(@"the current number is '(.*)'")]
    public void GivenTheCurrentNumberIs(int currentNumber)
    {
      this.currentNumber = currentNumber;
    }

    [When(@"I print the number")]
    public void WhenIPrintTheNumber()
    {
      ScenarioContext.Current.Pending();
    }

    [Then(@"the result is '(.*)'")]
    public void ThenTheResultIs(int p0)
    {
      ScenarioContext.Current.Pending();
    }
  }
}

Implement first step of automation layer


using Microsoft.Extensions.DependencyInjection;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Install.InstallSteps;
using Umbraco.Cms.Core.Install.Models;
using Umbraco.Cms.Infrastructure.Install;
using Umbraco.Cms.Infrastructure.Install.InstallSteps;
using Umbraco.Extensions;

namespace Umbraco.Cms.Infrastructure.DependencyInjection
{
    public static partial class UmbracoBuilderExtensions
    {
        /// <summary>
        /// Adds the services for the Umbraco installer
        /// </summary>
        internal static IUmbracoBuilder AddInstaller(this IUmbracoBuilder builder)
        {
            // register the installer steps
            builder.Services.AddScoped<InstallSetupStep, NewInstallStep>();
            builder.Services.AddScoped<InstallSetupStep, UpgradeStep>();
            builder.Services.AddScoped<InstallSetupStep, FilePermissionsStep>();
            builder.Services.AddScoped<InstallSetupStep, TelemetryIdentifierStep>();
            builder.Services.AddScoped<InstallSetupStep, DatabaseConfigureStep>();
            builder.Services.AddScoped<InstallSetupStep, DatabaseInstallStep>();
            builder.Services.AddScoped<InstallSetupStep, DatabaseUpgradeStep>();

            builder.Services.AddScoped<InstallSetupStep, CompleteInstallStep>();

            builder.Services.AddTransient<InstallStepCollection>();
            builder.Services.AddUnique<InstallHelper>();

            return builder;
        }
    }
}

using Microsoft.Extensions.DependencyInjection;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Install.InstallSteps;
using Umbraco.Cms.Core.Install.Models;
using Umbraco.Cms.Infrastructure.Install;
using Umbraco.Cms.Infrastructure.Install.InstallSteps;
using Umbraco.Extensions;

namespace Umbraco.Cms.Infrastructure.DependencyInjection
{
    public static partial class UmbracoBuilderExtensions
    {
        /// <summary>
        /// Adds the services for the Umbraco installer
        /// </summary>
        internal static IUmbracoBuilder AddInstaller(this IUmbracoBuilder builder)
        {
            // register the installer steps
            builder.Services.AddScoped<InstallSetupStep, NewInstallStep>();
            builder.Services.AddScoped<InstallSetupStep, UpgradeStep>();
            builder.Services.AddScoped<InstallSetupStep, FilePermissionsStep>();
            builder.Services.AddScoped<InstallSetupStep, TelemetryIdentifierStep>();
            builder.Services.AddScoped<InstallSetupStep, DatabaseConfigureStep>();
            builder.Services.AddScoped<InstallSetupStep, DatabaseInstallStep>();
            builder.Services.AddScoped<InstallSetupStep, DatabaseUpgradeStep>();

            builder.Services.AddScoped<InstallSetupStep, CompleteInstallStep>();

            builder.Services.AddTransient<InstallStepCollection>();
            builder.Services.AddUnique<InstallHelper>();

            builder.Services.AddTransient<PackageMigrationRunner>();

            return builder;
        }
    }
}

Fix integration tests - register PackageMigrationRunner


using System.Threading.Tasks;
using Microsoft.Owin;
using System.Linq;
using System;
using Foundation.Api.Implementations;
using System.Threading;

namespace Foundation.Api.Middlewares
{
    public class OwinCacheResponseMiddleware : DefaultOwinActionFilterMiddleware
    {
        public OwinCacheResponseMiddleware()
        {

        }

        public OwinCacheResponseMiddleware(OwinMiddleware next)
            : base(next)
        {

        }

        public override async Task OnActionExecutingAsync(IOwinContext owinContext)
        {
            if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Cache-Control", StringComparison.InvariantCultureIgnoreCase)))
                owinContext.Response.Headers.Remove("Cache-Control");
            owinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=31536000" });

            if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Pragma", StringComparison.InvariantCultureIgnoreCase)))
                owinContext.Response.Headers.Remove("Pragma");
            owinContext.Response.Headers.Add("Pragma", new[] { "public" });

            if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Expires", StringComparison.InvariantCultureIgnoreCase)))
                owinContext.Response.Headers.Remove("Expires");
            owinContext.Response.Headers.Add("Expires", new[] { "31536000" });

            await base.OnActionExecutingAsync(owinContext);
        }
    }
}

using System.Threading.Tasks;
using Microsoft.Owin;
using System.Linq;
using System;
using Foundation.Api.Implementations;

namespace Foundation.Api.Middlewares
{
    public class OwinCacheResponseMiddleware : DefaultOwinActionFilterMiddleware
    {
        public OwinCacheResponseMiddleware()
        {

        }

        public OwinCacheResponseMiddleware(OwinMiddleware next)
            : base(next)
        {

        }

        public override async Task OnActionExecutingAsync(IOwinContext owinContext)
        {
            if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Cache-Control", StringComparison.InvariantCultureIgnoreCase)))
                owinContext.Response.Headers.Remove("Cache-Control");
            owinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=31536000" });

            if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Pragma", StringComparison.InvariantCultureIgnoreCase)))
                owinContext.Response.Headers.Remove("Pragma");
            owinContext.Response.Headers.Add("Pragma", new[] { "public" });

            if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Expires", StringComparison.InvariantCultureIgnoreCase)))
                owinContext.Response.Headers.Remove("Expires");
            owinContext.Response.Headers.Add("Expires", new[] { "max" });

            await base.OnActionExecutingAsync(owinContext);
        }
    }
}

Set expires header to max when response is intented to be cached, so browsers will not use try-get pattern for those resources next time.


using System.IO;
using System.Xml;

namespace VanillaTransformer.PostTransformations.XML
{
    public class ReFormatXMLTransformation:IPostTransformation
    {
        public string Name { get { return "ReFormatXML"; } }
        public string Execute(string configContent)
        {
            var settings = new XmlWriterSettings()
            {
                Indent = true,
                IndentChars = "    ",
                NewLineChars = "\r\n",
                NewLineHandling = NewLineHandling.Replace,
            };
            var xDocument = new XmlDocument();
            xDocument.LoadXml(configContent);
            using (var textWriter = new StringWriter())
            {
                using (var writer = XmlWriter.Create(textWriter,settings))
                {
                    xDocument.WriteTo(writer);
                }
                return textWriter.ToString();
            }
        }
    }
}

using System;
using System.IO;
using System.Xml;

namespace VanillaTransformer.PostTransformations.XML
{
    public class ReFormatXMLTransformation:IPostTransformation
    {
        public string Name { get { return "ReFormatXML"; } }
        public string Execute(string configContent)
        {
            var settings = new XmlWriterSettings()
            {
                Indent = true,
                IndentChars = "    ",
                NewLineChars = Environment.NewLine,
                NewLineHandling = NewLineHandling.Replace,
            };
            var xDocument = new XmlDocument();
            xDocument.LoadXml(configContent);
            using (var textWriter = new StringWriter())
            {
                using (var writer = XmlWriter.Create(textWriter,settings))
                {
                    xDocument.WriteTo(writer);
                }
                return textWriter.ToString();
            }
        }
    }
}

Set line ending according to the enviroment in ReFormatXML


using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;

namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
    public class ImportLevyDeclarationsJob
    {
        private readonly IMessageSession _messageSession;

        public ImportLevyDeclarationsJob(IMessageSession messageSession)
        {
            _messageSession = messageSession;
        }

        public Task Run([TimerTrigger("0 0 15 20 * *")] TimerInfo timer, ILogger logger)
        {
            return _messageSession.Send(new ImportLevyDeclarationsCommand());
        }
    }
}

using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;

namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
    public class ImportLevyDeclarationsJob
    {
        private readonly IMessageSession _messageSession;

        public ImportLevyDeclarationsJob(IMessageSession messageSession)
        {
            _messageSession = messageSession;
        }

        public Task Run([TimerTrigger("0 0 15 23 * *")] TimerInfo timer, ILogger logger)
        {
            return _messageSession.Send(new ImportLevyDeclarationsCommand());
        }
    }
}

Update Timer for Levy to 23rd

Update Timer for Levy to 23rd


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

using osu.Framework.Platform;
using osu.Framework.Testing;

namespace osu.Game.Configuration
{
    [ExcludeFromDynamicCompile]
    public class DevelopmentOsuConfigManager : OsuConfigManager
    {
        protected override string Filename => base.Filename.Replace(".ini", ".dev.ini");

        public DevelopmentOsuConfigManager(Storage storage)
            : base(storage)
        {
            LookupKeyBindings = _ => "unknown";
            LookupSkinName = _ => "unknown";
        }
    }
}

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

using osu.Framework.Platform;
using osu.Framework.Testing;

namespace osu.Game.Configuration
{
    [ExcludeFromDynamicCompile]
    public class DevelopmentOsuConfigManager : OsuConfigManager
    {
        protected override string Filename => base.Filename.Replace(".ini", ".dev.ini");

        public DevelopmentOsuConfigManager(Storage storage)
            : base(storage)
        {
        }
    }
}

Revert "Fix potential crash in tests when attempting to lookup key bindings in cases the lookup is not available"

This reverts commit 8115a4bb8fd9e2d53c40b8607c7ad99f0f62e9a0.

Commit was cherrypicked out to a separate pull on a different merge
base, then reverted in that pull, so it should be reverted here too.


namespace PcscDotNet
{
    /// <summary>
    /// Indicates whether other applications may form connections to the card.
    /// </summary>
    public enum SCardShare
    {
        /// <summary>
        /// This application demands direct control of the reader, so it is not available to other applications.
        /// </summary>
        Direct = 3,
        /// <summary>
        /// This application is not willing to share this card with other applications.
        /// </summary>
        Exclusive = 1,
        /// <summary>
        /// This application is willing to share this card with other applications.
        /// </summary>
        Shared = 2,
        /// <summary>
        /// Share mode is undefined, can not be used to connect to card/reader.
        /// </summary>
        Undefined = 0
    }
}

Append new line at EOF

Append new line at EOF


using System.ComponentModel.DataAnnotations;

namespace TM.Shared
{
   public class AuthorBadge
   {
      [StringLength(400)]
      public string ImageSiteUrl { get; set; }

      [StringLength(100)]
      public string ImageName { get; set; }

      [StringLength(400)]
      public string Link { get; set; }

      [StringLength(100)]
      public string HoverText { get; set; }

      public bool IsEmpty
      {
         get { return string.IsNullOrWhiteSpace(Link); }
      }
   }
}

using System.ComponentModel.DataAnnotations;

namespace TM.Shared
{
   public class AuthorBadge
   {
      [StringLength(400)]
      public string ImageSiteUrl { get; set; }

      [StringLength(100)]
      public string ImageName { get; set; }

      [StringLength(400)]
      public string Link { get; set; }

      [StringLength(400)]
      public string HoverText { get; set; }

      public bool IsEmpty
      {
         get { return string.IsNullOrWhiteSpace(Link); }
      }
   }
}

Increase AuthorBage.HoverText db table column length


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

namespace IF.Lastfm.Core.Api.Helpers
{
    public static class ApiExtensions
    {
        public static T GetAttribute<T>(this Enum enumValue)
        where T : Attribute
        {
            return enumValue
                .GetType()
                .GetTypeInfo()
                .GetDeclaredField(enumValue.ToString())
                .GetCustomAttribute<T>();
        }

        public static string GetApiName(this Enum enumValue)
        {
            var attribute = enumValue.GetAttribute<ApiNameAttribute>();

            return (attribute != null && !string.IsNullOrWhiteSpace(attribute.Text))
                ? attribute.Text
                : enumValue.ToString();
        }

        public static int ToUnixTimestamp(this DateTime dt)
        {
            var d = (dt - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds;

            return Convert.ToInt32(d);
        }

        public static DateTime ToDateTimeUtc(this double stamp)
        {
            var d = new DateTime(1970, 1, 1).ToUniversalTime();
            d = d.AddSeconds(stamp);
            return d;
        }

        public static int CountOrDefault<T>(this IEnumerable<T> enumerable)
        {
            return enumerable != null
                ? enumerable.Count()
                : 0;
        }
    }
}

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

namespace IF.Lastfm.Core.Api.Helpers
{
    public static class ApiExtensions
    {
        public static T GetAttribute<T>(this Enum enumValue)
        where T : Attribute
        {
            return enumValue
                .GetType()
                .GetTypeInfo()
                .GetDeclaredField(enumValue.ToString())
                .GetCustomAttribute<T>();
        }

        public static string GetApiName(this Enum enumValue)
        {
            var attribute = enumValue.GetAttribute<ApiNameAttribute>();

            return (attribute != null && !string.IsNullOrWhiteSpace(attribute.Text))
                ? attribute.Text
                : enumValue.ToString();
        }

        public static int ToUnixTimestamp(this DateTime dt)
        {
            var d = (dt - new DateTime(1970, 1, 1)).TotalSeconds;

            return Convert.ToInt32(d);
        }

        public static DateTime ToDateTimeUtc(this double stamp)
        {
            var d = new DateTime(1970, 1, 1).ToUniversalTime();
            d = d.AddSeconds(stamp);
            return d;
        }

        public static int CountOrDefault<T>(this IEnumerable<T> enumerable)
        {
            return enumerable != null
                ? enumerable.Count()
                : 0;
        }
    }
}

Fix time bug with scrobbles

Fix time bug with scrobbles

no need for "ToUniversalTime" to the epoch DateTime


using System;
using Xamarin.Forms;
using System.Collections.Generic;

namespace FreshMvvm
{
    public class FreshTabbedNavigationContainer : TabbedPage, IFreshNavigationService
    {
        public FreshTabbedNavigationContainer ()
        {
            RegisterNavigation ();
        }

        protected void RegisterNavigation ()
        {
            FreshIOC.Container.Register<IFreshNavigationService> (this);
        }

        public virtual Page AddTab<T> (string title, string icon, object data = null) where T : FreshBasePageModel
        {
            var page = FreshPageModelResolver.ResolvePageModel<T> (data);
            var navigationContainer = CreateContainerPage (page);
            navigationContainer.Title = title;
            navigationContainer.Icon = icon;
            Children.Add (navigationContainer);
            return navigationContainer;
        }

        protected virtual Page CreateContainerPage (Page page)
        {
            return new NavigationPage (page);
        }

        public async System.Threading.Tasks.Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false)
        {
            if (modal)
                await this.CurrentPage.Navigation.PushModalAsync (CreateContainerPage (page));
            else
                await this.CurrentPage.Navigation.PushAsync (page);
        }

        public async System.Threading.Tasks.Task PopPage (bool modal = false)
        {
            if (modal)
                await this.CurrentPage.Navigation.PopModalAsync ();
            else
                await this.CurrentPage.Navigation.PopAsync ();
        }

    }
}

using System;
using Xamarin.Forms;
using System.Collections.Generic;

namespace FreshMvvm
{
    public class FreshTabbedNavigationContainer : TabbedPage, IFreshNavigationService
    {
        public FreshTabbedNavigationContainer ()
        {
            RegisterNavigation ();
        }

        protected void RegisterNavigation ()
        {
            FreshIOC.Container.Register<IFreshNavigationService> (this);
        }

        public virtual Page AddTab<T> (string title, string icon, object data = null) where T : FreshBasePageModel
        {
            var page = FreshPageModelResolver.ResolvePageModel<T> (data);
            var navigationContainer = CreateContainerPage (page);
            navigationContainer.Title = title;
            if (!string.IsNullOrWhiteSpace(icon))
                navigationContainer.Icon = icon;
            Children.Add (navigationContainer);
            return navigationContainer;
        }

        protected virtual Page CreateContainerPage (Page page)
        {
            return new NavigationPage (page);
        }

        public async System.Threading.Tasks.Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false)
        {
            if (modal)
                await this.CurrentPage.Navigation.PushModalAsync (CreateContainerPage (page));
            else
                await this.CurrentPage.Navigation.PushAsync (page);
        }

        public async System.Threading.Tasks.Task PopPage (bool modal = false)
        {
            if (modal)
                await this.CurrentPage.Navigation.PopModalAsync ();
            else
                await this.CurrentPage.Navigation.PopAsync ();
        }

    }
}

Fix issue with nulll image icon in tabbed navigation container


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

using System.IdentityModel.Claims;
using System.Runtime;
using System.Security.Principal;

namespace System.ServiceModel
{
    public class SpnEndpointIdentity : EndpointIdentity
    {
        private static TimeSpan _spnLookupTime = TimeSpan.FromMinutes(1);

        public SpnEndpointIdentity(string spnName)
        {
            if (spnName == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("spnName");

            base.Initialize(Claim.CreateSpnClaim(spnName));
        }

        public SpnEndpointIdentity(Claim identity)
        {
            if (identity == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");

            if (!identity.ClaimType.Equals(ClaimTypes.Spn))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.UnrecognizedClaimTypeForIdentity, identity.ClaimType, ClaimTypes.Spn));

            base.Initialize(identity);
        }

        public static TimeSpan SpnLookupTime
        {
            get
            {
                return _spnLookupTime;
            }
            set
            {
                if (value.Ticks < 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new ArgumentOutOfRangeException("value", value.Ticks, SR.Format(SR.ValueMustBeNonNegative)));
                }
                _spnLookupTime = value;
            }
        }

    }
}

Implement supported parts of Spn/UpnEndpointIdentity


// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.

namespace SixLabors.Fonts
{
    /// <summary>
    /// Extension methods for <see cref="IFontCollection"/>.
    /// </summary>
    public static class FontCollectionExtensions
    {
        /// <summary>
        /// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>.
        /// </summary>
        /// <param name="collection">The font collection.</param>
        /// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns>
        public static FontCollection AddSystemFonts(this FontCollection collection)
        {
            // This cast is safe because our underlying SystemFontCollection implements
            // both interfaces separately.
            foreach (FontMetrics? metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection)
            {
                ((IFontMetricsCollection)collection).AddMetrics(metric);
            }

            return collection;
        }
    }
}

// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.

using System;

namespace SixLabors.Fonts
{
    /// <summary>
    /// Extension methods for <see cref="IFontCollection"/>.
    /// </summary>
    public static class FontCollectionExtensions
    {
        /// <summary>
        /// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>.
        /// </summary>
        /// <param name="collection">The font collection.</param>
        /// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns>
        public static FontCollection AddSystemFonts(this FontCollection collection)
        {
            // This cast is safe because our underlying SystemFontCollection implements
            // both interfaces separately.
            foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection)
            {
                ((IFontMetricsCollection)collection).AddMetrics(metric);
            }

            return collection;
        }

        /// <summary>
        /// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>.
        /// </summary>
        /// <param name="collection">The font collection.</param>
        /// <param name="match">The System.Predicate delegate that defines the conditions of <see cref="FontMetrics"/> to add into the font collection.</param>
        /// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns>
        public static FontCollection AddSystemFonts(this FontCollection collection, Predicate<FontMetrics> match)
        {
            foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection)
            {
                if (match(metric))
                {
                    ((IFontMetricsCollection)collection).AddMetrics(metric);
                }
            }

            return collection;
        }
    }
}

Add an overload of `AddSystemFonts`

Add an overload of `AddSystemFonts`


@model Portal.CMS.Web.Areas.Admin.ViewModels.Settings.EditViewModel
@{
    Layout = "";
}

@using (Html.BeginForm("Edit", "Settings", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    @Html.HiddenFor(x => x.SettingId)

    @Html.ValidationMessage("SettingName")

        @Html.LabelFor(x => x.SettingName)

        @if (Model.SettingName != "Website Name")
        {
            @Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name" })
        }
        else
        {
            @Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name", @readonly="true" })
        }

        @Html.LabelFor(x => x.SettingValue)
        @Html.TextBoxFor(x => x.SettingValue, new { placeholder = "Setting Value" })

        <button class="btn primary">Save</button>
        @if (Model.SettingName != "Website Name")
        {
            Delete
        }
        <button class="btn" data-dismiss="modal">Cancel</button>

}

@model Portal.CMS.Web.Areas.Admin.ViewModels.Settings.EditViewModel
@{
    Layout = "";
}

@using (Html.BeginForm("Edit", "Settings", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    @Html.HiddenFor(x => x.SettingId)

    @Html.ValidationMessage("SettingName")

        @Html.LabelFor(x => x.SettingName)
        @Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name" })

        @Html.LabelFor(x => x.SettingValue)
        @Html.TextBoxFor(x => x.SettingValue, new { placeholder = "Setting Value" })

        <button class="btn primary">Save</button>
        Delete
        <button class="btn" data-dismiss="modal">Cancel</button>

}

Remove ViewLogic Validation on Edit Settings Screen


using System;
using System.Collections;
using System.Collections.Generic;
using TSQLLint.Lib.Rules.RuleViolations;

namespace TSQLLint.Tests.Helpers
{
    public class RuleViolationComparer : IComparer, IComparer<RuleViolation>
    {
        public int Compare(object x, object y)
        {
            if (!(x is RuleViolation lhs) || !(y is RuleViolation rhs))
            {
                throw new InvalidOperationException("cannot compare null object");
            }

            return Compare(lhs, rhs);
        }

        public int Compare(RuleViolation left, RuleViolation right)
        {
            if (right != null && left != null && left.Line != right.Line)
            {
                return -1;
            }

            if (right != null && left != null && left.Column != right.Column)
            {
                return -1;
            }

            if (right != null && left != null && left.RuleName != right.RuleName)
            {
                return -1;
            }

            return 0;
        }
    }
}

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using TSQLLint.Lib.Rules.RuleViolations;

namespace TSQLLint.Tests.Helpers
{
    [ExcludeFromCodeCoverage]
    public class RuleViolationComparer : IComparer, IComparer<RuleViolation>
    {
        public int Compare(object x, object y)
        {
            if (!(x is RuleViolation lhs) || !(y is RuleViolation rhs))
            {
                throw new InvalidOperationException("cannot compare null object");
            }

            return Compare(lhs, rhs);
        }

        public int Compare(RuleViolation left, RuleViolation right)
        {
            if (right != null && left != null && left.Line != right.Line)
            {
                return -1;
            }

            if (right != null && left != null && left.Column != right.Column)
            {
                return -1;
            }

            if (right != null && left != null && left.RuleName != right.RuleName)
            {
                return -1;
            }

            return 0;
        }
    }
}

Exclude test utility from coverage

Exclude test utility from coverage


using System;
using System.Linq;
using Abp.Dependency;
using Castle.Core;
using Castle.MicroKernel;

namespace Abp.Auditing
{
    internal class AuditingInterceptorRegistrar
    {
        private readonly IAuditingConfiguration _auditingConfiguration;
        private readonly IIocManager _iocManager;

        public AuditingInterceptorRegistrar(IIocManager iocManager)
        {
            _auditingConfiguration = _iocManager.Resolve<IAuditingConfiguration>();
            _iocManager = iocManager;
        }

        public void Initialize()
        {
            if (!_auditingConfiguration.IsEnabled)
            {
                return;
            }

            _iocManager.IocContainer.Kernel.ComponentRegistered += Kernel_ComponentRegistered;
        }

        private void Kernel_ComponentRegistered(string key, IHandler handler)
        {
            if (ShouldIntercept(handler.ComponentModel.Implementation))
            {
                handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AuditingInterceptor)));
            }
        }

        private bool ShouldIntercept(Type type)
        {
            if (_auditingConfiguration.Selectors.Any(selector => selector.Predicate(type)))
            {
                return true;
            }

            if (type.IsDefined(typeof(AuditedAttribute), true)) //TODO: true or false?
            {
                return true;
            }

            if (type.GetMethods().Any(m => m.IsDefined(typeof(AuditedAttribute), true))) //TODO: true or false?
            {
                return true;
            }

            return false;
        }
    }
}

using System;
using System.Linq;
using Abp.Dependency;
using Castle.Core;
using Castle.MicroKernel;

namespace Abp.Auditing
{
    internal class AuditingInterceptorRegistrar
    {
        private readonly IIocManager _iocManager;
        private readonly IAuditingConfiguration _auditingConfiguration;

        public AuditingInterceptorRegistrar(IIocManager iocManager)
        {
            _iocManager = iocManager;
            _auditingConfiguration = _iocManager.Resolve<IAuditingConfiguration>();
        }

        public void Initialize()
        {
            if (!_auditingConfiguration.IsEnabled)
            {
                return;
            }

            _iocManager.IocContainer.Kernel.ComponentRegistered += Kernel_ComponentRegistered;
        }

        private void Kernel_ComponentRegistered(string key, IHandler handler)
        {
            if (ShouldIntercept(handler.ComponentModel.Implementation))
            {
                handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AuditingInterceptor)));
            }
        }

        private bool ShouldIntercept(Type type)
        {
            if (_auditingConfiguration.Selectors.Any(selector => selector.Predicate(type)))
            {
                return true;
            }

            if (type.IsDefined(typeof(AuditedAttribute), true)) //TODO: true or false?
            {
                return true;
            }

            if (type.GetMethods().Any(m => m.IsDefined(typeof(AuditedAttribute), true))) //TODO: true or false?
            {
                return true;
            }

            return false;
        }
    }
}

Fix for previous minor refactoring.

Fix for previous minor refactoring.


// vimage - http://torrunt.net/vimage
// Corey Zeke Womack (Torrunt) - me@torrunt.net

using System;

namespace vimage
{
    class Program
    {
        static void Main(string[] args)
        {
            string file;
            if (args.Length == 0)
            {
#if DEBUG
                //file = @"C:\Users\Corey\Pictures\Test Images\Beaver_Transparent.png";
                //file = @"C:\Users\Corey\Pictures\Test Images\AdventureTime_TransparentAnimation.gif";
                //file = @"C:\Users\Corey\Pictures\Test Images\AnimatedGif.gif";
                file = @"G:\Misc\Desktop Backgrounds\0diHF.jpg";
#else
                return;
#endif
            }
            else
                file = args[0];

            ImageViewer ImageViewer = new ImageViewer(file);
        }
    }
}

// vimage - http://torrunt.net/vimage
// Corey Zeke Womack (Torrunt) - me@torrunt.net

using System;

namespace vimage
{
    class Program
    {
        static void Main(string[] args)
        {
            string file;
            if (args.Length == 0)
                return;
            else
                file = args[0];

            if (System.IO.File.Exists(file))
            {
                ImageViewer imageViewer = new ImageViewer(file);
            }
        }
    }
}

Load only if the file given exists

Load only if the file given exists


// Copyright 2013-2021 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
//   https://www.imagemagick.org/script/license.php
//
// 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.IO;

namespace ImageMagick.Configuration
{
    internal sealed class ConfigurationFile : IConfigurationFile
    {
        public ConfigurationFile(string fileName)
        {
            FileName = fileName;
            Data = LoadData();
        }

        public string FileName { get; }

        public string Data { get; set; }

        private string LoadData()
        {
            using (Stream stream = TypeHelper.GetManifestResourceStream(typeof(ConfigurationFile), "ImageMagick.Resources.Xml", FileName))
            {
                using (var reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
}

// Copyright 2013-2021 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
//   https://www.imagemagick.org/script/license.php
//
// 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.IO;

namespace ImageMagick.Configuration
{
    internal sealed class ConfigurationFile : IConfigurationFile
    {
        public ConfigurationFile(string fileName)
        {
            FileName = fileName;
            Data = LoadData();
        }

        public string FileName { get; }

        public string Data { get; set; }

        private string LoadData()
        {
            using (Stream stream = TypeHelper.GetManifestResourceStream(typeof(ConfigurationFile), "ImageMagick.Resources.Xml", FileName))
            {
                using (var reader = new StreamReader(stream))
                {
                    var data = reader.ReadToEnd();

                    data = UpdateDelegatesXml(data);

                    return data;
                }
            }
        }

        private string UpdateDelegatesXml(string data)
        {
            if (OperatingSystem.IsWindows || FileName != "delegates.xml")
                return data;

            return data.Replace("@PSDelegate@", "gs");
        }
    }
}

Patch delegates.xml for non Windows platform.


#region

using System.Collections.Generic;

#endregion

namespace Snooze
{
    public static class ResourceFormatters
    {
        static readonly IList<IResourceFormatter> _formatters = new List<IResourceFormatter>();

        static ResourceFormatters()
        {
            // The order of formatters matters.

            // Browsers like Chrome will ask for "text/xml, application/xhtml+xml, ..."
            // But we don't want to use the XML formatter by default
            // - which would happen since "text/xml" appears first in the list.
            // So we add an explicitly typed ViewFormatter first.
            _formatters.Add(new ViewFormatter("application/xhtml+xml"));
            _formatters.Add(new ViewFormatter("*/*")); // similar reason for this.
            _formatters.Add(new JsonFormatter());
            _formatters.Add(new XmlFormatter());
            _formatters.Add(new ViewFormatter());
            _formatters.Add(new StringFormatter());
            _formatters.Add(new ByteArrayFormatter());
        }

        public static IList<IResourceFormatter> Formatters
        {
            get { return _formatters; }
        }
    }
}

#region

using System.Collections.Generic;

#endregion

namespace Snooze
{
    public static class ResourceFormatters
    {
        static readonly IList<IResourceFormatter> _formatters = new List<IResourceFormatter>();

        static ResourceFormatters()
        {
            // The order of formatters matters.

            // Browsers like Chrome will ask for "text/xml, application/xhtml+xml, ..."
            // But we don't want to use the XML formatter by default
            // - which would happen since "text/xml" appears first in the list.
            // So we add an explicitly typed ViewFormatter first.

            _formatters.Add(new ViewFormatter("text/html"));
            _formatters.Add(new ViewFormatter("application/xhtml+xml"));
            _formatters.Add(new ViewFormatter("*/*")); // similar reason for this.
            _formatters.Add(new JsonFormatter());
            _formatters.Add(new XmlFormatter());
            _formatters.Add(new ViewFormatter());
            _formatters.Add(new StringFormatter());
            _formatters.Add(new ByteArrayFormatter());
        }

        public static IList<IResourceFormatter> Formatters
        {
            get { return _formatters; }
        }
    }
}

Add text/html as first content type, should possible detect IE..


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

namespace Griddly.Mvc
{
    public class GriddlyContext
    {
        public string Name { get; set; }
        public bool IsDefaultSkipped { get; set; }
        public bool IsDeepLink { get; set; }

        public GriddlyFilterCookieData CookieData { get; set; }

        public string CookieName => "gf_" + Name;

        public Dictionary<string, object> Defaults { get; set; } = new Dictionary<string, object>();
        public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();

        public int PageNumber { get; set; }
        public int PageSize { get; set; }
        public GriddlyExportFormat? ExportFormat { get; set; }
        public SortField[] SortFields { get; set; }
    }

    public class GriddlyFilterCookieData
    {
        public Dictionary<string, string[]> Values { get; set; }
        public SortField[] SortFields { get; set; }
    }
}

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

namespace Griddly.Mvc
{
    public class GriddlyContext
    {
        public string Name { get; set; }
        public bool IsDefaultSkipped { get; set; }
        public bool IsDeepLink { get; set; }

        public GriddlyFilterCookieData CookieData { get; set; }

        public string CookieName => "gf_" + Name;

        public Dictionary<string, object> Defaults { get; set; } = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
        public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);

        public int PageNumber { get; set; }
        public int PageSize { get; set; }
        public GriddlyExportFormat? ExportFormat { get; set; }
        public SortField[] SortFields { get; set; }
    }

    public class GriddlyFilterCookieData
    {
        public Dictionary<string, string[]> Values { get; set; }
        public SortField[] SortFields { get; set; }
    }
}

Make griddly defaults and parameters case insensitive


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

namespace SlackAPI
{
    [RequestPath("conversations.open")]
    public class ConversationsOpenResponse : Response
    {
        public string no_op;
        public string already_open;
        public Channel channel;
    }
}

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

namespace SlackAPI
{
    [RequestPath("conversations.open")]
    public class ConversationsOpenResponse : Response
    {
        public string no_op;
        public string already_open;
        public Channel channel;
        public string error;

}

Add field for error responses

Add field for error responses


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

namespace CefSharp.Wpf.Example.Handlers
{

    public class MenuHandler : IMenuHandler
    {

        public bool OnBeforeContextMenu(IWebBrowser browser, IContextMenuParams parameters)
        {

            Console.WriteLine("Context menu opened");
            Console.WriteLine(parameters.MisspelledWord);

            return true;
        }

    }
}

// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;

namespace CefSharp.Wpf.Example.Handlers
{
    public class MenuHandler : IMenuHandler
    {
        public bool OnBeforeContextMenu(IWebBrowser browser, IContextMenuParams parameters)
        {
            Console.WriteLine("Context menu opened");
            Console.WriteLine(parameters.MisspelledWord);

            return true;
        }
    }
}

Add license disclaimer Cleanup formatting


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

namespace Fatec.Treinamento.Model.DTO
{
    public class DetalhesCurso
    {
        public int Id { get; set; }

        public string Nome { get; set; }

        public string Assunto { get; set; }

        public string Autor { get; set; }

        public DateTime DataCriacao { get; set; }

        public int Classificacao { get; set; }

    }
}

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

namespace Fatec.Treinamento.Model.DTO
{
    public class DetalhesCurso
    {
        public int Id { get; set; }

        public string Nome { get; set; }

        public string Assunto { get; set; }

        public string Autor { get; set; }

        public DateTime DataCriacao { get; set; }

        public int Classificacao { get; set; }

        //public string Descricao { get; set; }

    }
}

Add property 'Descricao' to class 'DetalheCurso'


@{
    ViewBag.Title = "Contact";
}

@ViewBag.Title.

@ViewBag.Message

<address>
    One Microsoft Way

    Redmond, WA 98052-6399

    P:
    425.555.0100
</address>

<address>
    Support:   Support@wechangedthis.com

    Marketing: Marketing@example.com
    Batman: Batman@batman.com
</address>

@{
    ViewBag.Title = "Contact";
}

@ViewBag.Title.

@ViewBag.Message

<address>
    One Microsoft Way

    Redmond, WA 98052-6399

    P:
    425.555.0100
</address>

<address>
    Support:   Support@wechangedthis.com

    Marketing: Marketing@example.com
    Batman: Batman@batman.com
    Peter Parker Spiderman@spiderman.com
</address>

Add Peter Parker to contact page.

Add Peter Parker to contact page.


//
//  Image.cs
//
//  Author:
//       Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
//  Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
using System;

namespace Deblocus.Entities
{
    public class Image
    {
        private string name;

        public Image()
        {
            Name = DefaultName;
        }

        public static string DefaultName {
            get { return "No Title"; }
        }

        public virtual int Id { get; protected set; }
        public virtual byte[] Data { get; set; }
        public virtual string Name {
            get { return name; }
            set { name = string.IsNullOrEmpty(value) ? DefaultName : value; }
        }
        public virtual string Description { get; set; }
    }
}

//
//  Image.cs
//
//  Author:
//       Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
//  Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
using System;

namespace Deblocus.Entities
{
    public class Image
    {
        private string name;

        public Image()
        {
            Name = DefaultName;
        }

        public static string DefaultName {
            get { return "No Name"; }
        }

        public virtual int Id { get; protected set; }
        public virtual byte[] Data { get; set; }
        public virtual string Name {
            get { return name; }
            set { name = string.IsNullOrEmpty(value) ? DefaultName : value; }
        }
        public virtual string Description { get; set; }
    }
}

Fix default name for images

Fix default name for images


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

namespace AppStudio.Uwp.Html
{
    public sealed class HtmlText : HtmlFragment
    {
        public string Content { get; set; }

        public HtmlText()
        {
            Name = "text";
        }

        public HtmlText(string doc, int startIndex, int endIndex) : this()
        {
            if (!string.IsNullOrEmpty(doc) && endIndex - startIndex > 0)
            {
                Content = WebUtility.HtmlDecode(doc.Substring(startIndex, endIndex - startIndex));
            }
        }

        public override string ToString()
        {
            return Content;
        }

        internal static HtmlText Create(string doc, HtmlTag startTag, HtmlTag endTag)
        {
            var startIndex = 0;

            if (startTag != null)
            {
                startIndex = startTag.StartIndex + startTag.Length;
            }

            var endIndex = doc.Length;

            if (endTag != null)
            {
                endIndex = endTag.StartIndex;
            }

            var text = new HtmlText(doc, startIndex, endIndex);
            if (text != null && !string.IsNullOrEmpty(text.Content))
            {
                return text;
            }

            return null;
        }
    }
}

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

namespace AppStudio.Uwp.Html
{
    public sealed class HtmlText : HtmlFragment
    {
        private string _content;
        public string Content
        {
            get
            {
                return _content;
            }
            set
            {
                _content = WebUtility.HtmlDecode(value);
            }
        }

        public HtmlText()
        {
            Name = "text";
        }

        public HtmlText(string doc, int startIndex, int endIndex) : this()
        {
            if (!string.IsNullOrEmpty(doc) && endIndex - startIndex > 0)
            {
                Content = doc.Substring(startIndex, endIndex - startIndex);
            }
        }

        public override string ToString()
        {
            return Content;
        }

        internal static HtmlText Create(string doc, HtmlTag startTag, HtmlTag endTag)
        {
            var startIndex = 0;

            if (startTag != null)
            {
                startIndex = startTag.StartIndex + startTag.Length;
            }

            var endIndex = doc.Length;

            if (endTag != null)
            {
                endIndex = endTag.StartIndex;
            }

            var text = new HtmlText(doc, startIndex, endIndex);
            if (text != null && !string.IsNullOrEmpty(text.Content))
            {
                return text;
            }

            return null;
        }
    }
}

Fix html enconded characters in plain text


namespace Halcyon.HAL {
    public interface IHALModelConfig {
        string LinkBase { get; }
        bool ForceHAL { get; }
    }
}

namespace Halcyon.HAL {
    public interface IHALModelConfig {
        string LinkBase { get; set; }
        bool ForceHAL { get; set; }
    }
}

Allow model config to be modified

Allow model config to be modified


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

namespace LoveSeat
{
    public interface IObjectSerializer<T>
    {
        T Deserialize(string json);
        string Serialize(object obj);
    }
    public class ObjectSerializer<T> : IObjectSerializer<T>
    {
        protected readonly JsonSerializerSettings settings;
        public ObjectSerializer()
        {
            settings = new JsonSerializerSettings();
            var converters = new List<JsonConverter> { new IsoDateTimeConverter() };
            settings.Converters = converters;
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            settings.NullValueHandling = NullValueHandling.Ignore;
        }

        public virtual T Deserialize(string json)
        {
            return JsonConvert.DeserializeObject<T>(json.Replace("_id", "id").Replace("_rev", "rev"), settings);
        }
        public virtual string Serialize(object obj)
        {
            return JsonConvert.SerializeObject(obj, Formatting.Indented, settings).Replace("id", "_id").Replace("rev", "_rev");
        }
    }
}

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

namespace LoveSeat
{
    public interface IObjectSerializer<T>
    {
        T Deserialize(string json);
        string Serialize(object obj);
    }
    public class ObjectSerializer<T> : IObjectSerializer<T>
    {
        protected readonly JsonSerializerSettings settings;
        public ObjectSerializer()
        {
            settings = new JsonSerializerSettings();
            var converters = new List<JsonConverter> { new IsoDateTimeConverter() };
            settings.Converters = converters;
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            settings.NullValueHandling = NullValueHandling.Include;
        }

        public virtual T Deserialize(string json)
        {
            return JsonConvert.DeserializeObject<T>(json.Replace("_id", "id").Replace("_rev", "rev"), settings);
        }
        public virtual string Serialize(object obj)
        {
            return JsonConvert.SerializeObject(obj, Formatting.Indented, settings).Replace("id", "_id").Replace("rev", "_rev");
        }
    }
}

Change the behavior of the object serializer so that objects are initialized with values instead of Nulls


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

namespace VasysRomanNumeralsKataTest
{
    [TestClass]
    public class ToRomanNumeralsTest
    {
        [TestMethod]
        public void WhenRomanNumeralExtensionIsPassedTenItReturnsX()
        {
            int ten = 10;
            Assert.IsTrue(ten.ToRomanNumeral() == "X");
        }

        [TestMethod]
        public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral()
        {
            int oneThousand = 1000;
            Assert.IsTrue(oneThousand.ToRomanNumeral() == "M");
            int nineHundred = 900;
            Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM");
            int fiveHundred = 500;
            Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D");
            int fourHundred = 400;
            Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD");
            int oneHundred = 100;
            Assert.IsTrue(oneHundred.ToRomanNumeral() == "C");
            int twoHundred = 200;
            Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC");
            int threeHundred = 300;
            Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC");
        }
    }
}

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

namespace VasysRomanNumeralsKataTest
{
    [TestClass]
    public class ToRomanNumeralsTest
    {
        [TestMethod]
        public void WhenRomanNumeralExtensionIsPassedTenItReturnsX()
        {
            int ten = 10;
            Assert.IsTrue(ten.ToRomanNumeral() == "X");
        }

        [TestMethod]
        public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral()
        {
            int oneThousand = 1000;
            Assert.IsTrue(oneThousand.ToRomanNumeral() == "M");
            int nineHundred = 900;
            Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM");
            int fiveHundred = 500;
            Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D");
            int fourHundred = 400;
            Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD");
            int oneHundred = 100;
            Assert.IsTrue(oneHundred.ToRomanNumeral() == "C");
            int twoHundred = 200;
            Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC");
            int threeHundred = 300;
            Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC");
            int twoThousand = 2000;
            Assert.IsTrue(twoThousand.ToRomanNumeral() == "MM");
        }
    }
}

Add test for 2000 (MM) - this should have been done before adding loop for M.


using System.Web.Mvc;
using System.Web.Routing;
using SFA.DAS.EAS.Account.Api.Client;
using SFA.DAS.EAS.Account.Api.Types;

namespace SFA.DAS.EmployerFinance.Web.Filters
{
    public class LevyEmployerTypeOnly : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var hashedAccountId = filterContext.ActionParameters["HashedAccountId"].ToString();
            var accountApi = DependencyResolver.Current.GetService<IAccountApiClient>();
            var account = accountApi.GetAccount(hashedAccountId).Result;
            if (account.ApprenticeshipEmployerType == "1")
            {
                base.OnActionExecuting(filterContext);
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
                        new
                        {
                            controller = "AccessDenied",
                            action = "Index",
                        }));
            }
        }
    }
}

using System;
using System.Web.Mvc;
using System.Web.Routing;
using SFA.DAS.EAS.Account.Api.Client;
using SFA.DAS.EmployerFinance.Web.Helpers;

namespace SFA.DAS.EmployerFinance.Web.Filters
{
    public class LevyEmployerTypeOnly : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                var hashedAccountId = filterContext.ActionParameters["HashedAccountId"].ToString();
                var accountApi = DependencyResolver.Current.GetService<IAccountApiClient>();
                var task = accountApi.GetAccount(hashedAccountId);
                task.RunSynchronously();
                var account = task.Result;

                if (account.ApprenticeshipEmployerType == "1")
                {
                    base.OnActionExecuting(filterContext);
                }
                else
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
                            new
                            {
                                controller = ControllerConstants.AccessDeniedControllerName,
                                action = "Index",
                            }));
                }
            }
            catch (Exception ex)
            {
                filterContext.Result = new ViewResult { ViewName = ControllerConstants.BadRequestViewName };
            }
        }
    }
}

[CON-730] Handle failed Api call within Action Filter


using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

namespace GogoKit.Http
{
    public class UserAgentHandler : DelegatingHandler
    {
        private readonly IReadOnlyList<ProductInfoHeaderValue> _userAgentHeaderValues;

        public UserAgentHandler(ProductHeaderValue product)
        {
            Requires.ArgumentNotNull(product, nameof(product));

            _userAgentHeaderValues = GetUserAgentHeaderValues(product);
        }

        private IReadOnlyList<ProductInfoHeaderValue> GetUserAgentHeaderValues(ProductHeaderValue product)
        {
            return new List<ProductInfoHeaderValue>
            {
                new ProductInfoHeaderValue(product),
                //new ProductInfoHeaderValue($"({CultureInfo.CurrentCulture.Name}; GogoKit {AssemblyVersionInformation.Version})")
            };
        }

        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            foreach (var product in _userAgentHeaderValues)
            {
                request.Headers.UserAgent.Add(product);
            }

            return base.SendAsync(request, cancellationToken);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

namespace GogoKit.Http
{
    public class UserAgentHandler : DelegatingHandler
    {
        private static readonly ProductInfoHeaderValue GogoKitVersionHeaderValue =
            new ProductInfoHeaderValue(
                "GogoKit",
                FileVersionInfo.GetVersionInfo(typeof(UserAgentHandler).Assembly.Location).ProductVersion);

        private readonly IReadOnlyList<ProductInfoHeaderValue> _userAgentHeaderValues;

        public UserAgentHandler(ProductHeaderValue product)
        {
            Requires.ArgumentNotNull(product, nameof(product));

            _userAgentHeaderValues = GetUserAgentHeaderValues(product);
        }

        private IReadOnlyList<ProductInfoHeaderValue> GetUserAgentHeaderValues(ProductHeaderValue product)
        {
            return new List<ProductInfoHeaderValue>
            {
                new ProductInfoHeaderValue(product),
                GogoKitVersionHeaderValue
            };
        }

        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            foreach (var product in _userAgentHeaderValues)
            {
                request.Headers.UserAgent.Add(product);
            }

            return base.SendAsync(request, cancellationToken);
        }
    }
}

Include GogoKit version in User-Agent header


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)
		{
			foreach (var instruction in instructions)
			{
				var method = instruction.operand as MethodBase;
				if (method == from)
					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.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
	}
}

Make MethodReplacer change opcode to CALL as default


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentValidation;
using PlanetWars.Shared;

namespace PlanetWars.Validators
{
    public class LogonRequestValidator : AbstractValidator<LogonRequest>
    {
        public LogonRequestValidator()
        {
            RuleFor(logon => logon.AgentName)
                .NotEmpty().WithMessage("Please use a non empty agent name, logon failed")
                .Length(1, 20).WithMessage("Please use an agent name between 1-20 characters, logon failed");

            RuleFor(logon => logon.MapGeneration)
                .Must(x => x == MapGenerationOption.Basic || x == MapGenerationOption.Random).WithMessage("Please use a valid Map Generation Option");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentValidation;
using PlanetWars.Shared;

namespace PlanetWars.Validators
{
    public class LogonRequestValidator : AbstractValidator<LogonRequest>
    {
        public LogonRequestValidator()
        {
            RuleFor(logon => logon.AgentName)
                .NotEmpty().WithMessage("Please use a non empty agent name, logon failed")
                .Length(1, 18).WithMessage("Please use an agent name between 1-18 characters, logon failed");

            RuleFor(logon => logon.MapGeneration)
                .Must(x => x == MapGenerationOption.Basic || x == MapGenerationOption.Random).WithMessage("Please use a valid Map Generation Option");
        }
    }
}

Update agent name to only allow 18 characters so that it looks good on the screen


using System;
using engine.core;

namespace engine.rules
{
    public class PercentageDiscount : Rule
    {
        private readonly string m_ApplicableItemName;
        private readonly int m_Percentage;

        public PercentageDiscount(string applicableItemName, int percentage)
        {
            m_ApplicableItemName = applicableItemName;
            m_Percentage = percentage;
        }

        public override Basket Apply(Basket basket)
        {
            var discountedBasket = new Basket();

            foreach (var item in basket)
            {
                discountedBasket.Add(item);

                if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
                {
                    var discountToApply =  -(int) Math.Ceiling(item.Price * ((double) m_Percentage / 100));
                    discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply);
                }
            }

            return discountedBasket;
        }
    }
}

using System;
using engine.core;

namespace engine.rules
{
    public class PercentageDiscount : Rule
    {
        private readonly string m_ApplicableItemName;
        private readonly double m_Percentage;

        public PercentageDiscount(string applicableItemName, int percentage)
        {
            m_ApplicableItemName = applicableItemName;
            m_Percentage = percentage;
        }

        public override Basket Apply(Basket basket)
        {
            var discountedBasket = new Basket();

            foreach (var item in basket)
            {
                discountedBasket.Add(item);

                if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
                {
                    var discountToApply =  -(int) Math.Ceiling(item.Price * (m_Percentage / 100));
                    discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply);
                }
            }

            return discountedBasket;
        }
    }
}

Change this to a double so that we don't have to always cast.


using System;
using System.Collections.Generic;
using System.Threading;

namespace Ensconce.Console
{
    /// <summary>
    /// Retry logic applied from this Stack Overflow thread
    /// http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-logic
    /// </summary>
    public static class Retry
    {
        public static void Do(Action action, TimeSpan retryInterval, int retryCount = 3)
        {
            Do<object>(() =>
            {
                action();
                return null;
            }, retryInterval, retryCount);
        }

        public static T Do<T>(Func<T> action, TimeSpan retryInterval, int retryCount = 3)
        {
            var exceptions = new List<Exception>();

            for (var retry = 0; retry < retryCount; retry++)
            {
                try
                {
                    return action();
                }
                catch (Exception ex)
                {
                    System.Console.Out.WriteLine("Something went wrong, but we're going to try again...");
                    System.Console.Out.WriteLine(ex.Message);
                    exceptions.Add(ex);
                    Thread.Sleep(retryInterval);
                }
            }

            throw new AggregateException(exceptions);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading;

namespace Ensconce.Console
{
    /// <summary>
    /// Retry logic applied from this Stack Overflow thread
    /// http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-logic
    /// </summary>
    public static class Retry
    {
        private static readonly int retryCount = 5;

        public static void Do(Action action, TimeSpan retryInterval)
        {
            Do<object>(() =>
            {
                action();
                return null;
            }, retryInterval);
        }

        public static T Do<T>(Func<T> action, TimeSpan retryInterval)
        {
            var exceptions = new List<Exception>();

            for (var retry = 0; retry < retryCount; retry++)
            {
                try
                {
                    return action();
                }
                catch (Exception ex) when (retry + 1 < retryCount)
                {
                    System.Console.Out.WriteLine($"Something went wrong on attempt {retry + 1} of {retryCount}, but we're going to try again in {retryInterval.TotalMilliseconds}ms...");
                    exceptions.Add(ex);
                    Thread.Sleep(retryInterval);
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                    System.Console.Out.WriteLine($"Something went wrong on attempt {retry + 1} of {retryCount}, throwing all {exceptions.Count} exceptions...");
                }
            }

            throw new AggregateException(exceptions);
        }
    }
}

Improve logging in retry logic & increase to 5 tries


using AxoCover.Models.Extensions;
using AxoCover.Properties;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace AxoCover.Models
{
  public abstract class TelemetryManager : ITelemetryManager
  {
    protected IEditorContext _editorContext;

    public bool IsTelemetryEnabled
    {
      get { return Settings.Default.IsTelemetryEnabled; }
      set { Settings.Default.IsTelemetryEnabled = value; }
    }

    public TelemetryManager(IEditorContext editorContext)
    {
      _editorContext = editorContext;

      Application.Current.DispatcherUnhandledException += OnDispatcherUnhandledException;
    }

    private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
      var description = e.Exception.GetDescription();
      if (description.Contains(nameof(AxoCover)))
      {
        _editorContext.WriteToLog(Resources.ExceptionEncountered);
        _editorContext.WriteToLog(description);
        UploadExceptionAsync(e.Exception);
        e.Handled = true;
      }
    }

    public abstract Task<bool> UploadExceptionAsync(Exception exception);
  }
}

using AxoCover.Models.Extensions;
using AxoCover.Properties;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace AxoCover.Models
{
  public abstract class TelemetryManager : ITelemetryManager
  {
    protected IEditorContext _editorContext;

    public bool IsTelemetryEnabled
    {
      get { return Settings.Default.IsTelemetryEnabled; }
      set { Settings.Default.IsTelemetryEnabled = value; }
    }

    public TelemetryManager(IEditorContext editorContext)
    {
      _editorContext = editorContext;

      Application.Current.DispatcherUnhandledException += OnDispatcherUnhandledException;
    }

    private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
      var description = e.Exception.GetDescription();
      if (description.Contains(nameof(AxoCover)))
      {
        _editorContext.WriteToLog(Resources.ExceptionEncountered);
        _editorContext.WriteToLog(description);
        if (Debugger.IsAttached)
        {
          Debugger.Break();
        }
        else
        {
          UploadExceptionAsync(e.Exception);
        }
        e.Handled = true;
      }
    }

    public abstract Task<bool> UploadExceptionAsync(Exception exception);
  }
}

Make telemetry break execution if debugger is attached instead of pushing report


using MultiMiner.Engine;
using MultiMiner.Utility.Serialization;
using System.Collections.Generic;
using System.IO;

namespace MultiMiner.Win.Data.Configuration
{
    public class NetworkDevices
    {
        public class NetworkDevice
        {
            public string IPAddress { get; set; }
            public int Port { get; set; }
        }

        public List<NetworkDevice> Devices { get; set; }

        private static string NetworkDevicesConfigurationFileName()
        {
            return Path.Combine(ApplicationPaths.AppDataPath(), "NetworkDevicesConfiguration.xml");
        }

        public void SaveNetworkDevicesConfiguration()
        {
            ConfigurationReaderWriter.WriteConfiguration(Devices, NetworkDevicesConfigurationFileName());
        }

        public void LoadNetworkDevicesConfiguration()
        {
            Devices = ConfigurationReaderWriter.ReadConfiguration<List<NetworkDevice>>(NetworkDevicesConfigurationFileName());
        }
    }
}

using MultiMiner.Engine;
using MultiMiner.Utility.Serialization;
using System.Collections.Generic;
using System.IO;

namespace MultiMiner.Win.Data.Configuration
{
    public class NetworkDevices
    {
        public class NetworkDevice
        {
            public string IPAddress { get; set; }
            public int Port { get; set; }
        }

        public List<NetworkDevice> Devices { get; set; }

        public NetworkDevices()
        {
            //set a default - null ref errors if submitting MobileMiner stats before scan is completed
            Devices = new List<NetworkDevice>();
        }

        private static string NetworkDevicesConfigurationFileName()
        {
            return Path.Combine(ApplicationPaths.AppDataPath(), "NetworkDevicesConfiguration.xml");
        }

        public void SaveNetworkDevicesConfiguration()
        {
            ConfigurationReaderWriter.WriteConfiguration(Devices, NetworkDevicesConfigurationFileName());
        }

        public void LoadNetworkDevicesConfiguration()
        {
            Devices = ConfigurationReaderWriter.ReadConfiguration<List<NetworkDevice>>(NetworkDevicesConfigurationFileName());
        }
    }
}

Fix a null ref error submitting MobileMiner stats without Network Devices


<!DOCTYPE html>
<html lang="en-gb">
<head>
    <title>@SettingHelper.Get("Website Name"): @ViewBag.Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
    <meta name="description" content="@SettingHelper.Get("Description Meta Tag")">

    @RenderSection("Styles", false)
    @Styles.Render("~/Resources/CSS/Bootstrap")
    @Styles.Render("~/Resources/CSS/FontAwesome")
    @Styles.Render("~/Resources/CSS/Administration/Framework")
    @Styles.Render("~/Resources/CSS/PageBuilder/Framework")
    @Styles.Render("~/Resources/CSS/Framework")

    @Scripts.Render("~/Resources/JavaScript/JQuery")
    @Scripts.Render("~/Resources/JavaScript/JQueryUI")

    @RenderSection("HEADScripts", false)

    @Html.Partial("_Analytics")
</head>
<body>
    @Html.Partial("_NavBar")
    @Html.Partial("_Administration")
    @RenderBody()

    @if (UserHelper.IsAdmin)
    {
        @Styles.Render("~/Resources/CSS/Bootstrap/Tour")
        @Styles.Render("~/Resources/CSS/PageBuilder/Framework/Administration")
    }

    <link href="@Url.Action("Render", "Theme", new { area = "Builder" })" rel="stylesheet" type="text/css" />

    @Html.Partial("_DOMScripts")
    @RenderSection("DOMScripts", false)
</body>
</html>

<!DOCTYPE html>
<html lang="en-gb">
<head>
    <title>@SettingHelper.Get("Website Name"): @ViewBag.Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
    <meta name="description" content="@SettingHelper.Get("Description Meta Tag")">

    @RenderSection("Styles", false)
    @Styles.Render("~/Resources/CSS/Bootstrap")
    @Styles.Render("~/Resources/CSS/FontAwesome")
    @Styles.Render("~/Resources/CSS/Administration/Framework")
    @Styles.Render("~/Resources/CSS/PageBuilder/Framework")
    @Styles.Render("~/Resources/CSS/Framework")

    @if (UserHelper.IsAdmin)
    {
        @Styles.Render("~/Resources/CSS/Bootstrap/Tour")
        @Styles.Render("~/Resources/CSS/PageBuilder/Framework/Administration")
    }

    <link href="@Url.Action("Render", "Theme", new { area = "Builder" })" rel="stylesheet" type="text/css" />

    @Scripts.Render("~/Resources/JavaScript/JQuery")
    @Scripts.Render("~/Resources/JavaScript/JQueryUI")

    @RenderSection("HEADScripts", false)

    @Html.Partial("_Analytics")
</head>
<body>
    @Html.Partial("_NavBar")
    @Html.Partial("_Administration")
    @RenderBody()
    @Html.Partial("_DOMScripts")
    @RenderSection("DOMScripts", false)
</body>
</html>

Change Order of Loading Styles

Change Order of Loading Styles


using static MyOwnSearchEngine.HtmlFactory;

namespace MyOwnSearchEngine
{
    public class Hex : IProcessor
    {
        public string GetResult(Query query)
        {
            var integer = query.TryGetStructure<Integer>();
            if (integer != null)
            {
                return GetResult(integer.Value);
            }

            var separatedList = query.TryGetStructure<SeparatedList>();
            if (separatedList != null && separatedList.Count >= 2)
            {
                var number = separatedList.TryGetStructure<Integer>(0);
                if (number != null)
                {
                    var keyword1 = separatedList.TryGetStructure<Keyword>(1);
                    if (keyword1 != null)
                    {
                        if (keyword1 == "hex" && separatedList.Count == 2)
                        {
                            return GetResult(number.Value);
                        }

                        if (separatedList.Count == 3 &&
                            (keyword1 == "in" || keyword1 == "to") &&
                            separatedList.TryGetStructure<Keyword>(2) == "hex")
                        {
                            return GetResult(number.Value);
                        }
                    }
                }
            }

            return null;
        }

        private string GetResult(int value)
        {
            return Div(Escape($"{value} = 0x{value.ToString("X")}"));
        }
    }
}

using static MyOwnSearchEngine.HtmlFactory;

namespace MyOwnSearchEngine
{
    public class Hex : IProcessor
    {
        public string GetResult(Query query)
        {
            var integer = query.TryGetStructure<Integer>();
            if (integer != null)
            {
                return GetResult(integer.Value);
            }

            var separatedList = query.TryGetStructure<SeparatedList>();
            if (separatedList != null && separatedList.Count >= 2)
            {
                var number = separatedList.TryGetStructure<Integer>(0);
                if (number != null)
                {
                    var keyword1 = separatedList.TryGetStructure<Keyword>(1);
                    if (keyword1 != null)
                    {
                        if (keyword1 == "hex" && separatedList.Count == 2)
                        {
                            return GetResult(number.Value);
                        }

                        if (separatedList.Count == 3 &&
                            (keyword1 == "in" || keyword1 == "to") &&
                            separatedList.TryGetStructure<Keyword>(2) == "hex")
                        {
                            return GetResult(number.Value);
                        }
                    }
                }
                else
                {
                    number = separatedList.TryGetStructure<Integer>(1);
                    var keyword1 = separatedList.TryGetStructure<Keyword>(0);
                    if (number != null && keyword1 != null && keyword1 == "hex" && separatedList.Count == 2)
                    {
                        return GetResult(number.Value);
                    }
                }
            }

            return null;
        }

        private string GetResult(int value)
        {
            return Div(Escape($"{value} = 0x{value.ToString("X")}"));
        }
    }
}

Allow syntax like "hex 56"

Allow syntax like "hex 56"


using System;
using DesktopWidgets.Classes;

namespace DesktopWidgets.Widgets.CountdownClock
{
    public class Settings : WidgetClockSettingsBase
    {
        public DateTime EndDateTime { get; set; } = DateTime.Now;
    }
}

using System;
using DesktopWidgets.Classes;

namespace DesktopWidgets.Widgets.CountdownClock
{
    public class Settings : WidgetClockSettingsBase
    {
        public Settings()
        {
            TimeFormat = "dd:hh:mm:ss";
        }

        public DateTime EndDateTime { get; set; } = DateTime.Now;
    }
}

Change "Countdown" widget default "TimeFormat"


public class Conditional : DecoratorTask {
    private ConditionalDelegate conditionalDelegate;

    public Conditional(string name, ConditionalDelegate conditionalDelegate) : base(name)
    {
        this.conditionalDelegate = conditionalDelegate;
    }

    public override ReturnCode Update()
    {
        var value = conditionalDelegate();
        if (value)
        {
            return ReturnCode.Succeed;
        }
        else
        {
            return ReturnCode.Fail;
        }
    }
}

public delegate bool ConditionalDelegate();

public class Conditional : Task {
    private ConditionalDelegate conditionalDelegate;

    public Conditional(string name, ConditionalDelegate conditionalDelegate) : base(name)
    {
        this.conditionalDelegate = conditionalDelegate;
    }

    public override ReturnCode Update()
    {
        var value = conditionalDelegate();
        if (value)
        {
            return ReturnCode.Succeed;
        }
        else
        {
            return ReturnCode.Fail;
        }
    }
}

public delegate bool ConditionalDelegate();

Change conditional from decorator to a task


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

namespace SharpConfig
{
    public interface ITypeStringConverter
    {
        string ConvertToString(object value);
        object ConvertFromString(string value, Type hint);
        Type ConvertibleType { get; }
    }

    public abstract class TypeStringConverter<T> : ITypeStringConverter
    {
        public abstract string ConvertToString(object value);
        public abstract object ConvertFromString(string value, Type hint);

        public Type ConvertibleType
        {
            get { return typeof(T); }
        }
    }
}

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

namespace SharpConfig
{
    /// <summary>
    /// Defines a type-to-string and string-to-type converter
    /// that is used for the conversion of setting values.
    /// </summary>
    public interface ITypeStringConverter
    {
        /// <summary>
        /// Converts an object to its string representation.
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <returns>The object's string representation.</returns>
        string ConvertToString(object value);

        /// <summary>
        /// Converts a string value to an object of this converter's type.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="hint">
        ///     A type hint. This is used rarely, such as in the enum converter.
        ///     The enum converter's official type is Enum, whereas the type hint
        ///     represents the underlying enum type.
        ///     This parameter can be safely ignored for custom converters.
        /// </param>
        /// <returns>The converted object.</returns>
        object ConvertFromString(string value, Type hint);

        /// <summary>
        /// The type that this converter is able to convert to and from a string.
        /// </summary>
        Type ConvertibleType { get; }
    }

    /// <summary>
    /// Represents a type-to-string and string-to-type converter
    /// that is used for the conversion of setting values.
    /// </summary>
    /// <typeparam name="T">The type that this converter is able to convert.</typeparam>
    public abstract class TypeStringConverter<T> : ITypeStringConverter
    {
        /// <summary>
        /// Converts an object to its string representation.
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <returns>The object's string representation.</returns>
        public abstract string ConvertToString(object value);

        /// <summary>
        /// Converts a string value to an object of this converter's type.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="hint">
        ///     A type hint. This is used rarely, such as in the enum converter.
        ///     The enum converter's official type is Enum, whereas the type hint
        ///     represents the underlying enum type.
        ///     This parameter can be safely ignored for custom converters.
        /// </param>
        /// <returns>The converted object.</returns>
        public abstract object ConvertFromString(string value, Type hint);

        /// <summary>
        /// The type that this converter is able to convert to and from a string.
        /// </summary>
        public Type ConvertibleType
        {
            get { return typeof(T); }
        }
    }
}

Add type string converter documentation.


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

namespace Camunda.Api.Client.Identity
{
    public class IdentityVerifiedUser
    {
        /// <summary>
        /// The id of the user
        /// </summary>
        public string AuthenticatedUser;
        /// <summary>
        /// Verification successful or not
        /// </summary>
        public bool IsAuthenticated;

    }
}

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

namespace Camunda.Api.Client.Identity
{
    public class IdentityVerifiedUser
    {
        /// <summary>
        /// The id of the user
        /// </summary>
        public string AuthenticatedUser;
        /// <summary>
        /// Verification successful or not
        /// </summary>
        public bool Authenticated;

    }
}

Fix isAuthenticated -> authenticated to get it working - Camunda docs error