using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SSMScripter.Runner;

namespace SSMScripter.Config
{
    public partial class RunnerConfigForm : Form
    {
        private RunConfig _runConfig;

        public RunnerConfigForm()
        {
            InitializeComponent();
        }

        public RunnerConfigForm(RunConfig runConfig)
            : this()
        {
            _runConfig = runConfig;
            tbTool.Text = _runConfig.IsUndefined() ? String.Empty : (_runConfig.RunTool ?? String.Empty);
            tbArgs.Text = _runConfig.RunArgs ?? String.Empty;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            _runConfig.RunTool = tbTool.Text;
            _runConfig.RunArgs = tbArgs.Text;
            DialogResult = DialogResult.OK;
        }

        private void btnTool_Click(object sender, EventArgs e)
        {
            using(OpenFileDialog dialog = new OpenFileDialog())
            {
                dialog.InitialDirectory = Path.GetDirectoryName(tbTool.Text) ?? String.Empty;
                dialog.FileName = Path.GetFileName(tbTool.Text) ?? String.Empty;
                dialog.Filter = "Exe files (*.exe)|*.exe|All files (*.*)|*.*";
                dialog.RestoreDirectory = true;

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    tbTool.Text = dialog.FileName;
                }
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SSMScripter.Runner;

namespace SSMScripter.Config
{
    public partial class RunnerConfigForm : Form
    {
        private RunConfig _runConfig;

        public RunnerConfigForm()
        {
            InitializeComponent();
        }

        public RunnerConfigForm(RunConfig runConfig)
            : this()
        {
            _runConfig = runConfig;
            tbTool.Text = _runConfig.IsUndefined() ? String.Empty : (_runConfig.RunTool ?? String.Empty);
            tbArgs.Text = _runConfig.RunArgs ?? String.Empty;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            _runConfig.RunTool = tbTool.Text;
            _runConfig.RunArgs = tbArgs.Text;
            DialogResult = DialogResult.OK;
        }

        private void btnTool_Click(object sender, EventArgs e)
        {
            using(OpenFileDialog dialog = new OpenFileDialog())
            {
                if (!String.IsNullOrEmpty(tbTool.Text))
                    dialog.InitialDirectory = Path.GetDirectoryName(tbTool.Text);

                dialog.FileName = Path.GetFileName(tbTool.Text) ?? String.Empty;
                dialog.Filter = "Exe files (*.exe)|*.exe|All files (*.*)|*.*";
                dialog.RestoreDirectory = true;

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    tbTool.Text = dialog.FileName;
                }
            }
        }
    }
}

Fix exception caused by getting directory name from empty string in runner config editor


namespace NerdBank.GitVersioning.CloudBuildServices
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using Nerdbank.GitVersioning;

    internal class GitHubActions : ICloudBuild
    {
        public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true";

        public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent";

        public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null;

        public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null;

        public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA");

        private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF");

        public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr)
        {
            return new Dictionary<string, string>();
        }

        public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr)
        {
            return new Dictionary<string, string>();
        }
    }
}

namespace NerdBank.GitVersioning.CloudBuildServices
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using Nerdbank.GitVersioning;

    internal class GitHubActions : ICloudBuild
    {
        public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true";

        public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent";

        public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null;

        public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null;

        public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA");

        private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF");

        public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr)
        {
            return new Dictionary<string, string>();
        }

        public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr)
        {
            (stdout ?? Console.Out).WriteLine($"##[set-env name={name};]{value}");
            return GetDictionaryFor(name, value);
        }

        private static IReadOnlyDictionary<string, string> GetDictionaryFor(string variableName, string value)
        {
            return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { GetEnvironmentVariableNameForVariable(variableName), value },
            };
        }

        private static string GetEnvironmentVariableNameForVariable(string name) => name.ToUpperInvariant().Replace('.', '_');
    }
}

Set env vars in GitHub Actions

Set env vars in GitHub Actions


using System;
using System.Data;
using Dapper.FastCrud;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
    public class UnitOfWork : DbTransaction, IUnitOfWork
    {
        public SqlDialect SqlDialect { get; }
        private readonly Guid _guid = Guid.NewGuid();

        public UnitOfWork(IDbFactory factory, ISession session,
            IsolationLevel isolationLevel = IsolationLevel.Serializable, bool sessionOnlyForThisUnitOfWork = false) : base(factory)
        {
            if (sessionOnlyForThisUnitOfWork)
            {
                Session = session;
            }
            Transaction = session.BeginTransaction(isolationLevel);
            SqlDialect = session.SqlDialect;
        }

        protected bool Equals(UnitOfWork other)
        {
            return _guid.Equals(other._guid);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((UnitOfWork) obj);
        }

        public override int GetHashCode()
        {
            return _guid.GetHashCode();
        }

        public static bool operator ==(UnitOfWork left, UnitOfWork right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(UnitOfWork left, UnitOfWork right)
        {
            return !Equals(left, right);
        }
    }
}

using System;
using System.Data;
using Dapper.FastCrud;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
    public class UnitOfWork : DbTransaction, IUnitOfWork
    {
        public SqlDialect SqlDialect { get; }
        private readonly Guid _guid = Guid.NewGuid();

        public UnitOfWork(IDbFactory factory, ISession session,
            IsolationLevel isolationLevel = IsolationLevel.RepeatableRead, bool sessionOnlyForThisUnitOfWork = false) : base(factory)
        {
            if (sessionOnlyForThisUnitOfWork)
            {
                Session = session;
            }
            Transaction = session.BeginTransaction(isolationLevel);
            SqlDialect = session.SqlDialect;
        }

        protected bool Equals(UnitOfWork other)
        {
            return _guid.Equals(other._guid);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((UnitOfWork) obj);
        }

        public override int GetHashCode()
        {
            return _guid.GetHashCode();
        }

        public static bool operator ==(UnitOfWork left, UnitOfWork right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(UnitOfWork left, UnitOfWork right)
        {
            return !Equals(left, right);
        }
    }
}

Change uow to default to IsolationLevel.RepeatableRead


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

public class ScoreCounter : MonoBehaviour
{
    [Inject]
    public StageStats Stats { get; private set; }

    void Start() {
        Stats.BallsTotal = Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length;
        StartCoroutine(Count());
	}

    IEnumerator Count()
    {
        while (true)
        {
            yield return new WaitForSeconds(1);
            Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length;
        }
    }

}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Zenject;

public class ScoreCounter : MonoBehaviour
{
    [Inject]
    public StageStats Stats { get; private set; }

    void Start() {
        Stats.BallsTotal = Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length;
        StartCoroutine(Count());
	}

    IEnumerator Count()
    {
        while (true)
        {
            yield return new WaitForSeconds(1);
            Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length;

            if (Stats.BallsLeft == 0)
            {
                SceneManager.LoadScene("MainMenu");
            }
        }
    }

}

Revert to main menu on 0 balls left.

Revert to main menu on 0 balls left.


using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class ReloadScene : MonoBehaviour {

    GlobalControl globalController;
    bool allowLevelLoad = true;

    void OnEnable()
    {
        allowLevelLoad = true;
    }

    // Use this for initialization
    public void ReloadActiveScene () {
        if (allowLevelLoad)
        {
            allowLevelLoad = false;
            globalController = (GlobalControl)FindObjectOfType(typeof(GlobalControl));
            globalController.globalMultiplayerManager.gameObject.SetActive(true);
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
    }
}

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class ReloadScene : MonoBehaviour {

    GlobalControl globalController;
    bool allowLevelLoad = true;

    void OnEnable()
    {
        allowLevelLoad = true;
    }

    // Use this for initialization
    public void ReloadActiveScene () {
        if (allowLevelLoad)
        {
            allowLevelLoad = false;

            Invoke("LoadScene", 0.33f);
        }
    }

    private void LoadScene()
    {
        globalController = (GlobalControl)FindObjectOfType(typeof(GlobalControl));
        globalController.globalMultiplayerManager.gameObject.SetActive(true);
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}

Add delay for ReloadActiveScene to prevent stuck button


using Nito.AsyncEx;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Alteridem.GetChanges
{
    class Program
    {
        static int Main(string[] args)
        {
            var options = new Options();
            if (!CommandLine.Parser.Default.ParseArguments(args, options))
            {
                Console.WriteLine(options.GetUsage());
                return -1;
            }

            AsyncContext.Run(() => MainAsync(options));

            Console.WriteLine("*** Press ENTER to Exit ***");
            Console.ReadLine();
            return 0;
        }

        static async void MainAsync(Options options)
        {
            var github = new GitHubApi("nunit", "nunit");

            var milestones = await github.GetAllMilestones();
            var issues = await github.GetClosedIssues();

            var noMilestoneIssues = from i in issues where i.Milestone == null select i;
            DisplayIssuesForMilestone("Issues with no milestone", noMilestoneIssues);

            foreach (var milestone in milestones)
            {
                var milestoneIssues = from i in issues where i.Milestone != null && i.Milestone.Number == milestone.Number select i;
                DisplayIssuesForMilestone(milestone.Title, milestoneIssues);
            }
        }

        static void DisplayIssuesForMilestone(string milestone, IEnumerable<Issue> issues)
        {
            Console.WriteLine("## {0}", milestone);
            Console.WriteLine();

            foreach (var issue in issues)
            {
                Console.WriteLine(" * {0:####} {1}", issue.Number, issue.Title);
            }
            Console.WriteLine();
        }
    }
}

using Nito.AsyncEx;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Alteridem.GetChanges
{
    class Program
    {
        static int Main(string[] args)
        {
            var options = new Options();
            if (!CommandLine.Parser.Default.ParseArguments(args, options))
            {
                Console.WriteLine(options.GetUsage());
                return -1;
            }

            AsyncContext.Run(() => MainAsync(options));

            Console.WriteLine("*** Press ENTER to Exit ***");
            Console.ReadLine();
            return 0;
        }

        static async void MainAsync(Options options)
        {
            var github = new GitHubApi(options.Organization, options.Repository);

            var milestones = await github.GetAllMilestones();
            var issues = await github.GetClosedIssues();

            var noMilestoneIssues = from i in issues where i.Milestone == null select i;
            DisplayIssuesForMilestone("Issues with no milestone", noMilestoneIssues);

            foreach (var milestone in milestones)
            {
                var milestoneIssues = from i in issues where i.Milestone != null && i.Milestone.Number == milestone.Number select i;
                DisplayIssuesForMilestone(milestone.Title, milestoneIssues);
            }
        }

        static void DisplayIssuesForMilestone(string milestone, IEnumerable<Issue> issues)
        {
            Console.WriteLine("## {0}", milestone);
            Console.WriteLine();

            foreach (var issue in issues)
            {
                Console.WriteLine(" * {0:####} {1}", issue.Number, issue.Title);
            }
            Console.WriteLine();
        }
    }
}

Use the options when connecting to GitHub


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

namespace Bugsnag
{
  public class Event : Dictionary<string, object>
  {
    public Event(IConfiguration configuration, System.Exception exception, Severity severity)
    {
      this["payloadVersion"] = 2;
      this["exceptions"] = new Exceptions(exception).ToArray();
      this["app"] = new App(configuration);

      switch (severity)
      {
        case Severity.Info:
          this["severity"] = "info";
          break;
        case Severity.Warning:
          this["severity"] = "warning";
          break;
        default:
          this["severity"] = "error";
          break;
      }
    }

    public Exception[] Exceptions
    {
      get { return this["exceptions"] as Exception[]; }
      set { this.AddToPayload("exceptions", value); }
    }
  }
}

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

namespace Bugsnag
{
  public class Event : Dictionary<string, object>
  {
    public Event(IConfiguration configuration, System.Exception exception, Severity severity)
    {
      this["payloadVersion"] = 4;
      this["exceptions"] = new Exceptions(exception).ToArray();
      this["app"] = new App(configuration);

      switch (severity)
      {
        case Severity.Info:
          this["severity"] = "info";
          break;
        case Severity.Warning:
          this["severity"] = "warning";
          break;
        default:
          this["severity"] = "error";
          break;
      }
    }

    public Exception[] Exceptions
    {
      get { return this["exceptions"] as Exception[]; }
      set { this.AddToPayload("exceptions", value); }
    }

    public string Context
    {
      get { return this["context"] as string; }
      set { this.AddToPayload("context", value); }
    }

    public string GroupingHash
    {
      get { return this["groupingHash"] as string; }
      set { this.AddToPayload("groupingHash", value); }
    }
  }
}

Allow setting grouping hash and context

Allow setting grouping hash and context


/*
 * John.Hall <john.hall@camtechconsultants.com>
 * Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved.
 */

using System;
using System.Collections.Generic;

namespace CTC.CvsntGitImporter.Utils
{
	/// <summary>
	/// Extension methods for IEnumerable.
	/// </summary>
	static class IEnumerableExtensions
	{
		/// <summary>
		/// Perform the equivalent of String.Join on a sequence.
		/// </summary>
		/// <typeparam name="T">the type of the elements of source</typeparam>
		/// <param name="source">the sequence of values to join</param>
		/// <param name="separator">a string to insert between each item</param>
		/// <returns>a string containing the items in the sequence concenated and separated by the separator</returns>
		public static string StringJoin<T>(this IEnumerable<T> source, string separator)
		{
			return String.Join(separator, source);
		}
	}
}

/*
 * John.Hall <john.hall@camtechconsultants.com>
 * Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved.
 */

using System;
using System.Collections.Generic;

namespace CTC.CvsntGitImporter.Utils
{
	/// <summary>
	/// Extension methods for IEnumerable.
	/// </summary>
	static class IEnumerableExtensions
	{
		/// <summary>
		/// Perform the equivalent of String.Join on a sequence.
		/// </summary>
		/// <typeparam name="T">the type of the elements of source</typeparam>
		/// <param name="source">the sequence of values to join</param>
		/// <param name="separator">a string to insert between each item</param>
		/// <returns>a string containing the items in the sequence concenated and separated by the separator</returns>
		public static string StringJoin<T>(this IEnumerable<T> source, string separator)
		{
			return String.Join(separator, source);
		}

		/// <summary>
		/// Create a HashSet from a list of items.
		/// </summary>
		public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
		{
			return new HashSet<T>(source);
		}

		/// <summary>
		/// Create a HashSet from a list of items.
		/// </summary>
		public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer)
		{
			return new HashSet<T>(source, comparer);
		}
	}
}

Add ToHashSet extension methods on IEnumerable.


//-----------------------------------------------------------------------
// <copyright file="ValidatingReceiver.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace CommSample
{
    using System;
    using System.Threading.Tasks;

    internal sealed class ValidatingReceiver
    {
        private readonly Receiver receiver;
        private readonly DataOracle oracle;

        private byte lastSeen;
        private int lastCount;

        public ValidatingReceiver(MemoryChannel channel, Logger logger, int bufferSize, DataOracle oracle)
        {
            this.receiver = new Receiver(channel, logger, bufferSize);
            this.oracle = oracle;
            this.receiver.DataReceived += this.OnDataReceived;
        }

        public Task<long> RunAsync()
        {
            return this.receiver.RunAsync();
        }

        private void OnDataReceived(object sender, DataEventArgs e)
        {
            for (int i = 0; i < e.BytesRead; ++i)
            {
                if (this.lastSeen != e.Buffer[i])
                {
                    if (this.lastSeen != 0)
                    {
                        this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount);
                    }

                    this.lastSeen = e.Buffer[i];
                    this.lastCount = 0;
                }

                ++this.lastCount;
            }
        }
    }
}

//-----------------------------------------------------------------------
// <copyright file="ValidatingReceiver.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace CommSample
{
    using System;
    using System.Threading.Tasks;

    internal sealed class ValidatingReceiver
    {
        private readonly Receiver receiver;
        private readonly DataOracle oracle;

        private byte lastSeen;
        private int lastCount;

        public ValidatingReceiver(MemoryChannel channel, Logger logger, int bufferSize, DataOracle oracle)
        {
            this.receiver = new Receiver(channel, logger, bufferSize);
            this.oracle = oracle;
            this.receiver.DataReceived += this.OnDataReceived;
        }

        public Task<long> RunAsync()
        {
            return this.receiver.RunAsync();
        }

        private void OnDataReceived(object sender, DataEventArgs e)
        {
            for (int i = 0; i < e.BytesRead; ++i)
            {
                if (this.lastSeen != e.Buffer[i])
                {
                    if (this.lastSeen != 0)
                    {
                        this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount);
                    }

                    this.lastSeen = e.Buffer[i];
                    this.lastCount = 0;
                }

                ++this.lastCount;
            }

            if (e.BytesRead == 0)
            {
                this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount);
            }
        }
    }
}

Add missing final validation pass (bytes read == 0)


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

namespace Ploeh.AutoFixture
{
    public static class IFixtureExtensions
    {
        public static IEnumerable<T> Repeat<T>(this IFixture fixture, Func<T> function)
        {
            throw new NotImplementedException();
        }
    }
}

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

namespace Ploeh.AutoFixture
{
    public static class IFixtureExtensions
    {
        public static IEnumerable<T> Repeat<T>(this IFixture fixture, Func<T> function)
        {
            if (fixture == null)
            {
                throw new ArgumentNullException("fixture");
            }

            throw new NotImplementedException();
        }
    }
}

Implement code making the previously failing unit test pass.


// Copyright 2016 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using Microsoft.AspNetCore.Mvc;
using NodaTime.TimeZones;
using NodaTime.TzValidate.NodaDump;
using System.IO;
using System.Net;

namespace NodaTime.Web.Controllers
{
    public class TzValidateController : Controller
    {
        // This will do something soon :)
        [Route("/tzvalidate/generate")]
        public IActionResult Generate(int startYear = 1, int endYear = 2035)
        {
            var source = TzdbDateTimeZoneSource.Default;
            var writer = new StringWriter();
            var options = new Options { FromYear = startYear, ToYear = endYear };
            var dumper = new ZoneDumper(source, options);
            dumper.Dump(writer);

            return new ContentResult
            {
                Content = writer.ToString(),
                ContentType = "text/plain",
                StatusCode = (int) HttpStatusCode.OK
            };
        }
    }
}

// Copyright 2016 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using Microsoft.AspNetCore.Mvc;
using NodaTime.TimeZones;
using NodaTime.TzValidate.NodaDump;
using NodaTime.Web.Models;
using System.IO;
using System.Linq;
using System.Net;

namespace NodaTime.Web.Controllers
{
    public class TzValidateController : Controller
    {
        private readonly ITzdbRepository repository;

        public TzValidateController(ITzdbRepository repository) =>
            this.repository = repository;

        [Route("/tzvalidate/generate")]
        public IActionResult Generate(int startYear = 1, int endYear = 2035, string zone = null, string version = null)
        {
            if (startYear < 1 || endYear > 3000 || startYear > endYear)
            {
                return BadRequest("Invalid start/end year combination");
            }

            var source = TzdbDateTimeZoneSource.Default;
            if (version != null)
            {
                var release = repository.GetRelease($"tzdb{version}.nzd");
                if (release == null)
                {
                    return BadRequest("Unknown version");
                }
                source = TzdbDateTimeZoneSource.FromStream(release.GetContent());
            }

            if (zone != null && !source.GetIds().Contains(zone))
            {
                return BadRequest("Unknown zone");
            }

            var writer = new StringWriter();
            var options = new Options { FromYear = startYear, ToYear = endYear, ZoneId = zone };
            var dumper = new ZoneDumper(source, options);
            dumper.Dump(writer);

            return new ContentResult
            {
                Content = writer.ToString(),
                ContentType = "text/plain",
                StatusCode = (int) HttpStatusCode.OK
            };
        }
    }
}

Allow a zone and version to be specified in the tzvalidate controller


using Autofac;
using Chassis.Features;
using Chassis.Types;

namespace Chassis.Startup
{
    public class StartupFeature : Feature
    {
        public override void RegisterComponents(ContainerBuilder builder, TypePool pool)
        {
            builder.RegisterType<StartupBootstrapper>()
                .SingleInstance()
                .AsSelf();

            var actions = pool.FindImplementorsOf<IStartupStep>();

            foreach (var action in actions)
            {
                builder.RegisterType(action)
                    .As<IStartupStep>()
                    .AsSelf();
            }

            var webActions = pool.FindImplementorsOf<IWebStartupStep>();

            foreach (var action in webActions)
            {
                builder.RegisterType(action)
                    .As<IWebStartupStep>()
                    .AsSelf();
            }
        }
    }
}

using Autofac;
using Chassis.Features;
using Chassis.Types;

namespace Chassis.Startup
{
    public class StartupFeature : Feature
    {
        public override void RegisterComponents(ContainerBuilder builder, TypePool pool)
        {
            builder.RegisterType<StartupBootstrapper>()
                .InstancePerLifetimeScope()
                .AsSelf();

            var actions = pool.FindImplementorsOf<IStartupStep>();

            foreach (var action in actions)
            {
                builder.RegisterType(action)
                    .As<IStartupStep>()
                    .AsSelf();
            }

            var webActions = pool.FindImplementorsOf<IWebStartupStep>();

            foreach (var action in webActions)
            {
                builder.RegisterType(action)
                    .As<IWebStartupStep>()
                    .AsSelf();
            }
        }
    }
}

Change Scope to support multi-tenant scenarios


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

namespace CalSync.Infrastructure
{
    class Config
    {
        public int SyncRangeDays { get; private set; }
        public string TargetEmailAddress { get; private set; }
        public bool Receive { get; private set; }
        public bool DetailedAppointment { get; private set; }
        public bool Send { get; private set; }
        public String ErrorMessage { get; private set; }

        public static Config Read()
        {
            try
            {
                return new Config()
                {
                    SyncRangeDays = int.Parse(ConfigurationManager.AppSettings["SyncRangeDays"]),
                    TargetEmailAddress = ConfigurationManager.AppSettings["TargetEmailAddress"],
                    Receive = bool.Parse(ConfigurationManager.AppSettings["Receive"] ?? "true"),
                    DetailedAppointment = bool.Parse(ConfigurationManager.AppSettings["DetailedAppointment"] ?? "true"),
                    Send = bool.Parse(ConfigurationManager.AppSettings["Send"] ?? "true"),
                };
            }
            catch(Exception e)
            {
                if(e is ConfigurationErrorsException || e is FormatException || e is OverflowException )
                {
                    return new Config()
                    {
                        ErrorMessage = e.Message
                    };
                }
                throw;
            }

        }
    }
}

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

namespace CalSync.Infrastructure
{
    class Config
    {
        public int SyncRangeDays { get; private set; }
        public string TargetEmailAddress { get; private set; }
        public bool Receive { get; private set; }
        public bool Send { get; private set; }
        public bool DetailedAppointment { get; private set; }
        public String ErrorMessage { get; private set; }

        public static Config Read()
        {
            try
            {
                return new Config()
                {
                    SyncRangeDays = int.Parse(ConfigurationManager.AppSettings["SyncRangeDays"]),
                    TargetEmailAddress = ConfigurationManager.AppSettings["TargetEmailAddress"],
                    Receive = bool.Parse(ConfigurationManager.AppSettings["Receive"] ?? "true"),
                    Send = bool.Parse(ConfigurationManager.AppSettings["Send"] ?? "true"),
                    DetailedAppointment = bool.Parse(ConfigurationManager.AppSettings["DetailedAppointment"] ?? "false"),
                };
            }
            catch(Exception e)
            {
                if(e is ConfigurationErrorsException || e is FormatException || e is OverflowException )
                {
                    return new Config()
                    {
                        ErrorMessage = e.Message
                    };
                }
                throw;
            }

        }
    }
}

Change default for DetailedAppointments to 'false'


using System;
using System.Linq;
using System.Web.Mvc;
using FujiyBlog.Core.DomainObjects;

namespace FujiyBlog.Web.Infrastructure
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AuthorizePermissionAttribute : AuthorizeAttribute
    {
        public AuthorizePermissionAttribute(params Permission[] permissions)
        {
            if (permissions == null)
            {
                throw new ArgumentNullException("permissions");
            }

            Roles = string.Join(",", permissions.Select(r => r.ToString()));
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);
            filterContext.HttpContext.Response.StatusCode = 401;
            filterContext.HttpContext.Response.WriteFile("~/errors/401.htm");
            filterContext.HttpContext.Response.End();
        }
    }
}

using System;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using FujiyBlog.Core.DomainObjects;
using FujiyBlog.Core.Extensions;

namespace FujiyBlog.Web.Infrastructure
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AuthorizePermissionAttribute : AuthorizeAttribute
    {
        public AuthorizePermissionAttribute(params Permission[] permissions)
        {
            if (permissions == null)
            {
                throw new ArgumentNullException("permissions");
            }

            Roles = string.Join(",", permissions.Select(r => r.ToString()));
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            IPrincipal user = httpContext.User;

            var usersSplit = SplitString(Users);
            var rolesSplit = SplitString(Roles).Select(x => (Permission) Enum.Parse(typeof (Permission), x)).ToArray();

            if (usersSplit.Length > 0 && !usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
            {
                return false;
            }

            if (rolesSplit.Length > 0 && !rolesSplit.Any(user.IsInRole))
            {
                return false;
            }

            return true;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);
            filterContext.HttpContext.Response.StatusCode = 401;
            filterContext.HttpContext.Response.WriteFile("~/errors/401.htm");
            filterContext.HttpContext.Response.End();
        }

        static string[] SplitString(string original)
        {
            if (String.IsNullOrEmpty(original))
            {
                return new string[0];
            }

            var split = from piece in original.Split(',')
                        let trimmed = piece.Trim()
                        where !String.IsNullOrEmpty(trimmed)
                        select trimmed;
            return split.ToArray();
        }
    }
}

Fix to work with Anonymous Roles

Fix to work with Anonymous Roles


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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")]

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

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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")]

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

Rename finished, Bumped version to 0.9

Rename finished, Bumped version to 0.9


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

namespace RichardSzalay.MockHttp.Matchers
{
    public class QueryStringMatcher : IMockedRequestMatcher
    {
        readonly IEnumerable<KeyValuePair<string, string>> values;

        public QueryStringMatcher(string queryString)
            : this(ParseQueryString(queryString))
        {

        }

        public QueryStringMatcher(IEnumerable<KeyValuePair<string, string>> values)
        {
            this.values = values;
        }

        public bool Matches(System.Net.Http.HttpRequestMessage message)
        {
            var queryString = ParseQueryString(message.RequestUri.Query.TrimStart('?'));

            return values.All(matchPair =>
                queryString.Any(p => p.Key == matchPair.Key && p.Value == matchPair.Value));
        }

        internal static IEnumerable<KeyValuePair<string, string>> ParseQueryString(string input)
        {
            return input.TrimStart('?').Split('&')
                .Select(pair => StringUtil.Split(pair, '=', 2))
                .Select(pair => new KeyValuePair<string, string>(
                    Uri.UnescapeDataString(pair[0]),
                    pair.Length == 2 ? Uri.UnescapeDataString(pair[1]) : null
                    ))
                .ToList();
        }
    }
}

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

namespace RichardSzalay.MockHttp.Matchers
{
    public class QueryStringMatcher : IMockedRequestMatcher
    {
        readonly IEnumerable<KeyValuePair<string, string>> values;

        public QueryStringMatcher(string queryString)
            : this(ParseQueryString(queryString))
        {

        }

        public QueryStringMatcher(IEnumerable<KeyValuePair<string, string>> values)
        {
            this.values = values;
        }

        public bool Matches(System.Net.Http.HttpRequestMessage message)
        {
            var queryString = ParseQueryString(message.RequestUri.Query.TrimStart('?'));

            return values.All(matchPair =>
                queryString.Any(p => p.Key == matchPair.Key && p.Value == matchPair.Value));
        }

        internal static IEnumerable<KeyValuePair<string, string>> ParseQueryString(string input)
        {
            return input.TrimStart('?').Split('&')
                .Select(pair => StringUtil.Split(pair, '=', 2))
                .Select(pair => new KeyValuePair<string, string>(
                    Uri.UnescapeDataString(pair[0]),
                    pair.Length == 2 ? Uri.UnescapeDataString(pair[1]) : ""
                    ))
                .ToList();
        }
    }
}

Update key-only querystring comparisons to use "" rather than null to make it more compatible with form data


using System.Runtime.Serialization;

namespace Omise.Models
{
    public enum OffsiteTypes
    {
        [EnumMember(Value = null)]
        None,
        [EnumMember(Value = "internet_banking_scb")]
        InternetBankingSCB,
        [EnumMember(Value = "internet_banking_bbl")]
        InternetBankingBBL,
        [EnumMember(Value = "internet_banking_ktb")]
        InternetBankingKTB,
        [EnumMember(Value = "internet_banking_bay")]
        InternetBankingBAY,
        [EnumMember(Value = "alipay")]
        AlipayOnline,
        [EnumMember(Value = "installment_bay")]
        InstallmentBAY,
        [EnumMember(Value = "installment_kbank")]
        InstallmentKBank,
        [EnumMember(Value = "bill_payment_tesco_lotus")]
        BillPaymentTescoLotus,
        [EnumMember(Value = "barcode_alipay")]
        BarcodeAlipay,
        [EnumMember(Value = "paynow")]
        Paynow,
        [EnumMember(Value = "points_citi")]
        PointsCiti,
        [EnumMember(Value = "promptpay")]
        PromptPay,
        [EnumMember(Value = "truemoney")]
        TrueMoney
    }
}

using System.Runtime.Serialization;

namespace Omise.Models
{
    public enum OffsiteTypes
    {
        [EnumMember(Value = null)]
        None,
        [EnumMember(Value = "internet_banking_scb")]
        InternetBankingSCB,
        [EnumMember(Value = "internet_banking_bbl")]
        InternetBankingBBL,
        [EnumMember(Value = "internet_banking_ktb")]
        InternetBankingKTB,
        [EnumMember(Value = "internet_banking_bay")]
        InternetBankingBAY,
        [EnumMember(Value = "alipay")]
        AlipayOnline,
        [EnumMember(Value = "installment_bay")]
        InstallmentBAY,
        [EnumMember(Value = "installment_kbank")]
        InstallmentKBank,
        [EnumMember(Value = "installment_citi")]
        InstallmentCiti,
        [EnumMember(Value = "bill_payment_tesco_lotus")]
        BillPaymentTescoLotus,
        [EnumMember(Value = "barcode_alipay")]
        BarcodeAlipay,
        [EnumMember(Value = "paynow")]
        Paynow,
        [EnumMember(Value = "points_citi")]
        PointsCiti,
        [EnumMember(Value = "promptpay")]
        PromptPay,
        [EnumMember(Value = "truemoney")]
        TrueMoney
    }
}

Add offsite types for installment citi

Add offsite types for installment citi


using System.IO;
using System.Linq;
using System.Windows.Forms;
using GUI.Utils;

namespace GUI.Types.Viewers
{
    public class ByteViewer : IViewer
    {
        public static bool IsAccepted() => true;

        public TabPage Create(VrfGuiContext vrfGuiContext, byte[] input)
        {
            var tab = new TabPage();
            var resTabs = new TabControl
            {
                Dock = DockStyle.Fill,
            };
            tab.Controls.Add(resTabs);

            var bvTab = new TabPage("Hex");
            var bv = new System.ComponentModel.Design.ByteViewer
            {
                Dock = DockStyle.Fill,
            };
            bvTab.Controls.Add(bv);
            resTabs.TabPages.Add(bvTab);

            if (input == null)
            {
                input = File.ReadAllBytes(vrfGuiContext.FileName);
            }

            if (!input.Contains<byte>(0x00))
            {
                var textTab = new TabPage("Text");
                var text = new TextBox
                {
                    Dock = DockStyle.Fill,
                    ScrollBars = ScrollBars.Vertical,
                    Multiline = true,
                    ReadOnly = true,
                    Text = System.Text.Encoding.UTF8.GetString(input),
                };
                textTab.Controls.Add(text);
                resTabs.TabPages.Add(textTab);
                resTabs.SelectedTab = textTab;
            }

            Program.MainForm.Invoke((MethodInvoker)(() =>
            {
                bv.SetBytes(input);
            }));

            return tab;
        }
    }
}

using System.IO;
using System.Linq;
using System.Windows.Forms;
using GUI.Utils;

namespace GUI.Types.Viewers
{
    public class ByteViewer : IViewer
    {
        public static bool IsAccepted() => true;

        public TabPage Create(VrfGuiContext vrfGuiContext, byte[] input)
        {
            var tab = new TabPage();
            var resTabs = new TabControl
            {
                Dock = DockStyle.Fill,
            };
            tab.Controls.Add(resTabs);

            var bvTab = new TabPage("Hex");
            var bv = new System.ComponentModel.Design.ByteViewer
            {
                Dock = DockStyle.Fill,
            };
            bvTab.Controls.Add(bv);
            resTabs.TabPages.Add(bvTab);

            if (input == null)
            {
                input = File.ReadAllBytes(vrfGuiContext.FileName);
            }

            if (!input.Contains<byte>(0x00))
            {
                var textTab = new TabPage("Text");
                var text = new TextBox
                {
                    Dock = DockStyle.Fill,
                    ScrollBars = ScrollBars.Vertical,
                    Multiline = true,
                    ReadOnly = true,
                    Text = Utils.Utils.NormalizeLineEndings(System.Text.Encoding.UTF8.GetString(input)),
                };
                textTab.Controls.Add(text);
                resTabs.TabPages.Add(textTab);
                resTabs.SelectedTab = textTab;
            }

            Program.MainForm.Invoke((MethodInvoker)(() =>
            {
                bv.SetBytes(input);
            }));

            return tab;
        }
    }
}

Normalize line endings in text viewer

Normalize line endings in text viewer


using System;
using System.Collections.Generic;
using System.Numerics;

namespace ValveResourceFormat.ResourceTypes.ModelAnimation
{
    public class Frame
    {
        public Dictionary<string, FrameBone> Bones { get; }

        public Frame()
        {
            Bones = new Dictionary<string, FrameBone>();
        }

        public void SetAttribute(string bone, string attribute, object data)
        {
            switch (attribute)
            {
                case "Position":
                    GetBone(bone).Position = (Vector3)data;
                    break;

                case "Angle":
                    GetBone(bone).Angle = (Quaternion)data;
                    break;

                case "data":
                    //ignore
                    break;
#if DEBUG
                default:
                    Console.WriteLine($"Unknown frame attribute '{attribute}' encountered");
                    break;
#endif
            }
        }

        private FrameBone GetBone(string name)
        {
            if (!Bones.TryGetValue(name, out var bone))
            {
                bone = new FrameBone(new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 1));

                Bones[name] = bone;
            }

            return bone;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Numerics;

namespace ValveResourceFormat.ResourceTypes.ModelAnimation
{
    public class Frame
    {
        public Dictionary<string, FrameBone> Bones { get; }

        public Frame()
        {
            Bones = new Dictionary<string, FrameBone>();
        }

        public void SetAttribute(string bone, string attribute, Vector3 data)
        {
            switch (attribute)
            {
                case "Position":
                    GetBone(bone).Position = data;
                    break;

                case "data":
                    //ignore
                    break;

#if DEBUG
                default:
                    Console.WriteLine($"Unknown frame attribute '{attribute}' encountered with Vector3 data");
                    break;
#endif
            }
        }

        public void SetAttribute(string bone, string attribute, Quaternion data)
        {
            switch (attribute)
            {
                case "Angle":
                    GetBone(bone).Angle = data;
                    break;

                case "data":
                    //ignore
                    break;

#if DEBUG
                default:
                    Console.WriteLine($"Unknown frame attribute '{attribute}' encountered with Quaternion data");
                    break;
#endif
            }
        }

        private FrameBone GetBone(string name)
        {
            if (!Bones.TryGetValue(name, out var bone))
            {
                bone = new FrameBone(new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 1));

                Bones[name] = bone;
            }

            return bone;
        }
    }
}

Add separate overloads for Vector3/Quaternion to remove casts


using System;
using Microsoft.Extensions.Options;

namespace Meraki
{
    /// <summary>
    /// Initialize a <see cref="MerakiDashboardClientSettings"/> object.
    /// </summary>
    internal class MerakiDashboardClientSettingsSetup : ConfigureOptions<MerakiDashboardClientSettings>
    {
        /// <summary>
        /// Create a new <see cref="MerakiDashboardClientSettingsSetup"/> object.
        /// </summary>
        public MerakiDashboardClientSettingsSetup() : base(ConfigureOptions)
        {
            // Do nothing
        }

        /// <summary>
        /// Configure the <see cref="MerakiDashboardClientSettings"/> object.
        /// </summary>
        /// <param name="options">
        /// The <see cref="MerakiDashboardClientSettings"/> object to configure.
        /// </param>
        private static void ConfigureOptions(MerakiDashboardClientSettings options)
        {
            options.Address = new Uri("https://dashboard.meraki.com", UriKind.Absolute);
            options.Key = "";
        }
    }
}

using System;
using Microsoft.Extensions.Options;

namespace Meraki
{
    /// <summary>
    /// Initialize a <see cref="MerakiDashboardClientSettings"/> object.
    /// </summary>
    internal class MerakiDashboardClientSettingsSetup : ConfigureOptions<MerakiDashboardClientSettings>
    {
        public static readonly string DefaultMerakiDashboardApiBaseAddress = "https://dashboard.meraki.com";

        /// <summary>
        /// Create a new <see cref="MerakiDashboardClientSettingsSetup"/> object.
        /// </summary>
        public MerakiDashboardClientSettingsSetup() : base(ConfigureOptions)
        {
            // Do nothing
        }

        /// <summary>
        /// Configure the <see cref="MerakiDashboardClientSettings"/> object.
        /// </summary>
        /// <param name="options">
        /// The <see cref="MerakiDashboardClientSettings"/> object to configure.
        /// </param>
        private static void ConfigureOptions(MerakiDashboardClientSettings options)
        {
            options.Address = new Uri(DefaultMerakiDashboardApiBaseAddress, UriKind.Absolute);
            options.Key = "";
        }
    }
}

Move default Dashboard API base address to constant


using System.Linq;
using System.Xml.Linq;

namespace Tests.Daterpillar.Helpers
{
    public static class ConnectionString
    {
        private static readonly string _configFile = "database.config.xml";

        public static string GetMySQLServerConnectionString()
        {
            return GetConnectionString("mysql");
        }

        public static string GetSQLServerConnectionString()
        {
            return GetConnectionString("mssql");
        }

        internal static string GetConnectionString(string name)
        {
            var doc = XDocument.Load(_configFile);
            var connectionStrings = doc.Element("connectionStrings");

            var record = (from element in connectionStrings.Descendants("add")
                          where element.Attribute("name").Value == name
                          select element)
                          .First();

            var connStr = new System.Data.Common.DbConnectionStringBuilder();
            connStr.Add("server", record.Attribute("server").Value);
            connStr.Add("user", record.Attribute("user").Value);
            connStr.Add("password", record.Attribute("password").Value);

            return connStr.ConnectionString;
        }
    }
}

using System.Configuration;

namespace Tests.Daterpillar.Helpers
{
    public static class ConnectionString
    {
        public static string GetMySQLServerConnectionString()
        {
            return GetConnectionString("mysql");
        }

        public static string GetSQLServerConnectionString()
        {
            return GetConnectionString("mssql");
        }

        internal static string GetConnectionString(string name)
        {
            var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = "user.config" };
            var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            return config.ConnectionStrings.ConnectionStrings[name].ConnectionString;
        }
    }
}

Change user.config format to app.confg schema


using CefSharp;

namespace TweetDuck.Core.Handling{
    class RequestHandlerBrowser : RequestHandler{
        public override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status){
            browser.Reload();
        }

        public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback){
            if (request.ResourceType == ResourceType.Script && request.Url.Contains("google_analytics.")){
                return CefReturnValue.Cancel;
            }

            return CefReturnValue.Continue;
        }
    }
}

using CefSharp;

namespace TweetDuck.Core.Handling{
    class RequestHandlerBrowser : RequestHandler{
        public override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status){
            browser.Reload();
        }

        public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback){
            if (request.ResourceType == ResourceType.Script && request.Url.Contains("analytics.")){
                return CefReturnValue.Cancel;
            }

            return CefReturnValue.Continue;
        }
    }
}

Tweak google analytics detection to work on twitter.com


// 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.Audio;
using osu.Framework.IO.Stores;
using osuTK.Graphics;

namespace osu.Game.Skinning
{
    public class DefaultLegacySkin : LegacySkin
    {
        public DefaultLegacySkin(IResourceStore<byte[]> storage, AudioManager audioManager)
            : base(Info, storage, audioManager, string.Empty)
        {
            Configuration.CustomColours["SliderBall"] = new Color4(2, 170, 255, 255);
        }

        public static SkinInfo Info { get; } = new SkinInfo
        {
            ID = -1, // this is temporary until database storage is decided upon.
            Name = "osu!classic",
            Creator = "team osu!"
        };
    }
}

// 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.Audio;
using osu.Framework.IO.Stores;
using osuTK.Graphics;

namespace osu.Game.Skinning
{
    public class DefaultLegacySkin : LegacySkin
    {
        public DefaultLegacySkin(IResourceStore<byte[]> storage, AudioManager audioManager)
            : base(Info, storage, audioManager, string.Empty)
        {
            Configuration.CustomColours["SliderBall"] = new Color4(2, 170, 255, 255);
            Configuration.ComboColours.AddRange(new[]
            {
                new Color4(255, 192, 0, 255),
                new Color4(0, 202, 0, 255),
                new Color4(18, 124, 255, 255),
                new Color4(242, 24, 57, 255),
            });
        }

        public static SkinInfo Info { get; } = new SkinInfo
        {
            ID = -1, // this is temporary until database storage is decided upon.
            Name = "osu!classic",
            Creator = "team osu!"
        };
    }
}

Add back combo colours for osu!classic

Add back combo colours for osu!classic


using MomWorld.DataContexts;
using MomWorld.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MomWorld.Controllers
{
    public class HomeController : Controller
    {

        private ArticleDb articleDb = new ArticleDb();
        private IdentityDb identityDb = new IdentityDb();

        public ActionResult Index()
        {
            List<Article> articles = articleDb.Articles.OrderBy(art=>art.PostedDate).Take(5).ToList();
            ViewData["Top5Articles"] = articles;

            if (User.Identity.IsAuthenticated)
            {
                var user = identityDb.Users.FirstOrDefault(u => u.UserName.Equals(User.Identity.Name));
                ViewData["CurrentUser"] = user;
            }

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [HttpPost]
        public void uploadnow(HttpPostedFileWrapper upload)
        {
            if (upload != null)
            {
                string ImageName = upload.FileName;
                string path = System.IO.Path.Combine(Server.MapPath("~/Images/uploads"), ImageName);
                upload.SaveAs(path);
            }
        }
    }
}

using MomWorld.DataContexts;
using MomWorld.Entities;
using MomWorld.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MomWorld.Controllers
{
    public class HomeController : Controller
    {

        private ArticleDb articleDb = new ArticleDb();
        private IdentityDb identityDb = new IdentityDb();

        public ActionResult Index()
        {
            List<Article> articles = articleDb.Articles.OrderBy(art=>art.PostedDate).Take(5).ToList();
            ViewData["Top5Articles"] = articles;

            if (User.Identity.IsAuthenticated)
            {
                var user = identityDb.Users.FirstOrDefault(u => u.UserName.Equals(User.Identity.Name));
                ViewData["CurrentUser"] = user;
            }
            else
            {
                //Fix sau
                ViewData["CurrentUser"] = new ApplicationUser();
            }

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [HttpPost]
        public void uploadnow(HttpPostedFileWrapper upload)
        {
            if (upload != null)
            {
                string ImageName = upload.FileName;
                string path = System.IO.Path.Combine(Server.MapPath("~/Images/uploads"), ImageName);
                upload.SaveAs(path);
            }
        }
    }
}

Update tạm fix lỗi Home/Index

Update tạm fix lỗi Home/Index


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

namespace Merlin.Extensions
{
    public static class WeatherExtensions
    {
        public static void EnableFog(this Weather weather)
        {
            weather.fogSummer = new MinMax(4f, 54f);
            weather.fogWinter = new MinMax(0f, 45f);
            weather.fogMapSelect = new MinMax(8f, 70f);
            weather.fogNormalRain = new MinMax(1f, 50f);
            weather.fogHeavyRain = new MinMax(0f, 45f);
        }

        public static void DisableFog(this Weather weather)
        {
            weather.fogSummer = new MinMax(100, 100);
            weather.fogWinter = new MinMax(100, 100);
            weather.fogMapSelect = new MinMax(100, 100);
            weather.fogHeavyRain = new MinMax(100, 100);
        }
    }
}

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

namespace Merlin.Extensions
{
    public static class WeatherExtensions
    {
        public static void EnableFog(this Weather weather)
        {
            weather.fogSummer = new MinMax(4f, 54f);
            weather.fogWinter = new MinMax(0f, 45f);
            weather.fogMapSelect = new MinMax(8f, 70f);
            weather.fogNormalRain = new MinMax(1f, 50f);
            weather.fogHeavyRain = new MinMax(0f, 45f);
        }

        public static void DisableFog(this Weather weather)
        {
            weather.fogSummer = new MinMax(150, 150);
            weather.fogWinter = new MinMax(150, 150);
            weather.fogMapSelect = new MinMax(150, 150);
            weather.fogNormalRain = new MinMax(150, 150);
            weather.fogHeavyRain = new MinMax(150, 150);
        }
    }
}

Update fog values (new maps are bigger)

Update fog values (new maps are bigger)


using System;
using NSemble.Core.Nancy;
using NSemble.Modules.ContentPages.Models;
using Raven.Client;

namespace NSemble.Modules.ContentPages
{
    public class ContentPagesModule : NSembleModule
    {
        public static readonly string HomepageSlug = "home";

        public ContentPagesModule(IDocumentSession session)
            : base("ContentPages")
        {
            Get["/{slug?" + HomepageSlug + "}"] = p =>
                                 {
                                     var slug = (string)p.slug;

                                     // For fastest loading, we define the content page ID to be the slug. Therefore, slugs have to be < 50 chars, probably
                                     // much shorter for readability.
                                     var cp = session.Load<ContentPage>(DocumentPrefix + ContentPage.FullContentPageId(slug));
                                     if (cp == null)
                                         return "
The requested content page was not found
"; // we will return a 404 instead once the system stabilizes...

                                     Model.ContentPage = cp;

                                     return View["Read", Model];
                                 };

            Get["/error"] = o =>
                                {
                                    throw new NotSupportedException("foo");
                                };
        }
    }
}

using System;
using NSemble.Core.Models;
using NSemble.Core.Nancy;
using NSemble.Modules.ContentPages.Models;
using Raven.Client;

namespace NSemble.Modules.ContentPages
{
    public class ContentPagesModule : NSembleModule
    {
        public static readonly string HomepageSlug = "home";

        public ContentPagesModule(IDocumentSession session)
            : base("ContentPages")
        {
            Get["/{slug?" + HomepageSlug + "}"] = p =>
                                 {
                                     var slug = (string)p.slug;

                                     // For fastest loading, we define the content page ID to be the slug. Therefore, slugs have to be < 50 chars, probably
                                     // much shorter for readability.
                                     var cp = session.Load<ContentPage>(DocumentPrefix + ContentPage.FullContentPageId(slug));
                                     if (cp == null)
                                         return "
The requested content page was not found
"; // we will return a 404 instead once the system stabilizes...

                                     Model.ContentPage = cp;
                                     ((PageModel) Model.Page).Title = cp.Title;

                                     return View["Read", Model];
                                 };

            Get["/error"] = o =>
                                {
                                    throw new NotSupportedException("foo");
                                };
        }
    }
}

Fix page titles for ContentPages module

Fix page titles for ContentPages module


namespace TensorSharp.Operations
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class AddDoubleDoubleOperation : IBinaryOperation<double, double, double>
    {
        public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
        {
            Tensor<double> result = new Tensor<double>();

            result.SetValue(tensor1.GetValue() + tensor2.GetValue());

            return result;
        }
    }
}

namespace TensorSharp.Operations
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class AddDoubleDoubleOperation : IBinaryOperation<double, double, double>
    {
        public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
        {
            double[] values1 = tensor1.GetValues();
            int l = values1.Length;

            double[] values2 = tensor2.GetValues();

            double[] newvalues = new double[l];

            for (int k = 0; k < l; k++)
                newvalues[k] = values1[k] + values2[k];

            return tensor1.CloneWithNewValues(newvalues);
        }
    }
}

Refactor Add Doubles Operation to use GetValues and CloneWithValues


using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Portal.CMS.Web.Areas.Admin.ViewModels.SettingManager
{
    public class SetupViewModel
    {
        [Required]
        [DisplayName("Website Name")]
        public string WebsiteName { get; set; }

        [Required]
        [DisplayName("Website Description")]
        public string WebsiteDescription { get; set; }

        [DisplayName("Google Tracking Code")]
        public string GoogleAnalyticsId { get; set; }

        [DisplayName("Email From Address")]
        public string EmailFromAddress { get; set; }

        [DisplayName("SendGrid API Key")]
        public string SendGridApiKey { get; set; }

        [DisplayName("SendGrid Password")]
        public string SendGridPassword { get; set; }

        [DisplayName("CDN Address")]
        public string CDNAddress { get; set; }
    }
}

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Portal.CMS.Web.Areas.Admin.ViewModels.SettingManager
{
    public class SetupViewModel
    {
        [Required]
        [DisplayName("Website Name")]
        public string WebsiteName { get; set; }

        [Required]
        [DisplayName("Website Description")]
        public string WebsiteDescription { get; set; }

        [DisplayName("Google Tracking Code")]
        public string GoogleAnalyticsId { get; set; }

        [DisplayName("Email From Address")]
        public string EmailFromAddress { get; set; }

        [DisplayName("SendGrid API Key")]
        public string SendGridApiKey { get; set; }

        [DisplayName("CDN Address")]
        public string CDNAddress { get; set; }
    }
}

Remove Obselete ViewModel Property for SendGrid Password


using System;
using System.IO;
using System.Linq;
using System.Text;

namespace HandlebarsDotNet.Compiler.Lexer
{
    internal class WordParser : Parser
    {
        private const string validWordStartCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$.@";

        public override Token Parse(TextReader reader)
        {
            if (IsWord(reader))
            {
                var buffer = AccumulateWord(reader);

                if (buffer.Contains("="))
                {
                    return Token.HashParameter(buffer);
                }
                else
                {
                    return Token.Word(buffer);
                }
            }
            return null;
        }

        private bool IsWord(TextReader reader)
        {
            var peek = (char)reader.Peek();
            return validWordStartCharacters.Contains(peek.ToString());
        }

        private string AccumulateWord(TextReader reader)
        {
            StringBuilder buffer = new StringBuilder();

            var inString = false;

            while (true)
            {
                if (!inString)
                {
                    var peek = (char)reader.Peek();

                    if (peek == '}' || peek == '~' || peek == ')' || char.IsWhiteSpace(peek))
                    {
                        break;
                    }
                }

                var node = reader.Read();

                if (node == -1)
                {
                    throw new InvalidOperationException("Reached end of template before the expression was closed.");
                }

                if (node == '\'' || node == '"')
                {
                    inString = !inString;
                }

                buffer.Append((char)node);
            }
            return buffer.ToString();
        }
    }
}

using System;
using System.IO;
using System.Linq;
using System.Text;

namespace HandlebarsDotNet.Compiler.Lexer
{
    internal class WordParser : Parser
    {
        private const string validWordStartCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$.@[]";

        public override Token Parse(TextReader reader)
        {
            if (IsWord(reader))
            {
                var buffer = AccumulateWord(reader);

                if (buffer.Contains("="))
                {
                    return Token.HashParameter(buffer);
                }
                else
                {
                    return Token.Word(buffer);
                }
            }
            return null;
        }

        private bool IsWord(TextReader reader)
        {
            var peek = (char)reader.Peek();
            return validWordStartCharacters.Contains(peek.ToString());
        }

        private string AccumulateWord(TextReader reader)
        {
            StringBuilder buffer = new StringBuilder();

            var inString = false;

            while (true)
            {
                if (!inString)
                {
                    var peek = (char)reader.Peek();

                    if (peek == '}' || peek == '~' || peek == ')' || (char.IsWhiteSpace(peek) && !buffer.ToString().Contains("[")))
                    {
                        break;
                    }
                }

                var node = reader.Read();

                if (node == -1)
                {
                    throw new InvalidOperationException("Reached end of template before the expression was closed.");
                }

                if (node == '\'' || node == '"')
                {
                    inString = !inString;
                }

                buffer.Append((char)node);
            }

            return buffer.ToString().Trim();
        }
    }
}

Fix whitespace bug with dictionary support


using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver;
using RightpointLabs.ConferenceRoom.Domain.Models;
using RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Models;

namespace RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Collections
{
    public abstract class EntityCollectionDefinition<T> where T : Entity
    {
        protected EntityCollectionDefinition(IMongoConnectionHandler connectionHandler)
        {
            if (connectionHandler == null) throw new ArgumentNullException("connectionHandler");

            // ReSharper disable once VirtualMemberCallInConstructor
            Collection = connectionHandler.Database.GetCollection<T>(CollectionName);

            // setup serialization
            if (!BsonClassMap.IsClassMapRegistered(typeof(Entity)))
            {
                try
                {
                    BsonClassMap.RegisterClassMap<Entity>(
                        cm =>
                        {
                            cm.AutoMap();
                            cm.SetIdMember(cm.GetMemberMap(i => i.Id));
                            cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance).SetSerializer(new StringSerializer(BsonType.ObjectId));
                        });
                }
                catch (ArgumentException)
                {
                    // this fails with an argument exception at startup, but otherwise works fine.  Probably should try to figure out why, but ignoring it is easier :(
                }
            }
        }

        public readonly MongoCollection<T> Collection;

        protected virtual string CollectionName => typeof(T).Name.Replace("Entity", "").ToLower() + "s";
    }
}

using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver;
using RightpointLabs.ConferenceRoom.Domain.Models;
using RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Models;

namespace RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Collections
{
    public abstract class EntityCollectionDefinition<T> where T : Entity
    {
        protected EntityCollectionDefinition(IMongoConnectionHandler connectionHandler)
        {
            if (connectionHandler == null) throw new ArgumentNullException("connectionHandler");

            // ReSharper disable once VirtualMemberCallInConstructor
            Collection = connectionHandler.Database.GetCollection<T>(CollectionName, new MongoCollectionSettings() { AssignIdOnInsert = true});

            // setup serialization
            if (!BsonClassMap.IsClassMapRegistered(typeof(Entity)))
            {
                if (!Collection.Exists())
                {
                    // ReSharper disable once VirtualMemberCallInConstructor
                    Collection.Database.CreateCollection(CollectionName);
                }

                try
                {
                    BsonClassMap.RegisterClassMap<Entity>(
                        cm =>
                        {
                            cm.AutoMap();
                            cm.SetIdMember(cm.GetMemberMap(i => i.Id));
                            cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance).SetSerializer(new StringSerializer(BsonType.ObjectId));
                        });
                }
                catch (ArgumentException)
                {
                    // this fails with an argument exception at startup, but otherwise works fine.  Probably should try to figure out why, but ignoring it is easier :(
                }
            }
        }

        public readonly MongoCollection<T> Collection;

        protected virtual string CollectionName => typeof(T).Name.Replace("Entity", "").ToLower() + "s";
    }
}

Enable Mongo entity auto-create and auto-ID


using UnityEngine;

public class AttackHandler : MonoBehaviour {

	[HideInInspector] public float damage;
	[HideInInspector] public float duration;
	[HideInInspector] public BoxCollider hitBox;

	private float timer = 0f;

	void Start() {
		hitBox = gameObject.GetComponent<BoxCollider>();
	}

	void Update()
	{
		timer += Time.deltaTime;
		if(timer >= duration) {
			timer = 0f;
			hitBox.enabled = false;
		}
	}

	void OnTriggerEnter(Collider other)	{
		bool isPlayer = other.GetComponent<Collider>().CompareTag("Player");

		if(isPlayer) {
			// Debug.Log("ATTACK");
		}
	}
}

using UnityEngine;

public class AttackHandler : MonoBehaviour {

	[HideInInspector] public float damage;
	[HideInInspector] public float duration;
	[HideInInspector] public BoxCollider hitBox;

	private float timer = 0f;

	void Start() {
		hitBox = gameObject.GetComponent<BoxCollider>();
	}

	void Update()
	{
		timer += Time.deltaTime;
		if(timer >= duration) {
			timer = 0f;
			hitBox.enabled = false;
		}
	}

	void OnTriggerEnter(Collider other)	{
		bool isPlayer = other.GetComponent<Collider>().CompareTag("Player");

		if(isPlayer) {
			other.gameObject.GetComponent<CharacterStatus>().life.decrease(damage);
		}
	}
}

Add damage capabilities to the enemy

Add damage capabilities to the enemy


using NUnit.Framework;
using tungsten.core.Elements;
using tungsten.core.Search;
using tungsten.nunit;

namespace tungsten.sampletest
{
    [TestFixture]
    public class CheckBoxTest : TestBase
    {
        [Test]
        public void Hupp()
        {
            var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain"));
            var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff"));
            checkBox.AssertThat(x => x.IsChecked(), Is.True);

            checkBox.Click();
            checkBox.AssertThat(x => x.IsChecked(), Is.False);
        }
    }
}

using NUnit.Framework;
using tungsten.core.Elements;
using tungsten.core.Search;
using tungsten.nunit;

namespace tungsten.sampletest
{
    [TestFixture]
    public class CheckBoxTest : TestBase
    {
        [Test]
        public void CheckBoxIsChecked()
        {
            var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain"));
            var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff"));
            checkBox.AssertThat(x => x.IsChecked(), Is.True);

            checkBox.Click();
            checkBox.AssertThat(x => x.IsChecked(), Is.False);
        }

        [Test]
        public void CheckBoxChangeIsChecked()
        {
            var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain"));
            var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff"));

            checkBox.Click();
            checkBox.AssertThat(x => x.IsChecked(), Is.False);
        }
    }
}

Split CheckBox test into two, give better name.


using System;
using System.Collections.Generic;
using Exceptionless.Core.Pipeline;
using Exceptionless.Core.Extensions;
using Exceptionless.Core.Models;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Logging;

namespace Exceptionless.Core.Plugins.EventParser {
    [Priority(0)]
    public class JsonEventParserPlugin : PluginBase, IEventParserPlugin {
        private readonly JsonSerializerSettings _settings;
        private readonly JsonSerializer _serializer;

        public JsonEventParserPlugin(IOptions<AppOptions> options, JsonSerializerSettings settings) : base(options) {
            _settings = settings;
            _serializer = JsonSerializer.CreateDefault(_settings);
        }

        public List<PersistentEvent> ParseEvents(string input, int apiVersion, string userAgent) {
            if (apiVersion < 2)
                return null;

            var events = new List<PersistentEvent>();

            var reader = new JsonTextReader(new StringReader(input));
            reader.DateParseHandling = DateParseHandling.None;

            while (reader.Read()) {
                if (reader.TokenType == JsonToken.StartObject) {
                    var ev = JToken.ReadFrom(reader);

                    var data = ev["data"];
                    if (data != null) {
                        foreach (var property in data.Children<JProperty>()) {
                            // strip out large data entries
                            if (property.Value.ToString().Length > 50000) {
                                property.Value = "(Data Too Large)";
                            }
                        }
                    }

                    try {
                        events.Add(ev.ToObject<PersistentEvent>(_serializer));
                    } catch (Exception ex) {
                        _logger.LogError(ex, "Error deserializing event.");
                    }
                }
            }

            return events.Count > 0 ? events : null;
        }
    }
}

using System;
using System.Collections.Generic;
using Exceptionless.Core.Pipeline;
using Exceptionless.Core.Extensions;
using Exceptionless.Core.Models;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Exceptionless.Core.Plugins.EventParser {
    [Priority(0)]
    public class JsonEventParserPlugin : PluginBase, IEventParserPlugin {
        private readonly JsonSerializerSettings _settings;

        public JsonEventParserPlugin(IOptions<AppOptions> options, JsonSerializerSettings settings) : base(options) {
            _settings = settings;
        }

        public List<PersistentEvent> ParseEvents(string input, int apiVersion, string userAgent) {
            if (apiVersion < 2)
                return null;

            var events = new List<PersistentEvent>();
            switch (input.GetJsonType()) {
                case JsonType.Object: {
                    if (input.TryFromJson(out PersistentEvent ev, _settings))
                        events.Add(ev);
                    break;
                }
                case JsonType.Array: {
                    if (input.TryFromJson(out PersistentEvent[] parsedEvents, _settings))
                        events.AddRange(parsedEvents);

                    break;
                }
            }

            return events.Count > 0 ? events : null;
        }
    }
}

Revert Strip large data values out of events


namespace elbsms_core
{
    internal static class Extensions
    {
        internal static bool Bit(this byte v, int bit)
        {
            int mask = 1 << bit;

            return (v & mask) == mask;
        }

        internal static bool Bit(this int v, int bit)
        {
            int mask = 1 << bit;

            return (v & mask) == mask;
        }

        internal static bool EvenParity(this int v)
        {
            v ^= v >> 4;
            v ^= v >> 2;
            v ^= v >> 1;

            return (v & 1) != 1;
        }
    }
}

namespace elbsms_core
{
    internal static class Extensions
    {
        internal static bool Bit(this byte v, int bit)
        {
            int mask = 1 << bit;

            return (v & mask) != 0;
        }

        internal static bool Bit(this int v, int bit)
        {
            int mask = 1 << bit;

            return (v & mask) != 0;
        }

        internal static bool EvenParity(this int v)
        {
            v ^= v >> 4;
            v ^= v >> 2;
            v ^= v >> 1;

            return (v & 1) != 1;
        }
    }
}

Update the mask check in the Bit() extension method

Apparently comparing against zero helps the JIT produce slightly more efficient code, based on research in this article https://www.tabsoverspaces.com/233785-is-it-better-to-not-equals-0-or-equals-mask-when-working-with-enums-csharp-ryujit


using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using SoundCloud.Api;
using SoundCloud.Api.Entities;
using SoundCloud.Api.Entities.Enums;
using SoundCloud.Api.QueryBuilders;

namespace ConsoleApp
{
    internal static class Program
    {
        private static async Task Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddSoundCloudClient(string.Empty, args[0]);

            using (var provider = serviceCollection.BuildServiceProvider())
            {
                var client = provider.GetService<SoundCloudClient>();

                var entity = await client.Resolve.GetEntityAsync("https://soundcloud.com/diplo");
                if (entity.Kind != Kind.User)
                {
                    Console.WriteLine("Couldn't resolve account of diplo");
                    return;
                }

                var diplo = entity as User;
                Console.WriteLine($"Found: {diplo.Username} @ {diplo.PermalinkUrl}");

                var tracks = await client.Users.GetTracksAsync(diplo, 10);

                Console.WriteLine();
                Console.WriteLine("Latest 10 Tracks:");
                foreach (var track in tracks)
                {
                    Console.WriteLine(track.Title);
                }

                var majorLazerResults = await client.Tracks.GetAllAsync(new TrackQueryBuilder { SearchString = "Major Lazer", Limit = 10 });
                Console.WriteLine();
                Console.WriteLine("Found Major Lazer Tracks:");
                foreach (var track in majorLazerResults)
                {
                    Console.WriteLine(track.Title);
                }
            }
        }
    }
}

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using SoundCloud.Api;
using SoundCloud.Api.Entities;
using SoundCloud.Api.Entities.Enums;
using SoundCloud.Api.QueryBuilders;

namespace ConsoleApp
{
    internal static class Program
    {
        private static async Task Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddSoundCloudClient(string.Empty, args[0]);

            using (var provider = serviceCollection.BuildServiceProvider())
            {
                var client = provider.GetService<SoundCloudClient>();

                var entity = await client.Resolve.GetEntityAsync("https://soundcloud.com/diplo");
                if (entity.Kind != Kind.User)
                {
                    Console.WriteLine("Couldn't resolve account of diplo");
                    return;
                }

                var diplo = entity as User;
                Console.WriteLine($"Found: {diplo.Username} @ {diplo.PermalinkUrl}");

                var tracks = await client.Users.GetTracksAsync(diplo, 10);

                Console.WriteLine();
                Console.WriteLine("Latest 10 Tracks:");
                foreach (var track in tracks)
                {
                    Console.WriteLine(track.Title);
                }

                var majorLazerResults = await client.Tracks.GetAllAsync(new TrackQueryBuilder { SearchString = "Major Lazer", Limit = 10 });
                Console.WriteLine();
                Console.WriteLine("Found Major Lazer Tracks:");
                foreach (var track in majorLazerResults)
                {
                    Console.WriteLine(track.Title);
                }
            }
        }
    }
}

Move to .NET Standard - cleanup

Move to .NET Standard
- cleanup


using Bugsnag;
using Bugsnag.Clients;
using EarTrumpet.Extensions;
using System;
using System.Diagnostics;
using System.IO;
using Windows.ApplicationModel;

namespace EarTrumpet.Services
{
    class ErrorReportingService
    {
        internal static void Initialize()
        {
            try
            {
#if DEBUG
                WPFClient.Config.ApiKey = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\eartrumpet.bugsnag.apikey");
#endif
                WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal";
                WPFClient.Start();

                WPFClient.Config.BeforeNotify(OnBeforeNotify);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }
        }

        private static bool OnBeforeNotify(Event error)
        {
            error.Metadata.AddToTab("Device", "machineName", "<redacted>");
            error.Metadata.AddToTab("Device", "hostname", "<redacted>");

            return true;
        }
    }
}

using Bugsnag;
using Bugsnag.Clients;
using EarTrumpet.Extensions;
using EarTrumpet.Misc;
using System;
using System.Diagnostics;
using System.IO;
using Windows.ApplicationModel;

namespace EarTrumpet.Services
{
    class ErrorReportingService
    {
        internal static void Initialize()
        {
            try
            {
#if DEBUG
                WPFClient.Config.ApiKey = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\eartrumpet.bugsnag.apikey");
#endif
                WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal";
                WPFClient.Start();

                WPFClient.Config.BeforeNotify(OnBeforeNotify);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }
        }

        private static bool OnBeforeNotify(Event error)
        {
            // Remove default metadata we don't need nor want.
            error.Metadata.AddToTab("Device", "machineName", "<redacted>");
            error.Metadata.AddToTab("Device", "hostname", "<redacted>");

            error.Metadata.AddToTab("AppSettings", "IsLightTheme", GetNoError(() => SystemSettings.IsLightTheme));
            error.Metadata.AddToTab("AppSettings", "IsRTL", GetNoError(() => SystemSettings.IsRTL));
            error.Metadata.AddToTab("AppSettings", "IsTransparencyEnabled", GetNoError(() => SystemSettings.IsTransparencyEnabled));
            error.Metadata.AddToTab("AppSettings", "UseAccentColor", GetNoError(() => SystemSettings.UseAccentColor));

            return true;
        }

        private static string GetNoError(Func<object> get)
        {
            try
            {
                var ret = get();
                return ret == null ? "null" : ret.ToString();
            }
            catch (Exception ex)
            {
                return $"{ex}";
            }
        }
    }
}

Add some settings to bugsnag

Add some settings to bugsnag


namespace Kudu.Contracts.Functions
{
    public class FunctionTestData
    {
        // test shows test_data of size 8310000 bytes still delivers as an ARM package
        // whereas test_data of size 8388608 bytes fails
        public const long PackageMaxSizeInBytes = 8300000;

        public long BytesLeftInPackage { get; set; } = PackageMaxSizeInBytes;

        public bool DeductFromBytesLeftInPackage(long fileSize)
        {
            long spaceLeft = BytesLeftInPackage - fileSize;
            if (spaceLeft >= 0)
            {
                BytesLeftInPackage = spaceLeft;
                return true;
            }
            return false;
        }
    }
}

namespace Kudu.Contracts.Functions
{
    public class FunctionTestData
    {
        // ARM has a limit of 8 MB -> 8388608 bytes
        // divid by 2 to limit the over all size of test data to half of arm requirement to be safe.
        public const long PackageMaxSizeInBytes = 8388608 / 2;

        public long BytesLeftInPackage { get; set; } = PackageMaxSizeInBytes;

        public bool DeductFromBytesLeftInPackage(long fileSize)
        {
            long spaceLeft = BytesLeftInPackage - fileSize;
            if (spaceLeft >= 0)
            {
                BytesLeftInPackage = spaceLeft;
                return true;
            }
            return false;
        }
    }
}

Reduce size of test_data for ARM requests to 8MB/2


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using MetroTrilithon.Serialization;

namespace TirkxDownloader.Models.Settings
{
    public class DownloadingSetting
    {
        public static SerializableProperty<int> MaximumBytesPerSec { get; }
            = new SerializableProperty<int>(GetKey(), SettingsProviders.Local, 0);

        public static SerializableProperty<byte> MaxConcurrentDownload { get; }
            = new SerializableProperty<byte>(GetKey(), SettingsProviders.Local, 1);

        private static string GetKey([CallerMemberName] string caller = "")
        {
            return nameof(DownloadingSetting) + "." + caller;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using MetroTrilithon.Serialization;

namespace TirkxDownloader.Models.Settings
{
    public class DownloadingSetting
    {
        public static SerializableProperty<long> MaximumBytesPerSec { get; }
            = new SerializableProperty<long>(GetKey(), SettingsProviders.Local, 0);

        public static SerializableProperty<byte> MaxConcurrentDownload { get; }
            = new SerializableProperty<byte>(GetKey(), SettingsProviders.Local, 1);

        private static string GetKey([CallerMemberName] string caller = "")
        {
            return nameof(DownloadingSetting) + "." + caller;
        }
    }
}

Change type of MaximumBytesPerSec to long


using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core.Etl;
using NBi.Xml.Items;

namespace NBi.Xml.Decoration.Command
{
    public class EtlRunXml : DecorationCommandXml, IEtlRunCommand
    {
        [XmlAttribute("server")]
        public string Server { get; set; }

        [XmlAttribute("path")]
        public string Path { get; set; }

        [XmlAttribute("name")]
        public string Name { get; set; }

        [XmlAttribute("username")]
        public string UserName { get; set; }

        [XmlAttribute("password")]
        public string Password { get; set; }

        [XmlAttribute("catalog")]
        public string Catalog { get; set; }

        [XmlAttribute("folder")]
        public string Folder { get; set; }

        [XmlAttribute("project")]
        public string Project { get; set; }

        [XmlAttribute("bits-32")]
        public bool Is32Bits { get; set; }

        [XmlIgnore]
        public List<EtlParameter> Parameters
        {
            get
            {
                return InternalParameters.ToList<EtlParameter>();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        [XmlElement("parameter")]
        public List<EtlParameterXml> InternalParameters { get; set; }

        public EtlRunXml()
        {
            InternalParameters = new List<EtlParameterXml>();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core.Etl;
using NBi.Xml.Items;

namespace NBi.Xml.Decoration.Command
{
    public class EtlRunXml : DecorationCommandXml, IEtlRunCommand
    {
        [XmlAttribute("server")]
        public string Server { get; set; }

        [XmlAttribute("path")]
        public string Path { get; set; }

        [XmlAttribute("name")]
        public string Name { get; set; }

        [XmlAttribute("username")]
        public string UserName { get; set; }

        [XmlAttribute("password")]
        public string Password { get; set; }

        [XmlAttribute("catalog")]
        public string Catalog { get; set; }

        [XmlAttribute("folder")]
        public string Folder { get; set; }

        [XmlAttribute("project")]
        public string Project { get; set; }

        [XmlAttribute("bits-32")]
        public bool Is32Bits { get; set; }

        [XmlAttribute("timeout")]
        public int Timeout { get; set; }

        [XmlIgnore]
        public List<EtlParameter> Parameters
        {
            get
            {
                return InternalParameters.ToList<EtlParameter>();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        [XmlElement("parameter")]
        public List<EtlParameterXml> InternalParameters { get; set; }

        public EtlRunXml()
        {
            InternalParameters = new List<EtlParameterXml>();
        }
    }
}

Add timeout to decoration etl-run

Add timeout to decoration etl-run


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace PixelPet.Commands {
	internal class GenerateTilemapCmd : CliCommand {
		public GenerateTilemapCmd()
			: base("Generate-Tilemap", new Parameter[] {
				new Parameter("palette-size", "ps", false, new ParameterValue("count",  "16")),
				new Parameter("no-reduce",    "nr", false),
			}) { }

		public override void Run(Workbench workbench, Cli cli) {
			cli.Log("Generating tilemap...");

			int  palSize  = FindNamedParameter("--palette-size").Values[0].ToInt32();
			bool noReduce = FindNamedParameter("--no-reduce").IsPresent;

			workbench.Tilemap = new Tilemap(workbench.Bitmap, workbench.Tileset, workbench.Palette, palSize, !noReduce);
		}
	}
}

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace PixelPet.Commands {
	internal class GenerateTilemapCmd : CliCommand {
		public GenerateTilemapCmd()
			: base("Generate-Tilemap",
				new Parameter("palette-size", "ps", false, new ParameterValue("count",  "16")),
				new Parameter("no-reduce",    "nr", false),
				new Parameter("x",            "x",  false, new ParameterValue("pixels", "0")),
				new Parameter("y",            "y",  false, new ParameterValue("pixels", "0")),
				new Parameter("width",        "w",  false, new ParameterValue("pixels", "-1")),
				new Parameter("height",       "h",  false, new ParameterValue("pixels", "-1"))
			) { }

		public override void Run(Workbench workbench, Cli cli) {
			cli.Log("Generating tilemap...");

			int  palSize  = FindNamedParameter("--palette-size").Values[0].ToInt32();
			bool noReduce = FindNamedParameter("--no-reduce"   ).IsPresent;
			int  x        = FindNamedParameter("--x"           ).Values[0].ToInt32();
			int  y        = FindNamedParameter("--y"           ).Values[0].ToInt32();
			int  w        = FindNamedParameter("--width"       ).Values[0].ToInt32();
			int  h        = FindNamedParameter("--height"      ).Values[0].ToInt32();

			using (Bitmap bmp = workbench.GetCroppedBitmap(x, y, w, h, cli)) {
				workbench.Tilemap = new Tilemap(bmp, workbench.Tileset, workbench.Palette, palSize, !noReduce);
			}
		}
	}
}

Add cropping options into Generate-Tilemap directly.