using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace AustinSite
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

using AustinSite.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace AustinSite
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddScoped<ArticlesRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Add Articles rep into DI scope

Add Articles rep into DI scope


using System;

namespace TestUtility
{
    public partial class TestAssets
    {
        private class TestProject : ITestProject
        {
            private bool _disposed;

            public string Name { get; }
            public string BaseDirectory { get; }
            public string Directory { get; }
            public bool ShadowCopied { get; }

            public TestProject(string name, string baseDirectory, string directory, bool shadowCopied)
            {
                this.Name = name;
                this.BaseDirectory = baseDirectory;
                this.Directory = directory;
                this.ShadowCopied = shadowCopied;
            }

            ~TestProject()
            {
                throw new InvalidOperationException($"{nameof(ITestProject)}.{nameof(Dispose)}() not called for {this.Name}");
            }

            public virtual void Dispose()
            {
                if (_disposed)
                {
                    throw new InvalidOperationException($"{nameof(ITestProject)} for {this.Name} already disposed.");
                }

                if (this.ShadowCopied)
                {
                    System.IO.Directory.Delete(this.BaseDirectory, recursive: true);

                    if (System.IO.Directory.Exists(this.BaseDirectory))
                    {
                        throw new InvalidOperationException($"{nameof(ITestProject)} directory still exists: '{this.BaseDirectory}'");
                    }
                }

                this._disposed = true;
                GC.SuppressFinalize(this);
            }
        }
    }
}

using System;
using System.Threading;

namespace TestUtility
{
    public partial class TestAssets
    {
        private class TestProject : ITestProject
        {
            private bool _disposed;

            public string Name { get; }
            public string BaseDirectory { get; }
            public string Directory { get; }
            public bool ShadowCopied { get; }

            public TestProject(string name, string baseDirectory, string directory, bool shadowCopied)
            {
                this.Name = name;
                this.BaseDirectory = baseDirectory;
                this.Directory = directory;
                this.ShadowCopied = shadowCopied;
            }

            ~TestProject()
            {
                throw new InvalidOperationException($"{nameof(ITestProject)}.{nameof(Dispose)}() not called for {this.Name}");
            }

            public virtual void Dispose()
            {
                if (_disposed)
                {
                    throw new InvalidOperationException($"{nameof(ITestProject)} for {this.Name} already disposed.");
                }

                if (this.ShadowCopied)
                {
                    var retries = 0;
                    while (retries <= 5)
                    {
                        try
                        {
                            System.IO.Directory.Delete(this.BaseDirectory, recursive: true);
                            break;
                        }
                        catch
                        {
                            Thread.Sleep(1000);
                            retries++;
                        }
                    }

                    if (System.IO.Directory.Exists(this.BaseDirectory))
                    {
                        throw new InvalidOperationException($"{nameof(ITestProject)} directory still exists: '{this.BaseDirectory}'");
                    }
                }

                this._disposed = true;
                GC.SuppressFinalize(this);
            }
        }
    }
}

Add retry logic for test clean up

Add retry logic for test clean up


/*
 JustMock Lite
 Copyright © 2019 Progress Software Corporation

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System.ComponentModel;
using System.Reflection;

namespace Telerik.JustMock.Core.Context
{
    public static class AsyncContextResolver
    {
#if NETCORE
        static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
        static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
        [EditorBrowsable(EditorBrowsableState.Never)]
        public static MethodBase GetContext()
        {
            return resolver.GetContext();
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public static void CaptureContext()
        {
            resolver.CaptureContext();
        }
    }
}

/*
 JustMock Lite
 Copyright © 2019 Progress Software Corporation

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System.ComponentModel;
using System.Reflection;

namespace Telerik.JustMock.Core.Context
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class AsyncContextResolver
    {
#if NETCORE
        static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
        static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
        public static MethodBase GetContext()
        {
            return resolver.GetContext();
        }

        public static void CaptureContext()
        {
            resolver.CaptureContext();
        }
    }
}

Move EditorBrowsable to class level

Move EditorBrowsable to class level


using System;
using Faithlife.Build;

internal static class Build
{
	public static int Main(string[] args) => BuildRunner.Execute(args, build =>
	{
		build.AddDotNetTargets(
			new DotNetBuildSettings
			{
				DocsSettings = new DotNetDocsSettings
				{
					GitLogin = new GitLoginInfo("ejball", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""),
					GitAuthor = new GitAuthorInfo("ejball", "ejball@gmail.com"),
					SourceCodeUrl = "https://github.com/ejball/ArgsReading/tree/master/src",
				},
			});

		build.Target("default")
			.DependsOn("build");
	});
}

using System;
using Faithlife.Build;

internal static class Build
{
	public static int Main(string[] args) => BuildRunner.Execute(args, build =>
	{
		build.AddDotNetTargets(
			new DotNetBuildSettings
			{
				DocsSettings = new DotNetDocsSettings
				{
					GitLogin = new GitLoginInfo("ejball", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""),
					GitAuthor = new GitAuthorInfo("ejball", "ejball@gmail.com"),
					SourceCodeUrl = "https://github.com/ejball/ArgsReading/tree/master/src",
					ToolVersion = "1.5.1",
				},
			});

		build.Target("default")
			.DependsOn("build");
	});
}

Use latest xmldocmd to fix publish.

Use latest xmldocmd to fix publish.


using System.Linq;
using Raven.Client.Indexes;

namespace Raven.TimeZones
{
    public class ZoneShapesIndex : AbstractIndexCreationTask<ZoneShape>
    {
        public ZoneShapesIndex()
        {
            Map = shapes => from shape in shapes
                            select new
                                {
                                    shape.Zone,
                                    _ = SpatialGenerate("location", shape.Shape)
                                };
        }
    }
}

using System.Linq;
using Raven.Abstractions.Indexing;
using Raven.Client.Indexes;

namespace Raven.TimeZones
{
    public class ZoneShapesIndex : AbstractIndexCreationTask<ZoneShape>
    {
        public ZoneShapesIndex()
        {
            Map = shapes => from shape in shapes
                            select new
                                {
                                    shape.Zone,
                                    _ = SpatialGenerate("location", shape.Shape, SpatialSearchStrategy.GeohashPrefixTree, 3)
                                };
        }
    }
}

Use a lower maxTreeLevel precision

Use a lower maxTreeLevel precision

https://groups.google.com/d/topic/ravendb/a6xFRI8nKZc/discussion


using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using EnumsNET;
using Microsoft.Extensions.FileProviders;

namespace SJP.Schematic.Reporting.Html
{
    internal class TemplateProvider : ITemplateProvider
    {
        public string GetTemplate(ReportTemplate template)
        {
            if (!template.IsValid())
                throw new ArgumentException($"The { nameof(ReportTemplate) } provided must be a valid enum.", nameof(template));

            var resource = GetResource(template);
            return GetResourceAsString(resource);
        }

        private static IFileInfo GetResource(ReportTemplate template)
        {
            var templateKey = template.ToString();
            var templateFileName = templateKey + TemplateExtension;

            var resourceFiles = _fileProvider.GetDirectoryContents("/");
            var templateResource = resourceFiles.FirstOrDefault(r => r.Name.EndsWith(templateFileName));
            if (templateResource == null)
                throw new NotSupportedException($"The given template: { templateKey } is not a supported template.");

            return templateResource;
        }

        private static string GetResourceAsString(IFileInfo fileInfo)
        {
            if (fileInfo == null)
                throw new ArgumentNullException(nameof(fileInfo));

            using (var stream = new MemoryStream())
            using (var reader = fileInfo.CreateReadStream())
            {
                reader.CopyTo(stream);
                return Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length);
            }
        }

        private static readonly IFileProvider _fileProvider = new EmbeddedFileProvider(Assembly.GetExecutingAssembly(), Assembly.GetExecutingAssembly().GetName().Name + ".Html.Templates");
        private const string TemplateExtension = ".cshtml";
    }
}

using System;
using System.IO;
using System.Linq;
using System.Reflection;
using EnumsNET;
using Microsoft.Extensions.FileProviders;

namespace SJP.Schematic.Reporting.Html
{
    internal class TemplateProvider : ITemplateProvider
    {
        public string GetTemplate(ReportTemplate template)
        {
            if (!template.IsValid())
                throw new ArgumentException($"The { nameof(ReportTemplate) } provided must be a valid enum.", nameof(template));

            var resource = GetResource(template);
            return GetResourceAsString(resource);
        }

        private static IFileInfo GetResource(ReportTemplate template)
        {
            var templateKey = template.ToString();
            var templateFileName = templateKey + TemplateExtension;

            var resourceFiles = _fileProvider.GetDirectoryContents("/");
            var templateResource = resourceFiles.FirstOrDefault(r => r.Name.EndsWith(templateFileName));
            if (templateResource == null)
                throw new NotSupportedException($"The given template: { templateKey } is not a supported template.");

            return templateResource;
        }

        private static string GetResourceAsString(IFileInfo fileInfo)
        {
            if (fileInfo == null)
                throw new ArgumentNullException(nameof(fileInfo));

            using (var stream = fileInfo.CreateReadStream())
            using (var reader = new StreamReader(stream))
                return reader.ReadToEnd();
        }

        private static readonly IFileProvider _fileProvider = new EmbeddedFileProvider(Assembly.GetExecutingAssembly(), Assembly.GetExecutingAssembly().GetName().Name + ".Html.Templates");
        private const string TemplateExtension = ".cshtml";
    }
}

Clean up reading templates from embedded resources.

Use a StreamReader instead of a MemoryStream that assumes UTF-8.


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

namespace Alexa.NET.Management.Package
{
    public enum ImportStatus
    {
        FAILED,
        IN_PROGRESS,
        SUCCEEEDED
    }
}

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

namespace Alexa.NET.Management.Package
{
    public enum ImportStatus
    {
        FAILED,
        IN_PROGRESS,
        SUCCEEDED
    }
}

Fix import status succeeded spelling error


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

public class UnlockCursorOnStart : MonoBehaviour
{

    void Start()
    {
        Invoke("unlockCursor", .1f);
    }

    void unlockCursor()
    {
        Cursor.lockState = GameController.DefaultCursorMode;
    }
}

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

public class UnlockCursorOnStart : MonoBehaviour
{
    [SerializeField]
    bool forceOnUpdate = true;

    void Start()
    {
        Invoke("unlockCursor", .1f);
    }

    void unlockCursor()
    {
        Cursor.lockState = GameController.DefaultCursorMode;
    }

    private void Update()
    {
        if (Cursor.lockState != GameController.DefaultCursorMode)
            Cursor.lockState = GameController.DefaultCursorMode;
    }
}

Make cursor redundancy more redundant

Make cursor redundancy more redundant


@if (Model.DiscountedPrice != Model.Price)
{
    @Model.Price.ToString("c")
    @Model.DiscountedPrice.ToString("c")
    @Model.DiscountComment
}
else
{
    @Model.Price.ToString("c")
}

Use {0:c} rather than ToString("c") where possible.

--HG--
branch : currency_string_format


using System;
using System.Collections.Generic;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing;

namespace RawRabbit.Common
{
	public interface IBasicPropertiesProvider
	{
		IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null);
	}

	public class BasicPropertiesProvider : IBasicPropertiesProvider
	{
		public IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null)
		{
			var properties = new BasicProperties
			{
				MessageId = Guid.NewGuid().ToString(),
				Persistent = true,
				Headers = new Dictionary<string, object>
				{
					{ PropertyHeaders.Sent, DateTime.UtcNow.ToString("u") },
					{ PropertyHeaders.MessageType, typeof(TMessage).FullName }
				}
			};
			custom?.Invoke(properties);
			return properties;
		}
	}
}

using System;
using System.Collections.Generic;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing;
using RawRabbit.Configuration;

namespace RawRabbit.Common
{
	public interface IBasicPropertiesProvider
	{
		IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null);
	}

	public class BasicPropertiesProvider : IBasicPropertiesProvider
	{
		private readonly RawRabbitConfiguration _config;

		public BasicPropertiesProvider(RawRabbitConfiguration config)
		{
			_config = config;
		}

		public IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null)
		{
			var properties = new BasicProperties
			{
				MessageId = Guid.NewGuid().ToString(),
				Persistent = _config.PersistentDeliveryMode,
				Headers = new Dictionary<string, object>
				{
					{ PropertyHeaders.Sent, DateTime.UtcNow.ToString("u") },
					{ PropertyHeaders.MessageType, typeof(TMessage).FullName }
				}
			};
			custom?.Invoke(properties);
			return properties;
		}
	}
}

Use Persist value from config.

Use Persist value from config.


#region Using

using System;
using System.Numerics;
using Emotion.Graphics.Objects;
using Emotion.Primitives;

#endregion

namespace Emotion.Plugins.ImGuiNet
{
    public static class ImGuiExtensions
    {
        public static Tuple<Vector2, Vector2> GetImGuiUV(this Texture t, Rectangle? uv = null)
        {
            Rectangle reqUv;
            if (uv == null)
                reqUv = new Rectangle(0, 0, t.Size);
            else
                reqUv = (Rectangle) uv;

            Vector2 uvOne = new Vector2(
                reqUv.X / t.Size.X,
                reqUv.Y / t.Size.Y * -1
            );
            Vector2 uvTwo = new Vector2(
                (reqUv.X + reqUv.Size.X) / t.Size.X,
                (reqUv.Y + reqUv.Size.Y) / t.Size.Y * -1
            );

            return new Tuple<Vector2, Vector2>(uvOne, uvTwo);
        }
    }
}

#region Using

using System;
using System.Numerics;
using Emotion.Graphics;
using Emotion.Graphics.Objects;
using Emotion.Primitives;
using ImGuiNET;

#endregion

namespace Emotion.Plugins.ImGuiNet
{
    public static class ImGuiExtensions
    {
        public static Tuple<Vector2, Vector2> GetImGuiUV(this Texture t, Rectangle? uv = null)
        {
            Rectangle reqUv;
            if (uv == null)
                reqUv = new Rectangle(0, 0, t.Size);
            else
                reqUv = (Rectangle) uv;

            Vector2 uvOne = new Vector2(
                reqUv.X / t.Size.X,
                reqUv.Y / t.Size.Y * -1
            );
            Vector2 uvTwo = new Vector2(
                (reqUv.X + reqUv.Size.X) / t.Size.X,
                (reqUv.Y + reqUv.Size.Y) / t.Size.Y * -1
            );

            return new Tuple<Vector2, Vector2>(uvOne, uvTwo);
        }

        public static void RenderUI(this RenderComposer composer)
        {
            ImGuiNetPlugin.RenderUI(composer);
        }
    }
}

Add util extention for rendering GUI.

feat: Add util extention for rendering GUI.


namespace AngleSharp.Core.Tests.Library
{
    using AngleSharp.Core.Tests.Mocks;
    using AngleSharp.Dom.Html;
    using AngleSharp.Extensions;
    using NUnit.Framework;
    using System;
    using System.Threading.Tasks;

    [TestFixture]
    public class PageImportTests
    {
        [Test]
        public async Task ImportPageFromVirtualRequest()
        {
            var requester = new MockRequester();
            var receivedRequest = new TaskCompletionSource<String>();
            requester.OnRequest = request => receivedRequest.SetResult(request.Address.Href);
            var config = Configuration.Default.WithDefaultLoader(setup => setup.IsResourceLoadingEnabled = true, new[] { requester });

            var document = await BrowsingContext.New(config).OpenAsync(m => m.Content("<!doctype html><link rel=import href=http://example.com/test.html>"));
            var link = document.QuerySelector<IHtmlLinkElement>("link");
            var result = await receivedRequest.Task;

            Assert.AreEqual("import", link.Relation);
            Assert.IsNotNull(link.Import);
            Assert.AreEqual("http://example.com/test.html", result);
        }
    }
}

namespace AngleSharp.Core.Tests.Library
{
    using AngleSharp.Core.Tests.Mocks;
    using AngleSharp.Dom.Html;
    using AngleSharp.Extensions;
    using NUnit.Framework;
    using System;
    using System.Threading.Tasks;

    [TestFixture]
    public class PageImportTests
    {
        [Test]
        public async Task ImportPageFromVirtualRequest()
        {
            var requester = new MockRequester();
            var receivedRequest = new TaskCompletionSource<String>();
            requester.OnRequest = request => receivedRequest.SetResult(request.Address.Href);
            var config = Configuration.Default.WithDefaultLoader(setup => setup.IsResourceLoadingEnabled = true, new[] { requester });

            var document = await BrowsingContext.New(config).OpenAsync(m => m.Content("<!doctype html><link rel=import href=http://example.com/test.html>"));
            var link = document.QuerySelector<IHtmlLinkElement>("link");
            var result = await receivedRequest.Task;

            Assert.AreEqual("import", link.Relation);
            Assert.IsNotNull(link.Import);
            Assert.AreEqual("http://example.com/test.html", result);
        }

        [Test]
        public async Task ImportPageFromDataRequest()
        {
            var receivedRequest = new TaskCompletionSource<Boolean>();
            var config = Configuration.Default.WithDefaultLoader(setup =>
            {
                setup.IsResourceLoadingEnabled = true;
                setup.Filter = request =>
                {
                    receivedRequest.SetResult(true);
                    return true;
                };
            });

            var document = await BrowsingContext.New(config).OpenAsync(m => m.Content("<!doctype html><link rel=import href='data:text/html,
foo
'>"));
            var link = document.QuerySelector<IHtmlLinkElement>("link");
            var finished = await receivedRequest.Task;

            Assert.AreEqual("import", link.Relation);
            Assert.IsNotNull(link.Import);
            Assert.AreEqual("foo", link.Import.QuerySelector("div").TextContent);
        }
    }
}

Test for loading import from data url

Test for loading import from data url


@model PagedList.IPagedList<DynThings.Data.Models.Endpoint>

            Title
            Type
            GUID

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Title)

                @Html.DisplayFor(modelItem => item.EndPointType.Title)

                @Html.DisplayFor(modelItem => item.GUID)

                @Html.ActionLink("Details", "Details", new { id = item.ID })

    }

    <input id="EndPointCurrentPage" value="@Model.PageNumber.ToString()" hidden />

    @Html.PagedListPager(Model, page => Url.Action("ListPV", new { page }))

@model PagedList.IPagedList<DynThings.Data.Models.Endpoint>

            Title
            Type
            Device
            Thing

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Title)

                @Html.DisplayFor(modelItem => item.EndPointType.Title)

                @Html.DisplayFor(modelItem => item.Device.Title)

                @Html.DisplayFor(modelItem => item.Thing.Title)

                @Html.ActionLink("Details", "Details", new { id = item.ID })

    }

    <input id="EndPointCurrentPage" value="@Model.PageNumber.ToString()" hidden />

    @Html.PagedListPager(Model, page => Url.Action("ListPV", new { page }))

Add Device & Thing Titles to Endpoint GridList


using LiteDB;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;

namespace TIKSN.Data.LiteDB
{
    /// <summary>
    ///     Create LiteDB database
    /// </summary>
    public class LiteDbDatabaseProvider : ILiteDbDatabaseProvider
    {
        private readonly IConfigurationRoot _configuration;
        private readonly string _connectionStringKey;
        private readonly IFileProvider _fileProvider;

        public LiteDbDatabaseProvider(IConfigurationRoot configuration, string connectionStringKey,
            IFileProvider fileProvider = null)
        {
            this._configuration = configuration;
            this._connectionStringKey = connectionStringKey;
            this._fileProvider = fileProvider;
        }

        /// <summary>
        ///     Creates LiteDB database with mapper
        /// </summary>
        /// <param name="mapper">Mapper</param>
        /// <returns></returns>
        public LiteDatabase GetDatabase(BsonMapper mapper)
        {
            var connectionString =
                new ConnectionString(this._configuration.GetConnectionString(this._connectionStringKey));

            if (this._fileProvider != null)
            {
                connectionString.Filename = this._fileProvider.GetFileInfo(connectionString.Filename).PhysicalPath;
            }

            return new LiteDatabase(connectionString);
        }

        /// <summary>
        ///     Creates LiteDB database
        /// </summary>
        /// <returns></returns>
        public LiteDatabase GetDatabase() => this.GetDatabase(null);
    }
}

using LiteDB;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;

namespace TIKSN.Data.LiteDB
{
    /// <summary>
    ///     Create LiteDB database
    /// </summary>
    public class LiteDbDatabaseProvider : ILiteDbDatabaseProvider
    {
        private readonly IConfiguration _configuration;
        private readonly string _connectionStringKey;
        private readonly IFileProvider _fileProvider;

        public LiteDbDatabaseProvider(IConfiguration configuration, string connectionStringKey,
            IFileProvider fileProvider = null)
        {
            this._configuration = configuration;
            this._connectionStringKey = connectionStringKey;
            this._fileProvider = fileProvider;
        }

        /// <summary>
        ///     Creates LiteDB database with mapper
        /// </summary>
        /// <param name="mapper">Mapper</param>
        /// <returns></returns>
        public LiteDatabase GetDatabase(BsonMapper mapper)
        {
            var connectionString =
                new ConnectionString(this._configuration.GetConnectionString(this._connectionStringKey));

            if (this._fileProvider != null)
            {
                connectionString.Filename = this._fileProvider.GetFileInfo(connectionString.Filename).PhysicalPath;
            }

            return new LiteDatabase(connectionString);
        }

        /// <summary>
        ///     Creates LiteDB database
        /// </summary>
        /// <returns></returns>
        public LiteDatabase GetDatabase() => this.GetDatabase(null);
    }
}

Use IConfiguration instead of IConfigurationRoot


/*
 * SDB - Mono Soft Debugger Client
 * Copyright 2013 Alex Rønne Petersen
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using System.Collections.Generic;

namespace Mono.Debugger.Client.Commands
{
    sealed class KillCommand : Command
    {
        public override string[] Names
        {
            get { return new[] { "kill", "stop" }; }
        }

        public override string Summary
        {
            get { return "Kill the inferior process."; }
        }

        public override string Syntax
        {
            get { return "kill|stop"; }
        }

        public override void Process(string args)
        {
            if (Debugger.State == State.Exited)
                Log.Error("No inferior process");
            else
                Debugger.Kill();
        }
    }
}

/*
 * SDB - Mono Soft Debugger Client
 * Copyright 2013 Alex Rønne Petersen
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using System.Collections.Generic;

namespace Mono.Debugger.Client.Commands
{
    sealed class KillCommand : Command
    {
        public override string[] Names
        {
            get { return new[] { "kill" }; }
        }

        public override string Summary
        {
            get { return "Kill the inferior process."; }
        }

        public override string Syntax
        {
            get { return "kill|stop"; }
        }

        public override void Process(string args)
        {
            if (Debugger.State == State.Exited)
                Log.Error("No inferior process");
            else
                Debugger.Kill();
        }
    }
}

Remove the silly `stop` alias for `kill`.


using System.Diagnostics;

namespace Cams
{
	public static class VideoConverter
	{
		public static bool CodecCopy(string inputFile, string outputFile)
		{
			return Run($"-y -i {inputFile} -codec copy {outputFile}");
		}

		public static bool Concat(string listFilePath, string outputFile)
		{
			return Run($"-y -safe 0 -f concat -i {listFilePath} -c copy {outputFile}");
		}

		public static bool FastForward(string inputFile, string outputFile)
		{
			return Run($"-y -i {inputFile} -filter:v \"setpts = 0.01 * PTS\" {outputFile}");
		}

		public static bool CheckValidVideoFile(string inputFile)
		{
			return Run($"-v error -i {inputFile} -f null -");
		}

		static bool Run(string args)
		{
			using (var process = new Process
			{
				StartInfo = new ProcessStartInfo
				{
					CreateNoWindow = true,
					FileName = "ffmpeg",
					Arguments = args
				}
			})
			{
				process.Start();
				process.WaitForExit();

				return process.ExitCode == 0;
			}
		}
	}
}

using System.Diagnostics;

namespace Cams
{
	public static class VideoConverter
	{
		public static bool CodecCopy(string inputFile, string outputFile)
		{
			return Run($"-y -i {inputFile} -codec copy {outputFile}");
		}

		public static bool Concat(string listFilePath, string outputFile)
		{
			return Run($"-y -safe 0 -f concat -i {listFilePath} -c copy {outputFile}");
		}

		public static bool FastForward(string inputFile, string outputFile)
		{
			return Run($"-y -i {inputFile} -filter:v \"setpts = 0.01 * PTS\" -an {outputFile}");
		}

		public static bool CheckValidVideoFile(string inputFile)
		{
			return Run($"-v error -i {inputFile} -f null -");
		}

		static bool Run(string args)
		{
			using (var process = new Process
			{
				StartInfo = new ProcessStartInfo
				{
					CreateNoWindow = true,
					FileName = "ffmpeg",
					Arguments = args
				}
			})
			{
				process.Start();
				process.WaitForExit();

				return process.ExitCode == 0;
			}
		}
	}
}

Drop audio in summary videos

Drop audio in summary videos

New Amcrest cameras record audio now


using System;

namespace $safeprojectname$
{
	public class Program
    {
        public static void Main()
        {

        }
    }
}

using System;

namespace $safeprojectname$
{
	public class Program
    {
        public static void Main()
        {
	  // Insert your code below this line

          // The main() method has to end with this infinite loop.
          // Do not use the NETMF style : Thread.Sleep(Timeout.Infinite)
	  while (true)
          {
              Thread.Sleep(200);
          }
        }
    }
}

Update application template with working code to prevent the main thread from exiting


namespace PcscDotNet
{
    public class PcscConnection
    {
        public PcscContext Context { get; private set; }

        public IPcscProvider Provider { get; private set; }

        public string ReaderName { get; private set; }

        public PcscConnection(PcscContext context, string readerName)
        {
            Provider = (Context = context).Provider;
            ReaderName = readerName;
        }
    }
}

using System;

namespace PcscDotNet
{
    public class PcscConnection : IDisposable
    {
        public PcscContext Context { get; private set; }

        public SCardHandle Handle { get; private set; }

        public bool IsConnect => Handle.HasValue;

        public bool IsDisposed { get; private set; } = false;

        public SCardProtocols Protocols { get; private set; } = SCardProtocols.Undefined;

        public IPcscProvider Provider { get; private set; }

        public string ReaderName { get; private set; }

        public PcscConnection(PcscContext context, string readerName)
        {
            Provider = (Context = context).Provider;
            ReaderName = readerName;
        }

        ~PcscConnection()
        {
            Dispose();
        }

        public unsafe PcscConnection Connect(SCardShare shareMode, SCardProtocols protocols, PcscExceptionHandler onException = null)
        {
            SCardHandle handle;
            Provider.SCardConnect(Context.Handle, ReaderName, shareMode, protocols, &handle, &protocols).ThrowIfNotSuccess(onException);
            Handle = handle;
            Protocols = protocols;
            return this;
        }

        public PcscConnection Disconnect(SCardDisposition disposition = SCardDisposition.Leave, PcscExceptionHandler onException = null)
        {
            if (IsDisposed) throw new ObjectDisposedException(nameof(PcscConnection), nameof(Disconnect));
            DisconnectInternal(disposition, onException);
            return this;
        }

        public void Dispose()
        {
            if (IsDisposed) return;
            DisconnectInternal();
            IsDisposed = true;
            GC.SuppressFinalize(this);
        }

        private void DisconnectInternal(SCardDisposition disposition = SCardDisposition.Leave, PcscExceptionHandler onException = null)
        {
            if (!IsConnect) return;
            Provider.SCardDisconnect(Handle, disposition).ThrowIfNotSuccess(onException);
            Handle = SCardHandle.Default;
            Protocols = SCardProtocols.Undefined;
        }
    }
}

Add properties and methods about connection. Implement `IDisposable` interface.


using System;
using System.Collections.Generic;
using Castle.Core;

namespace Orchard.Caching {
    public class DefaultCacheHolder : ICacheHolder {
        private readonly IDictionary<CacheKey, object> _caches = new Dictionary<CacheKey, object>();

        class CacheKey : Pair<Type, Pair<Type, Type>> {
            public CacheKey(Type component, Type key, Type result)
                : base(component, new Pair<Type, Type>(key, result)) {
            }
        }

        public ICache<TKey, TResult> GetCache<TKey, TResult>(Type component) {
            var cacheKey = new CacheKey(component, typeof(TKey), typeof(TResult));
            lock (_caches) {
                object value;
                if (!_caches.TryGetValue(cacheKey, out value)) {
                    value = new Cache<TKey, TResult>();
                    _caches[cacheKey] = value;
                }
                return (ICache<TKey, TResult>)value;
            }
        }
    }
}

using System;
using System.Collections.Concurrent;

namespace Orchard.Caching {
    public class DefaultCacheHolder : ICacheHolder {
        private readonly ConcurrentDictionary<CacheKey, object> _caches = new ConcurrentDictionary<CacheKey, object>();

        class CacheKey : Tuple<Type, Type, Type> {
            public CacheKey(Type component, Type key, Type result)
                : base(component, key, result) {
            }
        }

        public ICache<TKey, TResult> GetCache<TKey, TResult>(Type component) {
            var cacheKey = new CacheKey(component, typeof(TKey), typeof(TResult));
            var result = _caches.GetOrAdd(cacheKey, k => new Cache<TKey, TResult>());
            return (Cache<TKey, TResult>)result;
        }
    }
}

Use ConcurrentDictionary to simplify code

--HG--
branch : dev


using System;
using System.Linq;

namespace Gherkin.AstGenerator
{
    class Program
    {
        static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: Gherkin.AstGenerator.exe test-feature-file.feature");
                return 100;
            }

            var startTime = Environment.TickCount;
            foreach (var featureFilePath in args)
            {
                try
                {
                    var astText = AstGenerator.GenerateAst(featureFilePath);
                    Console.WriteLine(astText);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.Message);
                    return 1;
                }
            }
            var endTime = Environment.TickCount;
            if (Environment.GetEnvironmentVariable("GHERKIN_PERF") != null)
            {
                Console.Error.WriteLine(endTime - startTime);
            }
            return 0;
        }
    }
}

using System;
using System.Linq;

namespace Gherkin.AstGenerator
{
    class Program
    {
        static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: Gherkin.AstGenerator.exe test-feature-file.feature");
                return 100;
            }

            var startTime = Environment.TickCount;
            foreach (var featureFilePath in args)
            {
                try
                {
                    var astText = AstGenerator.GenerateAst(featureFilePath);
                    Console.WriteLine(astText);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return 1;
                }
            }
            var endTime = Environment.TickCount;
            if (Environment.GetEnvironmentVariable("GHERKIN_PERF") != null)
            {
                Console.Error.WriteLine(endTime - startTime);
            }
            return 0;
        }
    }
}

Print to STDOUT - 2> is broken on Mono/OS X


using Content.Client.Utility;
using Robust.Client.Graphics;
using Robust.Client.Interfaces.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.IoC;

namespace Content.Client.UserInterface
{
    /// <summary>
    ///     The status effects display on the right side of the screen.
    /// </summary>
    public sealed class StatusEffectsUI : Control
    {
        private readonly VBoxContainer _vBox;

        private TextureRect _healthStatusRect;

        public StatusEffectsUI()
        {
            _vBox = new VBoxContainer {GrowHorizontal = GrowDirection.Begin};
            AddChild(_vBox);

            _vBox.AddChild(_healthStatusRect = new TextureRect
            {
                Texture = IoCManager.Resolve<IResourceCache>().GetTexture("/Textures/Mob/UI/Human/human0.png")
            });

            SetAnchorAndMarginPreset(LayoutPreset.TopRight);
            MarginTop = 200;
        }

        public void SetHealthIcon(Texture texture)
        {
            _healthStatusRect.Texture = texture;
        }
    }
}

using Content.Client.Utility;
using Robust.Client.Graphics;
using Robust.Client.Interfaces.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.IoC;

namespace Content.Client.UserInterface
{
    /// <summary>
    ///     The status effects display on the right side of the screen.
    /// </summary>
    public sealed class StatusEffectsUI : Control
    {
        private readonly VBoxContainer _vBox;

        private TextureRect _healthStatusRect;

        public StatusEffectsUI()
        {
            _vBox = new VBoxContainer {GrowHorizontal = GrowDirection.Begin};
            AddChild(_vBox);

            _vBox.AddChild(_healthStatusRect = new TextureRect
            {
                TextureScale = (2, 2),
                Texture = IoCManager.Resolve<IResourceCache>().GetTexture("/Textures/Mob/UI/Human/human0.png")
            });

            SetAnchorAndMarginPreset(LayoutPreset.TopRight);
            MarginTop = 200;
            MarginRight = 10;
        }

        public void SetHealthIcon(Texture texture)
        {
            _healthStatusRect.Texture = texture;
        }
    }
}

Make Status Effects UI better positioned.


using System;

namespace RapidCore.Locking
{
    /// <summary>
    /// When implemented in a downstream locker provider, this instance contains a handle to the underlying lock instance
    /// </summary>
    public interface IDistributedAppLock : IDisposable
    {
        /// <summary>
        /// The name of the lock acquired
        /// </summary>
        string Name { get; set; }
    }
}

using System;

namespace RapidCore.Locking
{
    /// <summary>
    /// When implemented in a downstream locker provider, this instance contains a handle to the underlying lock instance
    /// </summary>
    public interface IDistributedAppLock : IDisposable
    {
        /// <summary>
        /// The name of the lock acquired
        /// </summary>
        string Name { get; set; }

        /// <summary>
        /// Determines whether the lock has been taken in the underlying source and is still active
        /// </summary>
        bool IsActive { get; set; }

        /// <summary>
        /// When implemented in a downstream provider it will verify that the current instance of the lock is in an
        /// active (locked) state and has the name given to the method
        /// </summary>
        /// <param name="name"></param>
        /// <exception cref="InvalidOperationException">
        /// When the lock is either not active, or has a different name than provided in <paramref name="name"/>
        /// </exception>
        void ThrowIfNotActiveWithGivenName(string name);
    }
}

Add IsActive and ThrowIfNotActiveWithGivenName to AppLock interface


/* Empiria Extensions ****************************************************************************************
*                                                                                *
*  Module   : Cognitive Services                         Component : Service provider                        *
*  Assembly : Empiria.Cognition.dll                      Pattern   : Data Transfer Objects                   *
*  Type     : TranslatorDataTypes                        License   : Please read LICENSE.txt file            *
*                                                                                *
*  Summary  : Define data types for Microsoft Azure Cognition Translator Services.                           *
*                                                                                *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;

namespace Empiria.Cognition.Providers {
  /// <summary>Summary  : Define data types for Microsoft Azure Cognition Translator Services.</summary>

  internal class Alignment {
    internal string Proj {
      get; set;
    }

  }

  internal class SentenceLength {
    internal int[] SrcSentLen {
      get; set;
    }

    internal int[] TransSentLen {
      get; set;
    }

  }

  internal class Translation {
    internal string Text {
      get; set;
    }

    internal TextResult Transliteration {
      get; set;
    }

    internal string To {
      get; set;
    }

    internal Alignment Alignment {
      get; set;
    }
    internal SentenceLength SentLen {
      get; set;
    }

  }

  internal class DetectedLanguage {
    internal string Language {
      get; set;
    }

    internal float Score {
      get; set;
    }

  }

  internal class TextResult {
    internal string Text {
      get; set;
    }

    internal string Script {
      get; set;
    }

  }

  internal class TranslatorDataTypes {
    internal DetectedLanguage DetectedLanguage {
      get; set;
    }

    internal TextResult SourceText {
      get; set;
    }

    internal Translation[] Translations {
      get; set;
    }

  }

}

/* Empiria Extensions ****************************************************************************************
*                                                                                *
*  Module   : Cognitive Services                         Component : Service provider                        *
*  Assembly : Empiria.Cognition.dll                      Pattern   : Data Transfer Objects                   *
*  Type     : TranslatorDataTypes                        License   : Please read LICENSE.txt file            *
*                                                                                *
*  Summary  : Define data types for Microsoft Azure Cognition Translator Services.                           *
*                                                                                *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
using Newtonsoft.Json;

namespace Empiria.Cognition.Providers {

  internal class Translation {

    [JsonProperty]
    internal string Text {
      get; set;
    }

    [JsonProperty]
    internal string To {
      get; set;
    }

  }

  internal class TranslatorResult {

    [JsonProperty]
    internal Translation[] Translations {
      get; set;
    }

  }

}

Use JsonProperty attribute and remove unused types


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

// [START vision_quickstart]

using Google.Cloud.Vision.V1;
using System;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            var client = ImageAnnotatorClient.Create();
            var image = Image.FromFile("wakeupcat.jpg");
            var response = client.DetectLabels(image);
            foreach (var annotation in response)
            {
                if (annotation.Description != null)
                    Console.WriteLine(annotation.Description);
            }
        }
    }
}
// [END vision_quickstart]

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

// [START vision_quickstart]

using Google.Cloud.Vision.V1;
using System;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            // Instantiates a client
            var client = ImageAnnotatorClient.Create();
            // Load the image file into memory
            var image = Image.FromFile("wakeupcat.jpg");
            // Performs label detection on the image file
            var response = client.DetectLabels(image);
            foreach (var annotation in response)
            {
                if (annotation.Description != null)
                    Console.WriteLine(annotation.Description);
            }
        }
    }
}
// [END vision_quickstart]

Add comments to vision quickstart.

Add comments to vision quickstart.


using TAP;
using System;
using System.Net;

public class TAPCfgTest {
	private static void Main(string[] args) {
		EthernetDevice dev = new EthernetDevice();
		dev.Start("Device name");
		Console.WriteLine("Got device name: {0}", dev.DeviceName);
		dev.MTU = 1280;
		dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16);
		dev.SetAddress(IPAddress.Parse("fc00::1"), 64);
		dev.Enabled = true;

		while (true) {
			EthernetFrame frame = dev.Read();
			if (frame == null)
				break;

			if (frame.EtherType == EtherType.IPv6) {
				IPv6Packet packet = new IPv6Packet(frame.Payload);
				if (packet.NextHeader == ProtocolType.ICMPv6) {
					ICMPv6Type type = (ICMPv6Type) packet.Payload[0];
					Console.WriteLine("Got ICMPv6 packet type {0}", type);
					Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload));
				}
			}

			Console.WriteLine("Read Ethernet frame of type {0}",
			                  frame.EtherType);
			Console.WriteLine("Source address: {0}",
			                  BitConverter.ToString(frame.SourceAddress));
			Console.WriteLine("Destination address: {0}",
			                  BitConverter.ToString(frame.DestinationAddress));
		}
	}
}

using TAP;
using System;
using System.Net;

public class TAPCfgTest {
	private static void Main(string[] args) {
		EthernetDevice dev = new EthernetDevice();
		dev.Start("Device name");
		Console.WriteLine("Got device name: {0}", dev.DeviceName);
		dev.MTU = 1280;
		dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16);
		dev.SetAddress(IPAddress.Parse("fc00::1"), 64);
		dev.Enabled = true;

		while (true) {
			EthernetFrame frame = dev.Read();
			if (frame == null)
				break;

			if (frame.EtherType == EtherType.IPv6) {
				IPv6Packet packet = new IPv6Packet(frame.Payload);
				if (packet.NextHeader == ProtocolType.ICMPv6) {
					ICMPv6Type type = (ICMPv6Type) packet.Payload[0];
					Console.WriteLine("Got ICMPv6 packet type {0}", type);
					Console.WriteLine("Src: {0}", packet.Source);
					Console.WriteLine("Dst: {0}", packet.Destination);
					Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload));
				}
			}

			Console.WriteLine("Read Ethernet frame of type {0}",
			                  frame.EtherType);
			Console.WriteLine("Source address: {0}",
			                  BitConverter.ToString(frame.SourceAddress));
			Console.WriteLine("Destination address: {0}",
			                  BitConverter.ToString(frame.DestinationAddress));
		}
	}
}

Print source and destination addresses on ICMPv6 packets

git-svn-id: 8d82213adbbc6b1538a984bace977d31fcb31691@115 2f5d681c-ba19-11dd-a503-ed2d4bea8bb5


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

namespace apod_api
{
    public sealed class APOD_API
    {
        public APOD_API()
        {
            date = DateTime.Today;
        }
        public void sendRequest()
        {
            generateURL();
            WebRequest request = WebRequest.Create(api_url);
            api_response = request.GetResponse();
            Stream responseStream = api_response.GetResponseStream();
            sr = new StreamReader(responseStream);
            myAPOD = JsonConvert.DeserializeObject<APOD>(sr.ReadToEnd());

            sr.Close();
            responseStream.Close();
            api_response.Close();
        }
        public APOD_API setDate(DateTime newDate)
        {
            date = newDate;

            return this;
        }
        private void generateURL()
        {
            api_url = api + "?api_key=" + api_key + "&date=" + date.ToString("yyyy-MM-dd");
        }
        private string api_key = "DEMO_KEY";
        private string api = "https://api.nasa.gov/planetary/apod";
        private string api_url;
        private DateTime date;
        private WebResponse api_response;
        private StreamReader sr;
        private APOD myAPOD;
        public APOD apod { get { return myAPOD; } }
    }
}

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

namespace apod_api
{
    public sealed class APOD_API
    {
        public APOD_API()
        {
            date = DateTime.Today;
        }
        public void sendRequest()
        {
            generateURL();
            WebRequest request = WebRequest.Create(api_url);
            api_response = request.GetResponse();
            Stream responseStream = api_response.GetResponseStream();
            sr = new StreamReader(responseStream);
            myAPOD = JsonConvert.DeserializeObject<APOD>(sr.ReadToEnd());

            sr.Dispose();
            responseStream.Dispose();
            api_response.Dispose();
        }
        public APOD_API setDate(DateTime newDate)
        {
            date = newDate;

            return this;
        }
        private void generateURL()
        {
            api_url = api + "?api_key=" + api_key + "&date=" + date.ToString("yyyy-MM-dd");
        }
        private string api_key = "DEMO_KEY";
        private string api = "https://api.nasa.gov/planetary/apod";
        private string api_url;
        private DateTime date;
        private WebResponse api_response;
        private StreamReader sr;
        private APOD myAPOD;
        public APOD apod { get { return myAPOD; } }
    }
}

Switch to .Dispose() from .Close().

Switch to .Dispose() from .Close().


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

public class SoundSpawn : MonoBehaviour
{
	public AudioSource audioSource;
	//We need to handle this manually to prevent multiple requests grabbing sound pool items in the same frame
	public bool isPlaying = false;
	private float waitLead = 0;

	public void PlayOneShot()
	{
		audioSource.PlayOneShot(audioSource.clip);
		WaitForPlayToFinish();
	}

	public void PlayNormally()
	{
		audioSource.Play();
		WaitForPlayToFinish();
	}

	void WaitForPlayToFinish()
	{
		waitLead = 0f;
		UpdateManager.Add(CallbackType.UPDATE, UpdateMe);
	}

	void UpdateMe()
	{
		waitLead += Time.deltaTime;
		if (waitLead > 0.2f)
		{
			if (!audioSource.isPlaying)
			{
				UpdateManager.Remove(CallbackType.UPDATE, UpdateMe);
				isPlaying = false;
				waitLead = 0f;
			}
		}
	}
}

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

public class SoundSpawn : MonoBehaviour
{
	public AudioSource audioSource;
	//We need to handle this manually to prevent multiple requests grabbing sound pool items in the same frame
	public bool isPlaying = false;
	private float waitLead = 0;

	public void PlayOneShot()
	{
		audioSource.PlayOneShot(audioSource.clip);
		WaitForPlayToFinish();
	}

	public void PlayNormally()
	{
		audioSource.Play();
		WaitForPlayToFinish();
	}

	void WaitForPlayToFinish()
	{
		waitLead = 0f;
		UpdateManager.Add(CallbackType.UPDATE, UpdateMe);
	}

	private void OnDisable()
	{
		if(isPlaying)
		{
			UpdateManager.Remove(CallbackType.UPDATE, UpdateMe);
			isPlaying = false;
		}
	}

	void UpdateMe()
	{
		waitLead += Time.deltaTime;
		if (waitLead > 0.2f)
		{
			if (!audioSource.isPlaying)
			{
				UpdateManager.Remove(CallbackType.UPDATE, UpdateMe);
				isPlaying = false;
				waitLead = 0f;
			}
		}
	}
}

Fix UpdateManager NRE for soundspawn

Fix UpdateManager NRE for soundspawn


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

using Topshelf;

namespace MassTransit.Host.RabbitMQ
{
	/// <summary>
	/// Entry point of the host process used to construct the Topshelf service.
	/// </summary>
	class Program
	{
		static void Main(string[] args)
		{
			HostFactory.Run(x =>
			{
				x.Service<ServiceHost>(s =>
				{
					s.ConstructUsing(name => new ServiceHost());
					s.WhenStarted(tc => tc.Start());
					s.WhenStopped(tc => tc.Stop());
				});
				x.RunAsLocalSystem();

				x.SetDescription("MassTransit RabbitMQ Service Bus Host");
				x.SetDisplayName("MassTransitServiceBusHost");
				x.SetServiceName("MassTransitServiceBusHost");
			});

			//TODO: extra parameter stuff

		}
	}
}

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

using System;
using Magnum.Extensions;
using Topshelf;

namespace MassTransit.Host.RabbitMQ
{
	/// <summary>
	/// Entry point of the host process used to construct the Topshelf service.
	/// </summary>
	class Program
	{
		static void Main(string[] args)
		{
			var exitCode = HostFactory.Run(x =>
			{
				x.Service<ServiceHost>(s =>
				{
					s.ConstructUsing(name => new ServiceHost());
					s.WhenStarted(tc => tc.Start());
					s.WhenStopped(tc => tc.Stop());
				});
				x.RunAsLocalSystem();

				x.SetDescription("MassTransit RabbitMQ Service Bus Host");
				x.SetDisplayName("MassTransitServiceBusHost");
				x.SetServiceName("MassTransitServiceBusHost");
			});
			//TODO: extra parameter stuff

			Environment.Exit((int)exitCode);
		}
	}
}

Add exit code to console app; return HostFactory.Run result


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

using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Game.Configuration;

namespace osu.Desktop.Windows
{
    public class GameplayWinKeyBlocker : Component
    {
        private Bindable<bool> allowScreenSuspension;
        private Bindable<bool> disableWinKey;

        private GameHost host;

        [BackgroundDependencyLoader]
        private void load(GameHost host, OsuConfigManager config)
        {
            this.host = host;

            allowScreenSuspension = host.AllowScreenSuspension.GetBoundCopy();
            allowScreenSuspension.BindValueChanged(_ => updateBlocking());

            disableWinKey = config.GetBindable<bool>(OsuSetting.GameplayDisableWinKey);
            disableWinKey.BindValueChanged(_ => updateBlocking(), true);
        }

        private void updateBlocking()
        {
            bool shouldDisable = disableWinKey.Value && !allowScreenSuspension.Value;

            if (shouldDisable)
                host.InputThread.Scheduler.Add(WindowsKey.Disable);
            else
                host.InputThread.Scheduler.Add(WindowsKey.Enable);
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Game;
using osu.Game.Configuration;

namespace osu.Desktop.Windows
{
    public class GameplayWinKeyBlocker : Component
    {
        private Bindable<bool> disableWinKey;
        private Bindable<bool> localUserPlaying;

        [Resolved]
        private GameHost host { get; set; }

        [BackgroundDependencyLoader(true)]
        private void load(OsuGame game, OsuConfigManager config)
        {
            localUserPlaying = game.LocalUserPlaying.GetBoundCopy();
            localUserPlaying.BindValueChanged(_ => updateBlocking());

            disableWinKey = config.GetBindable<bool>(OsuSetting.GameplayDisableWinKey);
            disableWinKey.BindValueChanged(_ => updateBlocking(), true);
        }

        private void updateBlocking()
        {
            bool shouldDisable = disableWinKey.Value && localUserPlaying.Value;

            if (shouldDisable)
                host.InputThread.Scheduler.Add(WindowsKey.Disable);
            else
                host.InputThread.Scheduler.Add(WindowsKey.Enable);
        }
    }
}

Fix windows key blocking applying when window is inactive / when watching a replay

Closes #10467.


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

namespace Eco.Variables
{
    public class PublicIpVariable : IVariableProvider
    {
        string _lastIp;
        DateTime _lastUpdate;

        public Dictionary<string, Func<string>> GetVariables()
        {
            var now = DateTime.Now;
            if (now -  _lastUpdate > TimeSpan.FromMinutes(1))
            {
                _lastIp = new WebClient().DownloadString("http://icanhazip.com").Trim();
                _lastUpdate = now;
            }
            return new Dictionary<string, Func<string>>()
            {
                { "publicIp", () => _lastIp }
            };
        }
    }
}

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

namespace Eco.Variables
{
    public class PublicIpVariable : IVariableProvider
    {
        string _lastIp;
        DateTime _lastUpdate;

        public Dictionary<string, Func<string>> GetVariables()
        {
            Func<string> getIp = () =>
            {
                var now = DateTime.Now;
                if (now - _lastUpdate > TimeSpan.FromMinutes(1))
                {
                    _lastIp = new WebClient().DownloadString("http://icanhazip.com").Trim();
                    _lastUpdate = now;
                }
                return _lastIp;
            };
            return new Dictionary<string, Func<string>>()
            {

                { "publicIp", getIp }
            };
        }
    }
}

Make PublicIp variable lazy again.

Make PublicIp variable lazy again.


using System.IO;
using Xunit;

namespace TfsHipChat.Tests
{
    public class TfsIdentityTests
    {
        [Fact]
        public void Url_ShouldReturnTheServerUrl_WhenDeserializedByValidXml()
        {
            const string serverUrl = "http://some-tfs-server.com";
            const string tfsIdentityXml = "<TeamFoundationServer url=\"" + serverUrl + "\" />";
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof (TfsIdentity));
            string url = null;

            using (var reader = new StringReader(tfsIdentityXml))
            {
                var tfsIdentity = serializer.Deserialize(reader) as TfsIdentity;
                if (tfsIdentity != null) url = tfsIdentity.Url;
            }

            Assert.Equal(url, serverUrl);
        }
    }
}

using System.IO;
using Xunit;

namespace TfsHipChat.Tests
{
    public class TfsIdentityTests
    {
        [Fact]
        public void Url_ShouldReturnTheServerUrl_WhenDeserializedUsingValidXml()
        {
            const string serverUrl = "http://some-tfs-server.com";
            const string tfsIdentityXml = "<TeamFoundationServer url=\"" + serverUrl + "\" />";
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof (TfsIdentity));
            string url = null;

            using (var reader = new StringReader(tfsIdentityXml))
            {
                var tfsIdentity = serializer.Deserialize(reader) as TfsIdentity;
                if (tfsIdentity != null) url = tfsIdentity.Url;
            }

            Assert.Equal(url, serverUrl);
        }
    }
}

Fix grammar in test name

Fix grammar in test name


namespace LoadTests
{
    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.Threading.Tasks;
    using EasyConsole;
    using SqlStreamStore.Streams;

    public class ReadAll : LoadTest
    {
        protected override async Task RunAsync(CancellationToken ct)
        {
            Output.WriteLine("");
            Output.WriteLine(ConsoleColor.Green, "Appends events to streams and reads them all back in a single task.");
            Output.WriteLine("");

            var streamStore = GetStore();

            await new AppendExpectedVersionAnyParallel()
                .Append(streamStore, ct);

            int readPageSize = Input.ReadInt("Read page size: ", 1, 10000);

            var stopwatch = Stopwatch.StartNew();
            int count = 0;
            var position = Position.Start;
            ReadAllPage page;
            do
            {
                page = await streamStore.ReadAllForwards(position, readPageSize, cancellationToken: ct);
                count += page.Messages.Length;
                Console.Write($"\r> Read {count}");
                position = page.NextPosition;
            } while (!page.IsEnd);

            stopwatch.Stop();
            var rate = Math.Round((decimal)count / stopwatch.ElapsedMilliseconds * 1000, 0);

            Output.WriteLine("");
            Output.WriteLine($"> {count} messages read in {stopwatch.Elapsed} ({rate} m/s)");
        }
    }
}

namespace LoadTests
{
    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.Threading.Tasks;
    using EasyConsole;
    using SqlStreamStore.Streams;

    public class ReadAll : LoadTest
    {
        protected override async Task RunAsync(CancellationToken ct)
        {
            Output.WriteLine("");
            Output.WriteLine(ConsoleColor.Green, "Appends events to streams and reads them all back in a single task.");
            Output.WriteLine("");

            var streamStore = GetStore();

            await new AppendExpectedVersionAnyParallel()
                .Append(streamStore, ct);

            int readPageSize = Input.ReadInt("Read page size: ", 1, 10000);
            var prefectch = Input.ReadEnum<YesNo>("Prefetch: ");

            var stopwatch = Stopwatch.StartNew();
            int count = 0;
            var position = Position.Start;
            ReadAllPage page;
            do
            {
                page = await streamStore.ReadAllForwards(position, readPageSize, prefetchJsonData: prefectch == YesNo.Yes, cancellationToken: ct);
                count += page.Messages.Length;
                Console.Write($"\r> Read {count}");
                position = page.NextPosition;
            } while (!page.IsEnd);

            stopwatch.Stop();
            var rate = Math.Round((decimal)count / stopwatch.ElapsedMilliseconds * 1000, 0);

            Output.WriteLine("");
            Output.WriteLine($"> {count} messages read in {stopwatch.Elapsed} ({rate} m/s)");
        }

        private enum YesNo
        {
            Yes,
            No
        }
    }
}

Add option to enable prefetch or not.

Add option to enable prefetch or not.


using System;
using System.Threading.Tasks;
using static System.Console;

namespace AsyncLambda
{
    class Program
    {
        static async Task Main()
        {
            WriteLine("Started");
            try
            {
                Process(async () =>
                {
                    await Task.Delay(500);
                    throw new Exception();
                });
            }
            catch (Exception)
            {
                WriteLine("Catch");
            }

            await Task.Delay(2000);
            WriteLine("Finished");
        }

        private static void Process(Action action)
        {
            action();
        }

        private static void Process(Func<Task> action)
        {
            action();
        }
    }
}

using System;
using System.Threading.Tasks;
using static System.Console;

namespace AsyncLambda
{
    class Program
    {
        static async Task Main()
        {
            WriteLine("Started");
            try
            {
                Process(async () =>
                {
                    await Task.Delay(500);
                    throw new Exception();
                });
            }
            catch (Exception)
            {
                WriteLine("Catch");
            }

            await Task.Delay(2000);
            WriteLine("Finished");
        }

        private static void Process(Action action)
        {
            action();
        }

//        private static void Process(Func<Task> action)
//        {
//            action();
//        }
    }
}

Comment code according to presentation's flow


// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using Avalonia.Visuals.Media.Imaging;

namespace Avalonia.Media
{
    public class RenderOptions
    {
        /// <summary>
        /// Defines the <see cref="BitmapInterpolationMode"/> property.
        /// </summary>
        public static readonly StyledProperty<BitmapInterpolationMode> BitmapInterpolationModeProperty =
            AvaloniaProperty.RegisterAttached<RenderOptions, AvaloniaObject, BitmapInterpolationMode>(
                "BitmapInterpolationMode",
                BitmapInterpolationMode.HighQuality,
                inherits: true);

        /// <summary>
        /// Gets the value of the BitmapInterpolationMode attached property for a control.
        /// </summary>
        /// <param name="element">The control.</param>
        /// <returns>The control's left coordinate.</returns>
        public static BitmapInterpolationMode GetBitmapInterpolationMode(AvaloniaObject element)
        {
            return element.GetValue(BitmapInterpolationModeProperty);
        }

        /// <summary>
        /// Sets the value of the BitmapInterpolationMode attached property for a control.
        /// </summary>
        /// <param name="element">The control.</param>
        /// <param name="value">The left value.</param>
        public static void SetBitmapInterpolationMode(AvaloniaObject element, BitmapInterpolationMode value)
        {
            element.SetValue(BitmapInterpolationModeProperty, value);
        }
    }
}

// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using Avalonia.Visuals.Media.Imaging;

namespace Avalonia.Media
{
    public class RenderOptions
    {
        /// <summary>
        /// Defines the <see cref="BitmapInterpolationMode"/> property.
        /// </summary>
        public static readonly StyledProperty<BitmapInterpolationMode> BitmapInterpolationModeProperty =
            AvaloniaProperty.RegisterAttached<RenderOptions, AvaloniaObject, BitmapInterpolationMode>(
                "BitmapInterpolationMode",
                BitmapInterpolationMode.MediumQuality,
                inherits: true);

        /// <summary>
        /// Gets the value of the BitmapInterpolationMode attached property for a control.
        /// </summary>
        /// <param name="element">The control.</param>
        /// <returns>The control's left coordinate.</returns>
        public static BitmapInterpolationMode GetBitmapInterpolationMode(AvaloniaObject element)
        {
            return element.GetValue(BitmapInterpolationModeProperty);
        }

        /// <summary>
        /// Sets the value of the BitmapInterpolationMode attached property for a control.
        /// </summary>
        /// <param name="element">The control.</param>
        /// <param name="value">The left value.</param>
        public static void SetBitmapInterpolationMode(AvaloniaObject element, BitmapInterpolationMode value)
        {
            element.SetValue(BitmapInterpolationModeProperty, value);
        }
    }
}

Set default render quality to medium

Set default render quality to medium


using System.Drawing;
using System.Windows;

namespace NetSparkle.TestAppWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Sparkle _sparkle;

        public MainWindow()
        {
            InitializeComponent();

            // remove the netsparkle key from registry
            try
            {
                Microsoft.Win32.Registry.CurrentUser.DeleteSubKeyTree("Software\\Microsoft\\NetSparkle.TestAppWPF");
            }
            catch { }

            _sparkle = new Sparkle("https://deadpikle.github.io/NetSparkle/files/sample-app/appcast.xml", SystemIcons.Application); //, "NetSparkleTestApp.exe");
            _sparkle.RunningFromWPF = true;
            _sparkle.CloseWPFWindow += _sparkle_CloseWPFWindow;
            _sparkle.StartLoop(true, true);
        }

        private void _sparkle_CloseWPFWindow()
        {
            Dispatcher.Invoke(() => {
                Application.Current.Shutdown();
            });
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            _sparkle.CheckForUpdatesAtUserRequest();
           // _sparkle.StopLoop();
          //  Close();
        }
    }
}

using System.Drawing;
using System.Windows;

namespace NetSparkle.TestAppWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Sparkle _sparkle;

        public MainWindow()
        {
            InitializeComponent();

            // remove the netsparkle key from registry
            try
            {
                Microsoft.Win32.Registry.CurrentUser.DeleteSubKeyTree("Software\\Microsoft\\NetSparkle.TestAppWPF");
            }
            catch { }

            _sparkle = new Sparkle("https://deadpikle.github.io/NetSparkle/files/sample-app/appcast.xml", SystemIcons.Application); //, "NetSparkleTestApp.exe");
            _sparkle.RunningFromWPF = true;
            _sparkle.StartLoop(true, true);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            _sparkle.CheckForUpdatesAtUserRequest();
           // _sparkle.StopLoop();
          //  Close();
        }
    }
}

Remove unnecessary event callback in WPF demo


using System;

namespace AutoQueryable.Models.Enums
{
    [Flags]
    public enum ClauseType : short
    {
        Select = 1 << 1,
        Top = 1 << 2,
        Take = 1 << 3,
        Skip = 1 << 4,
        OrderBy = 1 << 5,
        OrderByDesc = 1 << 6,
        Include = 1 << 7,
        GroupBy = 1 << 8,
        First = 1 << 9,
        Last = 1 << 10,
        WrapWith = 1 << 11
    }
}

using System;

namespace AutoQueryable.Models.Enums
{
    [Flags]
    public enum ClauseType : short
    {
        Select = 1 << 1,
        Top = 1 << 2,
        Take = 1 << 3,
        Skip = 1 << 4,
        OrderBy = 1 << 5,
        OrderByDesc = 1 << 6,
        GroupBy = 1 << 8,
        First = 1 << 9,
        Last = 1 << 10,
        WrapWith = 1 << 11
    }
}

Remove Include from clause types.

Remove Include from clause types.


using System.Windows.Input;

namespace DesktopWidgets.Events
{
    internal class WidgetMouseDownEvent : WidgetEventBase
    {
        public MouseButton MouseButton { get; set; }
    }
}

using System.ComponentModel;
using System.Windows.Input;

namespace DesktopWidgets.Events
{
    internal class WidgetMouseDownEvent : WidgetEventBase
    {
        [DisplayName("Mouse Button")]
        public MouseButton MouseButton { get; set; }
    }
}

Fix "Widget Mouse Down" event property friendly names


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

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("Xamarin.Social")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin, Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012 Xamarin, Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

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

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

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

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("Xamarin.Social")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012-2013 Xamarin Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

[assembly: AssemblyVersion("1.0.2.0")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

Fix version and update copyright

Fix version and update copyright


using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;

namespace Example_Drawing
{
	[Register("AppDelegate")]
	public class AppDelegate : UIApplicationDelegate
	{
		#region -= declarations and properties =-

		protected UIWindow window;
		protected UINavigationController mainNavController;
		protected Example_Drawing.Screens.iPad.Home.HomeScreen iPadHome;

		#endregion

		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			// create our window
			window = new UIWindow (UIScreen.MainScreen.Bounds);
			window.MakeKeyAndVisible ();

			// instantiate our main navigatin controller and add it's view to the window
			mainNavController = new UINavigationController ();

			iPadHome = new Example_Drawing.Screens.iPad.Home.HomeScreen ();
			mainNavController.PushViewController (iPadHome, false);

			window.RootViewController = mainNavController;

			//
			return true;
		}
	}
}

using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;

namespace Example_Drawing
{
	[Register("AppDelegate")]
	public class AppDelegate : UIApplicationDelegate
	{
		#region -= declarations and properties =-

		protected UIWindow window;
		protected UINavigationController mainNavController;
		protected Example_Drawing.Screens.iPad.Home.HomeScreen iPadHome;

		#endregion

		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			// create our window
			window = new UIWindow (UIScreen.MainScreen.Bounds);
			window.MakeKeyAndVisible ();

			// instantiate our main navigatin controller and add it's view to the window
			mainNavController = new UINavigationController ();
			mainNavController.NavigationBar.Translucent = false;

			iPadHome = new Example_Drawing.Screens.iPad.Home.HomeScreen ();
			mainNavController.PushViewController (iPadHome, false);

			window.RootViewController = mainNavController;

			//
			return true;
		}
	}
}

[Drawing] Set navigation bar translucent to false to fix views overlapping. Fix bug [14631]


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SGEnviro;

namespace SGEnviroTest
{
    [TestClass]
    public class ApiTest
    {
        private string apiKey;

        [TestInitialize]
        public void TestInitialize()
        {
            apiKey = ConfigurationManager.AppSettings["ApiKey"];
        }

        [TestMethod]
        public void TestApiCanRetrieve()
        {
            var api = new SGEnviroApi(apiKey);
            var result = api.GetPsiUpdateAsync().Result;
            Assert.IsNotNull(result);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SGEnviro;

namespace SGEnviroTest
{
    [TestClass]
    public class ApiTest
    {
        private string apiKey;

        [TestInitialize]
        public void TestInitialize()
        {
            apiKey = ConfigurationManager.AppSettings["ApiKey"];
        }

        [TestMethod]
        public async Task TestApiCanRetrieve()
        {
            var api = new SGEnviroApi(apiKey);
            var result = await api.GetPsiUpdateAsync();
            Assert.IsNotNull(result);
        }
    }
}

Fix incorrectly implemented async test.

Fix incorrectly implemented async test.


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

[assembly: AssemblyTitle("RestKit")]
[assembly: AssemblyDescription("SIMPLE http client wrapper that eliminates the boilerplate code you don't want to write.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RestKit")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("de3a6223-af0a-4583-bdfb-63957829e7ba")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
[assembly: CLSCompliant(true)]

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

[assembly: AssemblyTitle("RestKit")]
[assembly: AssemblyDescription("SIMPLE http client wrapper that eliminates the boilerplate code you don't want to write.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RestKit")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("de3a6223-af0a-4583-bdfb-63957829e7ba")]
[assembly: AssemblyVersion("1.1.0.1")]
[assembly: AssemblyFileVersion("1.1.0.1")]
[assembly: CLSCompliant(true)]

Increment minor version - breaking changes.


using CommandLine;

namespace ProcessGremlinApp
{
    public class ArgumentParser
    {
        public bool TryParse(string[] args, out Arguments arguments)
        {
            string invokedVerb = null;
            object invokedVerbInstance = null;

            var options = new Options();
            if (Parser.Default.ParseArguments(
                args,
                options,
                (verb, subOptions) =>
                {
                    invokedVerb = verb;
                    invokedVerbInstance = subOptions;
                }) && invokedVerbInstance is CommonOptions)
            {
                arguments = new Arguments(invokedVerb, invokedVerbInstance);
                return true;
            }

            arguments = null;
            return false;
        }
    }
}

using CommandLine;

namespace ProcessGremlinApp
{
    public class ArgumentParser
    {
        public bool TryParse(string[] args, out Arguments arguments)
        {
            if (args != null && args.Length != 0)
            {
                string invokedVerb = null;
                object invokedVerbInstance = null;

                var options = new Options();
                if (Parser.Default.ParseArguments(
                    args,
                    options,
                    (verb, subOptions) =>
                    {
                        invokedVerb = verb;
                        invokedVerbInstance = subOptions;
                    }) && invokedVerbInstance is CommonOptions)
                {
                    arguments = new Arguments(invokedVerb, invokedVerbInstance);
                    return true;
                }
            }

            arguments = null;
            return false;
        }
    }
}

Fix crashing in the case of empty args

Fix crashing in the case of empty args


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

namespace AppHarbor
{
	class Program
	{
		static void Main(string[] args)
		{
			var container = new WindsorContainer()
				.Install(new AppHarborInstaller());

			var commandDispatcher = container.Resolve<CommandDispatcher>();

			if (args.Any())
			{
				commandDispatcher.Dispatch(args);
			}
		}
	}
}

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

namespace AppHarbor
{
	class Program
	{
		static void Main(string[] args)
		{
			var container = new WindsorContainer()
				.Install(new AppHarborInstaller());

			var commandDispatcher = container.Resolve<CommandDispatcher>();

			if (args.Any())
			{
				commandDispatcher.Dispatch(args);
			}

			Console.WriteLine("Usage: appharbor COMMAND [command-options]");
			Console.WriteLine("");
		}
	}
}

Write usage information if no parameters are specified


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("Lurking Window Detector")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lurking Window Detector")]
[assembly: AssemblyCopyright("Copyright (c) 2016 KAMADA Ken'ichi")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("700adee8-5d49-40f3-a3ae-05dc23501663")]

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

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lurking Window Detector")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lurking Window Detector")]
[assembly: AssemblyCopyright("Copyright (c) 2016 KAMADA Ken'ichi")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("700adee8-5d49-40f3-a3ae-05dc23501663")]

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

Increment the version to 1.1.

Increment the version to 1.1.


namespace Parsley;

partial class Grammar
{
    public static Parser<string> Keyword(string word)
    {
        if (word.Any(ch => !char.IsLetter(ch)))
            throw new ArgumentException("Keywords may only contain letters.", nameof(word));

        return input =>
        {
            var peek = input.Peek(word.Length + 1);

            if (peek.StartsWith(word, StringComparison.Ordinal))
            {
                if (peek.Length == word.Length || !char.IsLetter(peek[^1]))
                {
                    input.Advance(word.Length);

                    return new Parsed<string>(word, input.Position);
                }
            }

            return new Error<string>(input.Position, ErrorMessage.Expected(word));
        };
    }
}

namespace Parsley;

partial class Grammar
{
    public static Parser<string> Keyword(string word)
    {
        if (word.Any(ch => !char.IsLetter(ch)))
            throw new ArgumentException("Keywords may only contain letters.", nameof(word));

        return input =>
        {
            var peek = input.Peek(word.Length + 1);

            if (peek.StartsWith(word))
            {
                if (peek.Length == word.Length || !char.IsLetter(peek[^1]))
                {
                    input.Advance(word.Length);

                    return new Parsed<string>(word, input.Position);
                }
            }

            return new Error<string>(input.Position, ErrorMessage.Expected(word));
        };
    }
}

Remove superfluous StringComparison.Ordinal argument from ReadOnlySpan<char>.StarstWith(...) call, since the overload without a StringComparison in fact performs ordinal comparison semantics and the original call ultimately calls into the overload with no StringComparison argument anyway. In other words, you only have to specify StringComparison for span StartsWith calls when you are NOT using ordinal comparisons.


using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using Windows.ApplicationModel;

namespace EarTrumpet.Extensions
{
    public static class AppExtensions
    {
        public static Version GetVersion(this Application app)
        {
            if (HasIdentity(app))
            {
                var packageVer = Package.Current.Id.Version;
                return new Version(packageVer.Major, packageVer.Minor, packageVer.Build, packageVer.Revision);
            }
            else
            {
#if DEBUG
                var versionStr = new StreamReader(Application.GetResourceStream(new Uri("pack://application:,,,/EarTrumpet;component/Assets/DevVersion.txt")).Stream).ReadToEnd();
                return Version.Parse(versionStr);
#else
                return new Version(0, 0, 0, 0);
#endif
            }
        }

        static bool? _hasIdentity = null;
        public static bool HasIdentity(this Application app)
        {
#if VSDEBUG
            if (Debugger.IsAttached)
            {
                return false;
            }
#endif

            if (_hasIdentity == null)
            {
                try
                {
                    _hasIdentity = (Package.Current.Id != null);
                }
                catch (InvalidOperationException ex)
                {
#if !DEBUG
                    // We do not expect this to occur in production when the app is packaged.
                    AppTrace.LogWarning(ex);
#else
                    Trace.WriteLine($"AppExtensions HasIdentity: False {ex.Message}");
#endif
                    _hasIdentity = false;
                }
            }

            return (bool)_hasIdentity;
        }
    }
}

using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using Windows.ApplicationModel;
using EarTrumpet.Diagnosis;

namespace EarTrumpet.Extensions
{
    public static class AppExtensions
    {
        public static Version GetVersion(this Application app)
        {
            if (HasIdentity(app))
            {
                var packageVer = Package.Current.Id.Version;
                return new Version(packageVer.Major, packageVer.Minor, packageVer.Build, packageVer.Revision);
            }
            else
            {
#if DEBUG
                var versionStr = new StreamReader(Application.GetResourceStream(new Uri("pack://application:,,,/EarTrumpet;component/Assets/DevVersion.txt")).Stream).ReadToEnd();
                return Version.Parse(versionStr);
#else
                return new Version(0, 0, 0, 0);
#endif
            }
        }

        static bool? _hasIdentity = null;
        public static bool HasIdentity(this Application app)
        {
#if VSDEBUG
            if (Debugger.IsAttached)
            {
                return false;
            }
#endif

            if (_hasIdentity == null)
            {
                try
                {
                    _hasIdentity = (Package.Current.Id != null);
                }
                catch (InvalidOperationException ex)
                {
#if !DEBUG
                    // We do not expect this to occur in production when the app is packaged.
                    ErrorReporter.LogWarning(ex);
#else
                    Trace.WriteLine($"AppExtensions HasIdentity: False {ex.Message}");
#endif
                    _hasIdentity = false;
                }
            }

            return (bool)_hasIdentity;
        }
    }
}

Clean up lingering AppTrace reference

Clean up lingering AppTrace reference