using System.Collections.Generic;
using System.Threading.Tasks;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
    public interface IRepository<TEntity, TPk>
        where TEntity : class, IEntity<TPk>
    {
        TEntity Get(TPk key, ISession session = null);
        Task<TEntity> GetAsync(TPk key, ISession session = null);
        IEnumerable<TEntity>  GetAll(ISession session = null);
        Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null);
        TPk SaveOrUpdate(TEntity entity, IUnitOfWork transaction);
        Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork transaction);
    }
}

using System.Collections.Generic;
using System.Threading.Tasks;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
    public interface IRepository<TEntity, TPk>
        where TEntity : class, IEntity<TPk>
    {
        TEntity GetKey(TPk key, ISession session = null);
        Task<TEntity> GetKeyAsync(TPk key, ISession session = null);
        TEntity Get(TEntity entity, ISession session = null);
        Task<TEntity> GetAsync(TEntity entity, ISession session = null)
        IEnumerable<TEntity>  GetAll(ISession session = null);
        Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null);
        TPk SaveOrUpdate(TEntity entity, IUnitOfWork transaction);
        Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork transaction);
    }
}

Change get method and add the new getter


using System;
using System.Diagnostics;
using System.Linq;

namespace mountain_thoughts
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Process mountainProcess = NativeMethods.GetMountainProcess();
            if (mountainProcess == null)
            {
                Console.WriteLine("Could not get process. Is Mountain running?");
                Console.ReadLine();
                Environment.Exit(1);
            }

            IntPtr handle = mountainProcess.Handle;
            IntPtr address = NativeMethods.GetStringAddress(mountainProcess);

            Twitter.Authenticate();

            NativeMethods.StartReadingString(handle, address, Callback);
            Console.ReadLine();
            NativeMethods.StopReadingString();
        }

        private static void Callback(string thought)
        {
            string properThought = string.Empty;
            foreach (string word in thought.Split(' ').Skip(1))
            {
                string lowerWord = word;
                if (word != "I")
                    lowerWord = word.ToLowerInvariant();
                properThought += lowerWord + " ";
            }
            properThought = properThought.Trim();

            Console.WriteLine(properThought);
            Twitter.Tweet(string.Format("\"{0}\"", properThought));
        }
    }
}

using System;
using System.Diagnostics;

namespace mountain_thoughts
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Process mountainProcess = NativeMethods.GetMountainProcess();
            if (mountainProcess == null)
            {
                Console.WriteLine("Could not get process. Is Mountain running?");
                Console.ReadLine();
                Environment.Exit(1);
            }

            IntPtr handle = mountainProcess.Handle;
            IntPtr address = NativeMethods.GetStringAddress(mountainProcess);

            Twitter.Authenticate();

            NativeMethods.StartReadingString(handle, address, Callback);
            Console.ReadLine();
            NativeMethods.StopReadingString();
        }

        private static void Callback(string thought)
        {
            string properThought = string.Empty;
            foreach (string word in thought.Split(' '))
            {
                string lowerWord = word;
                if (word != "I")
                    lowerWord = word.ToLowerInvariant();
                properThought += lowerWord + " ";
            }
            properThought = properThought.Trim();

            Console.WriteLine(properThought);
            Twitter.Tweet(string.Format("\"{0}\"", properThought));
        }
    }
}

Revert "Exclude the first word"

Revert "Exclude the first word"

This reverts commit c5f9cf87bd3a18e4acf130a001f84b249598acc4.


//-----------------------------------------------------------------------
// <copyright file="AllScoreData.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------

#pragma warning disable SA1600 // Elements should be documented

using System.Collections.Generic;

namespace ThScoreFileConverter.Models.Th165
{
    internal class AllScoreData
    {
        private readonly List<IScore> scores;

        public AllScoreData() => this.scores = new List<IScore>(Definitions.SpellCards.Count);

        public Th095.HeaderBase Header { get; private set; }

        public IReadOnlyList<IScore> Scores => this.scores;

        public IStatus Status { get; private set; }

        public void Set(Th095.HeaderBase header) => this.Header = header;

        public void Set(IScore score) => this.scores.Add(score);

        public void Set(IStatus status) => this.Status = status;
    }
}

//-----------------------------------------------------------------------
// <copyright file="AllScoreData.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------

#pragma warning disable SA1600 // Elements should be documented

using System.Collections.Generic;

namespace ThScoreFileConverter.Models.Th165
{
    internal class AllScoreData
    {
        private readonly List<IScore> scores;

        public AllScoreData()
        {
            this.scores = new List<IScore>(Definitions.SpellCards.Count);
        }

        public Th095.HeaderBase Header { get; private set; }

        public IReadOnlyList<IScore> Scores => this.scores;

        public IStatus Status { get; private set; }

        public void Set(Th095.HeaderBase header) => this.Header = header;

        public void Set(IScore score) => this.scores.Add(score);

        public void Set(IStatus status) => this.Status = status;
    }
}

Fix not to use expression-bodied constructors (cont.)


namespace MultiMiner.Win.Extensions
{
    static class TimeIntervalExtensions
    {
        public static int ToMinutes(this MultiMiner.Win.ApplicationConfiguration.TimerInterval timerInterval)
        {
            int coinStatsMinutes;
            switch (timerInterval)
            {
                case ApplicationConfiguration.TimerInterval.FiveMinutes:
                    coinStatsMinutes = 5;
                    break;
                case ApplicationConfiguration.TimerInterval.ThirtyMinutes:
                    coinStatsMinutes = 30;
                    break;
                case ApplicationConfiguration.TimerInterval.OneHour:
                    coinStatsMinutes = 1 * 60;
                    break;
                case ApplicationConfiguration.TimerInterval.ThreeHours:
                    coinStatsMinutes = 3 * 60;
                    break;
                case ApplicationConfiguration.TimerInterval.SixHours:
                    coinStatsMinutes = 6 * 60;
                    break;
                case ApplicationConfiguration.TimerInterval.TwelveHours:
                    coinStatsMinutes = 12 * 60;
                    break;
                default:
                    coinStatsMinutes = 15;
                    break;
            }
            return coinStatsMinutes;
        }
    }
}

namespace MultiMiner.Win.Extensions
{
    static class TimeIntervalExtensions
    {
        public static int ToMinutes(this MultiMiner.Win.ApplicationConfiguration.TimerInterval timerInterval)
        {
            int coinStatsMinutes;
            switch (timerInterval)
            {
                case ApplicationConfiguration.TimerInterval.FiveMinutes:
                    coinStatsMinutes = 5;
                    break;
                case ApplicationConfiguration.TimerInterval.ThirtyMinutes:
                    coinStatsMinutes = 30;
                    break;
                case ApplicationConfiguration.TimerInterval.OneHour:
                    coinStatsMinutes = 1 * 60;
                    break;
                case ApplicationConfiguration.TimerInterval.TwoHours:
                    coinStatsMinutes = 2 * 60;
                    break;
                case ApplicationConfiguration.TimerInterval.ThreeHours:
                    coinStatsMinutes = 3 * 60;
                    break;
                case ApplicationConfiguration.TimerInterval.SixHours:
                    coinStatsMinutes = 6 * 60;
                    break;
                case ApplicationConfiguration.TimerInterval.TwelveHours:
                    coinStatsMinutes = 12 * 60;
                    break;
                default:
                    coinStatsMinutes = 15;
                    break;
            }
            return coinStatsMinutes;
        }
    }
}

Handle the TwoHour time interval for strategies - was defaulting to 15


using System;

namespace Csla.Serialization.Mobile
{
  /// <summary>
  /// Placeholder for null child objects.
  /// </summary>
  [Serializable()]
  public sealed class NullPlaceholder : IMobileObject
  {
    #region Constructors

    public NullPlaceholder()
    {
      // Nothing
    }

    #endregion

    #region IMobileObject Members

    public void GetState(SerializationInfo info)
    {
      // Nothing
    }

    public void GetChildren(SerializationInfo info, MobileFormatter formatter)
    {
      // Nothing
    }

    public void SetState(SerializationInfo info)
    {
      // Nothing
    }

    public void SetChildren(SerializationInfo info, MobileFormatter formatter)
    {
      // Nothing
    }

    #endregion
  }
}

using System;

namespace Csla.Serialization.Mobile
{
  /// <summary>
  /// Placeholder for null child objects.
  /// </summary>
  [Serializable()]
  public sealed class NullPlaceholder : IMobileObject
  {
    #region Constructors

    /// <summary>
    /// Creates an instance of the type.
    /// </summary>
    public NullPlaceholder()
    {
      // Nothing
    }

    #endregion

    #region IMobileObject Members

    /// <summary>
    /// Method called by MobileFormatter when an object
    /// should serialize its data. The data should be
    /// serialized into the SerializationInfo parameter.
    /// </summary>
    /// <param name="info">
    /// Object to contain the serialized data.
    /// </param>
    public void GetState(SerializationInfo info)
    {
      // Nothing
    }

    /// <summary>
    /// Method called by MobileFormatter when an object
    /// should serialize its child references. The data should be
    /// serialized into the SerializationInfo parameter.
    /// </summary>
    /// <param name="info">
    /// Object to contain the serialized data.
    /// </param>
    /// <param name="formatter">
    /// Reference to the formatter performing the serialization.
    /// </param>
    public void GetChildren(SerializationInfo info, MobileFormatter formatter)
    {
      // Nothing
    }

    /// <summary>
    /// Method called by MobileFormatter when an object
    /// should be deserialized. The data should be
    /// deserialized from the SerializationInfo parameter.
    /// </summary>
    /// <param name="info">
    /// Object containing the serialized data.
    /// </param>
    public void SetState(SerializationInfo info)
    {
      // Nothing
    }

    /// <summary>
    /// Method called by MobileFormatter when an object
    /// should deserialize its child references. The data should be
    /// deserialized from the SerializationInfo parameter.
    /// </summary>
    /// <param name="info">
    /// Object containing the serialized data.
    /// </param>
    /// <param name="formatter">
    /// Reference to the formatter performing the deserialization.
    /// </param>
    public void SetChildren(SerializationInfo info, MobileFormatter formatter)
    {
      // Nothing
    }

    #endregion
  }
}

Add missing XML docs to code. bugid: 272


// Copyright (c) ComUnity 2015
// Hans Malherbe <hansm@comunity.co.za>

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace CEP
{
    public class UserProfile
    {
        [Key, Required, StringLength(10, MinimumLength = 10, ErrorMessage = "Mobile number must be exactly 10 digits")]
        public string Cell { get; set; }

        [StringLength(50)]
        public string Name { get; set; }

        [StringLength(50)]
        public string Surname { get; set; }

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

        [StringLength(10)]
        public string PostalCode { get; set; }

        [StringLength(50)]
        public string Province { get; set; }

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

        [StringLength(10)]
        public string HomePhone { get; set; }

        [StringLength(10)]
        public string WorkPhone { get; set; }

        [StringLength(350)]
        public string Email { get; set; }

        [StringLength(13)]
        public string IdNumber { get; set; }

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

        public virtual ICollection<Feedback> Feedbacks { get; set; }
        public virtual ICollection<FaultLog> Faults { get; set; }
    }
}

// Copyright (c) ComUnity 2015
// Hans Malherbe <hansm@comunity.co.za>

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace CEP
{
    public class UserProfile
    {
        [Key, Required, StringLength(10, MinimumLength = 10, ErrorMessage = "Mobile number must be exactly 10 digits")]
        public string Cell { get; set; }

        [StringLength(50)]
        public string Name { get; set; }

        [StringLength(50)]
        public string Surname { get; set; }

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

        [StringLength(10)]
        public string PostalCode { get; set; }

        [StringLength(50)]
        public string Province { get; set; }

        [StringLength(2000)]
        public string PictureUrl { get; set; }

        [StringLength(10)]
        public string HomePhone { get; set; }

        [StringLength(10)]
        public string WorkPhone { get; set; }

        [StringLength(350)]
        public string Email { get; set; }

        [StringLength(13)]
        public string IdNumber { get; set; }

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

        public virtual ICollection<Feedback> Feedbacks { get; set; }
        public virtual ICollection<FaultLog> Faults { get; set; }
    }
}

Change user picture field to PictureUrl

Change user picture field to PictureUrl


using System.Collections.Generic;

namespace Ganss.Text
{
    /// <summary>
    /// Provides extension methods.
    /// </summary>
    public static class Extensions
    {
        /// <summary>
        /// Determines whether this instance contains the specified words.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="words">The words.</param>
        /// <returns>The matched words.</returns>
        public static IEnumerable<WordMatch> Contains(this string text, IEnumerable<string> words)
        {
            return new AhoCorasick(words).Search(text);
        }

        /// <summary>
        /// Determines whether this instance contains the specified words.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="words">The words.</param>
        /// <returns>The matched words.</returns>
        public static IEnumerable<WordMatch> Contains(this string text, params string[] words)
        {
            return new AhoCorasick(words).Search(text);
        }
    }
}

using System.Collections.Generic;

namespace Ganss.Text
{
    /// <summary>
    /// Provides extension methods.
    /// </summary>
    public static class Extensions
    {
        /// <summary>
        /// Determines whether this instance contains the specified words.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="words">The words.</param>
        /// <returns>The matched words.</returns>
        public static IEnumerable<WordMatch> Contains(this string text, IEnumerable<string> words)
        {
            return new AhoCorasick(words).Search(text);
        }

        /// <summary>
        /// Determines whether this instance contains the specified words.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="words">The words.</param>
        /// <returns>The matched words.</returns>
        public static IEnumerable<WordMatch> Contains(this string text, params string[] words)
        {
            return new AhoCorasick(words).Search(text);
        }

        /// <summary>
        /// Determines whether this instance contains the specified words.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="comparer">The comparer used to compare individual characters.</param>
        /// <param name="words">The words.</param>
        /// <returns>The matched words.</returns>
        public static IEnumerable<WordMatch> Contains(this string text, IEqualityComparer<char> comparer, IEnumerable<string> words)
        {
            return new AhoCorasick(comparer, words).Search(text);
        }

        /// <summary>
        /// Determines whether this instance contains the specified words.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="comparer">The comparer used to compare individual characters.</param>
        /// <param name="words">The words.</param>
        /// <returns>The matched words.</returns>
        public static IEnumerable<WordMatch> Contains(this string text, IEqualityComparer<char> comparer, params string[] words)
        {
            return new AhoCorasick(comparer, words).Search(text);
        }
    }
}

Add custom char comparison to extension methods


using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Event;
using Serilog.Events;
using Serilog.Parsing;

namespace Akka.Serilog.Event.Serilog
{
    public class SerilogLogMessageFormatter : ILogMessageFormatter
    {
        private readonly MessageTemplateCache _templateCache;

        public SerilogLogMessageFormatter()
        {
            _templateCache = new MessageTemplateCache(new MessageTemplateParser());
        }

        public string Format(string format, params object[] args)
        {
            var template = _templateCache.Parse(format);
            var propertyTokens = template.Tokens.OfType<PropertyToken>().ToArray();
            var properties = new Dictionary<string, LogEventPropertyValue>();

            if (propertyTokens.Length != args.Length)
                throw new FormatException("Invalid number or arguments provided.");

            for (var i = 0; i < propertyTokens.Length; i++)
            {
                var arg = args[i];

                properties.Add(propertyTokens[i].PropertyName, new ScalarValue(arg));
            }

            return template.Render(properties);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Event;
using Serilog.Events;
using Serilog.Parsing;

namespace Akka.Serilog.Event.Serilog
{
    public class SerilogLogMessageFormatter : ILogMessageFormatter
    {
        private readonly MessageTemplateCache _templateCache;

        public SerilogLogMessageFormatter()
        {
            _templateCache = new MessageTemplateCache(new MessageTemplateParser());
        }

        public string Format(string format, params object[] args)
        {
            var template = _templateCache.Parse(format);
            var propertyTokens = template.Tokens.OfType<PropertyToken>().ToArray();
            var properties = new Dictionary<string, LogEventPropertyValue>();

            for (var i = 0; i < args.Length; i++)
            {
                var propertyToken = propertyTokens.ElementAtOrDefault(i);
                if (propertyToken == null)
                    break;

                properties.Add(propertyToken.PropertyName, new ScalarValue(args[i]));
            }

            return template.Render(properties);
        }
    }
}

Change the way we match args to property tokens to more closely match Serilog when you pass in too few or too many arguments


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

using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;

using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;

using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

namespace RockyTV.Duality.Plugins.IronPython
{
	public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
	{
        public ContentRef<PythonScript> Script { get; set; }

        [DontSerialize]
        private PythonExecutionEngine _engine;
        protected PythonExecutionEngine Engine
        {
            get { return _engine; }
        }

		public void OnInit(InitContext context)
        {
            if (!Script.IsAvailable) return;

            _engine = new PythonExecutionEngine(Script.Res.Content);
            _engine.SetVariable("gameObject", GameObj);

            if (_engine.HasMethod("start"))
                _engine.CallMethod("start");
        }

        public void OnUpdate()
        {
            if (_engine.HasMethod("update"))
                _engine.CallMethod("update");
        }

        public void OnShutdown(ShutdownContext context)
        {
            if (context == ShutdownContext.Deactivate)
            {
                GameObj.DisposeLater();
            }
        }
	}
}

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

using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;

using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;

using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

namespace RockyTV.Duality.Plugins.IronPython
{
	public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
	{
        public ContentRef<PythonScript> Script { get; set; }

        [DontSerialize]
        private PythonExecutionEngine _engine;
        protected PythonExecutionEngine Engine
        {
            get { return _engine; }
        }

        protected virtual float Delta
        {
            get { return Time.MsPFMult * Time.TimeMult; }
        }

		public void OnInit(InitContext context)
        {
            if (!Script.IsAvailable) return;

            _engine = new PythonExecutionEngine(Script.Res.Content);
            _engine.SetVariable("gameObject", GameObj);

            if (_engine.HasMethod("start"))
                _engine.CallMethod("start");
        }

        public void OnUpdate()
        {
            if (_engine.HasMethod("update"))
                _engine.CallMethod("update", Delta);
        }

        public void OnShutdown(ShutdownContext context)
        {
            if (context == ShutdownContext.Deactivate)
            {
                GameObj.DisposeLater();
            }
        }
	}
}

Call 'update' with Delta time

Call 'update' with Delta time


using UnityEngine;
using System.Reflection;

[assembly: AssemblyVersion("1.0.0.*")]
public class Loader : MonoBehaviour
{
    /// <summary>
    /// DebugUI prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _debugUI;

    /// <summary>
    /// ModalDialog prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _modalDialog;

    /// <summary>
    /// MainMenu prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _mainMenu;

    /// <summary>
    /// InGameUI prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _inGameUI;

    /// <summary>
    /// SoundManager prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _soundManager;

    /// <summary>
    /// GameManager prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _gameManager;

    protected void Awake()
    {
        // Check if the instances have already been assigned to static variables or they are still null.

        if (DebugUI.Instance == null)
        {
            Instantiate(_debugUI);
        }
        if (ModalDialog.Instance == null)
        {
            Instantiate(_modalDialog);
        }
        if (MainMenu.Instance == null)
        {
            Instantiate(_mainMenu);
        }
        if (InGameUI.Instance == null)
        {
            Instantiate(_inGameUI);
        }
        if (SoundManager.Instance == null)
        {
            Instantiate(_soundManager);
        }
        if (GameManager.Instance == null)
        {
            Instantiate(_gameManager);
        }
    }
}

using UnityEngine;
using System.Reflection;

[assembly: AssemblyVersion("1.1.0.*")]
public class Loader : MonoBehaviour
{
    /// <summary>
    /// DebugUI prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _debugUI;

    /// <summary>
    /// ModalDialog prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _modalDialog;

    /// <summary>
    /// MainMenu prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _mainMenu;

    /// <summary>
    /// InGameUI prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _inGameUI;

    /// <summary>
    /// SoundManager prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _soundManager;

    /// <summary>
    /// GameManager prefab to instantiate.
    /// </summary>
    [SerializeField]
    private GameObject _gameManager;

    protected void Awake()
    {
        // Check if the instances have already been assigned to static variables or they are still null.

        if (DebugUI.Instance == null)
        {
            Instantiate(_debugUI);
        }
        if (ModalDialog.Instance == null)
        {
            Instantiate(_modalDialog);
        }
        if (MainMenu.Instance == null)
        {
            Instantiate(_mainMenu);
        }
        if (InGameUI.Instance == null)
        {
            Instantiate(_inGameUI);
        }
        if (SoundManager.Instance == null)
        {
            Instantiate(_soundManager);
        }
        if (GameManager.Instance == null)
        {
            Instantiate(_gameManager);
        }
    }
}

Change version up to 1.1.0

Change version up to 1.1.0


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Console;

namespace ConsoleApp
{
    public class Table
    {
        private readonly string tableName;
        private readonly IEnumerable<Column> columns;

        public Table(string tableName, IEnumerable<Column> columns)
        {
            this.tableName = tableName;
            this.columns = columns;
        }

        public void OutputMigrationCode(TextWriter writer)
        {
            writer.Write(@"namespace Cucu
{
    [Migration(");
            writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss"));
            writer.Write(@")]
    public class Vaca : Migration
    {
        public override void Up()
        {
            Create.Table(""");
            writer.Write(tableName);
            writer.Write(@""")");

            columns.ToList().ForEach(c =>
            {
                writer.WriteLine();
                writer.Write(c.FluentMigratorCode());
            });

            writer.WriteLine(@";
        }

        public override void Down()
        {
            // nothing here yet
        }
    }
}");
        }
    }

    class Program
    {
        private static void Main()
        {
            var columnsProvider = new ColumnsProvider(@"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;");
            var tableName = "Book";
            var columns = columnsProvider.GetColumnsAsync("dbo", tableName).GetAwaiter().GetResult();

            new Table(tableName, columns).OutputMigrationCode(Out);
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Console;

namespace ConsoleApp
{
    public class Table
    {
        private readonly string tableName;
        private readonly IEnumerable<Column> columns;

        public Table(string tableName, IEnumerable<Column> columns)
        {
            this.tableName = tableName;
            this.columns = columns;
        }

        public void OutputMigrationCode(TextWriter writer)
        {
            writer.Write(@"namespace Cucu
{
    [Migration(");
            writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss"));
            writer.Write(@")]
    public class Vaca : Migration
    {
        public override void Up()
        {
            Create.Table(""");
            writer.Write(tableName);
            writer.Write(@""")");

            columns.ToList().ForEach(c =>
            {
                writer.WriteLine();
                writer.Write(c.FluentMigratorCode());
            });

            writer.WriteLine(@";
        }

        public override void Down()
        {
            // nothing here yet
        }
    }
}");
        }
    }

    class Program
    {
        private static void Main()
        {
            var connectionString = @"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;";
            var schemaName = "dbo";
            var tableName = "Book";

            var columnsProvider = new ColumnsProvider(connectionString);
            var columns = columnsProvider.GetColumnsAsync(schemaName, tableName).GetAwaiter().GetResult();

            new Table(tableName, columns).OutputMigrationCode(Out);
        }
    }
}

Put variables in Main first

Put variables in Main first


// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using UnityEngine;
using Microsoft.MixedReality.Toolkit.Input;
using TMPro;
#if LEAPMOTIONCORE_PRESENT
using Microsoft.MixedReality.Toolkit.LeapMotion.Input;
#endif

namespace Microsoft.MixedReality.Toolkit.Examples
{
    /// <summary>
    /// Returns the orientation of Leap Motion Controller
    /// </summary>
    public class LeapMotionOrientationDisplay : MonoBehaviour
    {
#if LEAPMOTIONCORE_PRESENT
        [SerializeField]
        private TextMeshProUGUI orientationText;
        private LeapMotionDeviceManagerProfile managerProfile;

        private void Start()
        {
            if (GetLeapManager())
            {
                orientationText.text = "Orientation: " + GetLeapManager().LeapControllerOrientation.ToString();
            }
            else
            {
                orientationText.text = "Orientation: Unavailable";
            }
        }

        private LeapMotionDeviceManagerProfile GetLeapManager()
        {
            if (!MixedRealityToolkit.Instance.ActiveProfile)
            {
                return null;
            }
            foreach (MixedRealityInputDataProviderConfiguration config in MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.DataProviderConfigurations)
            {
                if (config.ComponentType == typeof(LeapMotionDeviceManager))
                {
                    managerProfile = (LeapMotionDeviceManagerProfile)config.Profile;
                    return managerProfile;
                }
            }
            return null;
        }
#endif
    }
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using UnityEngine;
using Microsoft.MixedReality.Toolkit.Input;
using TMPro;
#if LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE
using Microsoft.MixedReality.Toolkit.LeapMotion.Input;
#endif

namespace Microsoft.MixedReality.Toolkit.Examples
{
    /// <summary>
    /// Returns the orientation of Leap Motion Controller
    /// </summary>
    public class LeapMotionOrientationDisplay : MonoBehaviour
    {
#if LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE
        [SerializeField]
        private TextMeshProUGUI orientationText;
        private LeapMotionDeviceManagerProfile managerProfile;

        private void Start()
        {
            if (GetLeapManager())
            {
                orientationText.text = "Orientation: " + GetLeapManager().LeapControllerOrientation.ToString();
            }
            else
            {
                orientationText.text = "Orientation: Unavailable";
            }
        }

        private LeapMotionDeviceManagerProfile GetLeapManager()
        {
            if (!MixedRealityToolkit.Instance.ActiveProfile)
            {
                return null;
            }
            foreach (MixedRealityInputDataProviderConfiguration config in MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.DataProviderConfigurations)
            {
                if (config.ComponentType == typeof(LeapMotionDeviceManager))
                {
                    managerProfile = (LeapMotionDeviceManagerProfile)config.Profile;
                    return managerProfile;
                }
            }
            return null;
        }
#endif
    }
}

Add standalone ifdef to leap example scene script


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

namespace SmugMugCodeGen
{
    public static class Constants
    {
        public const string PropertyDefinition = @"public {0} {1} {{get; set;}}";

        public const string EnumDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace SmugMug.v2.Types
{{
    public enum {0}
    {{
        {1}
    }}
}}
";

        public const string ClassDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace SmugMug.v2.Types
{{
    public partial class {0}Entity
    {{
        {1}
    }}
}}
";
    }
}

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

namespace SmugMugCodeGen
{
    public static class Constants
    {
        public const string PropertyDefinition = @"public {0} {1} {{get; set;}}";

        public const string EnumDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace SmugMug.v2.Types
{{
    public enum {0}
    {{
        {1}
    }}
}}
";

        public const string ClassDefinition = @"// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace SmugMug.v2.Types
{{
    public partial class {0}Entity : SmugMugEntity
    {{
        {1}
    }}
}}
";
    }
}

Make sure that classes generated derive from a common type to allow code sharing


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

public class Levels : MonoBehaviour
{
    /* Cette classe a pour destin d'être sur un prefab.
     * Ce prefab agira comme une config manuelle de niveaux pour faciliter le level design.
     * On pourra faire différentes configs si on veut (mettons une par difficulté) et ultimement glisser cette config dans le gamecontroller
     * pour qu'il s'en serve.
     * */

    [SerializeField] WorkDay[] days;

    int currentLevel = 0;

    public void StartNext()
    {
        //starts next level
    }

    public void EndCurrent()
    {
        //ends current level
        currentLevel++;
        if (days[currentLevel].AddsJob)
        {
            // add a job to pool
        }
    }
}

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

public class Levels : MonoBehaviour
{
    /* Cette classe a pour destin d'être sur un prefab.
     * Ce prefab agira comme une config manuelle de niveaux pour faciliter le level design.
     * On pourra faire différentes configs si on veut (mettons une par difficulté) et ultimement glisser cette config dans le gamecontroller
     * pour qu'il s'en serve.
     * */

    [SerializeField] WorkDay[] days;
    [SerializeField] int maxJobCount;

    int currentLevel = 0;

    public void StartNext()
    {
        //starts next level
    }

    public void EndCurrent()
    {
        //ends current level
        currentLevel++;
        if (days[currentLevel].AddsJob)
        {
            // add a job to pool
            // if this brings us over maximum, change a job instead
        }
    }
}

Add max job count to levels

Add max job count to levels


using System;
using System.Text.RegularExpressions;
using Should;
using Xunit;

namespace Cassette.UI
{
    public class PlaceholderTracker_Tests
    {
        [Fact]
        public void WhenInsertPlaceholder_ThenPlaceholderIdHtmlReturned()
        {
            var tracker = new PlaceholderTracker();
            var result = tracker.InsertPlaceholder(() => (""));

            var guidRegex = new Regex(@"[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}");
            var output = result;
            guidRegex.IsMatch(output).ShouldBeTrue();
        }

        [Fact]
        public void GivenInsertPlaceholder_WhenReplacePlaceholders_ThenHtmlInserted()
        {
            var tracker = new PlaceholderTracker();
            var html = tracker.InsertPlaceholder(() => ("
test
"));

            tracker.ReplacePlaceholders(html).ShouldEqual(
                Environment.NewLine + "
test
" + Environment.NewLine
            );
        }
    }
}

using System;
using System.Text.RegularExpressions;
using Should;
using Xunit;

namespace Cassette
{
    public class PlaceholderTracker_Tests
    {
        [Fact]
        public void WhenInsertPlaceholder_ThenPlaceholderIdHtmlReturned()
        {
            var tracker = new PlaceholderTracker();
            var result = tracker.InsertPlaceholder(() => (""));

            var guidRegex = new Regex(@"[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}");
            var output = result;
            guidRegex.IsMatch(output).ShouldBeTrue();
        }

        [Fact]
        public void GivenInsertPlaceholder_WhenReplacePlaceholders_ThenHtmlInserted()
        {
            var tracker = new PlaceholderTracker();
            var html = tracker.InsertPlaceholder(() => ("
test
"));

            tracker.ReplacePlaceholders(html).ShouldEqual(
                Environment.NewLine + "
test
" + Environment.NewLine
            );
        }
    }
}

Move test into correct namespace.

Move test into correct namespace.


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

namespace Modix.Services.StackExchange
{
    public class StackExchangeService
    {
        private string _ApiReferenceUrl =
            $"http://api.stackexchange.com/2.2/search/advanced" +
            "?key={0}" +
            $"&order=desc" +
            $"&sort=votes" +
            $"&filter=default";

        public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags)
        {
            _ApiReferenceUrl = string.Format(_ApiReferenceUrl, token);
            phrase = Uri.EscapeDataString(phrase);
            site = Uri.EscapeDataString(site);
            tags = Uri.EscapeDataString(tags);
            var query = _ApiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}";

            var client = new HttpClient(new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip
            });

            var response = await client.GetAsync(query);

            if (!response.IsSuccessStatusCode)
            {
                throw new WebException("Something failed while querying the Stack Exchange API.");
            }

            var json = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<StackExchangeResponse>(json);
        }
    }
}

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

namespace Modix.Services.StackExchange
{
    public class StackExchangeService
    {
        private static HttpClient HttpClient => new HttpClient(new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip
        });

        private string _ApiReferenceUrl =
            $"http://api.stackexchange.com/2.2/search/advanced" +
            "?key={0}" +
            $"&order=desc" +
            $"&sort=votes" +
            $"&filter=default";

        public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags)
        {
            _ApiReferenceUrl = string.Format(_ApiReferenceUrl, token);
            phrase = Uri.EscapeDataString(phrase);
            site = Uri.EscapeDataString(site);
            tags = Uri.EscapeDataString(tags);
            var query = _ApiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}";

            var response = await HttpClient.GetAsync(query);

            if (!response.IsSuccessStatusCode)
            {
                throw new WebException("Something failed while querying the Stack Exchange API.");
            }

            var jsonResponse = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<StackExchangeResponse>(jsonResponse);
        }
    }
}

Use static HttpClient in SO module

Use static HttpClient in SO module


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle(".NET Winforms Gantt Chart Control")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Braincase Solutions")]
[assembly: AssemblyProduct("GanttChartControl")]
[assembly: AssemblyCopyright("Copyright ©  2012")]
[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("e316b126-c783-4060-95b9-aa8ee2e676d7")]

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

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle(".NET Winforms Gantt Chart Control")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Braincase Solutions")]
[assembly: AssemblyProduct("GanttChartControl")]
[assembly: AssemblyCopyright("Copyright ©  2012")]
[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("e316b126-c783-4060-95b9-aa8ee2e676d7")]

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

Fix assembly and file versions

Fix assembly and file versions


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

namespace Consul.Test
{
    [TestClass]
    public class CoordinateTest
    {
        [TestMethod]
        public void TestCoordinate_Datacenters()
        {
            var client = new Client();

            var info = client.Agent.Self();

            if (!info.Response.ContainsKey("Coord"))
            {
                Assert.Inconclusive("This version of Consul does not support the coordinate API");
            }

            var datacenters = client.Coordinate.Datacenters();

            Assert.IsNotNull(datacenters.Response);
            Assert.IsTrue(datacenters.Response.Length > 0);
        }

        [TestMethod]
        public void TestCoordinate_Nodes()
        {
            var client = new Client();

            var info = client.Agent.Self();

            if (!info.Response.ContainsKey("Coord"))
            {
                Assert.Inconclusive("This version of Consul does not support the coordinate API");
            }

            var nodes = client.Coordinate.Nodes();

            Assert.IsNotNull(nodes.Response);
            Assert.IsTrue(nodes.Response.Length > 0);
        }
    }
}

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

namespace Consul.Test
{
    [TestClass]
    public class CoordinateTest
    {
        [TestMethod]
        public void Coordinate_Datacenters()
        {
            var client = new Client();

            var info = client.Agent.Self();

            if (!info.Response.ContainsKey("Coord"))
            {
                Assert.Inconclusive("This version of Consul does not support the coordinate API");
            }

            var datacenters = client.Coordinate.Datacenters();

            Assert.IsNotNull(datacenters.Response);
            Assert.IsTrue(datacenters.Response.Length > 0);
        }

        [TestMethod]
        public void Coordinate_Nodes()
        {
            var client = new Client();

            var info = client.Agent.Self();

            if (!info.Response.ContainsKey("Coord"))
            {
                Assert.Inconclusive("This version of Consul does not support the coordinate API");
            }

            var nodes = client.Coordinate.Nodes();

            // There's not a good way to populate coordinates without
            // waiting for them to calculate and update, so the best
            // we can do is call the endpoint and make sure we don't
            // get an error. - from offical API.
            Assert.IsNotNull(nodes);
        }
    }
}

Reduce testing of coordinate nodes call

Reduce testing of coordinate nodes call


using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using PackageExplorerViewModel;

namespace PackageExplorer
{
    public class PackageIconConverter : IMultiValueConverter
    {
        #region IMultiValueConverter Members

        public object? Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values?.Length > 1 && values[0] is PackageViewModel package && values[1] is string str && !string.IsNullOrEmpty(str))
            {
                var metadata = package.PackageMetadata;

                if (!string.IsNullOrEmpty(metadata.Icon))
                {
                    foreach (var file in package.RootFolder.GetFiles())
                    {
                        if (string.Equals(file.Path, metadata.Icon, StringComparison.OrdinalIgnoreCase))
                        {
                            var image = new BitmapImage();
                            image.BeginInit();
                            image.CacheOption = BitmapCacheOption.OnLoad;
                            image.StreamSource = file.GetStream();
                            image.EndInit();
                            return image;
                        }
                    }

                }

                if (metadata.IconUrl != null)
                {
                    var image = new BitmapImage();
                    image.BeginInit();
                    image.UriSource = metadata.IconUrl;
                    image.EndInit();
                    return image;
                }
            }
            return null;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using PackageExplorerViewModel;

namespace PackageExplorer
{
    public class PackageIconConverter : IMultiValueConverter
    {
        #region IMultiValueConverter Members

        public object? Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values?.Length > 1 && values[0] is PackageViewModel package && values[1] is string str && !string.IsNullOrEmpty(str))
            {
                var metadata = package.PackageMetadata;

                if (!string.IsNullOrEmpty(metadata.Icon))
                {
                    // Normalize any directories to match what's the package
                    // We do this here instead of the metadata so that we round-trip
                    // whatever the user originally had when in edit view
                    var iconPath = metadata.Icon.Replace('/', '\\');
                    foreach (var file in package.RootFolder.GetFiles())
                    {
                        if (string.Equals(file.Path, iconPath, StringComparison.OrdinalIgnoreCase))
                        {
                            var image = new BitmapImage();
                            image.BeginInit();
                            image.CacheOption = BitmapCacheOption.OnLoad;
                            image.StreamSource = file.GetStream();
                            image.EndInit();
                            return image;
                        }
                    }

                }

                if (metadata.IconUrl != null)
                {
                    var image = new BitmapImage();
                    image.BeginInit();
                    image.UriSource = metadata.IconUrl;
                    image.EndInit();
                    return image;
                }
            }
            return null;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

Normalize directory separator char for finding the embedded icon


using System.Collections.Generic;
using System.Diagnostics;

namespace Octokit
{
    /// <summary>
    /// An enhanced git commit containing links to additional resources
    /// </summary>
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class GitHubCommit : GitReference
    {
        public GitHubCommit() { }

        public GitHubCommit(string url, string label, string @ref, string sha, User user, Repository repository, Author author, string commentsUrl, Commit commit, Author committer, string htmlUrl, GitHubCommitStats stats, IReadOnlyList<GitReference> parents, IReadOnlyList<GitHubCommitFile> files)
            : base(url, label, @ref, sha, user, repository)
        {
            Author = author;
            CommentsUrl = commentsUrl;
            Commit = commit;
            Committer = committer;
            HtmlUrl = htmlUrl;
            Stats = stats;
            Parents = parents;
            Files = files;
        }

        public Author Author { get; protected set; }

        public string CommentsUrl { get; protected set; }

        public Commit Commit { get; protected set; }

        public Author Committer { get; protected set; }

        public string HtmlUrl { get; protected set; }

        public GitHubCommitStats Stats { get; protected set; }

        public IReadOnlyList<GitReference> Parents { get; protected set; }

        public IReadOnlyList<GitHubCommitFile> Files { get; protected set; }
    }
}

using System.Collections.Generic;
using System.Diagnostics;

namespace Octokit
{
    /// <summary>
    /// An enhanced git commit containing links to additional resources
    /// </summary>
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class GitHubCommit : GitReference
    {
        public GitHubCommit() { }

        public GitHubCommit(string url, string label, string @ref, string sha, User user, Repository repository, Author author, string commentsUrl, Commit commit, Author committer, string htmlUrl, GitHubCommitStats stats, IReadOnlyList<GitReference> parents, IReadOnlyList<GitHubCommitFile> files)
            : base(url, label, @ref, sha, user, repository)
        {
            Author = author;
            CommentsUrl = commentsUrl;
            Commit = commit;
            Committer = committer;
            HtmlUrl = htmlUrl;
            Stats = stats;
            Parents = parents;
            Files = files;
        }

        /// <summary>
        /// Gets the GitHub account information for the commit author. It attempts to match the email
        /// address used in the commit with the email addresses registered with the GitHub account.
        /// If no account corresponds to the commit email, then this property is null.
        /// </summary>
        public Author Author { get; protected set; }

        public string CommentsUrl { get; protected set; }

        public Commit Commit { get; protected set; }

        /// <summary>
        /// Gets the GitHub account information for the commit committer. It attempts to match the email
        /// address used in the commit with the email addresses registered with the GitHub account.
        /// If no account corresponds to the commit email, then this property is null.
        /// </summary>
        public Author Committer { get; protected set; }

        public string HtmlUrl { get; protected set; }

        public GitHubCommitStats Stats { get; protected set; }

        public IReadOnlyList<GitReference> Parents { get; protected set; }

        public IReadOnlyList<GitHubCommitFile> Files { get; protected set; }
    }
}

Add doc comments for Author and Committer


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

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

namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
    internal static class Extensions
    {
        public static Task<bool> ToTask(this WaitHandle handle, int? timeoutMilliseconds)
        {
            RegisteredWaitHandle registeredHandle = null;
            var tcs = new TaskCompletionSource<bool>();
            registeredHandle = ThreadPool.RegisterWaitForSingleObject(
                handle,
                (_, timedOut) =>
                {
                    tcs.TrySetResult(!timedOut);
                    if (!timedOut)
                    {
                        registeredHandle.Unregister(waitObject: null);
                    }
                },
                null,
                timeoutMilliseconds ?? -1,
                executeOnlyOnce: true);
            return tcs.Task;
        }

        public static async Task<bool> WaitOneAsync(this WaitHandle handle, int? timeoutMilliseconds = null) => await handle.ToTask(timeoutMilliseconds);

        public static async ValueTask<T> TakeAsync<T>(this BlockingCollection<T> collection, TimeSpan? pollTimeSpan = null, CancellationToken cancellationToken = default)
        {
            var delay = pollTimeSpan ?? TimeSpan.FromSeconds(.25);
            do
            {
                if (collection.TryTake(out T value))
                {
                    return value;
                }

                await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
                cancellationToken.ThrowIfCancellationRequested();
            } while (true);
        }
    }
}

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

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

namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
    internal static class Extensions
    {
        public static Task ToTask(this WaitHandle handle, int? timeoutMilliseconds)
        {
            RegisteredWaitHandle registeredHandle = null;
            var tcs = new TaskCompletionSource<object>();
            registeredHandle = ThreadPool.RegisterWaitForSingleObject(
                handle,
                (_, timeout) =>
                {
                    tcs.TrySetResult(null);
                    if (registeredHandle is object)
                    {
                        registeredHandle.Unregister(waitObject: null);
                    }
                },
                null,
                timeoutMilliseconds ?? -1,
                executeOnlyOnce: true);
            return tcs.Task;
        }

        public static async Task WaitOneAsync(this WaitHandle handle, int? timeoutMilliseconds = null) => await handle.ToTask(timeoutMilliseconds);

        public static async ValueTask<T> TakeAsync<T>(this BlockingCollection<T> collection, TimeSpan? pollTimeSpan = null, CancellationToken cancellationToken = default)
        {
            var delay = pollTimeSpan ?? TimeSpan.FromSeconds(.25);
            do
            {
                if (collection.TryTake(out T value))
                {
                    return value;
                }

                await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
                cancellationToken.ThrowIfCancellationRequested();
            } while (true);
        }
    }
}

Fix race in VBCSCompiler test

Fix race in VBCSCompiler test

Need to account for the case that the callback executes before the handle is assigned. Or that the handle is visible in the call back.

closes #41788


using System;
using System.Drawing;
using NUnit.Framework;
using Palaso.UI.WindowsForms;

namespace PalasoUIWindowsForms.Tests.FontTests
{
	[TestFixture]
	public class FontHelperTests
	{

		[SetUp]
		public void SetUp()
		{
			// setup code goes here
		}

		[TearDown]
		public void TearDown()
		{
			// tear down code goes here
		}

		[Test]
		public void MakeFont_FontAndStyle_ValidFont()
		{
			Font sourceFont = SystemFonts.DefaultFont;

			Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);

			Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
			Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
		}
	}
}

using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;

namespace PalasoUIWindowsForms.Tests.FontTests
{
	[TestFixture]
	public class FontHelperTests
	{

		[SetUp]
		public void SetUp()
		{
			// setup code goes here
		}

		[TearDown]
		public void TearDown()
		{
			// tear down code goes here
		}

		[Test]
		public void MakeFont_FontName_ValidFont()
		{
			Font sourceFont = SystemFonts.DefaultFont;
			Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
			Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
		}

		[Test]
		public void MakeFont_FontNameAndStyle_ValidFont()
		{
			// use Times New Roman
			foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
			{
				Font sourceFont = new Font(family, 10f, FontStyle.Regular);
				Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);

				Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
				Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);

				break;
			}
		}
	}
}

Fix mono bug in the FontHelper class

Fix mono bug in the FontHelper class


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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;
using Chiro.Gap.Api.Models;
using Chiro.Gap.ServiceContracts.DataContracts;

namespace Chiro.Gap.Api
{
    public static class MappingHelper
    {
        public static void CreateMappings()
        {
            // TODO: Damn, nog steeds automapper 3. (zie #5401).

            Mapper.CreateMap<GroepInfo, GroepModel>();
        }
    }
}

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

using AutoMapper;
using Chiro.Gap.Api.Models;
using Chiro.Gap.ServiceContracts.DataContracts;

namespace Chiro.Gap.Api
{
    public static class MappingHelper
    {
        public static void CreateMappings()
        {
            // TODO: Damn, nog steeds automapper 3. (zie #5401).

            Mapper.CreateMap<GroepInfo, GroepModel>()
                .ForMember(dst => dst.StamNummer, opt => opt.MapFrom(src => src.StamNummer.Trim()));
        }
    }
}

Remove trailing spaces from stamnummer.

Remove trailing spaces from stamnummer.


/* Empiria Extensions Framework ******************************************************************************
*                                                                                *
*  Solution  : Empiria Extensions Framework                     System   : Empiria Microservices             *
*  Namespace : Empiria.Microservices                            Assembly : Empiria.Microservices.dll         *
*  Type      : LoggingController                                Pattern  : Web API Controller                *
*  Version   : 1.0                                              License  : Please read license.txt file      *
*                                                                                *
*  Summary   : Contains web api methods for application log services.                                        *
*                                                                                *
********************************** Copyright(c) 2016-2017. La Vía Óntica SC, Ontica LLC and contributors.  **/
using System;
using System.Web.Http;

using Empiria.Logging;
using Empiria.Security;
using Empiria.WebApi;

namespace Empiria.Microservices {

  /// Contains web api methods for application log services.
  public class LoggingController : WebApiController {

    #region Public APIs

    /// Stores an array of log entries.
    /// <param name="logEntries">The non-empty array of LogEntryModel instances.</param>
    [HttpPost, AllowAnonymous]
    [Route("v1/logging")]
    public void PostLogEntryArray(string apiKey, [FromBody] LogEntryModel[] logEntries) {
      try {
        ClientApplication clientApplication = base.GetClientApplication();

        var logTrail = new LogTrail(clientApplication);

        logTrail.Write(logEntries);

      } catch (Exception e) {
        throw base.CreateHttpException(e);
      }
    }

    #endregion Public APIs

  }  // class LoggingController

}  // namespace Empiria.Microservices

/* Empiria Extensions Framework ******************************************************************************
*                                                                                *
*  Module   : Empiria Web Api                              Component : Base controllers                      *
*  Assembly : Empiria.WebApi.dll                           Pattern   : Web Api Controller                    *
*  Type     : LoggingController                            License   : Please read LICENSE.txt file          *
*                                                                                *
*  Summary  : Contains web api methods for application log services.                                         *
*                                                                                *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
using System.Web.Http;

using Empiria.Logging;
using Empiria.Security;

namespace Empiria.WebApi.Controllers {

  /// Contains web api methods for application log services.
  public class LoggingController : WebApiController {

    #region Public APIs

    /// Stores an array of log entries.
    /// <param name="logEntries">The non-empty array of LogEntryModel instances.</param>
    [HttpPost, AllowAnonymous]
    [Route("v1/logging")]
    public void PostLogEntryArray([FromBody] LogEntryModel[] logEntries) {
      try {
        ClientApplication clientApplication = base.GetClientApplication();

        var logTrail = new LogTrail(clientApplication);

        logTrail.Write(logEntries);

      } catch (Exception e) {
        throw base.CreateHttpException(e);
      }
    }

    #endregion Public APIs

  }  // class LoggingController

}  // namespace Empiria.WebApi.Controllers

Fix remove logging controller apiKey parameter


using System;
using System.Threading.Tasks;
using Windows.Storage;

namespace Papyrus
{
    public static class EBookExtensions
    {
        public static async Task<bool> VerifyMimetypeAsync(this EBook ebook)
        {
            var mimetypeFile = await ebook._rootFolder.GetItemAsync("mimetype");

            if (mimetypeFile == null)                                           // Make sure file exists.
                return false;

            var fileContents = await FileIO.ReadTextAsync(mimetypeFile as StorageFile);

            if (fileContents != "application/epub+zip")                         // Make sure file contents are correct.
                return false;

            return true;
        }
    }
}

using System;
using System.Threading.Tasks;
using Windows.Storage;

namespace Papyrus
{
    public static class EBookExtensions
    {
        public static async Task<bool> VerifyMimetypeAsync(this EBook ebook)
        {
            bool VerifyMimetypeString(string value) =>
                value == "application/epub+zip";

            if (ebook._rootFolder == null)                                      // Make sure a root folder was specified.
                return false;

            var mimetypeFile = await ebook._rootFolder.GetItemAsync("mimetype");

            if (mimetypeFile == null)                                           // Make sure file exists.
                return false;

            var fileContents = await FileIO.ReadTextAsync(mimetypeFile as StorageFile);

            if (!VerifyMimetypeString(fileContents))                         // Make sure file contents are correct.
                return false;

            return true;
        }
    }
}

Use local function to verify mimetype string.


using AvalonStudio.MainMenu;
using AvalonStudio.Menus;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Text;

namespace WalletWasabi.Gui.Shell.MainMenu
{
	internal class ToolsMainMenuItems
	{
		private IMenuItemFactory _menuItemFactory;

		[ImportingConstructor]
		public ToolsMainMenuItems(IMenuItemFactory menuItemFactory)
		{
			_menuItemFactory = menuItemFactory;
		}

		#region MainMenu

		[ExportMainMenuItem("Tools")]
		[DefaultOrder(1)]
		public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null);

		#endregion MainMenu

		#region Group

		[ExportMainMenuDefaultGroup("Tools", "Managers")]
		[DefaultOrder(0)]
		public object ManagersGroup => null;

		[ExportMainMenuDefaultGroup("Tools", "Settings")]
		[DefaultOrder(1)]
		public object SettingsGroup => null;

		#endregion Group

		#region MenuItem

		[ExportMainMenuItem("Tools", "Wallet Manager")]
		[DefaultOrder(0)]
		[DefaultGroup("Managers")]
		public IMenuItem GenerateWallet => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager");

		[ExportMainMenuItem("Tools", "Settings")]
		[DefaultOrder(1)]
		[DefaultGroup("Settings")]
		public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings");

		#endregion MenuItem
	}
}

using AvalonStudio.MainMenu;
using AvalonStudio.Menus;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Text;

namespace WalletWasabi.Gui.Shell.MainMenu
{
	internal class ToolsMainMenuItems
	{
		private IMenuItemFactory _menuItemFactory;

		[ImportingConstructor]
		public ToolsMainMenuItems(IMenuItemFactory menuItemFactory)
		{
			_menuItemFactory = menuItemFactory;
		}

		#region MainMenu

		[ExportMainMenuItem("Tools")]
		[DefaultOrder(1)]
		public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null);

		#endregion MainMenu

		#region Group

		[ExportMainMenuDefaultGroup("Tools", "Managers")]
		[DefaultOrder(0)]
		public object ManagersGroup => null;

		[ExportMainMenuDefaultGroup("Tools", "Settings")]
		[DefaultOrder(1)]
		public object SettingsGroup => null;

		#endregion Group

		#region MenuItem

		[ExportMainMenuItem("Tools", "Wallet Manager")]
		[DefaultOrder(0)]
		[DefaultGroup("Managers")]
		public IMenuItem WalletManager => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager");

		[ExportMainMenuItem("Tools", "Settings")]
		[DefaultOrder(1)]
		[DefaultGroup("Settings")]
		public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings");

		#endregion MenuItem
	}
}

Rename GenerateWallet menuitem to WalletManager


using NBitcoin;
using Newtonsoft.Json;
using System;

namespace WalletWasabi.JsonConverters
{
	public class ExtPubKeyJsonConverter : JsonConverter
	{
		/// <inheritdoc />
		public override bool CanConvert(Type objectType)
		{
			return objectType == typeof(ExtPubKey);
		}

		/// <inheritdoc />
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var hex = (string)reader.Value;
			return new ExtPubKey(ByteHelpers.FromHex(hex));
		}

		/// <inheritdoc />
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var epk = (ExtPubKey)value;
			var hex = ByteHelpers.ToHex(epk.ToBytes());
			writer.WriteValue(hex);
		}
	}
}

using NBitcoin;
using Newtonsoft.Json;
using System;

namespace WalletWasabi.JsonConverters
{
	public class ExtPubKeyJsonConverter : JsonConverter
	{
		/// <inheritdoc />
		public override bool CanConvert(Type objectType)
		{
			return objectType == typeof(ExtPubKey);
		}

		/// <inheritdoc />
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var s = (string)reader.Value;
			ExtPubKey epk;

			try
			{
				epk = ExtPubKey.Parse(s);
			}
			catch
			{
				// Try hex, Old wallet format was like this.
				epk = new ExtPubKey(ByteHelpers.FromHex(s));
			}
			return epk;
		}

		/// <inheritdoc />
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var epk = (ExtPubKey)value;

			var xpub = epk.GetWif(Network.Main).ToWif();
			writer.WriteValue(xpub);
		}
	}
}

Save xpub instead of hex (wallet compatibility)


using System;
using System.Collections.Generic;
using System.Text;
using Draw = System.Drawing;
using Geo = ERY.AgateLib.Geometry;

namespace ERY.AgateLib.WinForms
{
    public static class FormsInterop
    {
        public static Draw.Rectangle ToRectangle(Geo.Rectangle rect)
        {
            return new System.Drawing.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using Draw = System.Drawing;
using ERY.AgateLib.Geometry;

namespace ERY.AgateLib.WinForms
{
    public static class FormsInterop
    {
        public static Draw.Color ConvertColor(Color clr)
        {
            return Draw.Color.FromArgb(clr.ToArgb());
        }
        public static Color ConvertColor(Draw.Color clr)
        {
            return Color.FromArgb(clr.ToArgb());
        }

        public static Draw.Rectangle ConvertRectangle(Rectangle rect)
        {
            return new Draw.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
        }
        public static Rectangle ConvertRectangle(Draw.Rectangle rect)
        {
            return new Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
        }

        public static Draw.RectangleF ConvertRectangleF(RectangleF rect)
        {
            return new Draw.RectangleF(rect.X, rect.Y, rect.Width, rect.Height);
        }
        public static RectangleF ConvertRectangleF(Draw.RectangleF rect)
        {
            return new RectangleF(rect.X, rect.Y, rect.Width, rect.Height);
        }

        public static Point ConvertPoint(Draw.Point pt)
        {
            return new Point(pt.X, pt.Y);
        }
        public static Draw.Point ConvertPoint(Point pt)
        {
            return new Draw.Point(pt.X, pt.Y);
        }

        public static PointF ConvertPointF(Draw.PointF pt)
        {
            return new PointF(pt.X, pt.Y);
        }
        public static Draw.PointF ConvertPointF(PointF pt)
        {
            return new Draw.PointF(pt.X, pt.Y);
        }

        public static Size ConvertSize(Draw.Size pt)
        {
            return new Size(pt.Width, pt.Height);
        }
        public static Draw.Size ConvertSize(Size pt)
        {
            return new Draw.Size(pt.Width, pt.Height);
        }

        public static SizeF ConvertSizeF(Draw.SizeF pt)
        {
            return new SizeF(pt.Width, pt.Height);
        }
        public static Draw.SizeF ConvertSizeF(SizeF pt)
        {
            return new Draw.SizeF(pt.Width, pt.Height);
        }

    }
}

Add converters for System.Drawing structures.


using System.Text.RegularExpressions;

namespace MarekMotykaBot.ExtensionsMethods
{
	public static class StringExtensions
	{
		public static string RemoveRepeatingChars(this string inputString)
		{
			string newString = string.Empty;
			char[] charArray = inputString.ToCharArray();

			for (int i = 0; i < charArray.Length; i++)
			{
				if (string.IsNullOrEmpty(newString))
					newString += charArray[i].ToString();
				else if (newString[newString.Length - 1] != charArray[i])
					newString += charArray[i].ToString();
			}

			return newString;
		}

		public static string RemoveEmojis(this string inputString)
		{
			return Regex.Replace(inputString, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
		}

		public static string RemoveEmotes(this string inputString)
		{
			return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled);
		}

		public static string RemoveEmojisAndEmotes(this string inputString)
		{
			return inputString.RemoveEmotes().RemoveEmojis();
		}
	}
}

using System.Text.RegularExpressions;

namespace MarekMotykaBot.ExtensionsMethods
{
	public static class StringExtensions
	{
		public static string RemoveRepeatingChars(this string inputString)
		{
			string newString = string.Empty;
			char[] charArray = inputString.ToCharArray();

			for (int i = 0; i < charArray.Length; i++)
			{
				if (string.IsNullOrEmpty(newString))
					newString += charArray[i].ToString();
				else if (newString[newString.Length - 1] != charArray[i])
					newString += charArray[i].ToString();
			}

			return newString;
		}

		public static string RemoveEmojis(this string inputString)
		{
			return Regex.Replace(inputString, @"[^a-zA-Z0-9\s]+", "", RegexOptions.Compiled);
		}

		public static string RemoveEmotes(this string inputString)
		{
			return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled);
		}

		public static string RemoveEmojisAndEmotes(this string inputString)
		{
			return inputString.RemoveEmotes().RemoveEmojis();
		}
	}
}

Allow spaces in !meme command.

Allow spaces in !meme command.


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("libcmdline")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("libcmdline")]
[assembly: AssemblyCopyright("")]
[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("853c7fe9-e12b-484c-93de-3f3de6907860")]

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

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("libcmdline")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("libcmdline")]
[assembly: AssemblyCopyright("")]
[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("853c7fe9-e12b-484c-93de-3f3de6907860")]

// 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.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]

Change version to a reasonable value

Change version to a reasonable value

Let's face it. This library is at v0.1.


using System;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using VirusTotalNET.Exceptions;

namespace VirusTotalNET.DateTimeParsers
{
    public class YearMonthDayConverter : DateTimeConverterBase
    {
        private readonly CultureInfo _culture = new CultureInfo("en-us");
        private const string _dateFormatString = "yyyyMMdd";

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.DateFormatString = _dateFormatString;
            writer.WriteValue(value);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null)
                return DateTime.MinValue;

            if (!(reader.Value is string))
                throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + reader.Value);

            string value = (string)reader.Value;

            if (DateTime.TryParseExact(value, _dateFormatString, _culture, DateTimeStyles.AllowWhiteSpaces, out DateTime result))
                return result;

            throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + value);
        }
    }
}

using System;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using VirusTotalNET.Exceptions;

namespace VirusTotalNET.DateTimeParsers
{
    public class YearMonthDayConverter : DateTimeConverterBase
    {
        private readonly CultureInfo _culture = new CultureInfo("en-us");
        private const string _dateFormatString = "yyyyMMdd";

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.DateFormatString = _dateFormatString;
            writer.WriteValue(value);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null)
                return DateTime.MinValue;

            if (!(reader.Value is string))
                throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + reader.Value);

            string value = (string)reader.Value;

            //VT sometimes have really old data that return '-' in timestamps
            if (value.Equals("-", StringComparison.OrdinalIgnoreCase))
                return DateTime.MinValue;

            if (DateTime.TryParseExact(value, _dateFormatString, _culture, DateTimeStyles.AllowWhiteSpaces, out DateTime result))
                return result;

            throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + value);
        }
    }
}

Fix a bug where dates are sometimes '-'

Fix a bug where dates are sometimes '-'


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

using System.ComponentModel;

namespace osu.Game.Configuration
{
    public enum ScoreMeterType
    {
        [Description("None")]
        None,

        [Description("Hit Error (left)")]
        HitErrorLeft,

        [Description("Hit Error (right)")]
        HitErrorRight,

        [Description("Hit Error (both)")]
        HitErrorBoth,
    }
}

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

using System.ComponentModel;

namespace osu.Game.Configuration
{
    public enum ScoreMeterType
    {
        [Description("None")]
        None,

        [Description("Hit Error (left)")]
        HitErrorLeft,

        [Description("Hit Error (right)")]
        HitErrorRight,

        [Description("Hit Error (both)")]
        HitErrorBoth,

        [Description("Colour (left)")]
        ColourLeft,

        [Description("Colour (right)")]
        ColourRight,

        [Description("Colour (both)")]
        ColourBoth,
    }
}

Add more types to dropdown

Add more types to dropdown


using System;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.Extensions.Configuration;

namespace AudioWorks.Common
{
    /// <summary>
    /// Manages the retrieval of configuration settings from disk.
    /// </summary>
    public static class ConfigurationManager
    {
        /// <summary>
        /// Gets the configuration.
        /// </summary>
        /// <value>The configuration.</value>
        [NotNull]
        [CLSCompliant(false)]
        public static IConfigurationRoot Configuration { get; }

        static ConfigurationManager()
        {
            var settingsPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "AudioWorks");
            const string settingsFileName = "settings.json";

            // Copy the settings template if the file doesn't already exist
            var settingsFile = Path.Combine(settingsPath, settingsFileName);
            if (!File.Exists(settingsFile))
            {
                Directory.CreateDirectory(settingsPath);
                File.Copy(
                    // ReSharper disable once AssignNullToNotNullAttribute
                    Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), settingsFileName),
                    settingsFile);
            }

            Configuration = new ConfigurationBuilder()
                .SetBasePath(settingsPath)
                .AddJsonFile(settingsFileName, true)
                .Build();
        }
    }
}

using System;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.Extensions.Configuration;

namespace AudioWorks.Common
{
    /// <summary>
    /// Manages the retrieval of configuration settings from disk.
    /// </summary>
    public static class ConfigurationManager
    {
        /// <summary>
        /// Gets the configuration.
        /// </summary>
        /// <value>The configuration.</value>
        [NotNull]
        [CLSCompliant(false)]
        public static IConfigurationRoot Configuration { get; }

        static ConfigurationManager()
        {
            var settingsPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "AudioWorks");
            const string settingsFileName = "settings.json";

            // Copy the settings template if the file doesn't already exist
            var settingsFile = Path.Combine(settingsPath, settingsFileName);
            if (!File.Exists(settingsFile))
            {
                Directory.CreateDirectory(settingsPath);
                File.Copy(
                    Path.Combine(
                        // ReSharper disable once AssignNullToNotNullAttribute
                        Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath),
                        settingsFileName),
                    settingsFile);
            }

            Configuration = new ConfigurationBuilder()
                .SetBasePath(settingsPath)
                .AddJsonFile(settingsFileName, true)
                .Build();
        }
    }
}

Correct issue where settings.json cannot be found when using a shadow copied DLL.


using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;

namespace RohlikAPITests
{
    [TestClass]
    public class RohlikovacTests
    {
        private string[] GetCredentials()
        {
            string filePath = @"..\..\..\loginPassword.txt";
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("Test needs credentials. Create 'loginPassword.txt' in solution root directory. Enter username@email.com:yourPassword on first line.");
            }
            var passwordString = File.ReadAllText(filePath);
            return passwordString.Split(':');
        }

        [TestMethod]
        public void RunTest()
        {
            var login = GetCredentials();
            var rohlikApi = new AuthenticatedRohlikApi(login[0], login[1]);
            var result = rohlikApi.RunRohlikovac();
            if (result.Contains("error"))
            {
                Assert.Fail($"Failed to login to rohlik. Login used: {login[0]}");
            }
        }
    }
}

using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;

namespace RohlikAPITests
{
    [TestClass]
    public class RohlikovacTests
    {
        private string[] GetCredentials()
        {
            string filePath = @"..\..\..\loginPassword.txt";
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("Test needs credentials. Create 'loginPassword.txt' in solution root directory. Enter username@email.com:yourPassword on first line.");
            }
            var passwordString = File.ReadAllText(filePath);
            return passwordString.Split(':');
        }

        [TestMethod, TestCategory("Authenticated")]
        public void RunTest()
        {
            var login = GetCredentials();
            var rohlikApi = new AuthenticatedRohlikApi(login[0], login[1]);
            var result = rohlikApi.RunRohlikovac();
            if (result.Contains("error"))
            {
                Assert.Fail($"Failed to login to rohlik. Login used: {login[0]}");
            }
        }
    }
}

Add test category to authenticated test

Add test category to authenticated test


using System;
using Reachmail.Easysmtp.Post.Request;

public void Main()
{
    var reachmail = Reachmail.Api.Create("<API Token>");

    var request = new DeliveryRequest {
        FromAddress = "from@from.com",
        Recipients = new Recipients {
            new Recipient {
                Address = "to@to.com"
            }
        },
        Subject = "Subject",
        BodyText = "Text",
        BodyHtml = "
html
",
        Headers = new Headers {
            { "name", "value" }
        },
        Attachments = new Attachments {
            new EmailAttachment {
                Filename = "text.txt",
                Data = "b2ggaGFp", // Base64 encoded
                ContentType = "text/plain",
                ContentDisposition = "attachment",
                Cid = "<text.txt>"
            }
        },
        Tracking = true,
        FooterAddress = "footer@footer.com",
        SignatureDomain = "signature.net"
    };

    var result = reachmail.Easysmtp.Post(request);
}

using System;
using Reachmail.Easysmtp.Post.Request;

public void Main()
{
    var reachmail = Reachmail.Api.Create("<API Token>");

    var request = new DeliveryRequest {
        FromAddress = "from@from.com",
        Recipients = new Recipients {
            new Recipient {
                Address = "to@to.com"
            }
        },
        Subject = "Subject",
        BodyText = "Text",
        BodyHtml = "html",
        Headers = new Headers {
            { "name", "value" }
        },
        Attachments = new Attachments {
            new EmailAttachment {
                Filename = "text.txt",
                Data = "b2ggaGFp", // Base64 encoded
                ContentType = "text/plain",
                ContentDisposition = "attachment",
                Cid = "<text.txt>"
            }
        },
        Tracking = true,
        FooterAddress = "footer@footer.com",
        SignatureDomain = "signature.net"
    };

    var result = reachmail.Easysmtp.Post(request);
}

Tweak to content for display on ES marketing site

Removed P tags from the HTML content node.


using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Discord;
using Discord.WebSocket;
using Discord.Commands;
using System.Threading.Tasks;

namespace ContactsBot.Modules
{
    class UserMotd : IMessageAction
    {
        private DiscordSocketClient _client;
        private BotConfiguration _config;

        public bool IsEnabled { get; private set; }

        public void Install(IDependencyMap map)
        {
            _client = map.Get<DiscordSocketClient>();
            _config = map.Get<BotConfiguration>();
        }

        public void Enable()
        {
            _client.UserJoined += ShowMotd;
            IsEnabled = true;
        }

        public void Disable()
        {
            _client.UserJoined -= ShowMotd;
            IsEnabled = false;
        }

        public async Task ShowMotd(SocketGuildUser user)
        {
            var channel = await user.Guild.GetDefaultChannelAsync();

            try
            {
                await channel.SendMessageAsync(String.Format(_config.MessageOfTheDay, user.Mention));
            }
            catch (FormatException)
            {
                await channel.SendMessageAsync("Tell the admin to fix the MOTD formatting!");
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Discord;
using Discord.WebSocket;
using Discord.Commands;
using System.Threading.Tasks;

namespace ContactsBot.Modules
{
    class UserMotd : IMessageAction
    {
        private DiscordSocketClient _client;
        private BotConfiguration _config;

        public bool IsEnabled { get; private set; }

        public void Install(IDependencyMap map)
        {
            _client = map.Get<DiscordSocketClient>();
            _config = map.Get<BotConfiguration>();
        }

        public void Enable()
        {
            _client.UserJoined += ShowMotd;
            IsEnabled = true;
        }

        public void Disable()
        {
            _client.UserJoined -= ShowMotd;
            IsEnabled = false;
        }

        public async Task ShowMotd(SocketGuildUser user)
        {
            var channel = await user.Guild.GetDefaultChannelAsync();

            try
            {
                await (await user.CreateDMChannelAsync()).SendMessageAsync(String.Format(_config.MessageOfTheDay, user.Mention));
            }
            catch (FormatException)
            {
                await channel.SendMessageAsync("Tell the admin to fix the MOTD formatting!");
            }
        }
    }
}

Send message as DM, not default channel

Send message as DM, not default channel


using System;

using Cake.Frosting;

public class Program
{
    public static int Main(string[] args)
    {
        return new CakeHost()
            .UseContext<Context>()
            .UseLifetime<Lifetime>()
            .UseWorkingDirectory("..")
            .InstallTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1"))
            .InstallTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0"))
            .InstallTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0"))
            .InstallTool(new Uri("nuget:?package=NuGet.CommandLine&version=5.8.0"))
            .Run(args);
    }
}

using System;

using Cake.Frosting;

public class Program
{
    public static int Main(string[] args)
    {
        return new CakeHost()
            .UseContext<Context>()
            .UseLifetime<Lifetime>()
            .UseWorkingDirectory("..")
            .SetToolPath("../tools")
            .InstallTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1"))
            .InstallTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0"))
            .InstallTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0"))
            .InstallTool(new Uri("nuget:?package=NuGet.CommandLine&version=5.8.0"))
            .Run(args);
    }
}

Fix tools being installed to wrong path

Fix tools being installed to wrong path


using System.Reactive.Linq;
using ReactiveUI;
using System;

namespace WalletWasabi.Fluent.ViewModels
{
	public class AddWalletPageViewModel : NavBarItemViewModel
	{
		private string _walletName = "";
		private bool _optionsEnabled;

		public AddWalletPageViewModel(NavigationStateViewModel navigationState) : base(navigationState, NavigationTarget.Dialog)
		{
			Title = "Add Wallet";

			this.WhenAnyValue(x => x.WalletName)
				.Select(x => !string.IsNullOrWhiteSpace(x))
				.Subscribe(x => OptionsEnabled = x);
		}

		public override string IconName => "add_circle_regular";

		public string WalletName
		{
			get => _walletName;
			set => this.RaiseAndSetIfChanged(ref _walletName, value);
		}

		public bool OptionsEnabled
		{
			get => _optionsEnabled;
			set => this.RaiseAndSetIfChanged(ref _optionsEnabled, value);
		}
	}
}

using System.Reactive.Linq;
using ReactiveUI;
using System;
using System.Windows.Input;

namespace WalletWasabi.Fluent.ViewModels
{
	public class AddWalletPageViewModel : NavBarItemViewModel
	{
		private string _walletName = "";
		private bool _optionsEnabled;

		public AddWalletPageViewModel(NavigationStateViewModel navigationState) : base(navigationState, NavigationTarget.Dialog)
		{
			Title = "Add Wallet";

			BackCommand = ReactiveCommand.Create(() => navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear());
			CancelCommand = ReactiveCommand.Create(() => navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear());

			this.WhenAnyValue(x => x.WalletName)
				.Select(x => !string.IsNullOrWhiteSpace(x))
				.Subscribe(x => OptionsEnabled = x);
		}

		public override string IconName => "add_circle_regular";

		public ICommand BackCommand { get; }
		public ICommand CancelCommand { get; }

		public string WalletName
		{
			get => _walletName;
			set => this.RaiseAndSetIfChanged(ref _walletName, value);
		}

		public bool OptionsEnabled
		{
			get => _optionsEnabled;
			set => this.RaiseAndSetIfChanged(ref _optionsEnabled, value);
		}
	}
}

Add back and cancel button commands

Add back and cancel button commands