// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

using AutomaticTypeMapper;
using EOLib.IO.Pub;

namespace EOLib.IO.Repositories
{
    [MappedType(BaseType = typeof(IPubFileRepository), IsSingleton = true)]
    [MappedType(BaseType = typeof(IEIFFileRepository), IsSingleton = true)]
    [MappedType(BaseType = typeof(IEIFFileProvider), IsSingleton = true)]
    [MappedType(BaseType = typeof(IENFFileRepository), IsSingleton = true)]
    [MappedType(BaseType = typeof(IENFFileProvider), IsSingleton = true)]
    [MappedType(BaseType = typeof(IESFFileRepository), IsSingleton = true)]
    [MappedType(BaseType = typeof(IESFFileProvider), IsSingleton = true)]
    [MappedType(BaseType = typeof(IECFFileRepository), IsSingleton = true)]
    [MappedType(BaseType = typeof(IECFFileProvider), IsSingleton = true)]
    public class PubFileRepository : IPubFileRepository, IPubFileProvider
    {
        public IPubFile<EIFRecord> EIFFile { get; set; }

        public IPubFile<ENFRecord> ENFFile { get; set; }

        public IPubFile<ESFRecord> ESFFile { get; set; }

        public IPubFile<ECFRecord> ECFFile { get; set; }
    }
}

// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

using AutomaticTypeMapper;
using EOLib.IO.Pub;

namespace EOLib.IO.Repositories
{
    [MappedType(BaseType = typeof(IPubFileRepository), IsSingleton = true)]
    [MappedType(BaseType = typeof(IPubFileProvider), IsSingleton = true)]
    [MappedType(BaseType = typeof(IEIFFileRepository), IsSingleton = true)]
    [MappedType(BaseType = typeof(IEIFFileProvider), IsSingleton = true)]
    [MappedType(BaseType = typeof(IENFFileRepository), IsSingleton = true)]
    [MappedType(BaseType = typeof(IENFFileProvider), IsSingleton = true)]
    [MappedType(BaseType = typeof(IESFFileRepository), IsSingleton = true)]
    [MappedType(BaseType = typeof(IESFFileProvider), IsSingleton = true)]
    [MappedType(BaseType = typeof(IECFFileRepository), IsSingleton = true)]
    [MappedType(BaseType = typeof(IECFFileProvider), IsSingleton = true)]
    public class PubFileRepository : IPubFileRepository, IPubFileProvider
    {
        public IPubFile<EIFRecord> EIFFile { get; set; }

        public IPubFile<ENFRecord> ENFFile { get; set; }

        public IPubFile<ESFRecord> ESFFile { get; set; }

        public IPubFile<ECFRecord> ECFFile { get; set; }
    }
}

Fix type mapping for IPubFileProvider

Fix type mapping for IPubFileProvider


using System.Collections.Generic;
using System.Linq;
using Wox.Plugin.BrowserBookmark.Commands;
using Wox.Plugin.SharedCommands;

namespace Wox.Plugin.BrowserBookmark
{
    public class Main : IPlugin
    {
        private PluginInitContext context;

        private List<Bookmark> cachedBookmarks = new List<Bookmark>();

        public void Init(PluginInitContext context)
        {
            this.context = context;

            cachedBookmarks = Bookmarks.LoadAllBookmarks();
        }

        public List<Result> Query(Query query)
        {
            string param = query.GetAllRemainingParameter().TrimStart();

            // Should top results be returned? (true if no search parameters have been passed)
            var topResults = string.IsNullOrEmpty(param);

            var returnList = cachedBookmarks;

            if (!topResults)
            {
                // Since we mixed chrome and firefox bookmarks, we should order them again
                returnList = cachedBookmarks.Where(o => Bookmarks.MatchProgram(o, param)).ToList();
                returnList = returnList.OrderByDescending(o => o.Score).ToList();
            }

            return returnList.Select(c => new Result()
            {
                Title = c.Name,
                SubTitle = "Bookmark: " + c.Url,
                IcoPath = @"Images\bookmark.png",
                Score = 5,
                Action = (e) =>
                {
                    context.API.HideApp();
                    c.Url.NewBrowserWindow("");
                    return true;
                }
            }).ToList();
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using Wox.Plugin.BrowserBookmark.Commands;
using Wox.Plugin.SharedCommands;

namespace Wox.Plugin.BrowserBookmark
{
    public class Main : IPlugin, IReloadable
    {
        private PluginInitContext context;

        private List<Bookmark> cachedBookmarks = new List<Bookmark>();

        public void Init(PluginInitContext context)
        {
            this.context = context;

            cachedBookmarks = Bookmarks.LoadAllBookmarks();
        }

        public List<Result> Query(Query query)
        {
            string param = query.GetAllRemainingParameter().TrimStart();

            // Should top results be returned? (true if no search parameters have been passed)
            var topResults = string.IsNullOrEmpty(param);

            var returnList = cachedBookmarks;

            if (!topResults)
            {
                // Since we mixed chrome and firefox bookmarks, we should order them again
                returnList = cachedBookmarks.Where(o => Bookmarks.MatchProgram(o, param)).ToList();
                returnList = returnList.OrderByDescending(o => o.Score).ToList();
            }

            return returnList.Select(c => new Result()
            {
                Title = c.Name,
                SubTitle = "Bookmark: " + c.Url,
                IcoPath = @"Images\bookmark.png",
                Score = 5,
                Action = (e) =>
                {
                    context.API.HideApp();
                    c.Url.NewBrowserWindow("");
                    return true;
                }
            }).ToList();
        }

        public void ReloadData()
        {
            cachedBookmarks.Clear();

            cachedBookmarks = Bookmarks.LoadAllBookmarks();
        }
    }
}

Add IReloadable interface and method

Add IReloadable interface and method


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

[assembly: AssemblyTitle("Skylight")]
[assembly: AssemblyDescription("An API by TakoMan02 for Everybody Edits")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("TakoMan02")]
[assembly: AssemblyProduct("Skylight")]
[assembly: AssemblyCopyright("Copyright © TakoMan02 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("Skylight")]
[assembly: ComVisible(false)]
[assembly: Guid("a460c245-2753-4861-ae17-751db86fbae2")]

//

//

[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("0.0.5.0")]

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

[assembly: AssemblyTitle("Skylight")]
[assembly: AssemblyDescription("An API by TakoMan02 for Everybody Edits")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("TakoMan02")]
[assembly: AssemblyProduct("Skylight")]
[assembly: AssemblyCopyright("Copyright © TakoMan02 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("Skylight")]
[assembly: ComVisible(false)]
[assembly: Guid("a460c245-2753-4861-ae17-751db86fbae2")]

//

//

[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("0.5.1.0")]

Change version number to v0.5.1.0

Change version number to v0.5.1.0


using System;

namespace SQLite.Net
{
    public class BlobSerializerDelegate : IBlobSerializer
    {
        public delegate byte[] SerializeDelegate(object obj);
        public delegate bool CanSerializeDelegate(Type type);
        public delegate object DeserializeDelegate(byte[] data, Type type);

        private readonly SerializeDelegate serializeDelegate;
        private readonly DeserializeDelegate deserializeDelegate;
        private readonly CanSerializeDelegate canDeserializeDelegate;

        public BlobSerializerDelegate (SerializeDelegate serializeDelegate,
            DeserializeDelegate deserializeDelegate,
            CanSerializeDelegate canDeserializeDelegate)
        {
            this.serializeDelegate = serializeDelegate;
            this.deserializeDelegate = deserializeDelegate;
            this.canDeserializeDelegate = canDeserializeDelegate;
        }

        #region IBlobSerializer implementation

        public byte[] Serialize<T>(T obj)
        {
            return this.serializeDelegate (obj);
        }

        public object Deserialize(byte[] data, Type type)
        {
            return this.deserializeDelegate (data, type);
        }

        public bool CanDeserialize(Type type)
        {
            return this.canDeserializeDelegate (type);
        }

        #endregion
    }
}

using System;

namespace SQLite.Net
{
    public class BlobSerializerDelegate : IBlobSerializer
    {
        public delegate byte[] SerializeDelegate(object obj);

        public delegate bool CanSerializeDelegate(Type type);

        public delegate object DeserializeDelegate(byte[] data, Type type);

        private readonly SerializeDelegate _serializeDelegate;
        private readonly DeserializeDelegate _deserializeDelegate;
        private readonly CanSerializeDelegate _canDeserializeDelegate;

        public BlobSerializerDelegate(SerializeDelegate serializeDelegate,
            DeserializeDelegate deserializeDelegate,
            CanSerializeDelegate canDeserializeDelegate)
        {
            _serializeDelegate = serializeDelegate;
            _deserializeDelegate = deserializeDelegate;
            _canDeserializeDelegate = canDeserializeDelegate;
        }

        #region IBlobSerializer implementation

        public byte[] Serialize<T>(T obj)
        {
            return _serializeDelegate(obj);
        }

        public object Deserialize(byte[] data, Type type)
        {
            return _deserializeDelegate(data, type);
        }

        public bool CanDeserialize(Type type)
        {
            return _canDeserializeDelegate(type);
        }

        #endregion
    }
}

core/BlobSerializer: Rename fields name pattern to match rest of code


using Cake.Core.IO;
using Ensconce.Update;
using System.IO;

namespace Ensconce.Cake
{
    public static class EnsconceFileUpdateExtensions
    {
        public static void TextSubstitute(this IFile file, FilePath fixedStructureFile)
        {
            var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath);
            Update.ProcessFiles.UpdateFile(new FileInfo(file.Path.FullPath), tagDictionary);
        }

        public static void TextSubstitute(this IDirectory directory, FilePath fixedStructureFile)
        {
            directory.TextSubstitute("*.*", fixedStructureFile);
        }

        public static void TextSubstitute(this IDirectory directory, string filter, FilePath fixedStructureFile)
        {
            var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath);
            Update.ProcessFiles.UpdateFiles(directory.Path.FullPath, filter, tagDictionary);
        }
    }
}

using Cake.Core.IO;
using Ensconce.Update;
using System.IO;

namespace Ensconce.Cake
{
    public static class EnsconceFileUpdateExtensions
    {
        public static void TextSubstitute(this IFile file, FilePath fixedStructureFile)
        {
            file.Path.TextSubstitute(fixedStructureFile);
        }

        public static void TextSubstitute(this IDirectory directory, FilePath fixedStructureFile)
        {
            directory.Path.TextSubstitute(fixedStructureFile);
        }

        public static void TextSubstitute(this IDirectory directory, string filter, FilePath fixedStructureFile)
        {
            directory.Path.TextSubstitute(filter, fixedStructureFile);
        }

        public static void TextSubstitute(this FilePath file, FilePath fixedStructureFile)
        {
            var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath);
            Update.ProcessFiles.UpdateFile(new FileInfo(file.FullPath), tagDictionary);
        }

        public static void TextSubstitute(this DirectoryPath directory, FilePath fixedStructureFile)
        {
            directory.TextSubstitute("*.*", fixedStructureFile);
        }

        public static void TextSubstitute(this DirectoryPath directory, string filter, FilePath fixedStructureFile)
        {
            var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath);
            Update.ProcessFiles.UpdateFiles(directory.FullPath, filter, tagDictionary);
        }
    }
}

Handle update based on a path object as well as the directory/file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using BForms.Models;
using BForms.Mvc;

namespace BForms.Docs
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //register BForms validation provider
            ModelValidatorProviders.Providers.Add(new BsModelValidatorProvider());

            BForms.Utilities.BsResourceManager.Register(Resources.Resource.ResourceManager);
            //BForms.Utilities.BsUIManager.Theme(BsTheme.Black);

            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");

#if !DEBUG
            BForms.Utilities.BsConfigurationManager.Release(true);
#endif

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using BForms.Models;
using BForms.Mvc;

namespace BForms.Docs
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //register BForms validation provider
            ModelValidatorProviders.Providers.Add(new BsModelValidatorProvider());

            BForms.Utilities.BsResourceManager.Register(Resources.Resource.ResourceManager);
            //BForms.Utilities.BsUIManager.Theme(BsTheme.Black);

#if !DEBUG
            BForms.Utilities.BsConfigurationManager.Release(true);
#endif

        }
    }
}

Revert "fixed mandatory field error message"

This reverts commit fe294ec07e8cf85ecea8f317b7aa2ee169bd2120.


namespace ServiceStack.Common.Web
{
    public static class HttpHeaders
    {
        public const string XParamOverridePrefix = "X-Param-Override-";

        public const string XHttpMethodOverride = "X-Http-Method-Override";

        public const string XUserAuthId = "X-UAId";

        public const string XForwardedFor = "X-Forwarded-For";

        public const string XRealIp = "X-Real-IP";

        public const string Referer = "Referer";

        public const string CacheControl = "Cache-Control";

        public const string IfModifiedSince = "If-Modified-Since";

        public const string LastModified = "Last-Modified";

        public const string Accept = "Accept";

        public const string AcceptEncoding = "Accept-Encoding";

        public const string ContentType = "Content-Type";

        public const string ContentEncoding = "Content-Encoding";

        public const string ContentLength = "Content-Length";

        public const string ContentDisposition = "Content-Disposition";

        public const string Location = "Location";

        public const string SetCookie = "Set-Cookie";

        public const string ETag = "ETag";

        public const string Authorization = "Authorization";

        public const string WwwAuthenticate = "WWW-Authenticate";

        public const string AllowOrigin = "Access-Control-Allow-Origin";

        public const string AllowMethods = "Access-Control-Allow-Methods";

        public const string AllowHeaders = "Access-Control-Allow-Headers";

        public const string AllowCredentials = "Access-Control-Allow-Credentials";
    }
}

namespace ServiceStack.Common.Web
{
    public static class HttpHeaders
    {
        public const string XParamOverridePrefix = "X-Param-Override-";

        public const string XHttpMethodOverride = "X-Http-Method-Override";

        public const string XUserAuthId = "X-UAId";

        public const string XForwardedFor = "X-Forwarded-For";

        public const string XRealIp = "X-Real-IP";

        public const string Referer = "Referer";

        public const string CacheControl = "Cache-Control";

        public const string IfModifiedSince = "If-Modified-Since";

        public const string IfNoneMatch = "If-None-Match";

        public const string LastModified = "Last-Modified";

        public const string Accept = "Accept";

        public const string AcceptEncoding = "Accept-Encoding";

        public const string ContentType = "Content-Type";

        public const string ContentEncoding = "Content-Encoding";

        public const string ContentLength = "Content-Length";

        public const string ContentDisposition = "Content-Disposition";

        public const string Location = "Location";

        public const string SetCookie = "Set-Cookie";

        public const string ETag = "ETag";

        public const string Authorization = "Authorization";

        public const string WwwAuthenticate = "WWW-Authenticate";

        public const string AllowOrigin = "Access-Control-Allow-Origin";

        public const string AllowMethods = "Access-Control-Allow-Methods";

        public const string AllowHeaders = "Access-Control-Allow-Headers";

        public const string AllowCredentials = "Access-Control-Allow-Credentials";
    }
}

Add a const string field for the If-None-Match HTTP header


using Nito.AsyncEx;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.Extensions.Caching.Memory
{
	public static class MemoryExtensions
	{
		private static Dictionary<object, AsyncLock> AsyncLocks { get; } = new Dictionary<object, AsyncLock>();
		private static object AsyncLocksLock { get; } = new object();

		public static async Task<TItem> AtomicGetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory)
		{
			if (cache.TryGetValue(key, out TItem value))
			{
				return value;
			}

			AsyncLock asyncLock;
			lock (AsyncLocksLock)
			{
				if (!AsyncLocks.TryGetValue(key, out asyncLock))
				{
					asyncLock = new AsyncLock();
					AsyncLocks.Add(key, asyncLock);
				}
			}

			using (await asyncLock.LockAsync().ConfigureAwait(false))
			{
				if (!cache.TryGetValue(key, out value))
				{
					value = await cache.GetOrCreateAsync(key, factory).ConfigureAwait(false);
				}

				return value;
			}
		}
	}
}

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

namespace Microsoft.Extensions.Caching.Memory
{
	public static class MemoryExtensions
	{
		private static Dictionary<object, AsyncLock> AsyncLocks { get; } = new Dictionary<object, AsyncLock>();

		private static object AsyncLocksLock { get; } = new object();

		public static async Task<TItem> AtomicGetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory)
		{
			if (cache.TryGetValue(key, out TItem value))
			{
				return value;
			}

			AsyncLock asyncLock;
			lock (AsyncLocksLock)
			{
				// Cleanup the evicted asynclocks first.
				foreach (var toRemove in AsyncLocks.Keys.Where(x => !cache.TryGetValue(x, out _)).ToList())
				{
					AsyncLocks.Remove(toRemove);
				}

				if (!AsyncLocks.TryGetValue(key, out asyncLock))
				{
					asyncLock = new AsyncLock();
					AsyncLocks.Add(key, asyncLock);
				}
			}

			using (await asyncLock.LockAsync().ConfigureAwait(false))
			{
				if (!cache.TryGetValue(key, out value))
				{
					value = await cache.GetOrCreateAsync(key, factory).ConfigureAwait(false);
				}

				return value;
			}
		}
	}
}

Make sure to clean my dic.

Make sure to clean my dic.


using System.Reflection;

[assembly: AssemblyTitle("Autofac.Tests.Integration.Web")]
[assembly: AssemblyDescription("")]

Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.


using System;

namespace XeroApi.Model
{
    public class Journal : EndpointModelBase
    {

        [ItemId]
        public Guid JournalID { get; set; }

        public DateTime JournalDate { get; set; }

        public long JournalNumber { get; set; }

        [ItemUpdatedDate]
        public DateTime CreatedDateUTC { get; set; }

        public string Reference { get; set; }

        public JournalLines JournalLines { get; set; }

        public override string ToString()
        {
            return string.Format("Journal:{0}", JournalNumber);
        }
    }

    public class Journals : ModelList<Journal>
    {
    }
}

using System;

namespace XeroApi.Model
{
    public class Journal : EndpointModelBase
    {

        [ItemId]
        public Guid JournalID { get; set; }

        public DateTime JournalDate { get; set; }

        public long JournalNumber { get; set; }

        [ItemUpdatedDate]
        public DateTime CreatedDateUTC { get; set; }

        public string Reference { get; set; }

        public JournalLines JournalLines { get; set; }

        public Guid SourceID { get; set; }

        public string SourceType { get; set; }

        public override string ToString()
        {
            return string.Format("Journal:{0}", JournalNumber);
        }
    }

    public class Journals : ModelList<Journal>
    {
    }
}

Add SourceID and SourceType to journal

Add SourceID and SourceType to journal


using System;
using System.Configuration;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;

namespace TrackableData.MySql.Tests
{
    public class Database : IDisposable
    {
        public Database()
        {
            var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;

            // create TestDb if not exist

            var cstrForMaster = "";
            {
                var connectionBuilder = new SqlConnectionStringBuilder(cstr);
                connectionBuilder.InitialCatalog = "sys";
                cstrForMaster = connectionBuilder.ToString();
            }

            using (var conn = new MySqlConnection(cstrForMaster))
            {
                conn.Open();

                using (var cmd = new MySqlCommand())
                {
                    cmd.CommandText = string.Format(@"
                        DROP DATABASE IF EXISTS {0};
                        CREATE DATABASE {0};
                    ", new SqlConnectionStringBuilder(cstr).InitialCatalog);
                    cmd.Connection = conn;

                    var result = cmd.ExecuteScalar();
                }
            }
        }

        public MySqlConnection Connection
        {
            get
            {
                var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;
                var connection = new MySqlConnection(cstr);
                connection.Open();
                return connection;
            }
        }

        public void Dispose()
        {
        }
    }
}

using System;
using System.Configuration;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;

namespace TrackableData.MySql.Tests
{
    public class Database : IDisposable
    {
        public Database()
        {
            var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;

            // create TestDb if not exist

            var cstrForMaster = "";
            {
                var connectionBuilder = new SqlConnectionStringBuilder(cstr);
                connectionBuilder.InitialCatalog = "";
                cstrForMaster = connectionBuilder.ToString();
            }

            using (var conn = new MySqlConnection(cstrForMaster))
            {
                conn.Open();

                using (var cmd = new MySqlCommand())
                {
                    cmd.CommandText = string.Format(@"
                        DROP DATABASE IF EXISTS {0};
                        CREATE DATABASE {0};
                    ", new SqlConnectionStringBuilder(cstr).InitialCatalog);
                    cmd.Connection = conn;

                    var result = cmd.ExecuteScalar();
                }
            }
        }

        public MySqlConnection Connection
        {
            get
            {
                var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;
                var connection = new MySqlConnection(cstr);
                connection.Open();
                return connection;
            }
        }

        public void Dispose()
        {
        }
    }
}

Fix bug to find non-existent sys db in mysql


namespace Certify.Models.Config
{
    public class ActionResult
    {
        public ActionResult() { }
        public ActionResult(string msg, bool isSuccess)
        {
            Message = msg;
            IsSuccess = isSuccess;
        }

        public bool IsSuccess { get; set; }
        public string Message { get; set; }

        /// <summary>
        /// Optional field to hold related information such as required info or error details
        /// </summary>
        public object Result { get; set; }
    }

    public class ActionResult<T> : ActionResult
    {
        public new T Result;

        public ActionResult() { }
        public ActionResult(string msg, bool isSuccess)
        {
            Message = msg;
            IsSuccess = isSuccess;
        }
        public ActionResult(string msg, bool isSuccess, T result)
        {
            Message = msg;
            IsSuccess = isSuccess;
            Result = result;
        }

    }
}

namespace Certify.Models.Config
{
    public class ActionResult
    {
        public ActionResult() { }
        public ActionResult(string msg, bool isSuccess)
        {
            Message = msg;
            IsSuccess = isSuccess;
        }

        public bool IsSuccess { get; set; }
        public bool IsWarning { get; set; }
        public string Message { get; set; }

        /// <summary>
        /// Optional field to hold related information such as required info or error details
        /// </summary>
        public object Result { get; set; }
    }

    public class ActionResult<T> : ActionResult
    {
        public new T Result;

        public ActionResult() { }
        public ActionResult(string msg, bool isSuccess)
        {
            Message = msg;
            IsSuccess = isSuccess;
        }
        public ActionResult(string msg, bool isSuccess, T result)
        {
            Message = msg;
            IsSuccess = isSuccess;
            Result = result;
        }

    }
}

Add IsWarning to action result

Add IsWarning to action result


using System.Threading.Tasks;
using Cake.Core;
using Cake.Core.Diagnostics;
using Cake.Frosting;

public static class Program
{
    public static int Main(string[] args)
    {
        return new CakeHost()
            .UseContext<BuildContext>()
            .UseWorkingDirectory("..")
            .Run(args);
    }
}

public class BuildContext : FrostingContext
{
    public bool Delay { get; set; }

    public BuildContext(ICakeContext context)
        : base(context)
    {
        Delay = context.Arguments.HasArgument("delay");
    }
}

[TaskName("Hello")]
public sealed class HelloTask : FrostingTask<BuildContext>
{
    public override void Run(BuildContext context)
    {
        context.Log.Information("Hello");
    }
}

[TaskName("World")]
[IsDependentOn(typeof(HelloTask))]
public sealed class WorldTask : AsyncFrostingTask<BuildContext>
{
    // Tasks can be asynchronous
    public override async Task RunAsync(BuildContext context)
    {
        if (context.Delay)
        {
            context.Log.Information("Waiting...");
            await Task.Delay(1500);
        }

        context.Log.Information("World");
    }
}

[TaskName("Default")]
[IsDependentOn(typeof(WorldTask))]
public class DefaultTask : FrostingTask
{
}

using System.Threading.Tasks;
using Cake.Core;
using Cake.Core.Diagnostics;
using Cake.Frosting;

public static class Program
{
    public static int Main(string[] args)
    {
        return new CakeHost()
            .UseContext<BuildContext>()
            .Run(args);
    }
}

public class BuildContext : FrostingContext
{
    public bool Delay { get; set; }

    public BuildContext(ICakeContext context)
        : base(context)
    {
        Delay = context.Arguments.HasArgument("delay");
    }
}

[TaskName("Hello")]
public sealed class HelloTask : FrostingTask<BuildContext>
{
    public override void Run(BuildContext context)
    {
        context.Log.Information("Hello");
    }
}

[TaskName("World")]
[IsDependentOn(typeof(HelloTask))]
public sealed class WorldTask : AsyncFrostingTask<BuildContext>
{
    // Tasks can be asynchronous
    public override async Task RunAsync(BuildContext context)
    {
        if (context.Delay)
        {
            context.Log.Information("Waiting...");
            await Task.Delay(1500);
        }

        context.Log.Information("World");
    }
}

[TaskName("Default")]
[IsDependentOn(typeof(WorldTask))]
public class DefaultTask : FrostingTask
{
}

Remove use of UseWorkingDirectory in default template


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

public enum Upgrade {

	NONE, ROBOT, NIGHTVISION, UNICORN, ZOMBIE, REDHAT, BEEARD

}

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

public enum Upgrade {

	NONE, ROBOT, NIGHTVISION, UNICORN, ZOMBIE, REDHAT, BEEARD, BEEBALL, SCHOOLBUZZ, BUZZFEED, BEACH, GUM, VISOR

}

Add other upgrades to enum

Add other upgrades to enum


using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Newtonsoft.Json.Serialization;

namespace Swashbuckle.Swagger
{
    public static class JsonPropertyExtensions
    {
        public static bool IsRequired(this JsonProperty jsonProperty)
        {
            return jsonProperty.HasAttribute<RequiredAttribute>();
        }

        public static bool IsObsolete(this JsonProperty jsonProperty)
        {
            return jsonProperty.HasAttribute<ObsoleteAttribute>();
        }

        public static bool HasAttribute<T>(this JsonProperty jsonProperty)
        {
            var propInfo = jsonProperty.PropertyInfo();
            return propInfo != null && Attribute.IsDefined(propInfo, typeof (T));
        }

        public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty)
        {
            if(jsonProperty.UnderlyingName == null) return null;
            return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType);
        }
    }
}

using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Swashbuckle.Swagger
{
    public static class JsonPropertyExtensions
    {
        public static bool IsRequired(this JsonProperty jsonProperty)
        {
            return jsonProperty.HasAttribute<RequiredAttribute>() || jsonProperty.Required == Required.Always;
        }

        public static bool IsObsolete(this JsonProperty jsonProperty)
        {
            return jsonProperty.HasAttribute<ObsoleteAttribute>();
        }

        public static bool HasAttribute<T>(this JsonProperty jsonProperty)
        {
            var propInfo = jsonProperty.PropertyInfo();
            return propInfo != null && Attribute.IsDefined(propInfo, typeof (T));
        }

        public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty)
        {
            if(jsonProperty.UnderlyingName == null) return null;
            return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType);
        }
    }
}

Fix to also check the Required property of the JsonProperty when determining if a model property is required or optional.


using Microsoft.Extensions.Configuration;
using Xunit;

namespace RedditSharpTests
{
    public class AuthenticatedTestsFixture
    {
        public IConfigurationRoot Config { get; private set; }
        public string AccessToken { get; private set; }
        public RedditSharp.BotWebAgent WebAgent { get; set; }
        public string TestUserName { get; private set; }
        public AuthenticatedTestsFixture()
        {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.AddJsonFile("private.config")
            .AddEnvironmentVariables();
            Config = builder.Build();
            WebAgent = new RedditSharp.BotWebAgent(Config["TestUserName"], Config["TestUserPassword"], Config["RedditClientID"], Config["RedditClientSecret"], Config["RedditRedirectURI"]);
            AccessToken = WebAgent.AccessToken;
            TestUserName = Config["TestUserName"];
        }
    }
    [CollectionDefinition("AuthenticatedTests")]
    public class AuthenticatedTestsCollection : ICollectionFixture<AuthenticatedTestsFixture>
    {
        // This class has no code, and is never created. Its purpose is simply
        // to be the place to apply [CollectionDefinition] and all the
        // ICollectionFixture<> interfaces.
    }
}

using Microsoft.Extensions.Configuration;
using Xunit;

namespace RedditSharpTests
{
    public class AuthenticatedTestsFixture
    {
        public IConfigurationRoot Config { get; private set; }
        public string AccessToken { get; private set; }
        public RedditSharp.BotWebAgent WebAgent { get; set; }
        public string TestUserName { get; private set; }
        public AuthenticatedTestsFixture()
        {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.AddJsonFile("private.config",true)
            .AddEnvironmentVariables();
            Config = builder.Build();
            WebAgent = new RedditSharp.BotWebAgent(Config["TestUserName"], Config["TestUserPassword"], Config["RedditClientID"], Config["RedditClientSecret"], Config["RedditRedirectURI"]);
            AccessToken = WebAgent.AccessToken;
            TestUserName = Config["TestUserName"];
        }
    }
    [CollectionDefinition("AuthenticatedTests")]
    public class AuthenticatedTestsCollection : ICollectionFixture<AuthenticatedTestsFixture>
    {
        // This class has no code, and is never created. Its purpose is simply
        // to be the place to apply [CollectionDefinition] and all the
        // ICollectionFixture<> interfaces.
    }
}

Set private.config to optional to fix unit tests on build server


using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;

namespace LiteNetLibManager
{
    public struct ServerTimeMessage : INetSerializable
    {
        public int serverUnixTime;
        public float serverTime;

        public void Deserialize(NetDataReader reader)
        {
            serverUnixTime = reader.GetInt();
            serverTime = reader.GetFloat();
        }

        public void Serialize(NetDataWriter writer)
        {
            writer.Put(serverUnixTime);
            writer.Put(serverTime);
        }
    }
}

using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;

namespace LiteNetLibManager
{
    public struct ServerTimeMessage : INetSerializable
    {
        public int serverUnixTime;

        public void Deserialize(NetDataReader reader)
        {
            serverUnixTime = reader.GetPackedInt();
        }

        public void Serialize(NetDataWriter writer)
        {
            writer.PutPackedInt(serverUnixTime);
        }
    }
}

Reduce packet size, remove bloated time codes


// Needed for Workaround

using System;
using System.Threading;
using Theraot.Collections.ThreadSafe;

namespace Theraot.Threading
{
    public static partial class GCMonitor
    {
        private static class Internal
        {
            private static readonly WeakDelegateCollection _collectedEventHandlers;
            private static readonly WaitCallback work;

            static Internal()
            {
                work = _ => RaiseCollected();
                _collectedEventHandlers = new WeakDelegateCollection(false, false, INT_MaxProbingHint);
            }

            public static WeakDelegateCollection CollectedEventHandlers
            {
                get
                {
                    return _collectedEventHandlers;
                }
            }

            public static void Invoke()
            {
                ThreadPool.QueueUserWorkItem(work);
            }

            private static void RaiseCollected()
            {
                var check = Thread.VolatileRead(ref _status);
                if (check == INT_StatusReady)
                {
                    try
                    {
                        _collectedEventHandlers.RemoveDeadItems();
                        _collectedEventHandlers.Invoke(null, new EventArgs());
                    }
                    catch (Exception exception)
                    {
                        // Pokemon
                        GC.KeepAlive(exception);
                    }
                    Thread.VolatileWrite(ref _status, INT_StatusReady);
                }
            }
        }
    }
}

// Needed for Workaround

using System;
using System.Threading;
using Theraot.Collections.ThreadSafe;

namespace Theraot.Threading
{
    public static partial class GCMonitor
    {
        private static class Internal
        {
            private static readonly WeakDelegateCollection _collectedEventHandlers;
            private static readonly WaitCallback _work;

            static Internal()
            {
                _work = _ => RaiseCollected();
                _collectedEventHandlers = new WeakDelegateCollection(false, false, INT_MaxProbingHint);
            }

            public static WeakDelegateCollection CollectedEventHandlers
            {
                get
                {
                    return _collectedEventHandlers;
                }
            }

            public static void Invoke()
            {
                ThreadPool.QueueUserWorkItem(_work);
            }

            private static void RaiseCollected()
            {
                var check = Thread.VolatileRead(ref _status);
                if (check == INT_StatusReady)
                {
                    try
                    {
                        _collectedEventHandlers.RemoveDeadItems();
                        _collectedEventHandlers.Invoke(null, new EventArgs());
                    }
                    catch (Exception exception)
                    {
                        // Pokemon
                        GC.KeepAlive(exception);
                    }
                    Thread.VolatileWrite(ref _status, INT_StatusReady);
                }
            }
        }
    }
}

Rename refactor;: GCMonitor.work -> GCMonitor._work


using UnityEngine;
using System.Collections;

/**
* Dealing with raw touch input from a Cardboard device
*/
public class ParsedTouchData {
  private bool wasTouched = false;

  public ParsedTouchData() {}

  public void Update() {
    wasTouched |= this.IsDown();
  }

  public bool IsDown() {
    return Input.touchCount > 0;
  }

  public bool IsUp() {
    if (!this.IsDown() && wasTouched) {
      wasTouched = false;
      return true;
    }
    return false;
  }
}

using UnityEngine;
using System.Collections;

/**
* Dealing with raw touch input from a Cardboard device
*/
public class ParsedTouchData {
  private bool wasTouched = false;

  public ParsedTouchData() {
    Cardboard cardboard = CardboardGameObject().GetComponent<Cardboard>();
    cardboard.TapIsTrigger = false;
  }

  private GameObject CardboardGameObject() {
    GameObject gameObject = Camera.main.gameObject;
    return gameObject.transform.parent.parent.gameObject;
  }

  public void Update() {
    wasTouched |= IsDown();
  }

  public bool IsDown() {
    return Input.touchCount > 0;
  }

  public bool IsUp() {
    if (!IsDown() && wasTouched) {
      wasTouched = false;
      return true;
    }
    return false;
  }
}

Update for new version of Cardboard SDK

Update for new version of Cardboard SDK


using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;

namespace BTCPayServer.Security;

public class AuthorizationFilterHandle
{
    public AuthorizationHandlerContext Context { get; }
    public PolicyRequirement Requirement { get; }
    public HttpContext HttpContext { get; }
    public bool Success { get; }

    public AuthorizationFilterHandle(
        AuthorizationHandlerContext context,
        PolicyRequirement requirement,
        HttpContext httpContext)
    {
        Context = context;
        Requirement = requirement;
        HttpContext = httpContext;
    }
}

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;

namespace BTCPayServer.Security;

public class AuthorizationFilterHandle
{
    public AuthorizationHandlerContext Context { get; }
    public PolicyRequirement Requirement { get; }
    public HttpContext HttpContext { get; }
    public bool Success { get; private set;  }

    public AuthorizationFilterHandle(
        AuthorizationHandlerContext context,
        PolicyRequirement requirement,
        HttpContext httpContext)
    {
        Context = context;
        Requirement = requirement;
        HttpContext = httpContext;
    }

    public void MarkSuccessful()
    {
        Success = true;
    }
}

Add ability to mark auth handle as successful

Without this, there is no way to let the handle finish with a successful state. I somehow missed to add this in #3977.


/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2009 Jason Booth
Copyright (c) 2011-2012 openxlive.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

namespace CocosSharp
{
    public interface ICCSAXDelegator
    {
        void StartElement(object ctx, string name, string[] atts);
        void EndElement(object ctx, string name);
        void TextHandler(object ctx, byte[] ch, int len);
    }
}

/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2009 Jason Booth
Copyright (c) 2011-2012 openxlive.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

namespace CocosSharp
{
	internal interface ICCSAXDelegator
    {
        void StartElement(object ctx, string name, string[] atts);
        void EndElement(object ctx, string name);
        void TextHandler(object ctx, byte[] ch, int len);
    }
}

Mark ICCSaxDelegator class as internal.

Mark ICCSaxDelegator class as internal.


using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace BoardGamesApi.Controllers
{
    [ApiExplorerSettings(IgnoreApi = true)]
    public class TempController : Controller
    {
        private readonly IConfiguration _configuration;

        public TempController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [AllowAnonymous]
        [Route("/get-token")]
        public IActionResult GenerateToken(string name = "mscommunity")
        {
            var jwt = JwtTokenGenerator
                .Generate(name, true, _configuration["Token:Issuer"], _configuration["Token:Key"]);

            return Ok(jwt);
        }
    }
}

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace BoardGamesApi.Controllers
{
    [ApiExplorerSettings(IgnoreApi = true)]
    public class TempController : Controller
    {
        private readonly IConfiguration _configuration;

        public TempController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [AllowAnonymous]
        [Route("/get-token")]
        public IActionResult GenerateToken(string name = "mscommunity")
        {
            var jwt = JwtTokenGenerator
                .Generate(name, true, _configuration["Tokens:Issuer"], _configuration["Tokens:Key"]);

            return Ok(jwt);
        }
    }
}

Fix the issue with settings name

Fix the issue with settings name


using Eto.Forms;
using MonoMac.AppKit;
using Eto.Drawing;

namespace Eto.Mac.Forms.Controls
{
	public abstract class MacButton<TControl, TWidget, TCallback> : MacControl<TControl, TWidget, TCallback>, TextControl.IHandler
		where TControl: NSButton
		where TWidget: Control
		where TCallback: Control.ICallback
	{
		public virtual string Text
		{
			get
			{
				return Control.Title;
			}
			set
			{
				var oldSize = GetPreferredSize(Size.MaxValue);
				Control.SetTitleWithMnemonic(value);
				LayoutIfNeeded(oldSize);
			}
		}
	}
}

using Eto.Forms;
using MonoMac.AppKit;
using Eto.Drawing;

namespace Eto.Mac.Forms.Controls
{
	public abstract class MacButton<TControl, TWidget, TCallback> : MacControl<TControl, TWidget, TCallback>, TextControl.IHandler
		where TControl: NSButton
		where TWidget: Control
		where TCallback: Control.ICallback
	{
		public virtual string Text
		{
			get
			{
				return Control.Title;
			}
			set
			{
				var oldSize = GetPreferredSize(Size.MaxValue);
				Control.SetTitleWithMnemonic(value ?? string.Empty);
				LayoutIfNeeded(oldSize);
			}
		}
	}
}

Allow Button.Text to be set to null

Mac: Allow Button.Text to be set to null


// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System.ComponentModel;
using osu.Framework.Input.Bindings;
using osu.Game.Rulesets.UI;

namespace osu.Game.Rulesets.Mania
{
    public class ManiaInputManager : RulesetInputManager<ManiaAction>
    {
        public ManiaInputManager(RulesetInfo ruleset, int variant)
            : base(ruleset, variant, SimultaneousBindingMode.Unique)
        {
        }
    }

    public enum ManiaAction
    {
        [Description("Special")]
        Special,
        [Description("Special")]
        Specia2,
        [Description("Key 1")]
        Key1 = 10,
        [Description("Key 2")]
        Key2,
        [Description("Key 3")]
        Key3,
        [Description("Key 4")]
        Key4,
        [Description("Key 5")]
        Key5,
        [Description("Key 6")]
        Key6,
        [Description("Key 7")]
        Key7,
        [Description("Key 8")]
        Key8,
        [Description("Key 9")]
        Key9
    }
}

// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System.ComponentModel;
using osu.Framework.Input.Bindings;
using osu.Game.Rulesets.UI;

namespace osu.Game.Rulesets.Mania
{
    public class ManiaInputManager : RulesetInputManager<ManiaAction>
    {
        public ManiaInputManager(RulesetInfo ruleset, int variant)
            : base(ruleset, variant, SimultaneousBindingMode.Unique)
        {
        }
    }

    public enum ManiaAction
    {
        [Description("Special")]
        Special,
        [Description("Special")]
        Specia2,
        [Description("Key 1")]
        Key1 = 1000,
        [Description("Key 2")]
        Key2,
        [Description("Key 3")]
        Key3,
        [Description("Key 4")]
        Key4,
        [Description("Key 5")]
        Key5,
        [Description("Key 6")]
        Key6,
        [Description("Key 7")]
        Key7,
        [Description("Key 8")]
        Key8,
        [Description("Key 9")]
        Key9
    }
}

Increase the point at which normal keys start in ManiaAction


using System;
using System.Linq;
using System.Threading.Tasks;
using Octokit;
using Rackspace.Threading;
using UnityEditor;
using UnityEngine;

namespace GitHub.Unity
{
    class LoadingView : Subview
    {
        private static readonly Vector2 viewSize = new Vector2(300, 250);
        private bool isBusy;

        private const string WindowTitle = "Loading...";
        private const string Header = "";

        public override void InitializeView(IView parent)
        {
            base.InitializeView(parent);
            Title = WindowTitle;
            Size = viewSize;
        }

        public override void OnGUI()
        {}

        public override bool IsBusy
        {
            get { return false; }
        }
    }
}

using System;
using System.Linq;
using System.Threading.Tasks;
using Octokit;
using Rackspace.Threading;
using UnityEditor;
using UnityEngine;

namespace GitHub.Unity
{
    class LoadingView : Subview
    {
        private static readonly Vector2 viewSize = new Vector2(300, 250);

        private const string WindowTitle = "Loading...";
        private const string Header = "";

        public override void InitializeView(IView parent)
        {
            base.InitializeView(parent);
            Title = WindowTitle;
            Size = viewSize;
        }

        public override void OnGUI()
        {}

        public override bool IsBusy
        {
            get { return false; }
        }
    }
}

Remove unused field, for now

Remove unused field, for now


using System;
using Xamarin.Forms;
using Xamarin.Forms.OAuth;

namespace OAuthTestApp
{
    public class ResultPage : ContentPage
    {
        public ResultPage(AuthenticatonResult result, Action returnCallback)
        {
            var stack = new StackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.Center
            };

            if (result)
            {
                stack.Children.Add(new Label
                {
                    Text = $"Provider: {result.Account.Provider}"
                });

                stack.Children.Add(new Label
                {
                    Text = $"Id: {result.Account.Id}"
                });

                stack.Children.Add(new Label
                {
                    Text = $"Name: {result.Account.DisplayName}"
                });

                stack.Children.Add(new Label
                {
                    Text = $"Access Token: {result.Account.AccessToken}"
                });
            }
            else
            {
                stack.Children.Add(new Label
                {
                    Text = "Authentication failed!"
                });

                stack.Children.Add(new Label
                {
                    Text = $"Reason: {result.ErrorMessage}"
                });
            }

            stack.Children.Add(new Button
            {
                Text = "Back",
                Command = new Command(returnCallback)
            });

            Content = stack;
        }
    }
}

using System;
using Xamarin.Forms;
using Xamarin.Forms.OAuth;
using Xamarin.Forms.OAuth.Views;

namespace OAuthTestApp
{
    public class ResultPage : ContentPage, IBackHandlingView
    {
        private readonly Action _returnCallback;
        public ResultPage(AuthenticatonResult result, Action returnCallback)
        {
            _returnCallback = returnCallback;

            var stack = new StackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.Center
            };

            if (result)
            {
                stack.Children.Add(new Label
                {
                    Text = $"Provider: {result.Account.Provider}"
                });

                stack.Children.Add(new Label
                {
                    Text = $"Id: {result.Account.Id}"
                });

                stack.Children.Add(new Label
                {
                    Text = $"Name: {result.Account.DisplayName}"
                });

                stack.Children.Add(new Label
                {
                    Text = $"Access Token: {result.Account.AccessToken}"
                });
            }
            else
            {
                stack.Children.Add(new Label
                {
                    Text = "Authentication failed!"
                });

                stack.Children.Add(new Label
                {
                    Text = $"Reason: {result.ErrorMessage}"
                });
            }

            stack.Children.Add(new Button
            {
                Text = "Back",
                Command = new Command(returnCallback)
            });

            Content = stack;
        }

        public void HandleBack()
        {
            _returnCallback?.Invoke();
        }
    }
}

Handle physical back button in result view


using Sync.Command;
using Sync.MessageFilter;
using Sync.Plugins;
using Sync.Source;
using Sync.Tools;
using System;
using System.Diagnostics;
using static Sync.Tools.IO;

namespace Sync
{
    public static class Program
    {
        //public static I18n i18n;

        static void Main(string[] args)
        {
            /*  程序工作流程：
             *    1.程序枚举所有插件，保存所有IPlugin到List中
             *    2.程序整理出所有的List<ISourceBase>
             *    3.初始化Sync类，Sync类检测配置文件，用正确的类初始化SyncInstance
             *    4.程序IO Manager开始工作，等待用户输入
             */
            I18n.Instance.ApplyLanguage(new DefaultI18n());

            while(true)
            {
                SyncHost.Instance = new SyncHost();
                SyncHost.Instance.Load();

                CurrentIO.WriteWelcome();

                string cmd = CurrentIO.ReadCommand();
                while (true)
                {
                    SyncHost.Instance.Commands.invokeCmdString(cmd);
                    cmd = CurrentIO.ReadCommand();
                }
            }

        }

    }
}

using Sync.Command;
using Sync.MessageFilter;
using Sync.Plugins;
using Sync.Source;
using Sync.Tools;
using System;
using System.Diagnostics;
using static Sync.Tools.IO;

namespace Sync
{
    public static class Program
    {
        //public static I18n i18n;

        static void Main(string[] args)
        {
            /*  程序工作流程：
             *    1.程序枚举所有插件，保存所有IPlugin到List中
             *    2.程序整理出所有的List<ISourceBase>
             *    3.初始化Sync类，Sync类检测配置文件，用正确的类初始化SyncInstance
             *    4.程序IO Manager开始工作，等待用户输入
             */
            I18n.Instance.ApplyLanguage(new DefaultI18n());

            while(true)
            {
                SyncHost.Instance = new SyncHost();
                SyncHost.Instance.Load();

                CurrentIO.WriteWelcome();

                string cmd = "";
                while (true)
                {
                    SyncHost.Instance.Commands.invokeCmdString(cmd);
                    cmd = CurrentIO.ReadCommand();
                }
            }

        }

    }
}

Move input block for thread safe

Move input block for thread safe


using Microsoft.VisualStudio.ConnectedServices;

namespace AzureIoTHubConnectedService
{
    [ConnectedServiceHandlerExport("Microsoft.AzureIoTHubService",
    AppliesTo = "VisualC+WindowsAppContainer")]
    internal class CppHandlerWAC : GenericAzureIoTHubServiceHandler
    {
        protected override HandlerManifest BuildHandlerManifest(ConnectedServiceHandlerContext context)
        {
            HandlerManifest manifest = new HandlerManifest();

            manifest.PackageReferences.Add(new NuGetReference("Newtonsoft.Json", "6.0.8"));
            manifest.PackageReferences.Add(new NuGetReference("Microsoft.Azure.Devices.Client", "1.0.1"));

            manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.cpp"));
            manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.h"));

            return manifest;
        }

        protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context)
        {
            return new AddServiceInstanceResult(
                "",
                null
                );
        }

        protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context)
        {
            return new AzureIoTHubConnectedServiceHandlerHelper(context);
        }
    }
}

using Microsoft.VisualStudio.ConnectedServices;

namespace AzureIoTHubConnectedService
{
#if false // Disabled to a bug: https://github.com/Azure/azure-iot-sdks/issues/289
    [ConnectedServiceHandlerExport("Microsoft.AzureIoTHubService",
    AppliesTo = "VisualC+WindowsAppContainer")]
#endif
    internal class CppHandlerWAC : GenericAzureIoTHubServiceHandler
    {
        protected override HandlerManifest BuildHandlerManifest(ConnectedServiceHandlerContext context)
        {
            HandlerManifest manifest = new HandlerManifest();

            manifest.PackageReferences.Add(new NuGetReference("Newtonsoft.Json", "6.0.8"));
            manifest.PackageReferences.Add(new NuGetReference("Microsoft.Azure.Devices.Client", "1.0.1"));

            manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.cpp"));
            manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.h"));

            return manifest;
        }

        protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context)
        {
            return new AddServiceInstanceResult(
                "",
                null
                );
        }

        protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context)
        {
            return new AzureIoTHubConnectedServiceHandlerHelper(context);
        }
    }
}

Disable UWP C++ (for now)

Disable UWP C++ (for now)


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

using System.Collections.Generic;
using Newtonsoft.Json;
using osu.Game.Online.API;

namespace osu.Game.Online.Multiplayer
{
    public class IndexPlaylistScoresRequest : APIRequest<RoomPlaylistScores>
    {
        private readonly int roomId;
        private readonly int playlistItemId;

        public IndexPlaylistScoresRequest(int roomId, int playlistItemId)
        {
            this.roomId = roomId;
            this.playlistItemId = playlistItemId;
        }

        protected override string Target => $@"rooms/{roomId}/playlist/{playlistItemId}/scores";
    }

    public class RoomPlaylistScores
    {
        [JsonProperty("scores")]
        public List<MultiplayerScore> Scores { get; set; }
    }
}

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

using System.Collections.Generic;
using Newtonsoft.Json;
using osu.Framework.IO.Network;
using osu.Game.Extensions;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;

namespace osu.Game.Online.Multiplayer
{
    /// <summary>
    /// Returns a list of scores for the specified playlist item.
    /// </summary>
    public class IndexPlaylistScoresRequest : APIRequest<RoomPlaylistScores>
    {
        private readonly int roomId;
        private readonly int playlistItemId;
        private readonly Cursor cursor;
        private readonly MultiplayerScoresSort? sort;

        public IndexPlaylistScoresRequest(int roomId, int playlistItemId, Cursor cursor = null, MultiplayerScoresSort? sort = null)
        {
            this.roomId = roomId;
            this.playlistItemId = playlistItemId;
            this.cursor = cursor;
            this.sort = sort;
        }

        protected override WebRequest CreateWebRequest()
        {
            var req = base.CreateWebRequest();

            req.AddCursor(cursor);

            switch (sort)
            {
                case MultiplayerScoresSort.Ascending:
                    req.AddParameter("sort", "scores_asc");
                    break;

                case MultiplayerScoresSort.Descending:
                    req.AddParameter("sort", "scores_desc");
                    break;
            }

            return req;
        }

        protected override string Target => $@"rooms/{roomId}/playlist/{playlistItemId}/scores";
    }

    public class RoomPlaylistScores
    {
        [JsonProperty("scores")]
        public List<MultiplayerScore> Scores { get; set; }
    }
}

Add additional params to index request

Add additional params to index request


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

using System;

namespace osu.Game.Rulesets.Difficulty
{
    /// <summary>
    /// Wraps a <see cref="DifficultyAttributes"/> object and adds a time value for which the attribute is valid.
    /// Output by <see cref="DifficultyCalculator.CalculateTimed"/>.
    /// </summary>
    public class TimedDifficultyAttributes : IComparable<TimedDifficultyAttributes>
    {
        /// <summary>
        /// The non-clock-adjusted time value at which the attributes take effect.
        /// </summary>
        public readonly double Time;

        /// <summary>
        /// The attributes.
        /// </summary>
        public readonly DifficultyAttributes Attributes;

        public TimedDifficultyAttributes(double time, DifficultyAttributes attributes)
        {
            Time = time;
            Attributes = attributes;
        }

        public int CompareTo(TimedDifficultyAttributes other) => Time.CompareTo(other.Time);
    }
}

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

using System;

namespace osu.Game.Rulesets.Difficulty
{
    /// <summary>
    /// Wraps a <see cref="DifficultyAttributes"/> object and adds a time value for which the attribute is valid.
    /// Output by <see cref="DifficultyCalculator.CalculateTimed"/>.
    /// </summary>
    public class TimedDifficultyAttributes : IComparable<TimedDifficultyAttributes>
    {
        /// <summary>
        /// The non-clock-adjusted time value at which the attributes take effect.
        /// </summary>
        public readonly double Time;

        /// <summary>
        /// The attributes.
        /// </summary>
        public readonly DifficultyAttributes Attributes;

        /// <summary>
        /// Creates new <see cref="TimedDifficultyAttributes"/>.
        /// </summary>
        /// <param name="time">The non-clock-adjusted time value at which the attributes take effect.</param>
        /// <param name="attributes">The attributes.</param>
        public TimedDifficultyAttributes(double time, DifficultyAttributes attributes)
        {
            Time = time;
            Attributes = attributes;
        }

        public int CompareTo(TimedDifficultyAttributes other) => Time.CompareTo(other.Time);
    }
}

Add xmldoc to ctor also

Add xmldoc to ctor also


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

namespace Orchard.Caching {
    public class Cache<TKey, TResult> : ICache<TKey, TResult> {
        private readonly Dictionary<TKey, CacheEntry> _entries;

        public Cache() {
            _entries = new Dictionary<TKey, CacheEntry>();
        }

        public TResult Get(TKey key, Func<AcquireContext<TKey>, TResult> acquire) {
            CacheEntry entry;
            if (!_entries.TryGetValue(key, out entry) || entry.Tokens.Any(t => !t.IsCurrent)) {
                entry = new CacheEntry { Tokens = new List<IVolatileToken>() };

                var context = new AcquireContext<TKey>(key, volatileItem => entry.Tokens.Add(volatileItem));
                entry.Result = acquire(context);
                _entries[key] = entry;
            }
            return entry.Result;
        }

        private class CacheEntry {
            public TResult Result { get; set; }
            public IList<IVolatileToken> Tokens { get; set; }
        }
    }

}

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

namespace Orchard.Caching {
    public class Cache<TKey, TResult> : ICache<TKey, TResult> {
        private readonly ConcurrentDictionary<TKey, CacheEntry> _entries;

        public Cache() {
            _entries = new ConcurrentDictionary<TKey, CacheEntry>();
        }

        public TResult Get(TKey key, Func<AcquireContext<TKey>, TResult> acquire) {
            var entry = _entries.AddOrUpdate(key,
                // "Add" lambda
                k => CreateEntry(k, acquire),
                // "Update" lamdba
                (k, currentEntry) => (currentEntry.Tokens.All(t => t.IsCurrent) ? currentEntry : CreateEntry(k, acquire)));
            return entry.Result;
        }

        private static CacheEntry CreateEntry(TKey k, Func<AcquireContext<TKey>, TResult> acquire) {
            var entry = new CacheEntry { Tokens = new List<IVolatileToken>() };
            var context = new AcquireContext<TKey>(k, volatileItem => entry.Tokens.Add(volatileItem));
            entry.Result = acquire(context);
            return entry;
        }

        private class CacheEntry {
            public TResult Result { get; set; }
            public IList<IVolatileToken> Tokens { get; set; }
        }
    }
}

Fix concurrency issue accessing Dictionary instance

--HG--
branch : dev


using FootballLeague.Models;
using System.DirectoryServices;

namespace FootballLeague.Services
{
    public class UsersADSearcher : IUsersADSearcher
    {
        public User LoadUserDetails(string userName)
        {
            var entry = new DirectoryEntry();
            var searcher = new DirectorySearcher(entry);
            searcher.Filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))";
            searcher.PropertiesToLoad.Add("givenName");
            searcher.PropertiesToLoad.Add("sn");
            searcher.PropertiesToLoad.Add("mail");
            var userProps = searcher.FindOne().Properties;
            var mail = userProps["mail"][0].ToString();
            var first = userProps["givenName"][0].ToString();
            var last = userProps["sn"][0].ToString();

            return new User { Name = userName, Mail = mail, FirstName = first, LastName = last };
        }
    }
}

using System.Linq;
using System.Web;
using FootballLeague.Models;
using System.DirectoryServices;

namespace FootballLeague.Services
{
    public class UsersADSearcher : IUsersADSearcher
    {
        public User LoadUserDetails(string userName)
        {
            var entry = new DirectoryEntry();
            var searcher = new DirectorySearcher(entry);
            searcher.Filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))";
            searcher.PropertiesToLoad.Add("givenName");
            searcher.PropertiesToLoad.Add("sn");
            searcher.PropertiesToLoad.Add("mail");
            try
            {
                var userProps = searcher.FindOne().Properties;
                var mail = userProps["mail"][0].ToString();
                var first = userProps["givenName"][0].ToString();
                var last = userProps["sn"][0].ToString();

                return new User { Name = userName, Mail = mail, FirstName = first, LastName = last };
            }
            catch
            {
                return new User { Name = HttpContext.Current.User.Identity.Name.Split('\\').Last(), Mail = "local@user.sk", FirstName = "Local", LastName = "User" };
            }
        }
    }
}

Use local user when not in domain

Use local user when not in domain


using UnityEditor;
using UnityEditor.Build;
#if UNITY_2018_1_OR_NEWER
using UnityEditor.Build.Reporting;
#endif
using UnityEngine;

class TeakPreProcessDefiner :
#if UNITY_2018_1_OR_NEWER
    IPreprocessBuildWithReport
#else
    IPreprocessBuild
#endif
{
    public int callbackOrder { get { return 0; } }
    public static readonly string[] TeakDefines = new string[] { "TEAK_2_0_OR_NEWER" };

#if UNITY_2018_1_OR_NEWER
    public void OnPreprocessBuild(BuildReport report) {
        SetTeakPreprocesorDefines(report.summary.platformGroup);
    }
#else

    public void OnPreprocessBuild(BuildTarget target, string path) {
        SetTeakPreprocesorDefines(BuildPipeline.GetBuildTargetGroup(target));
    }
#endif

    private void SetTeakPreprocesorDefines(BuildTargetGroup targetGroup) {
        string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
        if (!defines.EndsWith(";")) defines += ";";
        defines += string.Join(";", TeakDefines);
        PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, defines);
    }
}

using UnityEditor;
using UnityEditor.Build;
#if UNITY_2018_1_OR_NEWER
using UnityEditor.Build.Reporting;
#endif
using UnityEngine;

using System.Collections.Generic;

class TeakPreProcessDefiner :
#if UNITY_2018_1_OR_NEWER
    IPreprocessBuildWithReport
#else
    IPreprocessBuild
#endif
{
    public int callbackOrder { get { return 0; } }
    public static readonly string[] TeakDefines = new string[] { "TEAK_2_0_OR_NEWER" };

#if UNITY_2018_1_OR_NEWER
    public void OnPreprocessBuild(BuildReport report) {
        SetTeakPreprocesorDefines(report.summary.platformGroup);
    }
#else

    public void OnPreprocessBuild(BuildTarget target, string path) {
        SetTeakPreprocesorDefines(BuildPipeline.GetBuildTargetGroup(target));
    }
#endif

    private void SetTeakPreprocesorDefines(BuildTargetGroup targetGroup) {
        string[] existingDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup).Split(";");
        HashSet<string> defines = new HashSet<string>(existingDefines);
        defines.UnionWith(TeakDefines);
        PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defines.ToArray()));
    }
}

Use a set of defines, and some generics

Use a set of defines, and some generics


using System;
using System.Collections.Generic;

namespace Stripe.Tests.Xunit
{
    public class coupons_fixture : IDisposable
    {
        public StripeCouponCreateOptions CouponCreateOptions { get; set; }
        public StripeCouponUpdateOptions CouponUpdateOptions { get; set; }

        public StripeCoupon Coupon { get; set; }
        public StripeCoupon CouponRetrieved { get; set; }
        public StripeCoupon CouponUpdated { get; set; }
        public StripeDeleted CouponDeleted { get; set; }
        public StripeList<StripeCoupon> CouponsList { get; }

        public coupons_fixture()
        {
            CouponCreateOptions = new StripeCouponCreateOptions() {
              Id = "test-coupon-" + Guid.NewGuid().ToString() + " ",
              PercentOff = 25,
              Duration = "repeating",
              DurationInMonths = 3,
            };

            CouponUpdateOptions = new StripeCouponUpdateOptions {
              Metadata = new Dictionary<string, string>{{"key_1", "value_1"}}
            };

            var service = new StripeCouponService(Cache.ApiKey);
            Coupon = service.Create(CouponCreateOptions);
            CouponRetrieved = service.Get(Coupon.Id);
            CouponUpdated = service.Update(Coupon.Id, CouponUpdateOptions);
            CouponsList = service.List();
            CouponDeleted = service.Delete(Coupon.Id);
        }

        public void Dispose() { }
    }
}

using System;
using System.Collections.Generic;

namespace Stripe.Tests.Xunit
{
    public class coupons_fixture : IDisposable
    {
        public StripeCouponCreateOptions CouponCreateOptions { get; set; }
        public StripeCouponUpdateOptions CouponUpdateOptions { get; set; }

        public StripeCoupon Coupon { get; set; }
        public StripeCoupon CouponRetrieved { get; set; }
        public StripeCoupon CouponUpdated { get; set; }
        public StripeDeleted CouponDeleted { get; set; }
        public StripeList<StripeCoupon> CouponsList { get; }

        public coupons_fixture()
        {
            CouponCreateOptions = new StripeCouponCreateOptions() {
                // Add a space at the end to ensure the ID is properly URL encoded
                // when passed in the URL for other methods
                Id = "test-coupon-" + Guid.NewGuid().ToString() + " ",
                PercentOff = 25,
                Duration = "repeating",
                DurationInMonths = 3,
            };

            CouponUpdateOptions = new StripeCouponUpdateOptions {
              Metadata = new Dictionary<string, string>{{"key_1", "value_1"}}
            };

            var service = new StripeCouponService(Cache.ApiKey);
            Coupon = service.Create(CouponCreateOptions);
            CouponRetrieved = service.Get(Coupon.Id);
            CouponUpdated = service.Update(Coupon.Id, CouponUpdateOptions);
            CouponsList = service.List();
            CouponDeleted = service.Delete(Coupon.Id);
        }

        public void Dispose() { }
    }
}

Add a detailed comment to explain why we test this


using System.Resources;
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("NesZord.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NesZord.Core")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

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

[assembly: InternalsVisibleTo("NesZord.Tests")]

Enable NesZord.Tests to se internal members of NesZord.Core


using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace RazorLight.Extensions
{
    public static class TypeExtensions
    {
        public static ExpandoObject ToExpando(this object anonymousObject)
        {
            if (anonymousObject is ExpandoObject exp)
            {
                return exp;
            }

            IDictionary<string, object> expando = new ExpandoObject();
            foreach (var propertyDescriptor in anonymousObject.GetType().GetTypeInfo().GetProperties())
            {
                var obj = propertyDescriptor.GetValue(anonymousObject);
                expando.Add(propertyDescriptor.Name, obj);
            }

            return (ExpandoObject)expando;
        }

        public static bool IsAnonymousType(this Type type)
        {
            bool hasCompilerGeneratedAttribute = type.GetTypeInfo()
                .GetCustomAttributes(typeof(CompilerGeneratedAttribute), false)
                .Any();

            bool nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
            bool isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;

            return isAnonymousType;
        }

    }
}

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace RazorLight.Extensions
{
    public static class TypeExtensions
    {
        public static ExpandoObject ToExpando(this object anonymousObject)
        {
            if (anonymousObject is ExpandoObject exp)
            {
                return exp;
            }

            IDictionary<string, object> expando = new ExpandoObject();
            foreach (var propertyDescriptor in anonymousObject.GetType().GetTypeInfo().GetProperties())
            {
                var obj = propertyDescriptor.GetValue(anonymousObject);
                if (obj != null && obj.GetType().IsAnonymousType())
                {
                    obj = obj.ToExpando();
                }
                expando.Add(propertyDescriptor.Name, obj);
            }

            return (ExpandoObject)expando;
        }

        public static bool IsAnonymousType(this Type type)
        {
            bool hasCompilerGeneratedAttribute = type.GetTypeInfo()
                .GetCustomAttributes(typeof(CompilerGeneratedAttribute), false)
                .Any();

            bool nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
            bool isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;

            return isAnonymousType;
        }

    }
}

Add support for nested anonymous models

Add support for nested anonymous models


using UnityEngine;

namespace PrepareLanding.Core.Extensions
{
    public static class FilterBooleanExtensions
    {
        public static string ToStringHuman(this FilterBoolean filterBool)
        {
            switch (filterBool)
            {
                case FilterBoolean.AndFiltering:
                    return "AND";

                case FilterBoolean.OrFiltering:
                    return "OR";

                default:
                    return "UNK";
            }
        }

        public static FilterBoolean Next(this FilterBoolean filterBoolean)
        {
            return (FilterBoolean)(((int)filterBoolean + 1) % (int)FilterBoolean.Undefined);
        }

        public static Color Color(this FilterBoolean filterBoolean)
        {
            switch (filterBoolean)
            {
                case FilterBoolean.AndFiltering:
                    return Verse.ColorLibrary.BurntOrange;

                case FilterBoolean.OrFiltering:
                    return Verse.ColorLibrary.BrightBlue;

                default:
                    return UnityEngine.Color.black;
            }
        }
    }
}

using UnityEngine;
using Verse;

namespace PrepareLanding.Core.Extensions
{
    public static class FilterBooleanExtensions
    {
        public static string ToStringHuman(this FilterBoolean filterBool)
        {
            switch (filterBool)
            {
                case FilterBoolean.AndFiltering:
                    return "PLMWTT_FilterBooleanOr".Translate();

                case FilterBoolean.OrFiltering:
                    return "PLMWTT_FilterBooleanAnd".Translate();

                default:
                    return "UNK";
            }
        }

        public static FilterBoolean Next(this FilterBoolean filterBoolean)
        {
            return (FilterBoolean)(((int)filterBoolean + 1) % (int)FilterBoolean.Undefined);
        }

        public static Color Color(this FilterBoolean filterBoolean)
        {
            switch (filterBoolean)
            {
                case FilterBoolean.AndFiltering:
                    return Verse.ColorLibrary.BurntOrange;

                case FilterBoolean.OrFiltering:
                    return Verse.ColorLibrary.BrightBlue;

                default:
                    return UnityEngine.Color.black;
            }
        }
    }
}

Allow translation of boolean filtering text.


using System;
using System.Runtime.InteropServices;

namespace OpenSage.Utilities
{
    public static class PlatformUtility
    {
        /// <summary>
        /// Check if current platform is windows
        /// </summary>
        /// <returns></returns>
        public static bool IsWindowsPlatform()
        {
            switch (Environment.OSVersion.Platform)
            {
                case PlatformID.Win32Windows:
                case PlatformID.Win32NT:
                case PlatformID.WinCE:
                case PlatformID.Win32S:
                    return true;
                default:
                    return false;
            }
        }

        public static float GetDefaultDpi()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return 96.0f;
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                return 72.0f;
            }
            else
            {
                return 1.0f; // TODO: What happens on Linux?
            }
        }
    }
}

using System;
using System.Runtime.InteropServices;

namespace OpenSage.Utilities
{
    public static class PlatformUtility
    {
        /// <summary>
        /// Check if current platform is windows
        /// </summary>
        /// <returns></returns>
        public static bool IsWindowsPlatform()
        {
            switch (Environment.OSVersion.Platform)
            {
                case PlatformID.Win32Windows:
                case PlatformID.Win32NT:
                case PlatformID.WinCE:
                case PlatformID.Win32S:
                    return true;
                default:
                    return false;
            }
        }

        public static float GetDefaultDpi()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return 96.0f;
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                return 72.0f;
            }
            else
            {
                return 96.0f; // TODO: For GNOME3 the default DPI is 96
            }
        }
    }
}

Use correct Gnome3 default DPI

Use correct Gnome3 default DPI


using System.Text;
using TweetDuck.Plugins.Enums;

namespace TweetDuck.Plugins{
    static class PluginScriptGenerator{
        public static string GenerateConfig(PluginConfig config){
            return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty;
        }

        public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
            StringBuilder build = new StringBuilder(2*pluginIdentifier.Length+pluginContents.Length+165);

            build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");

            build.Append("let tmp={");
            build.Append("id:\"").Append(pluginIdentifier).Append("\",");
            build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
            build.Append("};");

            build.Append("tmp.obj.$id=\"").Append(pluginIdentifier).Append("\";");
            build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
            build.Append("window.TD_PLUGINS.install(tmp);");

            build.Append("})(").Append(environment.GetScriptVariables()).Append(");");

            return build.ToString();
        }
    }
}

using System.Globalization;
using TweetDuck.Plugins.Enums;

namespace TweetDuck.Plugins{
    static class PluginScriptGenerator{
        public static string GenerateConfig(PluginConfig config){
            return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty;
        }

        public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
            return PluginGen
                .Replace("%params", environment.GetScriptVariables())
                .Replace("%id", pluginIdentifier)
                .Replace("%token", pluginToken.ToString(CultureInfo.InvariantCulture))
                .Replace("%contents", pluginContents);
        }

        private const string PluginGen = "(function(%params,$d){let tmp={id:'%id',obj:new class extends PluginBase{%contents}};$d(tmp.obj,'$id',{value:'%id'});$d(tmp.obj,'$token',{value:%token});window.TD_PLUGINS.install(tmp);})(%params,Object.defineProperty);";

/* PluginGen

(function(%params, $i, $d){
  let tmp = {
    id: '%id',
    obj: new class extends PluginBase{%contents}
  };

  $d(tmp.obj, '$id', { value: '%id' });
  $d(tmp.obj, '$token', { value: %token });

  window.TD_PLUGINS.install(tmp);
})(%params, Object.defineProperty);

*/
    }
}

Make $id and $token properties in plugin objects unmodifiable


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

namespace OmniSharp.Models
{
    public class Request : SimpleFileRequest
    {
        [JsonConverter(typeof(ZeroBasedIndexConverter))]
        public int Line { get; set; }
        [JsonConverter(typeof(ZeroBasedIndexConverter))]
        public int Column { get; set; }
        public string Buffer { get; set; }
        public IEnumerable<LinePositionSpanTextChange> Changes { get; set; }
        public bool ApplyChangesTogether { get; set; }
    }
}

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

namespace OmniSharp.Models
{
    public class Request : SimpleFileRequest
    {
        [JsonConverter(typeof(ZeroBasedIndexConverter))]
        public int Line { get; set; }
        [JsonConverter(typeof(ZeroBasedIndexConverter))]
        public int Column { get; set; }
        public string Buffer { get; set; }
        public IEnumerable<LinePositionSpanTextChange> Changes { get; set; }
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
        public bool ApplyChangesTogether { get; set; }
    }
}

Make ApplyChangesTogether automatically filled to false if not present.


using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;

namespace LibYear.Lib.FileTypes
{
    public class ProjectJsonFile : IProjectFile
    {
        private string _fileContents;
        public string FileName { get; }
        public IDictionary<string, PackageVersion> Packages { get; }

        public ProjectJsonFile(string filename)
        {
            FileName = filename;
            _fileContents = File.ReadAllText(FileName);
            Packages = GetDependencies().ToDictionary(p => ((JProperty)p).Name.ToString(), p => PackageVersion.Parse(((JProperty)p).Value.ToString()));
        }

        private IEnumerable<JToken> GetDependencies()
        {
            return JObject.Parse(_fileContents).Descendants()
                .Where(d => d.Type == JTokenType.Property
                        && d.Path.Contains("dependencies")
                        && (!d.Path.Contains("[") || d.Path.EndsWith("]"))
                        && ((JProperty)d).Value.Type == JTokenType.String);
        }

        public void Update(IEnumerable<Result> results)
        {
            lock (_fileContents)
            {
                foreach (var result in results)
                    _fileContents = _fileContents.Replace($"\"{result.Name}\": \"{result.Installed.Version}\"", $"\"{result.Name}\": \"{result.Latest.Version}\"");

                File.WriteAllText(FileName, _fileContents);
            }
        }
    }
}

using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;

namespace LibYear.Lib.FileTypes
{
	public class ProjectJsonFile : IProjectFile
	{
		private string _fileContents;
		public string FileName { get; }
		public IDictionary<string, PackageVersion> Packages { get; }
		private readonly object _lock = new object();

		public ProjectJsonFile(string filename)
		{
			FileName = filename;
			_fileContents = File.ReadAllText(FileName);
			Packages = GetDependencies().ToDictionary(p => ((JProperty)p).Name.ToString(), p => PackageVersion.Parse(((JProperty)p).Value.ToString()));
		}

		private IEnumerable<JToken> GetDependencies()
		{
			return JObject.Parse(_fileContents).Descendants()
				.Where(d => d.Type == JTokenType.Property
				            && d.Path.Contains("dependencies")
				            && (!d.Path.Contains("[") || d.Path.EndsWith("]"))
				            && ((JProperty)d).Value.Type == JTokenType.String);
		}

		public void Update(IEnumerable<Result> results)
		{
			lock (_lock)
			{
				foreach (var result in results)
				{
					_fileContents = _fileContents.Replace($"\"{result.Name}\": \"{result.Installed.Version}\"", $"\"{result.Name}\": \"{result.Latest.Version}\"");
				}

				File.WriteAllText(FileName, _fileContents);
			}
		}
	}
}

Fix JSON file locking issue

Fix JSON file locking issue


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using LearnositySDK.Request;
using LearnositySDK.Utils;
// static LearnositySDK.Credentials;

namespace LearnosityDemo.Pages
{
    public class ItemsAPIDemoModel : PageModel
    {
        public void OnGet()
        {
            // prepare all the params
            string service = "items";

            JsonObject security = new JsonObject();
            security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey);
            security.set("domain", LearnositySDK.Credentials.Domain);
            security.set("user_id", Uuid.generate());
            string secret = LearnositySDK.Credentials.ConsumerSecret;

            //JsonObject config = new JsonObject();
            JsonObject request = new JsonObject();
            request.set("user_id", Uuid.generate());
            request.set("activity_template_id", "quickstart_examples_activity_template_001");
            request.set("session_id", Uuid.generate());
            request.set("activity_id", "quickstart_examples_activity_001");
            request.set("rendering_type", "assess");
            request.set("type", "submit_practice");
            request.set("name", "Items API Quickstart");
            //request.set("config", config);

            // Instantiate Init class
            Init init = new Init(service, security, secret, request);

            // Call the generate() method to retrieve a JavaScript object
            ViewData["InitJSON"] = init.generate();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using LearnositySDK.Request;
using LearnositySDK.Utils;
// static LearnositySDK.Credentials;

namespace LearnosityDemo.Pages
{
    public class ItemsAPIDemoModel : PageModel
    {
        public void OnGet()
        {
            // prepare all the params
            string service = "items";

            JsonObject security = new JsonObject();
            security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey);
            security.set("domain", LearnositySDK.Credentials.Domain);
            security.set("user_id", Uuid.generate());
            string secret = LearnositySDK.Credentials.ConsumerSecret;

            JsonObject request = new JsonObject();
            request.set("user_id", Uuid.generate());
            request.set("activity_template_id", "quickstart_examples_activity_template_001");
            request.set("session_id", Uuid.generate());
            request.set("activity_id", "quickstart_examples_activity_001");
            request.set("rendering_type", "assess");
            request.set("type", "submit_practice");
            request.set("name", "Items API Quickstart");
            request.set("state", "initial");

            // Instantiate Init class
            Init init = new Init(service, security, secret, request);

            // Call the generate() method to retrieve a JavaScript object
            ViewData["InitJSON"] = init.generate();
        }
    }
}

[DOC] Add example for state init option to quick-start guide example project.


namespace DesktopWidgets.Widgets.RSSFeed
{
    public static class Metadata
    {
        public const string FriendlyName = "RSS Headlines";
    }
}

namespace DesktopWidgets.Widgets.RSSFeed
{
    public static class Metadata
    {
        public const string FriendlyName = "RSS Feed";
    }
}

Change "RSS Headlines" widget name

Change "RSS Headlines" widget name


@using Microsoft.ApplicationInsights.Extensibility
@inject TelemetryConfiguration TelemetryConfiguration

<environment names="Production">

    <script type="text/javascript">
            (function (i, s, o, g, r, a, m) {
                i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
                    (i[r].q = i[r].q || []).push(arguments)
                }, i[r].l = 1 * new Date(); a = s.createElement(o),
                m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
            })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

            ga('create', 'UA-61337531-1', 'auto', { 'name': 'mscTracker' });
            ga('mscTracker.send', 'pageview');
    </script>

    @Html.ApplicationInsightsJavaScript(TelemetryConfiguration)
</environment>

@using Microsoft.ApplicationInsights.Extensibility
@inject TelemetryConfiguration TelemetryConfiguration

<environment names="Production">

    <script type="text/javascript">
            (function (i, s, o, g, r, a, m) {
                i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
                    (i[r].q = i[r].q || []).push(arguments)
                }, i[r].l = 1 * new Date(); a = s.createElement(o),
                m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
            })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

            ga('create', 'UA-61337531-1', 'auto', { 'name': 'mscTracker' });
            ga('create', 'UA-61337531-4', 'auto', { 'name': 'liveaspnetTracker' });
            ga('mscTracker.send', 'pageview');
            ga('liveaspnetTracker.send', 'pageview');
    </script>

    @Html.ApplicationInsightsJavaScript(TelemetryConfiguration)
</environment>

Add new Google Analytics tracking ID

Add new Google Analytics tracking ID


using System.Resources;
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("WordPressRestApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DevFoundries")]
[assembly: AssemblyProduct("WordPressRestApi")]
[assembly: AssemblyCopyright("Copyright ©  2017 Wm. Barrett Simms")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

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

using System.Resources;
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("WordPressRestApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DevFoundries")]
[assembly: AssemblyProduct("WordPressRestApi")]
[assembly: AssemblyCopyright("Copyright ©  2017 Wm. Barrett Simms")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

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

Package rename and add support for Media