using System.Collections.Generic;
using TirkxDownloader.Models;

namespace TirkxDownloader.Framework.Interface
{
    public delegate void DownloadCompleteHandler(GeneralDownloadItem downloadInfo);

    /// <summary>
    /// Implementation that implement this interface should implement PropertyChanged Event for data-binding
    /// </summary>
    public interface IDownloader
    {
        bool IsDownloading { get; }

        long MaximumBytesPerSecond { get; set; }

        int MaxDownloadingItems { get; set; }

        string DownloaderErrorMessage { get; set; }

        int DownloadingItems { get; set; }

        void DownloadItem(IDownloadItem item);

        void DownloadItems(IEnumerable<IDownloadItem> items);

        void StopDownloadItem(IDownloadItem item);

        void StopDownloadItems(IEnumerable<IDownloadItem> items);
    }
}

using System.Collections.Generic;
using TirkxDownloader.Models;

namespace TirkxDownloader.Framework.Interface
{
    public delegate void DownloadCompleteHandler(GeneralDownloadItem downloadInfo);

    /// <summary>
    /// Implementation that implement this interface should implement PropertyChanged Event for data-binding
    /// </summary>
    public interface IDownloader
    {
        bool IsDownloading { get; }

        long MaximumBytesPerSecond { get; }

        byte MaxDownloadingItems { get; }

        string DownloaderErrorMessage { get; set; }

        int DownloadingItems { get; set; }

        void DownloadItem(IDownloadItem item);

        void DownloadItems(IEnumerable<IDownloadItem> items);

        void StopDownloadItem(IDownloadItem item);

        void StopDownloadItems(IEnumerable<IDownloadItem> items);
    }
}

Change date type of MaxDownloadingItems to byte and change to get only


using System;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.Extensions.Configuration;

namespace QueueGettingStarted
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // configuration
            var builder = new ConfigurationBuilder()
                .AddJsonFile("./appsettings.json")
                .AddUserSecrets()
                .AddEnvironmentVariables();
            Configuration = builder.Build();
            // options
            ConfigurationBinder.Bind(Configuration.GetSection("Azure:Storage"), Options);
            Console.WriteLine("Queue encryption sample");
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("");
            CloudQueueClient client = storageAccount.CreateCloudQueueClient();
            if(client != null){
                Console.WriteLine("Client created");
            } else {
                Console.WriteLine("Error creating client");
            }
            Console.ReadKey();
        }

        static IConfiguration Configuration { get; set; }
        static AzureStorageOptions Options {get; set; } = new AzureStorageOptions();
    }

    class AzureStorageOptions {
        public string ConnectionString { get; set; }
    }
}

using System;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.Extensions.Configuration;

namespace QueueGettingStarted
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // configuration
            var builder = new ConfigurationBuilder()
                .AddJsonFile("./appsettings.json")
                .AddUserSecrets()
                .AddEnvironmentVariables();
            Configuration = builder.Build();
            // options
            ConfigurationBinder.Bind(Configuration.GetSection("Azure:Storage"), Options);
            Console.WriteLine("Queue encryption sample");
            Console.WriteLine($"Configuration for ConnectionString: {Options.ConnectionString}");
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Options.ConnectionString);
            CloudQueueClient client = storageAccount.CreateCloudQueueClient();
            if (client != null)
            {
                Console.WriteLine("Client created");
            }
            else
            {
                Console.WriteLine("Error creating client");
            }
            Console.ReadKey();
        }

        static IConfiguration Configuration { get; set; }
        static AzureStorageOptions Options { get; set; } = new AzureStorageOptions();
    }

    class AzureStorageOptions
    {
        public string ConnectionString { get; set; }
    }
}

Read connection string from configuration


using LogBook.Services;
using LogBook.Services.Models;
using Portal.CMS.Web.Architecture.ViewEngines;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Razor;
using System.Web.Routing;
using System.Web.WebPages;

namespace Portal.CMS.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());
            ViewEngines.Engines.Add(new CSSViewEngine());

            RazorCodeLanguage.Languages.Add("cscss", new CSharpRazorCodeLanguage());
            WebPageHttpHandler.RegisterExtension("cscss");

            MvcHandler.DisableMvcResponseHeader = true;
        }

        protected void Application_Error()
        {
            var logHandler = new LogHandler();

            var exception = Server.GetLastError();

            logHandler.WriteLog(LogType.Error, "PortalCMS", exception, "An Exception has occured while Running PortalCMS", string.Empty);

            if (System.Configuration.ConfigurationManager.AppSettings["CustomErrorPage"] == "true")
            {
                Response.Redirect("~/Home/Error");
            }
        }
    }
}

using LogBook.Services;
using LogBook.Services.Models;
using Portal.CMS.Web.Architecture.Helpers;
using Portal.CMS.Web.Architecture.ViewEngines;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Razor;
using System.Web.Routing;
using System.Web.WebPages;

namespace Portal.CMS.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());
            ViewEngines.Engines.Add(new CSSViewEngine());

            RazorCodeLanguage.Languages.Add("cscss", new CSharpRazorCodeLanguage());
            WebPageHttpHandler.RegisterExtension("cscss");

            MvcHandler.DisableMvcResponseHeader = true;
        }

        protected void Application_Error()
        {
            var logHandler = new LogHandler();

            var exception = Server.GetLastError();

            var userAccount = UserHelper.UserId;

            logHandler.WriteLog(LogType.Error, "PortalCMS", exception, "An Exception has occured while Running PortalCMS", userAccount.ToString());

            if (System.Configuration.ConfigurationManager.AppSettings["CustomErrorPage"] == "true")
            {
                Response.Redirect("~/Home/Error");
            }
        }
    }
}

Add UserName to LogEntries When Authenticated


namespace SnappyMap.IO
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using SnappyMap.Data;

    [Serializable]
    public struct SectionMapping
    {
        public SectionMapping(SectionType type, params string[] sections)
            : this()
        {
            this.Type = type;
            this.Sections = sections.ToList();
        }

        public SectionType Type { get; set; }

        public List<string> Sections { get; set; }
    }

    [Serializable]
    public class SectionConfig
    {
        public SectionConfig()
        {
            this.SectionMappings = new List<SectionMapping>();
        }

        public int SeaLevel { get; set; }

        public List<SectionMapping> SectionMappings { get; private set; }
    }
}

namespace SnappyMap.IO
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using SnappyMap.Data;

    [Serializable]
    public struct SectionMapping
    {
        public SectionMapping(SectionType type, params string[] sections)
            : this()
        {
            this.Type = type;
            this.Sections = sections.ToList();
        }

        public SectionType Type { get; set; }

        public List<string> Sections { get; set; }
    }

    [Serializable]
    public class SectionConfig
    {
        public SectionConfig()
        {
            this.SectionMappings = new List<SectionMapping>();
        }

        public int SeaLevel { get; set; }

        public List<SectionMapping> SectionMappings { get; set; }
    }
}

Fix potential crash in old .NET versions

Apparently in older .NET the XML deserializer
doesn't like it when the type to be deserialized
has properties with private setters.

https://stackoverflow.com/questions/891449/xmlserializer-and-collection-property-with-private-setter
https://www.fmork.net/software/writing/2010/Readonly-collection-properties-and-XmlSerializer.htm
https://stackoverflow.com/questions/23809092/unable-to-generate-a-temporary-class-result-1-cs0200


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

namespace elbgb.gameboy
{
	class Timer
	{
		public static class Registers
		{
			public const ushort DIV  = 0xFF04;
			public const ushort TIMA = 0xFF05;
			public const ushort TMA  = 0xFF06;
			public const ushort TAC  = 0xFF07;
		}

		private GameBoy _gb;
		private ulong _lastUpdate;

		private ushort _div;

		public Timer(GameBoy gameBoy)
		{
			_gb = gameBoy;
		}

		public byte ReadByte(ushort address)
		{
			switch (address)
			{
				case Registers.DIV: return (byte)(_div >> 8);

				default:
					throw new NotImplementedException();
			}
		}

		public void WriteByte(ushort address, byte value)
		{
			switch (address)
			{
				// a write always clears the upper 8 bits of DIV, regardless of value
				case Registers.DIV: _div &= 0x00FF; break;

				default:
					throw new NotImplementedException();
			}
		}

		public void Update()
		{
			ulong cyclesToUpdate = _gb.Timestamp - _lastUpdate;

			_lastUpdate = _gb.Timestamp;

			// update divider
			_div += (ushort)cyclesToUpdate;
		}
	}
}

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

namespace elbgb.gameboy
{
	class Timer
	{
		public static class Registers
		{
			public const ushort DIV  = 0xFF04;
			public const ushort TIMA = 0xFF05;
			public const ushort TMA  = 0xFF06;
			public const ushort TAC  = 0xFF07;
		}

		private GameBoy _gb;
		private ulong _lastUpdate;

		private ushort _div;

		public Timer(GameBoy gameBoy)
		{
			_gb = gameBoy;
		}

		public byte ReadByte(ushort address)
		{
			switch (address)
			{
				case Registers.DIV: return (byte)(_div >> 8);

				default:
					throw new NotImplementedException();
			}
		}

		public void WriteByte(ushort address, byte value)
		{
			switch (address)
			{
				// a write always clears the upper 8 bits of DIV, regardless of value
				case Registers.DIV: _div &= 0x00FF; break;

				default:
					throw new NotImplementedException();
			}
		}

		public void Update()
		{
			ulong cyclesToUpdate = _gb.Timestamp - _lastUpdate;

			_lastUpdate = _gb.Timestamp;

			UpdateDivider(cyclesToUpdate);
		}

		private void UpdateDivider(ulong cyclesToUpdate)
		{
			_div += (ushort)cyclesToUpdate;
		}
	}
}

Split out divider update in timer

Split out divider update in timer


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

namespace MeDaUmFilme
{
    public class Movie
    {
        public string Title { get; set; }
        public string Year { get; set; }
    }

    public class OmdbResult
    {
        public List<Movie> Search { get; set; }
    }
}

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

namespace MeDaUmFilme
{
    public class Movie
    {
        public string Title { get; set; }
        public string Year { get; set; }
        public string Poster { get; set; }
        public string Type { get; set; }
    }

    public class OmdbResult
    {
        public List<Movie> Search { get; set; }
    }
}

Add image link to movie

Add image link to movie


using Microsoft.EntityFrameworkCore;
using Mitternacht.Services.Database;

namespace Mitternacht.Services
{
    public class DbService
    {
        private readonly DbContextOptions _options;

        public DbService(IBotCredentials creds)
        {
            var optionsBuilder = new DbContextOptionsBuilder();
            optionsBuilder.UseSqlite(creds.DbConnectionString);
            _options = optionsBuilder.Options;
            //switch (_creds.Db.Type.ToUpperInvariant())
            //{
            //    case "SQLITE":
            //        dbType = typeof(NadekoSqliteContext);
            //        break;
            //    //case "SQLSERVER":
            //    //    dbType = typeof(NadekoSqlServerContext);
            //    //    break;
            //    default:
            //        break;

            //}
        }

        public NadekoContext GetDbContext()
        {
            var context = new NadekoContext(_options);
            context.Database.SetCommandTimeout(60);
            context.Database.Migrate();
            context.EnsureSeedData();

            //set important sqlite stuffs
            var conn = context.Database.GetDbConnection();
            conn.Open();

            context.Database.ExecuteSqlRaw("PRAGMA journal_mode=WAL");
            using (var com = conn.CreateCommand())
            {
                com.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=OFF";
                com.ExecuteNonQuery();
            }

            return context;
        }

        public IUnitOfWork UnitOfWork =>
            new UnitOfWork(GetDbContext());
    }
}

using Microsoft.EntityFrameworkCore;
using Mitternacht.Services.Database;

namespace Mitternacht.Services {
	public class DbService {
		private readonly DbContextOptions _options;

		public DbService(IBotCredentials creds) {
			var optionsBuilder = new DbContextOptionsBuilder();
			optionsBuilder.UseSqlite(creds.DbConnectionString);
			_options = optionsBuilder.Options;
		}

		public NadekoContext GetDbContext() {
			var context = new NadekoContext(_options);
			context.Database.SetCommandTimeout(60);
			context.Database.Migrate();
			context.EnsureSeedData();

			//set important sqlite stuffs
			var conn = context.Database.GetDbConnection();
			conn.Open();

			context.Database.ExecuteSqlRaw("PRAGMA journal_mode=WAL");
			using(var com = conn.CreateCommand()) {
				com.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=OFF";
				com.ExecuteNonQuery();
			}

			return context;
		}

		public IUnitOfWork UnitOfWork =>
			new UnitOfWork(GetDbContext());
	}
}

Format file, remove outcommented code.

Format file, remove outcommented code.


// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.Log4NetIntegration.Logging
{
    using System.IO;
    using MassTransit.Logging;
    using log4net;
    using log4net.Config;

    public class Log4NetLogger :
        ILogger
    {
        public MassTransit.Logging.ILog Get(string name)
        {
            return new Log4NetLog(LogManager.GetLogger(name));
        }

        public static void Use()
        {
            Logger.UseLogger(new Log4NetLogger());
        }

        public static void Use(string file)
        {
            Logger.UseLogger(new Log4NetLogger());

            var configFile = new FileInfo(file);
            XmlConfigurator.Configure(configFile);
        }
    }
}

// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.Log4NetIntegration.Logging
{
    using System;
    using System.IO;
    using MassTransit.Logging;
    using log4net;
    using log4net.Config;

    public class Log4NetLogger :
        ILogger
    {
        public MassTransit.Logging.ILog Get(string name)
        {
            return new Log4NetLog(LogManager.GetLogger(name));
        }

        public static void Use()
        {
            Logger.UseLogger(new Log4NetLogger());
        }

        public static void Use(string file)
        {
            Logger.UseLogger(new Log4NetLogger());

            file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file);
            var configFile = new FileInfo(file);
            XmlConfigurator.Configure(configFile);
        }
    }
}

Fix Log4Net path for loading config file

The Log4Net config file should be picked up from the base directory of
the current app domain so that when running as a windows service MT will
load the log4net config file from the app directory and not a Windows
system folder

Former-commit-id: 0d8ad7b1ff7239c974641b8c44bd82fe1d4e148b


// TokenList.cs
// Script#/Libraries/Web
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//

using System;
using System.Runtime.CompilerServices;

namespace System.Html {

    [IgnoreNamespace]
    [Imported]
    public class TokenList {

        internal TokenList() {
        }

        [IntrinsicProperty]
        [ScriptName("length")]
        public int Count {
            get {
                return 0;
            }
        }

        [IntrinsicProperty]
        public string this[int index] {
            get {
                return null;
            }
        }

        public bool Contains(string token) {
            return false;
        }

        public void Add(string token) {
        }

        public void Remove(string token) {
        }

        public bool Toggle(string token) {
            return false;
        }

        public override string ToString() {
            return null;
        }
    }
}

// TokenList.cs
// Script#/Libraries/Web
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//

using System;
using System.Runtime.CompilerServices;

namespace System.Html {

    [IgnoreNamespace]
    [Imported]
    public sealed class TokenList {

        private TokenList() {
        }

        [IntrinsicProperty]
        [ScriptName("length")]
        public int Count {
            get {
                return 0;
            }
        }

        [IntrinsicProperty]
        public string this[int index] {
            get {
                return null;
            }
        }

        public bool Contains(string token) {
            return false;
        }

        public void Add(string token) {
        }

        public void Remove(string token) {
        }

        public bool Toggle(string token) {
            return false;
        }

        public override string ToString() {
            return null;
        }
    }
}

Update access modifiers for metadata class


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

#nullable disable

using System;
using osu.Framework;
using osu.Framework.Platform;

namespace osu.Game.Tests
{
    public static class VisualTestRunner
    {
        [STAThread]
        public static int Main(string[] args)
        {
            using (DesktopGameHost host = Host.GetSuitableDesktopHost(@"osu", new HostOptions { BindIPC = true, }))
            {
                host.Run(new OsuTestBrowser());
                return 0;
            }
        }
    }
}

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

#nullable disable

using System;
using osu.Framework;
using osu.Framework.Platform;

namespace osu.Game.Tests
{
    public static class VisualTestRunner
    {
        [STAThread]
        public static int Main(string[] args)
        {
            using (DesktopGameHost host = Host.GetSuitableDesktopHost(@"osu-development", new HostOptions { BindIPC = true, }))
            {
                host.Run(new OsuTestBrowser());
                return 0;
            }
        }
    }
}

Update interactive visual test runs to use development directory


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("DiffPlex")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DiffPlex")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// 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.2.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("DiffPlex")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DiffPlex")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Assembly version should consist of just major and minor versions.
// We omit revision and build numbers so that folks who compile against
// 1.2.0 can also run against 1.2.1 without a recompile or a binding redirect.
[assembly: AssemblyVersion("1.2.0.0")]

// File version can include the revision and build numbers so
// file properties can reveal the true version of this build.
[assembly: AssemblyFileVersion("1.2.1.0")]

Update file version of DLL to match NuGet package.

Also remove the random component of the assembly version for easier runtime binding of clients.


using System.IO;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Wox.Plugin.WebSearch
{
    public class WebSearch
    {
        public const string DefaultIcon = "web_search.png";
        public string Title { get; set; }
        public string ActionKeyword { get; set; }
        [NotNull]
        private string _icon = DefaultIcon;

        [NotNull]
        public string Icon
        {
            get { return _icon; }
            set
            {
                _icon = value;
                IconPath = Path.Combine(WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, value);
            }
        }
        /// <summary>
        /// All icon should be put under Images directory
        /// </summary>
        [NotNull]
        [JsonIgnore]
        internal string IconPath { get; private set; }

        public string Url { get; set; }
        public bool Enabled { get; set; }
    }
}

using System.IO;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Wox.Plugin.WebSearch
{
    public class WebSearch
    {
        public const string DefaultIcon = "web_search.png";
        public string Title { get; set; }
        public string ActionKeyword { get; set; }
        [NotNull]
        private string _icon = DefaultIcon;

        [NotNull]
        public string Icon
        {
            get { return _icon; }
            set
            {
                _icon = value;
                IconPath = Path.Combine(WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, value);
            }
        }

        /// <summary>
        /// All icon should be put under Images directory
        /// </summary>
        [NotNull]
        [JsonIgnore]
        internal string IconPath { get; private set; } = Path.Combine
        (
            WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, DefaultIcon
        );

        public string Url { get; set; }
        public bool Enabled { get; set; }
    }
}

Fix default icon path when add new web search


using MultiMiner.Blockchain.Data;
using MultiMiner.ExchangeApi;
using MultiMiner.ExchangeApi.Data;
using MultiMiner.Utility.Net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace MultiMiner.Blockchain
{
    public class ApiContext : IApiContext
    {
        public IEnumerable<ExchangeInformation> GetExchangeInformation()
        {
            WebClient webClient = new ApiWebClient();
            webClient.Encoding = Encoding.UTF8;

            string response = webClient.DownloadString(new Uri(GetApiUrl()));

            Dictionary<string, TickerEntry> tickerEntries = JsonConvert.DeserializeObject<Dictionary<string, TickerEntry>>(response);

            List<ExchangeInformation> results = new List<ExchangeInformation>();

            foreach (KeyValuePair<string, TickerEntry> keyValuePair in tickerEntries)
            {
                results.Add(new ExchangeInformation()
                {
                    SourceCurrency = "BTC",
                    TargetCurrency = keyValuePair.Key,
                    TargetSymbol = keyValuePair.Value.Symbol,
                    ExchangeRate = keyValuePair.Value.Last
                });
            }

            return results;
        }

        public string GetInfoUrl()
        {
            return "https://blockchain.info";
        }

        public string GetApiUrl()
        {
            //use HTTP as HTTPS is down at times and returns:
            //The request was aborted: Could not create SSL/TLS secure channel.
            return "http://blockchain.info/ticker";
        }

        public string GetApiName()
        {
            return "Blockchain";
        }
    }
}

using MultiMiner.Blockchain.Data;
using MultiMiner.ExchangeApi;
using MultiMiner.ExchangeApi.Data;
using MultiMiner.Utility.Net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace MultiMiner.Blockchain
{
    public class ApiContext : IApiContext
    {
        public IEnumerable<ExchangeInformation> GetExchangeInformation()
        {
            ApiWebClient webClient = new ApiWebClient();
            webClient.Encoding = Encoding.UTF8;

            string response = webClient.DownloadFlakyString(new Uri(GetApiUrl()));

            Dictionary<string, TickerEntry> tickerEntries = JsonConvert.DeserializeObject<Dictionary<string, TickerEntry>>(response);

            List<ExchangeInformation> results = new List<ExchangeInformation>();

            foreach (KeyValuePair<string, TickerEntry> keyValuePair in tickerEntries)
            {
                results.Add(new ExchangeInformation()
                {
                    SourceCurrency = "BTC",
                    TargetCurrency = keyValuePair.Key,
                    TargetSymbol = keyValuePair.Value.Symbol,
                    ExchangeRate = keyValuePair.Value.Last
                });
            }

            return results;
        }

        public string GetInfoUrl()
        {
            return "https://blockchain.info";
        }

        public string GetApiUrl()
        {
            //use HTTP as HTTPS is down at times and returns:
            //The request was aborted: Could not create SSL/TLS secure channel.
            return "https://blockchain.info/ticker";
        }

        public string GetApiName()
        {
            return "Blockchain";
        }
    }
}

Introduce a retry machanism with the Blockchain API


// Copyright 2014 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;

namespace NodaTime.Annotations
{
    /// <summary>
    /// Indicates that a value-type field which would otherwise by <c>readonly</c>
    /// is read/write so that invoking members on the field avoids taking a copy of
    /// the field value.
    /// </summary>
    /// <remarks>
    /// See http://msmvps.com/blogs/jon_skeet/archive/2014/07/16/micro-optimization-the-surprising-inefficiency-of-readonly-fields.aspx
    /// for details of why we're doing this at all.
    /// </remarks>
    [AttributeUsage(AttributeTargets.Field)]
    internal sealed class ReadWriteForEfficiencyAttribute : Attribute
    {
    }
}

// Copyright 2014 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;

namespace NodaTime.Annotations
{
    /// <summary>
    /// Indicates that a value-type field which would otherwise by <c>readonly</c>
    /// is read/write so that invoking members on the field avoids taking a copy of
    /// the field value.
    /// </summary>
    /// <remarks>
    /// See http://noda-time.blogspot.com/2014/07/micro-optimization-surprising.html
    /// for details of why we're doing this at all.
    /// </remarks>
    [AttributeUsage(AttributeTargets.Field)]
    internal sealed class ReadWriteForEfficiencyAttribute : Attribute
    {
    }
}

Fix the URL to point at the Noda Time blog because msmvps.com 503.


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

namespace Training.CSharpWorkshop.Tests
{
    [TestClass]
    public class ProgramTests
    {
        [Ignore]
        [TestMethod]
        public void IgnoreTest()
        {
            Assert.Fail();
        }

        [TestMethod()]
        public void GetRoleMessageForAdminTest()
        {
            // Arrange
            var userName = "Andrew";
            var expected = "Role: Admin.";

            // Act
            var actual = Program.GetRoleMessage(userName);

            // Assert
            Assert.AreEqual(expected, actual);
        }
    }
}

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

namespace Training.CSharpWorkshop.Tests
{
    [TestClass]
    public class ProgramTests
    {
        [Ignore]
        [TestMethod]
        public void IgnoreTest()
        {
            Assert.Fail();
        }

        [TestMethod()]
        public void GetRoleMessageForAdminTest()
        {
            // Arrange
            var userName = "Andrew";
            var expected = "Role: Admin.";

            // Act
            var actual = Program.GetRoleMessage(userName);

            // Assert
            Assert.AreEqual(expected, actual);
        }

        [TestMethod()]
        public void GetRoleMessageForGuestTest()
        {
            // Arrange
            var userName = "Dave";
            var expected = "Role: Guest.";

            // Act
            var actual = Program.GetRoleMessage(userName);

            // Assert
            Assert.AreEqual(expected, actual);
        }
    }
}

Update Console Program with a Condition - Add unit test for Guest role


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;

namespace TramlineFive.Converters
{
    public class TimingConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            string[] timings = (string[])value;
            StringBuilder builder = new StringBuilder();
            foreach (string singleTiming in timings)
            {
                TimeSpan timing;
                if (TimeSpan.TryParse((string)singleTiming, out timing))
                {
                    TimeSpan timeLeft = timing - DateTime.Now.TimeOfDay;
                    builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft.Minutes < 0 ? 0 : timeLeft.Minutes);
                }
            }

            builder.Remove(builder.Length - 2, 2);
            return builder.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;

namespace TramlineFive.Converters
{
    public class TimingConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            string[] timings = (string[])value;
            StringBuilder builder = new StringBuilder();
            foreach (string singleTiming in timings)
            {
                TimeSpan timing;
                if (TimeSpan.TryParse((string)singleTiming, out timing))
                {
                    int timeLeft = (int)(timing - DateTime.Now.TimeOfDay).TotalMinutes;
                    builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft < 0 ? 0 : timeLeft);
                }
            }

            builder.Remove(builder.Length - 2, 2);
            return builder.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}

Fix showing only minutes of the hour insteal of total minutes in virtual table.


using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Hangfire.Mongo.Migration.Steps.Version11
{
    /// <summary>
    /// Create signal capped collection
    /// </summary>
    internal class UseObjectIdForJob : IMongoMigrationStep
    {
        public MongoSchema TargetSchema => MongoSchema.Version11;

        public long Sequence => 0;

        public bool Execute(IMongoDatabase database, MongoStorageOptions storageOptions, IMongoMigrationBag migrationBag)
        {
            var jobsCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".job");
            SetFieldAsObjectId(jobsCollection, "_id");

            var jobQueueCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".jobQueue");
            SetFieldAsObjectId(jobQueueCollection, "JobId");

            return true;
        }

        private static void SetFieldAsObjectId(IMongoCollection<BsonDocument> collection, string fieldName)
        {
            var documents = collection.Find(new BsonDocument()).ToList();

            if(!documents.Any()) return;

            foreach (var doc in documents)
            {
                var jobIdString = doc[fieldName].ToString();
                doc[fieldName] = ObjectId.Parse(jobIdString);
            }
            collection.DeleteMany(new BsonDocument());
            collection.InsertMany(documents);
        }
    }
}

using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Hangfire.Mongo.Migration.Steps.Version11
{
    /// <summary>
    /// Create signal capped collection
    /// </summary>
    internal class UseObjectIdForJob : IMongoMigrationStep
    {
        public MongoSchema TargetSchema => MongoSchema.Version11;

        public long Sequence => 0;

        public bool Execute(IMongoDatabase database, MongoStorageOptions storageOptions, IMongoMigrationBag migrationBag)
        {
            var jobsCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".job");
            SetFieldAsObjectId(jobsCollection, "_id");

            var jobQueueCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".jobQueue");
            SetFieldAsObjectId(jobQueueCollection, "JobId");

            return true;
        }

        private static void SetFieldAsObjectId(IMongoCollection<BsonDocument> collection, string fieldName)
        {
            var filter = Builders<BsonDocument>.Filter.Exists(fieldName);
            var documents = collection.Find(filter).ToList();

            if (!documents.Any()) return;

            foreach (var doc in documents)
            {
                var jobIdString = doc[fieldName].ToString();
                doc[fieldName] = ObjectId.Parse(jobIdString);
            }
            collection.DeleteMany(new BsonDocument());
            collection.InsertMany(documents);
        }
    }
}

Fix broken migration for v11

Fix broken migration for v11


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

namespace HjsonSample
{
  class Program
  {
    static void Main(string[] args)
    {
      var data=HjsonValue.Load("test.hjson").Qo();
      Console.WriteLine(data.Qs("hello"));

      Console.WriteLine("Saving as json...");
      HjsonValue.Save(data, "test.json");

      Console.WriteLine("Saving as hjson...");
      HjsonValue.Save(data, "test2.hjson");

      // edit (preserve whitespace and comments)
      var wdata=(WscJsonObject)HjsonValue.LoadWsc(new StreamReader("test.hjson")).Qo();

      // edit like you normally would
      wdata["hugo"]="value";
      // optionally set order and comments:
      wdata.Order.Insert(2, "hugo");
      wdata.Comments["hugo"]="just another test";

      var sw=new StringWriter();
      HjsonValue.SaveWsc(wdata, sw);
      Console.WriteLine(sw.ToString());
    }
  }
}

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

namespace HjsonSample
{
  class Program
  {
    static void Main(string[] args)
    {
      var data=HjsonValue.Load("test.hjson").Qo();
      Console.WriteLine(data.Qs("hello"));

      Console.WriteLine("Saving as json...");
      HjsonValue.Save(data, "test.json");

      Console.WriteLine("Saving as hjson...");
      HjsonValue.Save(data, "test2.hjson");

      // edit (preserve whitespace and comments)
      var wdata=(WscJsonObject)HjsonValue.Load(new StreamReader("test.hjson"), preserveComments:true).Qo();

      // edit like you normally would
      wdata["hugo"]="value";
      // optionally set order and comments:
      wdata.Order.Insert(2, "hugo");
      wdata.Comments["hugo"]="just another test";

      var sw=new StringWriter();
      HjsonValue.Save(wdata, sw, new HjsonOptions() { KeepWsc = true });
      Console.WriteLine(sw.ToString());
    }
  }
}

Update sample to use Save() and Load()

Update sample to use Save() and Load()

SaveWsc() no longer existed at all, and LoadWsc() was marked obsolete


using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Text;

namespace SolidworksAddinFramework
{
    public static class DisposableExtensions
    {
        public static IDisposable ToCompositeDisposable(this IEnumerable<IDisposable> d)
        {
            return new CompositeDisposable(d);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Text;

namespace SolidworksAddinFramework
{
    public static class DisposableExtensions
    {
        public static IDisposable ToCompositeDisposable(this IEnumerable<IDisposable> d)
        {
            return new CompositeDisposable(d);
        }

        public static void DisposeWith(this IDisposable disposable, CompositeDisposable container)
        {
            container.Add(disposable);
        }
    }
}

Add extension method to add a disposable to a composite disposable


// -----------------------------------------------------------------------
// <copyright file="MenuStyle.cs" company="Steven Kirk">
// Copyright 2015 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------

namespace Perspex.Themes.Default
{
    using Perspex.Controls;
    using Perspex.Controls.Presenters;
    using Perspex.Styling;
    using System.Linq;

    public class MenuStyle : Styles
    {
        public MenuStyle()
        {
            this.AddRange(new[]
            {
                new Style(x => x.OfType<Menu>())
                {
                    Setters = new[]
                    {
                        new Setter(Menu.TemplateProperty, ControlTemplate.Create<Menu>(this.Template)),
                    },
                },
            });
        }

        private Control Template(Menu control)
        {
            return new Border
            {
                [~Border.BackgroundProperty] = control[~Menu.BackgroundProperty],
                [~Border.BorderBrushProperty] = control[~Menu.BorderBrushProperty],
                [~Border.BorderThicknessProperty] = control[~Menu.BorderThicknessProperty],
                [~Border.PaddingProperty] = control[~Menu.PaddingProperty],
                Content = new ItemsPresenter
                {
                    Name = "itemsPresenter",
                    [~ItemsPresenter.ItemsProperty] = control[~Menu.ItemsProperty],
                    [~ItemsPresenter.ItemsPanelProperty] = control[~Menu.ItemsPanelProperty],
                }
            };
        }
    }
}

// -----------------------------------------------------------------------
// <copyright file="MenuStyle.cs" company="Steven Kirk">
// Copyright 2015 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------

namespace Perspex.Themes.Default
{
    using System.Linq;
    using Perspex.Controls;
    using Perspex.Controls.Presenters;
    using Perspex.Input;
    using Perspex.Styling;

    public class MenuStyle : Styles
    {
        public MenuStyle()
        {
            this.AddRange(new[]
            {
                new Style(x => x.OfType<Menu>())
                {
                    Setters = new[]
                    {
                        new Setter(Menu.TemplateProperty, ControlTemplate.Create<Menu>(this.Template)),
                    },
                },
            });
        }

        private Control Template(Menu control)
        {
            return new Border
            {
                [~Border.BackgroundProperty] = control[~Menu.BackgroundProperty],
                [~Border.BorderBrushProperty] = control[~Menu.BorderBrushProperty],
                [~Border.BorderThicknessProperty] = control[~Menu.BorderThicknessProperty],
                [~Border.PaddingProperty] = control[~Menu.PaddingProperty],
                Content = new ItemsPresenter
                {
                    Name = "itemsPresenter",
                    [~ItemsPresenter.ItemsProperty] = control[~Menu.ItemsProperty],
                    [~ItemsPresenter.ItemsPanelProperty] = control[~Menu.ItemsPanelProperty],
                    [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Continue,
                }
            };
        }
    }
}

Use TabNavigation.Continue for top-level menu.


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

namespace Bugsnag.Common
{
    public class BugsnagClient : IClient
    {
        static Uri _uri = new Uri("http://notify.bugsnag.com");
        static Uri _sslUri = new Uri("https://notify.bugsnag.com");
        static JsonSerializerSettings _settings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        };
        static HttpClient _HttpClient { get; } = new HttpClient();

        public void Send(INotice notice) => Send(notice, true);

        public void Send(INotice notice, bool useSSL)
        {
            var _ = SendAsync(notice, useSSL).Result;
        }

        public Task<HttpResponseMessage> SendAsync(INotice notice) => SendAsync(notice, true);

        public Task<HttpResponseMessage> SendAsync(INotice notice, bool useSSL)
        {
            var uri = useSSL ? _sslUri : _uri;
            var json = JsonConvert.SerializeObject(notice, _settings);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            return _HttpClient.PostAsync(uri, content);
        }
    }
}

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

namespace Bugsnag.Common
{
    public class BugsnagClient : IClient
    {
        static Uri _uri = new Uri("http://notify.bugsnag.com");
        static Uri _sslUri = new Uri("https://notify.bugsnag.com");
        static JsonSerializerSettings _settings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        };
        static HttpClient _HttpClient { get; } = new HttpClient();

        public void Send(INotice notice) => Send(notice, true);

        public void Send(INotice notice, bool useSSL) => SendAsync(notice, useSSL).Wait();

        public Task<HttpResponseMessage> SendAsync(INotice notice) => SendAsync(notice, true);

        public Task<HttpResponseMessage> SendAsync(INotice notice, bool useSSL)
        {
            var uri = useSSL ? _sslUri : _uri;
            var json = JsonConvert.SerializeObject(notice, _settings);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            return _HttpClient.PostAsync(uri, content);
        }
    }
}

Use Wait() instead of Result in void overload


using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Linq;

namespace StackExchange.Profiling.Mvc
{
    /// <summary>
    /// Extension methods for configuring MiniProfiler for MVC
    /// </summary>
    public static class MvcExtensions
    {
        /// <summary>
        /// Adds MiniProfiler timings for actions and views
        /// </summary>
        /// <param name="services">The services collection to configure</param>
        public static IServiceCollection AddMiniProfiler(this IServiceCollection services) =>
            services.AddTransient<IConfigureOptions<MvcOptions>, MiniPofilerSetup>()
                    .AddTransient<IConfigureOptions<MvcViewOptions>, MiniPofilerSetup>();
    }

    internal class MiniPofilerSetup : IConfigureOptions<MvcViewOptions>, IConfigureOptions<MvcOptions>
    {
        public void Configure(MvcViewOptions options)
        {
            var copy = options.ViewEngines.ToList();
            options.ViewEngines.Clear();
            foreach (var item in copy)
            {
                options.ViewEngines.Add(new ProfilingViewEngine(item));
            }
        }

        public void Configure(MvcOptions options)
        {
            options.Filters.Add(new ProfilingActionFilter());
        }
    }
}

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Linq;

namespace StackExchange.Profiling.Mvc
{
    /// <summary>
    /// Extension methods for configuring MiniProfiler for MVC
    /// </summary>
    public static class MvcExtensions
    {
        /// <summary>
        /// Adds MiniProfiler timings for actions and views
        /// </summary>
        /// <param name="services">The services collection to configure</param>
        public static IServiceCollection AddMiniProfiler(this IServiceCollection services) =>
            services.AddTransient<IConfigureOptions<MvcOptions>, MiniPofilerSetup>()
                    .AddTransient<IConfigureOptions<MvcViewOptions>, MiniPofilerSetup>();
    }

    internal class MiniPofilerSetup : IConfigureOptions<MvcViewOptions>, IConfigureOptions<MvcOptions>
    {
        public void Configure(MvcViewOptions options)
        {
            for (var i = 0; i < options.ViewEngines.Count; i++)
            {
                options.ViewEngines[i] = new ProfilingViewEngine(options.ViewEngines[i]);
            }
        }

        public void Configure(MvcOptions options)
        {
            options.Filters.Add(new ProfilingActionFilter());
        }
    }
}

Simplify view engine wrapping for MVC Core


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

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.UnitTests.Core.XUnit;
using Xunit;

namespace Microsoft.R.Host.Client.Test {
    [ExcludeFromCodeCoverage]
    public class RStringExtensionsTest {
        [Test]
        [Category.Variable.Explorer]
        public void ConvertCharacterCodesTest() {
            string target = "<U+4E2D><U+570B><U+8A9E>";
            target.ConvertCharacterCodes().Should().Be("中國語");
        }
    }
}

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

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.UnitTests.Core.XUnit;
using Xunit;

namespace Microsoft.R.Host.Client.Test {
    [ExcludeFromCodeCoverage]
    public class RStringExtensionsTest {
        [Test]
        [Category.Variable.Explorer]
        public void ConvertCharacterCodesTest() {
            string target = "<U+4E2D><U+570B><U+8A9E>";
            target.ConvertCharacterCodes().Should().Be("中國語");
        }

        [CompositeTest]
        [InlineData("\t\n", "\"\\t\\n\"")]
        [InlineData("\\t\n", "\"\\\\t\\n\"")]
        [InlineData("\n", "\"\\n\"")]
        [InlineData("\\n", "\"\\\\n\"")]
        public void EscapeCharacterTest(string source, string expectedLiteral) {
            string actualLiteral = source.ToRStringLiteral();
            actualLiteral.Should().Be(expectedLiteral);
            string actualSource = actualLiteral.FromRStringLiteral();
            actualSource.Should().Be(source);
        }
    }
}

Add some tests for string extension.

Add some tests for string extension.


//  --------------------------------------------------------------------------------------------------------------------
//  <copyright file="StrikeMarkdownProvider.cs" company="PicklesDoc">
//  Copyright 2011 Jeffrey Cameron
//  Copyright 2012-present PicklesDoc team and community contributors
//
//
//  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.
//  </copyright>
//  --------------------------------------------------------------------------------------------------------------------

using System;

using Strike;
using Strike.Jint;

namespace PicklesDoc.Pickles
{
    public class StrikeMarkdownProvider : IMarkdownProvider
    {
        private readonly Markdownify markdownify;

        public StrikeMarkdownProvider()
        {
            this.markdownify = new Markdownify(
                new Options { Xhtml = true },
                new RenderMethods());
        }

        public string Transform(string text)
        {
            return this.markdownify.Transform(text);
        }
    }
}

//  --------------------------------------------------------------------------------------------------------------------
//  <copyright file="StrikeMarkdownProvider.cs" company="PicklesDoc">
//  Copyright 2011 Jeffrey Cameron
//  Copyright 2012-present PicklesDoc team and community contributors
//
//
//  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.
//  </copyright>
//  --------------------------------------------------------------------------------------------------------------------

using System;

using Strike;
using Strike.Jint;

namespace PicklesDoc.Pickles
{
    public class StrikeMarkdownProvider : IMarkdownProvider
    {
        private readonly Markdownify markdownify;

        public StrikeMarkdownProvider()
        {
            this.markdownify = new Markdownify(
                new Options { Xhtml = true },
                new RenderMethods());
        }

        public string Transform(string text)
        {
            return this.markdownify.Transform(text).Replace(" ", string.Empty);
        }
    }
}

Add handling for non breaking spaces

Add handling for non breaking spaces


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

namespace MonoTorrent.Client.Tracker
{
    public abstract class TrackerResponseEventArgs : EventArgs
    {
        private bool successful;
        private Tracker tracker;

        /// <summary>
        /// True if the request completed successfully
        /// </summary>
        public bool Successful
        {
            get { return successful; }
            set { successful = value; }
        }

        /// <summary>
        /// The tracker which the request was sent to
        /// </summary>
        public Tracker Tracker
        {
            get { return tracker; }
            protected set { tracker = value; }
        }

        protected TrackerResponseEventArgs(Tracker tracker, bool successful)
        {
            if (tracker == null)
                throw new ArgumentNullException("tracker");

            this.tracker = tracker;
        }
    }
}

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

namespace MonoTorrent.Client.Tracker
{
    public abstract class TrackerResponseEventArgs : EventArgs
    {
        private bool successful;
        private Tracker tracker;

        /// <summary>
        /// True if the request completed successfully
        /// </summary>
        public bool Successful
        {
            get { return successful; }
            set { successful = value; }
        }

        /// <summary>
        /// The tracker which the request was sent to
        /// </summary>
        public Tracker Tracker
        {
            get { return tracker; }
            protected set { tracker = value; }
        }

        protected TrackerResponseEventArgs(Tracker tracker, bool successful)
        {
            if (tracker == null)
                throw new ArgumentNullException("tracker");

            this.successful = successful;
            this.tracker = tracker;
        }
    }
}

Fix bug spotted with Gendarme. Assign the value of 'successful'.

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


using System;
using System.Reflection;
using System.Reflection.Emit;

namespace ILGeneratorExtensions
{
    public static class MethodFlow
    {
        public static void JumpTo(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Jmp, method);

        public static void Call(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Call, method);

        public static void CallVirtual(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Callvirt, method);

        public static void TailCall(this ILGenerator generator, MethodInfo method)
        {
            generator.Emit(OpCodes.Tailcall);
            generator.Emit(OpCodes.Call, method);
        }

        public static void TailCallVirtual(this ILGenerator generator, MethodInfo method)
        {
            generator.Emit(OpCodes.Tailcall);
            generator.Emit(OpCodes.Callvirt, method);
        }

        public static void ConstrainedCallVirtual<T>(this ILGenerator generator, MethodInfo method)
        {
            generator.ConstrainedCallVirtual(typeof (T), method);
        }

        public static void ConstrainedCallVirtual(this ILGenerator generator, Type constrainedType, MethodInfo method)
        {
            generator.Emit(OpCodes.Constrained, constrainedType);
            generator.Emit(OpCodes.Callvirt, method);
        }

        public static void Return(this ILGenerator generator) => generator.Emit(OpCodes.Ret);
    }
}

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace ILGeneratorExtensions
{
    public static class MethodFlow
    {
        public static void JumpTo(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Jmp, method);

        public static void Call(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Call, method);

        public static void CallVirtual(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Callvirt, method);

        public static void TailCall(this ILGenerator generator, MethodInfo method)
        {
            generator.Emit(OpCodes.Tailcall);
            generator.Emit(OpCodes.Call, method);
        }

        public static void TailCallVirtual(this ILGenerator generator, MethodInfo method)
        {
            generator.Emit(OpCodes.Tailcall);
            generator.Emit(OpCodes.Callvirt, method);
        }

        public static void ConstrainedCall<T>(this ILGenerator generator, MethodInfo method)
        {
            generator.ConstrainedCall(typeof (T), method);
        }

        public static void ConstrainedCall(this ILGenerator generator, Type constrainedType, MethodInfo method)
        {
            generator.Emit(OpCodes.Constrained, constrainedType);
            generator.Emit(OpCodes.Callvirt, method);
        }

        public static void ConstrainedTailCall<T>(this ILGenerator generator, MethodInfo method)
        {
            generator.ConstrainedTailCall(typeof(T), method);
        }

        public static void ConstrainedTailCall(this ILGenerator generator, Type constrainedType, MethodInfo method)
        {
            generator.Emit(OpCodes.Constrained, constrainedType);
            generator.Emit(OpCodes.Tailcall);
            generator.Emit(OpCodes.Callvirt, method);
        }

        public static void Return(this ILGenerator generator) => generator.Emit(OpCodes.Ret);
    }
}

Add constrained and tail call methods, and remove virtual from method names, as constrained implies virtual


using UnityEngine;
using Animator = ATP.AnimationPathTools.AnimatorComponent.Animator;

namespace ATP.AnimationPathTools.AudioSourceControllerComponent {

    /// <summary>
    /// Allows controlling <c>AudioSource</c> component from inspector
    /// and with keyboard shortcuts.
    /// </summary>
    // todo add menu option to create component
    public sealed class AudioSourceController : MonoBehaviour {

        [SerializeField]
        private AudioSource audioSource;

        [SerializeField]
        private Animator animator;

        /// <summary>
        /// Reference to audio source component.
        /// </summary>
        public AudioSource AudioSource {
            get { return audioSource; }
            set { audioSource = value; }
        }

        /// <summary>
        /// Reference to animator component.
        /// </summary>
        public Animator Animator {
            get { return animator; }
            set { animator = value; }
        }

        private void Reset() {
            AudioSource = GetComponent<AudioSource>();
            Animator = GetComponent<Animator>();
        }

        private void Update() {
            HandleSpaceShortcut();
        }

        /// <summary>
        /// Handle space shortcut.
        /// </summary>
        private void HandleSpaceShortcut() {
            // If space pressed..
            if (Input.GetKeyDown(KeyCode.Space)) {
                // Pause
                if (AudioSource.isPlaying) {
                    AudioSource.Pause();
                }
                // Play
                else {
                    AudioSource.Play();
                }
            }
        }

    }

}

using UnityEngine;
using Animator = ATP.AnimationPathTools.AnimatorComponent.Animator;

namespace ATP.AnimationPathTools.AudioSourceControllerComponent {

    /// <summary>
    /// Allows controlling <c>AudioSource</c> component from inspector
    /// and with keyboard shortcuts.
    /// </summary>
    // todo add menu option to create component
    public sealed class AudioSourceController : MonoBehaviour {

        [SerializeField]
        private AudioSource audioSource;

        [SerializeField]
        private Animator animator;

        /// <summary>
        /// Reference to audio source component.
        /// </summary>
        public AudioSource AudioSource {
            get { return audioSource; }
            set { audioSource = value; }
        }

        /// <summary>
        /// Reference to animator component.
        /// </summary>
        public Animator Animator {
            get { return animator; }
            set { animator = value; }
        }

        private void Reset() {
            AudioSource = GetComponent<AudioSource>();
            Animator = GetComponent<Animator>();
        }

        private void Update() {
            HandleSpaceShortcut();
        }

        /// <summary>
        /// Handle space shortcut.
        /// </summary>
        private void HandleSpaceShortcut() {
            // Disable shortcut while animator awaits animation start.
            if (Animator.IsInvoking("StartAnimation")) return;

            // If space pressed..
            if (Input.GetKeyDown(KeyCode.Space)) {
                // Pause
                if (AudioSource.isPlaying) {
                    AudioSource.Pause();
                }
                // Play
                else {
                    AudioSource.Play();
                }
            }
        }

    }

}

Disable space shortcut in audio controller


using System;
using Cake.Core;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Client.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;

namespace Cake.DocumentDb.Factories
{
    public class ClientFactory
    {
        private readonly ConnectionSettings settings;
        private readonly ICakeContext context;

        public ClientFactory(ConnectionSettings settings, ICakeContext context)
        {
            this.settings = settings;
            this.context = context;
        }

        public IReliableReadWriteDocumentClient GetClient()
        {
            return new DocumentClient(
                new Uri(settings.Endpoint),
                settings.Key,
                new ConnectionPolicy
                {
                    ConnectionMode = ConnectionMode.Gateway,
                    ConnectionProtocol = Protocol.Https
                }).AsReliable(new FixedInterval(
                    15,
                    TimeSpan.FromSeconds(200)));
        }
    }
}

using System;
using Cake.Core;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Client.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;

namespace Cake.DocumentDb.Factories
{
    public class ClientFactory
    {
        private readonly ConnectionSettings settings;
        private readonly ICakeContext context;

        public ClientFactory(ConnectionSettings settings, ICakeContext context)
        {
            this.settings = settings;
            this.context = context;
        }

        public IReliableReadWriteDocumentClient GetClient()
        {
            return new DocumentClient(
                new Uri(settings.Endpoint),
                settings.Key,
                new ConnectionPolicy
                {
                    ConnectionMode = ConnectionMode.Gateway,
                    ConnectionProtocol = Protocol.Https
                })
                .AsReliable(
                    new FixedInterval(
                        15,
                        TimeSpan.FromSeconds(200)));
        }

        // https://github.com/Azure/azure-cosmos-dotnet-v2/blob/master/samples/documentdb-benchmark/Program.cs
        public IDocumentClient GetClientOptimistedForWrite()
        {
            return new DocumentClient(
                new Uri(settings.Endpoint),
                settings.Key,
                new ConnectionPolicy
                {
                    ConnectionMode = ConnectionMode.Direct,
                    ConnectionProtocol = Protocol.Tcp,
                    RequestTimeout = new TimeSpan(1, 0, 0),
                    MaxConnectionLimit = 1000,
                    RetryOptions = new RetryOptions
                    {
                        MaxRetryAttemptsOnThrottledRequests = 10,
                        MaxRetryWaitTimeInSeconds = 60
                    }
                });
        }
    }
}

Add method to create client optimised for write


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace anime_downloader {

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        String animeFolder;

        public MainWindow() {
            InitializeComponent();

            animeFolder = @"D:\Output\anime downloader";
        }

        private void button_folder_Click(object sender, RoutedEventArgs e) {
            Process.Start(animeFolder);
        }

        private void button_playlist_Click(object sender, RoutedEventArgs e) {
            string[] folders = Directory.GetDirectories(animeFolder)
                .Where(s => !s.EndsWith("torrents") && !s.EndsWith("Grace") && !s.EndsWith("Watched"))
                .ToArray();

            using (StreamWriter file = new StreamWriter(path: animeFolder + @"\playlist.m3u",
                                                        append: false)) {
                foreach(String folder in folders)
                    file.WriteLine(String.Join("\n", Directory.GetFiles(folder)));
            }

            // MessageBox.Show(String.Join(", ", folders));

            // System.Windows.MessageBox.Show(String.Join(", ", ));
            // Directory.GetDirectories(animeFolder);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace anime_downloader {

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        String animeFolder;

        public MainWindow() {
            InitializeComponent();

            animeFolder = @"D:\Output\anime downloader";
        }

        private void button_folder_Click(object sender, RoutedEventArgs e) {
            Process.Start(animeFolder);
        }

        private void button_playlist_Click(object sender, RoutedEventArgs e) {
            string[] videos = Directory.GetDirectories(animeFolder)
                .Where(s => !s.EndsWith("torrents") && !s.EndsWith("Grace") && !s.EndsWith("Watched"))
                .SelectMany(f => Directory.GetFiles(f))
                .ToArray();
            using (StreamWriter file = new StreamWriter(path: animeFolder + @"\playlist.m3u",
                                                        append: false)) {
                foreach(String video in videos)
                    file.WriteLine(video);
            }
        }
    }
}

Make LINQ in playlist function fancier (because why not)


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("Tralus.Shell.WorkflowService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Tralus.Shell.WorkflowService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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)]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
[assembly: AssemblyVersion("1.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("Tralus.Shell.WorkflowService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Tralus.Shell.WorkflowService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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)]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Set AssemblyVersion and AssemblyFileVersion to 1.0.0.0


using Microsoft.TemplateEngine.Abstractions;
using Newtonsoft.Json.Linq;

namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects
{
    public class DerivedSymbol : BaseValueSymbol
    {
        public const string TypeName = "derived";

        public string ValueTransform { get; set; }

        public string ValueSource { get; set; }

        public static ISymbolModel FromJObject(JObject jObject, IParameterSymbolLocalizationModel localization, string defaultOverride)
        {
            DerivedSymbol symbol = FromJObject<DerivedSymbol>(jObject, localization, defaultOverride);

            symbol.ValueTransform = jObject.ToString(nameof(ValueTransform));
            symbol.ValueSource = jObject.ToString(nameof(ValueSource));

            return symbol;
        }
    }
}

using Microsoft.TemplateEngine.Abstractions;
using Newtonsoft.Json.Linq;

namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects
{
    public class DerivedSymbol : BaseValueSymbol
    {
        internal const string TypeName = "derived";

        public string ValueTransform { get; set; }

        public string ValueSource { get; set; }

        public static ISymbolModel FromJObject(JObject jObject, IParameterSymbolLocalizationModel localization, string defaultOverride)
        {
            DerivedSymbol symbol = FromJObject<DerivedSymbol>(jObject, localization, defaultOverride);

            symbol.ValueTransform = jObject.ToString(nameof(ValueTransform));
            symbol.ValueSource = jObject.ToString(nameof(ValueSource));

            return symbol;
        }
    }
}

Change derived symbols type name to an internal const


Task("DevBuild")
    .IsDependentOn("Build")
    .IsDependentOn("Octopus-Packaging")
    .IsDependentOn("Octopus-Deployment");

Task("PrBuild")
    .IsDependentOn("Build")
    .IsDependentOn("Test-NUnit");

Task("KpiBuild")
    .IsDependentOn("Build")
    .IsDependentOn("Test-NUnit")
    .IsDependentOn("Octopus-Packaging")
    .IsDependentOn("Octopus-Deployment");

Task("DevBuild")
    .IsDependentOn("Build")
    .IsDependentOn("Octopus-Packaging")
    .IsDependentOn("Octopus-Deployment");

Task("KpiBuild")
    .IsDependentOn("Build")
    .IsDependentOn("Test-NUnit")
    .IsDependentOn("Upload-Coverage-Report")
    .IsDependentOn("Octopus-Packaging")
    .IsDependentOn("Octopus-Deployment");

Add uploading of coverage reports to Coveralls


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

namespace EntryPoint {

    /// <summary>
    /// Used to mark a method as a Command, in a CliCommands class
    /// </summary>
    [AttributeUsage(
        AttributeTargets.Method,
        AllowMultiple = false,
        Inherited = true)]
    public class CommandAttribute : Attribute {

        /// <summary>
        /// Marks a Method as a Command
        /// </summary>
        /// <param name="Name">The case in-sensitive name for the command, which is invoked to activate it</param>
        public CommandAttribute(string Name) {
            if (Name == null || Name.Length == 0) {
                throw new ArgumentException(
                    "You must give a Command a name");
            }
            this.Name = Name;
        }

        /// <summary>
        /// The case in-sensitive name for the command
        /// </summary>
        internal string Name { get; set; }
    }

}

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

namespace EntryPoint {

    /// <summary>
    /// Used to mark a method as a Command, in a CliCommands class
    /// </summary>
    [AttributeUsage(
        AttributeTargets.Method,
        AllowMultiple = false,
        Inherited = true)]
    public class CommandAttribute : Attribute {

        /// <summary>
        /// Marks a Method as a Command
        /// </summary>
        /// <param name="Name">The case in-sensitive name for the command, which is invoked to activate it</param>
        public CommandAttribute(string Name) {
            if (Name == null || Name.Length == 0) {
                throw new ArgumentException(
                    $"A {nameof(CommandAttribute)} was not given a name");
            }
            this.Name = Name;
        }

        /// <summary>
        /// The case in-sensitive name for the command
        /// </summary>
        internal string Name { get; set; }
    }

}

Clarify error throw when Command has no name string provided


using System;
using System.IO;
using System.Reflection;

namespace AIMP.SDK
{
    internal static class CustomAssemblyResolver
    {
        private static string curPath;
        private static bool isInited;

        /// <summary>
        /// Initializes the specified path.
        /// </summary>
        /// <param name="path">The path.</param>
        public static void Initialize(string path)
        {
            curPath = path +"\\";
            if (!isInited)
            {
                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
                isInited = true;
            }
        }

        /// <summary>
        /// Deinitializes this instance.
        /// </summary>
        public static void Deinitialize()
        {
            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainAssemblyResolve;
            isInited = false;
        }

        private static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
        {
            string projectDir = Path.GetDirectoryName(curPath);
            string shortAssemblyName = args.Name.Substring(0, args.Name.IndexOf(','));
            string fileName = Path.Combine(projectDir, shortAssemblyName + ".dll");
            if (File.Exists(fileName))
            {
                Assembly result = Assembly.LoadFrom(fileName);
                return result;
            }

            return Assembly.GetExecutingAssembly().FullName == args.Name ? Assembly.GetExecutingAssembly() : null;
        }
    }
}

using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace AIMP.SDK
{
    internal static class CustomAssemblyResolver
    {
        private static string curPath;
        private static bool isInited;

        /// <summary>
        /// Initializes the specified path.
        /// </summary>
        /// <param name="path">The path.</param>
        public static void Initialize(string path)
        {
            curPath = path +"\\";
            if (!isInited)
            {
                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
                isInited = true;
            }
        }

        /// <summary>
        /// Deinitializes this instance.
        /// </summary>
        public static void Deinitialize()
        {
            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainAssemblyResolve;
            isInited = false;
        }

        private static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
        {
            string projectDir = Path.GetDirectoryName(curPath);
            string shortAssemblyName = args.Name.Substring(0, args.Name.IndexOf(','));
            string fileName = Path.Combine(projectDir, shortAssemblyName + ".dll");
            if (File.Exists(fileName))
            {
                Assembly result = Assembly.LoadFrom(fileName);
                return result;
            }

            var assemblyPath = Directory.EnumerateFiles(projectDir, shortAssemblyName + ".dll", SearchOption.AllDirectories).FirstOrDefault();
            if (assemblyPath != null)
            {
                return Assembly.LoadFrom(assemblyPath);
            }

            return Assembly.GetExecutingAssembly().FullName == args.Name ? Assembly.GetExecutingAssembly() : null;
        }
    }
}

Fix assembly load for plugins

Fix assembly load for plugins


/*
 * Copyright (c) 2017 Google Inc.
 *
 * 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.
 */

// [START speech_quickstart]

using Google.Cloud.Speech.V1Beta1;
// [END speech_quickstart]
using System;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            // [START speech_quickstart]
            var speech = SpeechClient.Create();
            var response = speech.SyncRecognize(new RecognitionConfig()
            {
                Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
                SampleRate = 16000,
            }, RecognitionAudio.FromFile("audio.raw"));
            foreach (var result in response.Results)
            {
                foreach (var alternative in result.Alternatives)
                {
                    Console.WriteLine(alternative.Transcript);
                }
            }
            // [END speech_quickstart]
        }
    }
}

/*
 * Copyright (c) 2017 Google Inc.
 *
 * 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.
 */

// [START speech_quickstart]

using Google.Cloud.Speech.V1Beta1;
using System;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            var speech = SpeechClient.Create();
            var response = speech.SyncRecognize(new RecognitionConfig()
            {
                Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
                SampleRate = 16000,
            }, RecognitionAudio.FromFile("audio.raw"));
            foreach (var result in response.Results)
            {
                foreach (var alternative in result.Alternatives)
                {
                    Console.WriteLine(alternative.Transcript);
                }
            }
        }
    }
}
// [END speech_quickstart]

Move the speech_quickstart doc tag so that users can copy and paste all the code.


using System;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace SevenDigital.Api.Schema.Playlists.Response
{
	[Serializable]
	public class PlaylistLocation : UserBasedUpdatableItem
	{
		[XmlAttribute("id")]
		public string Id { get; set; }

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

		[XmlArray("links")]
		[XmlArrayItem("link")]
		public List<Link> Links { get; set; }

		[XmlElement("trackCount")]
		public int TrackCount { get; set; }

		[XmlElement("visibility")]
		public PlaylistVisibilityType Visibility { get; set; }

		[XmlElement("status")]
		public PlaylistStatusType Status { get; set; }

		public override string ToString()
		{
			return string.Format("{0}: {1}", Id, Name);
		}
	}
}

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace SevenDigital.Api.Schema.Playlists.Response
{
	[Serializable]
	public class PlaylistLocation : UserBasedUpdatableItem
	{
		[XmlAttribute("id")]
		public string Id { get; set; }

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

		[XmlArray("links")]
		[XmlArrayItem("link")]
		public List<Link> Links { get; set; }

		[XmlElement("trackCount")]
		public int TrackCount { get; set; }

		[XmlElement("visibility")]
		public PlaylistVisibilityType Visibility { get; set; }

		[XmlElement("status")]
		public PlaylistStatusType Status { get; set; }

		[XmlElement("tags")]
		public List<Tag> Tags { get; set; }

		public override string ToString()
		{
			return string.Format("{0}: {1}", Id, Name);
		}
	}
}

Add tags to playlist location

Add tags to playlist location


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BundleConfig.cs" company="KriaSoft LLC">
//   Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace App.Web
{
    using System.Web.Optimization;

    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/js/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/js/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/js/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/js/bootstrap").Include("~/Scripts/bootstrap/*"));

            bundles.Add(new ScriptBundle("~/js/site").Include(
                        "~/Scripts/Site.js"));

            bundles.Add(new StyleBundle("~/css/bootstrap").Include("~/Styles/bootstrap.css"));

            bundles.Add(new StyleBundle("~/css/site").Include("~/Styles/Site.css"));
        }
    }
}

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BundleConfig.cs" company="KriaSoft LLC">
//   Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace App.Web
{
    using System.Web.Optimization;

    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/js/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/js/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/js/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/js/bootstrap").Include("~/Scripts/bootstrap/*.js"));

            bundles.Add(new ScriptBundle("~/js/site").Include(
                        "~/Scripts/Site.js"));

            bundles.Add(new StyleBundle("~/css/bootstrap").Include("~/Styles/bootstrap.css"));

            bundles.Add(new StyleBundle("~/css/site").Include("~/Styles/Site.css"));
        }
    }
}

Fix wildcard path in bootstrap js bundle


using System.Collections.Generic;

namespace Elasticsearch.Net
{
	internal class DynamicBodyFormatter : IJsonFormatter<DynamicBody>
	{
		private static readonly DictionaryFormatter<string, object> DictionaryFormatter =
			new DictionaryFormatter<string, object>();

		public void Serialize(ref JsonWriter writer, DynamicBody value, IJsonFormatterResolver formatterResolver)
		{
			if (value == null)
			{
				writer.WriteNull();
				return;
			}

			writer.WriteBeginObject();
			var formatter = formatterResolver.GetFormatter<object>();
			foreach (var kv in (IDictionary<string, object>)value)
			{
				writer.WritePropertyName(kv.Key);
				formatter.Serialize(ref writer, kv.Value, formatterResolver);
			}
			writer.WriteEndObject();
		}

		public DynamicBody Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
		{
			var dictionary = DictionaryFormatter.Deserialize(ref reader, formatterResolver);
			return DynamicBody.Create(dictionary);
		}
	}
}

using System.Collections.Generic;

namespace Elasticsearch.Net
{
	internal class DynamicBodyFormatter : IJsonFormatter<DynamicBody>
	{
		private static readonly DictionaryFormatter<string, object> DictionaryFormatter =
			new DictionaryFormatter<string, object>();

		public void Serialize(ref JsonWriter writer, DynamicBody value, IJsonFormatterResolver formatterResolver)
		{
			if (value == null)
			{
				writer.WriteNull();
				return;
			}

			writer.WriteBeginObject();
			var formatter = formatterResolver.GetFormatter<object>();
			var count = 0;
			foreach (var kv in (IDictionary<string, object>)value)
			{
				if (count > 0)
					writer.WriteValueSeparator();
				writer.WritePropertyName(kv.Key);
				formatter.Serialize(ref writer, kv.Value, formatterResolver);
				count++;
			}
			writer.WriteEndObject();
		}

		public DynamicBody Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
		{
			var dictionary = DictionaryFormatter.Deserialize(ref reader, formatterResolver);
			return DynamicBody.Create(dictionary);
		}
	}
}

Write value separators when serializing dynamic body


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

namespace Harmony
{
	internal static class PatchTools
	{
		static readonly Dictionary<object, object> objectReferences = new Dictionary<object, object>();

		internal static void RememberObject(object key, object value)
		{
			objectReferences[key] = value;
		}

		internal static MethodInfo GetPatchMethod<T>(Type patchType, string name)
		{
			var attributeType = typeof(T).FullName;
			var method = patchType.GetMethods(AccessTools.all)
				.FirstOrDefault(m => m.GetCustomAttributes(true).Any(a => a.GetType().FullName == attributeType));
			if (method == null)
				method = AccessTools.Method(patchType, name);
			return method;
		}

		[UpgradeToLatestVersion(1)]
		internal static void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler)
		{
			prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix");
			postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix");
			transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler");
		}
	}
}

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

namespace Harmony
{
	internal static class PatchTools
	{
		static readonly Dictionary<object, object> objectReferences = new Dictionary<object, object>();

		internal static void RememberObject(object key, object value)
		{
			objectReferences[key] = value;
		}

		internal static MethodInfo GetPatchMethod<T>(Type patchType, string name)
		{
			var attributeType = typeof(T).FullName;
			var method = patchType.GetMethods(AccessTools.all)
				.FirstOrDefault(m => m.GetCustomAttributes(true).Any(a => a.GetType().FullName == attributeType));
			if (method == null)
			{
				// not-found is common and normal case, don't use AccessTools which will generate not-found warnings
				method = patchType.GetMethod(name, AccessTools.all);
			}
			return method;
		}

		[UpgradeToLatestVersion(1)]
		internal static void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler)
		{
			prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix");
			postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix");
			transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler");
		}
	}
}

Reduce unnecessary logging of missing optional methods


using System;
using Newtonsoft.Json;

namespace Stranne.VasttrafikNET.Models
{
    internal class Token
    {
        private DateTimeOffset _createDate = DateTimeOffset.Now;

        [JsonProperty("Expires_In")]
        public int ExpiresIn { get; set; }

        [JsonProperty("Access_Token")]
        public string AccessToken { get; set; }

        public bool IsValid() => _createDate.AddSeconds(ExpiresIn) < DateTimeOffset.Now;
    }
}

using System;
using Newtonsoft.Json;

namespace Stranne.VasttrafikNET.Models
{
    internal class Token
    {
        private DateTimeOffset _createDate = DateTimeOffset.Now;

        [JsonProperty("Expires_In")]
        public int ExpiresIn { get; set; }

        [JsonProperty("Access_Token")]
        public string AccessToken { get; set; }

        public bool IsValid() => _createDate.AddSeconds(ExpiresIn) > DateTimeOffset.Now;
    }
}

Fix bug with logic for if the token is valid


namespace awesome_bot.Giphy
{
    public static partial class GiphyEndPoints
    {
        public class RandomEndPoint
        {
            private const string RandomPath = "/v1/gifs/random";

            public string Build(string searchText, Rating rating = null)
                => string.Join(string.Empty, Root, RandomPath, "?",
                    $"api_key={ApiKey}&tag={searchText}&rating={rating ?? Rating.G}");
        }
    }
}

namespace awesome_bot.Giphy
{
    public static partial class GiphyEndPoints
    {
        public class RandomEndPoint
        {
            private const string RandomPath = "/v1/gifs/random";

            public string Build(string searchText, Rating rating = null)
                => string.Join(string.Empty, Root, RandomPath, "?",
                    $"api_key={ApiKey}&tag={searchText}&rating={rating ?? Rating.PG13}");
        }
    }
}

Raise rating of gif search

Raise rating of gif search


namespace Aliencube.ReCaptcha.Wrapper.Mvc.Parameters
{
    /// <summary>
    /// This represents the parameters entity to render api.js.
    /// </summary>
    /// <remarks>More details: https://developers.google.com/recaptcha/docs/display#js_param</remarks>
    public partial class ResourceParameters
    {
        /// <summary>
        /// Gets or sets the callback method name on load.
        /// </summary>
        public string OnLoad { get; set; }

        /// <summary>
        /// Gets or sets the render option.
        /// </summary>
        public WidgetRenderType Render { get; set; }

        /// <summary>
        /// Gets or sets the language code to display reCaptcha control.
        /// </summary>
        public WidgetLanguageCode LanguageCode { get; set; }
    }
}

using Newtonsoft.Json;

namespace Aliencube.ReCaptcha.Wrapper.Mvc.Parameters
{
    /// <summary>
    /// This represents the parameters entity to render api.js.
    /// </summary>
    /// <remarks>More details: https://developers.google.com/recaptcha/docs/display#js_param</remarks>
    public partial class ResourceParameters
    {
        /// <summary>
        /// Gets or sets the callback method name on load.
        /// </summary>
        [JsonProperty(PropertyName = "onload")]
        public string OnLoad { get; set; }

        /// <summary>
        /// Gets or sets the render option.
        /// </summary>
        [JsonProperty(PropertyName = "render")]
        public WidgetRenderType Render { get; set; }

        /// <summary>
        /// Gets or sets the language code to display reCaptcha control.
        /// </summary>
        [JsonProperty(PropertyName = "hl")]
        public WidgetLanguageCode LanguageCode { get; set; }
    }
}

Add JsonProperty attribute on each property


using System;
using System.Collections.Generic;
using System.Windows.Media.Imaging;

namespace DesktopWidgets.Helpers
{
    public static class ImageHelper
    {
        public static readonly List<string> SupportedExtensions = new List<string>
        {
            ".bmp",
            ".gif",
            ".ico",
            ".jpg",
            ".jpeg",
            ".png",
            ".tiff"
        };

        public static bool IsSupported(string extension)
        {
            return SupportedExtensions.Contains(extension.ToLower());
        }

        public static BitmapImage LoadBitmapImageFromPath(string path)
        {
            var bmi = new BitmapImage();
            bmi.BeginInit();
            bmi.CacheOption = BitmapCacheOption.OnLoad;
            bmi.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
            bmi.EndInit();
            bmi.Freeze();
            return bmi;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Windows.Media.Imaging;

namespace DesktopWidgets.Helpers
{
    public static class ImageHelper
    {
        // https://msdn.microsoft.com/en-us/library/ee719654(v=VS.85).aspx#wpfc_codecs.
        public static readonly List<string> SupportedExtensions = new List<string>
        {
            ".bmp",
            ".gif",
            ".ico",
            ".jpg",
            ".jpeg",
            ".png",
            ".tiff",
            ".wmp",
            ".dds"
        };

        public static bool IsSupported(string extension)
        {
            return SupportedExtensions.Contains(extension.ToLower());
        }

        public static BitmapImage LoadBitmapImageFromPath(string path)
        {
            var bmi = new BitmapImage();
            bmi.BeginInit();
            bmi.CacheOption = BitmapCacheOption.OnLoad;
            bmi.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
            bmi.EndInit();
            bmi.Freeze();
            return bmi;
        }
    }
}

Add more supported image extensions

Add more supported image extensions