// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
//   https://www.imagemagick.org/script/license.php
//
// 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.Drawing;
using ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Magick.NET.SystemDrawing.Tests
{
    public partial class MagickImageFactoryTests
    {
        public partial class TheCreateMethod
        {
            [TestMethod]
            public void ShouldCreateImageFromBitmap()
            {
                using (var bitmap = new Bitmap(Files.SnakewarePNG))
                {
                    var factory = new MagickImageFactory();
                    using (var image = factory.Create(bitmap))
                    {
                        Assert.AreEqual(286, image.Width);
                        Assert.AreEqual(67, image.Height);
                        Assert.AreEqual(MagickFormat.Png, image.Format);
                    }
                }
            }
        }
    }
}

// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
//   https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.

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

namespace Magick.NET.SystemDrawing.Tests
{
    public partial class MagickImageFactoryTests
    {
        [TestClass]
        public partial class TheCreateMethod
        {
            [TestMethod]
            public void ShouldThrowExceptionWhenBitmapIsNull()
            {
                var factory = new MagickImageFactory();
                ExceptionAssert.Throws<ArgumentNullException>("bitmap", () => factory.Create((Bitmap)null));
            }

            [TestMethod]
            public void ShouldCreateImageFromBitmap()
            {
                using (var bitmap = new Bitmap(Files.SnakewarePNG))
                {
                    var factory = new MagickImageFactory();
                    using (var image = factory.Create(bitmap))
                    {
                        Assert.AreEqual(286, image.Width);
                        Assert.AreEqual(67, image.Height);
                        Assert.AreEqual(MagickFormat.Png, image.Format);
                    }
                }
            }
        }
    }
}

Add extra tests and missing TestClass attribute.


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

namespace osu.Framework.Platform.Linux.Native
{
    public static class Library
    {
        [DllImport("libdl.so", EntryPoint = "dlopen")]
        private static extern IntPtr dlopen(string filename, int flags);
        public static void LoadLazyLocal(string filename)
        {
            dlopen(filename, 0x001); // RTLD_LOCAL + RTLD_NOW
        }
        public static void LoadNowLocal(string filename)
        {
            dlopen(filename, 0x002); // RTLD_LOCAL + RTLD_NOW
        }
        public static void LoadLazyGlobal(string filename)
        {
            dlopen(filename, 0x101); // RTLD_GLOBAL + RTLD_LAZY
        }
        public static void LoadNowGlobal(string filename)
        {
            dlopen(filename, 0x102); // RTLD_GLOBAL + RTLD_NOW
        }
    }
}

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

namespace osu.Framework.Platform.Linux.Native
{
    public static class Library
    {
        [DllImport("libdl.so", EntryPoint = "dlopen")]
        private static extern IntPtr dlopen(string filename, int flags);
        public static void LoadLazyLocal(string filename)
        {
            dlopen(filename, 0x001); // RTLD_LOCAL + RTLD_LAZY
        }
        public static void LoadNowLocal(string filename)
        {
            dlopen(filename, 0x002); // RTLD_LOCAL + RTLD_NOW
        }
        public static void LoadLazyGlobal(string filename)
        {
            dlopen(filename, 0x101); // RTLD_GLOBAL + RTLD_LAZY
        }
        public static void LoadNowGlobal(string filename)
        {
            dlopen(filename, 0x102); // RTLD_GLOBAL + RTLD_NOW
        }
    }
}

Make comment say that 0x001 is RTLD_LOCAL + RTLD_LAZY


// Copyright 2019 Google LLC
//
// 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
//
//     https://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 Google.Apis.Storage.v1.Data;
using System;
using System.Collections.Generic;
using System.Text;

namespace Google.Cloud.Storage.V1
{
    /// <summary>
    /// String constants for the names of the storage classes, as used in <see cref="HmacKeyMetadata.State" />.
    /// </summary>
    public static class HmacKeyStates
    {
        /// <summary>
        /// The key is active, and can be used for signing. It cannot be deleted in this state.
        /// </summary>
        public const string Active = "ACTIVE";

        /// <summary>
        /// The key is inactive, and can be used for signing. It can be deleted.
        /// </summary>
        public const string Inactive = "INACTIVE";

        /// <summary>
        /// The key has been deleted.
        /// </summary>
        public const string Deleted = "DELETE";
    }
}

// Copyright 2019 Google LLC
//
// 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
//
//     https://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 Google.Apis.Storage.v1.Data;
using System;
using System.Collections.Generic;
using System.Text;

namespace Google.Cloud.Storage.V1
{
    /// <summary>
    /// String constants for the names of the storage classes, as used in <see cref="HmacKeyMetadata.State" />.
    /// </summary>
    public static class HmacKeyStates
    {
        /// <summary>
        /// The key is active, and can be used for signing. It cannot be deleted in this state.
        /// </summary>
        public const string Active = "ACTIVE";

        /// <summary>
        /// The key is inactive, and can be used for signing. It can be deleted.
        /// </summary>
        public const string Inactive = "INACTIVE";

        /// <summary>
        /// The key has been deleted.
        /// </summary>
        public const string Deleted = "DELETED";
    }
}

Fix typo for HMAC key states

Fix typo for HMAC key states


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

namespace PogoLocationFeeder.Helper
{
    public class JsonSerializerSettingsCultureInvariant : JsonSerializerSettings
    {
        public JsonSerializerSettingsCultureInvariant()
        {
            Culture = CultureInfo.InvariantCulture;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace PogoLocationFeeder.Helper
{
    public class JsonSerializerSettingsCultureInvariant : JsonSerializerSettings
    {
        public JsonSerializerSettingsCultureInvariant()
        {
            Culture = CultureInfo.InvariantCulture;
            Converters = new List<JsonConverter> { new DoubleConverter()};
        }
    }

    public class DoubleConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(double) || objectType == typeof(double?));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken token = JToken.Load(reader);
            if (token.Type == JTokenType.Float || token.Type == JTokenType.Integer)
            {
                return token.ToObject<double>();
            }
            if (token.Type == JTokenType.String)
            {
                var match = Regex.Match(token.ToString(), @"(1?\-?\d+\.?\d*)");
                if (match.Success)
                {
                    return Double.Parse(match.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
                }
                return Double.Parse(token.ToString(),
                       System.Globalization.CultureInfo.InvariantCulture);
            }
            if (token.Type == JTokenType.Null && objectType == typeof(double?))
            {
                return null;
            }
            throw new JsonSerializationException("Unexpected token type: " +
                                                  token.Type.ToString());
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }

}

Fix error when unserializing json object


namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
    using Base.Get;
    using Objects.Basic;
    using Objects.Get.Shows.Common;

    internal class TraktShowsMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedShow>, TraktMostAnticipatedShow>
    {
        internal TraktShowsMostAnticipatedRequest(TraktClient client) : base(client) { }

        protected override string UriTemplate => "shows/anticipated{?extended,page,limit}";

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
    using Base;
    using Base.Get;
    using Objects.Basic;
    using Objects.Get.Shows.Common;

    internal class TraktShowsMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedShow>, TraktMostAnticipatedShow>
    {
        internal TraktShowsMostAnticipatedRequest(TraktClient client) : base(client) { }

        protected override string UriTemplate => "shows/anticipated{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}";

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        internal TraktShowFilter Filter { get; set; }

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

Add filter property to most anticipated shows request.


// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;

namespace Microsoft.CodeAnalysis.Experiments
{
    internal interface IExperimentationService : IWorkspaceService
    {
        bool IsExperimentEnabled(string experimentName);
    }

    [ExportWorkspaceService(typeof(IExperimentationService)), Shared]
    internal class DefaultExperimentationService : IExperimentationService
    {
        public bool ReturnValue = false;

        [ImportingConstructor]
        public DefaultExperimentationService()
        {
        }

        public bool IsExperimentEnabled(string experimentName) => ReturnValue;
    }

    internal static class WellKnownExperimentNames
    {
        public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
        public const string PartialLoadMode = "Roslyn.PartialLoadMode";
        public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
        public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
        public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
        public const string RoslynInlineRenameFile = "Roslyn.FileRename";

        // Syntactic LSP experiment treatments.
        public const string SyntacticExp_LiveShareTagger_Remote = "RoslynLsp_Tagger";
        public const string SyntacticExp_LiveShareTagger_TextMate = "RoslynTextMate_Tagger";
    }
}

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;

namespace Microsoft.CodeAnalysis.Experiments
{
    internal interface IExperimentationService : IWorkspaceService
    {
        bool IsExperimentEnabled(string experimentName);
    }

    [ExportWorkspaceService(typeof(IExperimentationService)), Shared]
    internal class DefaultExperimentationService : IExperimentationService
    {
        public bool ReturnValue = false;

        [ImportingConstructor]
        public DefaultExperimentationService()
        {
        }

        public bool IsExperimentEnabled(string experimentName) => ReturnValue;
    }

    internal static class WellKnownExperimentNames
    {
        public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
        public const string PartialLoadMode = "Roslyn.PartialLoadMode";
        public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
        public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
        public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
        public const string RoslynInlineRenameFile = "Roslyn.FileRename";

        // Syntactic LSP experiment treatments.
        public const string SyntacticExp_LiveShareTagger_Remote = "Roslyn.LspTagger";
        public const string SyntacticExp_LiveShareTagger_TextMate = "Roslyn.TextMateTagger";
    }
}

Add dots to experiment names so they can be enabled as feature flags.


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

using System.ComponentModel;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.BeatmapListing
{
    public enum SearchGeneral
    {
        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralRecommended))]
        [Description("Recommended difficulty")]
        Recommended,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralConverts))]
        [Description("Include converted beatmaps")]
        Converts,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFollows))]
        [Description("Subscribed mappers")]
        Follows,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFeaturedArtists))]
        [Description("Featured artists")]
        FeaturedArtists
    }
}

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

using System.ComponentModel;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.BeatmapListing
{
    public enum SearchGeneral
    {
        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralRecommended))]
        [Description("Recommended difficulty")]
        Recommended,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralConverts))]
        [Description("Include converted beatmaps")]
        Converts,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFollows))]
        [Description("Subscribed mappers")]
        Follows,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralSpotlights))]
        Spotlights,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFeaturedArtists))]
        [Description("Featured artists")]
        FeaturedArtists
    }
}

Add spotlighted beatmaps filter to beatmap listing


using System;
using Shuttle.Core.Infrastructure;

namespace Shuttle.Esb
{
	public class DefaultMessageHandlerInvoker : IMessageHandlerInvoker
	{
		public MessageHandlerInvokeResult Invoke(IPipelineEvent pipelineEvent)
		{
			Guard.AgainstNull(pipelineEvent, "pipelineEvent");

			var state = pipelineEvent.Pipeline.State;
			var bus = state.GetServiceBus();
			var message = state.GetMessage();
			var handler = bus.Configuration.MessageHandlerFactory.GetHandler(message);

			if (handler == null)
			{
				return MessageHandlerInvokeResult.InvokeFailure();
			}

			try
			{
				var transportMessage = state.GetTransportMessage();
				var messageType = message.GetType();
				var contextType = typeof (HandlerContext<>).MakeGenericType(messageType);
				var method = handler.GetType().GetMethod("ProcessMessage", new[] {contextType});

				if (method == null)
				{
					throw new ProcessMessageMethodMissingException(string.Format(
						EsbResources.ProcessMessageMethodMissingException,
						handler.GetType().FullName,
						messageType.FullName));
				}

				var handlerContext = Activator.CreateInstance(contextType, bus, transportMessage, message, state.GetActiveState());

				method.Invoke(handler, new[] {handlerContext});
			}
			finally
			{
				bus.Configuration.MessageHandlerFactory.ReleaseHandler(handler);
			}

			return MessageHandlerInvokeResult.InvokedHandler(handler);
		}
	}
}

using System;
using System.Linq;
using Shuttle.Core.Infrastructure;

namespace Shuttle.Esb
{
	public class DefaultMessageHandlerInvoker : IMessageHandlerInvoker
	{
		public MessageHandlerInvokeResult Invoke(IPipelineEvent pipelineEvent)
		{
			Guard.AgainstNull(pipelineEvent, "pipelineEvent");

			var state = pipelineEvent.Pipeline.State;
			var bus = state.GetServiceBus();
			var message = state.GetMessage();
			var handler = bus.Configuration.MessageHandlerFactory.GetHandler(message);

			if (handler == null)
			{
				return MessageHandlerInvokeResult.InvokeFailure();
			}

			try
			{
				var transportMessage = state.GetTransportMessage();
				var messageType = message.GetType();
				var interfaceType = typeof(IMessageHandler<>).MakeGenericType(messageType);
				var method = handler.GetType().GetInterfaceMap(interfaceType).TargetMethods.SingleOrDefault();

				if (method == null)
				{
					throw new ProcessMessageMethodMissingException(string.Format(
						EsbResources.ProcessMessageMethodMissingException,
						handler.GetType().FullName,
						messageType.FullName));
				}

				var contextType = typeof(HandlerContext<>).MakeGenericType(messageType);
				var handlerContext = Activator.CreateInstance(contextType, bus, transportMessage, message, state.GetActiveState());

				method.Invoke(handler, new[] {handlerContext});
			}
			finally
			{
				bus.Configuration.MessageHandlerFactory.ReleaseHandler(handler);
			}

			return MessageHandlerInvokeResult.InvokedHandler(handler);
		}
	}
}

Call the correct implementation if IMessageHandler.ProcessMessage method


using System;
using ExRam.Gremlinq.Providers.Neptune;
using Microsoft.Extensions.Configuration;

namespace ExRam.Gremlinq.Core.AspNet
{
    public static class GremlinqSetupExtensions
    {
        public static GremlinqSetup UseNeptune(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
        {
            return setup
                .UseProvider(
                    "Neptune",
                    (e, f) => e.UseNeptune(f),
                    (configurator, configuration) =>
                    {
                        if (configuration["ElasticSearchEndPoint"] is { } endPoint)
                        {
                            var indexConfiguration = Enum.TryParse<NeptuneElasticSearchIndexConfiguration>(configuration["IndexConfiguration"], true, out var outVar)
                                ? outVar
                                : NeptuneElasticSearchIndexConfiguration.Standard;

                            configurator = configurator
                                .UseElasticSearch(new Uri(endPoint), indexConfiguration);
                        }

                        return configurator;
                    },
                    extraConfiguration);
        }

        public static GremlinqSetup UseNeptune<TVertex, TEdge>(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
        {
            return setup
                .UseNeptune(extraConfiguration)
                .ConfigureEnvironment(env => env
                    .UseModel(GraphModel
                        .FromBaseTypes<TVertex, TEdge>(lookup => lookup
                            .IncludeAssembliesOfBaseTypes())));
        }
    }
}

using System;
using ExRam.Gremlinq.Providers.Neptune;
using Microsoft.Extensions.Configuration;

namespace ExRam.Gremlinq.Core.AspNet
{
    public static class GremlinqSetupExtensions
    {
        public static GremlinqSetup UseNeptune(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
        {
            return setup
                .UseProvider(
                    "Neptune",
                    (e, f) => e.UseNeptune(f),
                    (configurator, configuration) =>
                    {
                        if (configuration.GetSection("ElasticSearch") is { } elasticSearchSection)
                        {
                            if (bool.TryParse(elasticSearchSection["Enabled"], out var isEnabled) && isEnabled && configuration["EndPoint"] is { } endPoint)
                            {
                                var indexConfiguration = Enum.TryParse<NeptuneElasticSearchIndexConfiguration>(configuration["IndexConfiguration"], true, out var outVar)
                                    ? outVar
                                    : NeptuneElasticSearchIndexConfiguration.Standard;

                                configurator = configurator
                                    .UseElasticSearch(new Uri(endPoint), indexConfiguration);
                            }
                        }

                        return configurator;
                    },
                    extraConfiguration);
        }

        public static GremlinqSetup UseNeptune<TVertex, TEdge>(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
        {
            return setup
                .UseNeptune(extraConfiguration)
                .ConfigureEnvironment(env => env
                    .UseModel(GraphModel
                        .FromBaseTypes<TVertex, TEdge>(lookup => lookup
                            .IncludeAssembliesOfBaseTypes())));
        }
    }
}

Use a section for ElasticSearch.

Neptune: Use a section for ElasticSearch.


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper.FastCrud;
using Dapper.FastCrud.Configuration.StatementOptions.Builders;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
    public abstract partial class Repository<TSession, TEntity, TPk>
        where TEntity : class, IEntity<TPk>
        where TSession : ISession
    {
        public IEnumerable<TEntity> GetAll(ISession session = null)
        {
            return GetAllAsync(session).Result;
        }

        public async Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null)
        {
            if (session != null)
            {
                return await session.FindAsync<TEntity>();
            }
            using (var uow = Factory.CreateSession<TSession>())
            {
                return await uow.FindAsync<TEntity>();
            }
        }
        protected async Task<IEnumerable<TEntity>> GetAllAsync(ISession session, Action<IRangedBatchSelectSqlSqlStatementOptionsOptionsBuilder<TEntity>> statement)
        {
            if (session != null)
            {
                return await session.FindAsync(statement);
            }
            using (var uow = Factory.CreateSession<TSession>())
            {
                return await uow.FindAsync(statement);
            }
        }

    }
}

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper.FastCrud;
using Dapper.FastCrud.Configuration.StatementOptions.Builders;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
    public abstract partial class Repository<TSession, TEntity, TPk>
        where TEntity : class, IEntity<TPk>
        where TSession : ISession
    {
        public IEnumerable<TEntity> GetAll(ISession session = null)
        {
            return GetAllAsync(session).Result;
        }

        public async Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null)
        {
            if (session != null)
            {
                return await session.FindAsync<TEntity>();
            }
            using (var uow = Factory.CreateSession<TSession>())
            {
                return await uow.FindAsync<TEntity>();
            }
        }
    }
}

Remove get all with dynamic clause. SHould be handeled by user in own class. Otherwise forced to use FastCRUD


using System;

namespace Arango.Client
{
    [AttributeUsage(AttributeTargets.Property)]
    public class ArangoProperty : Attribute
    {
        public string Alias { get; set; }
        public bool Serializable { get; set; }

        public ArangoProperty()
        {
            Serializable = true;
        }
    }
}

using System;

namespace Arango.Client
{
    [AttributeUsage(AttributeTargets.Property)]
    public class ArangoProperty : Attribute
    {
        public bool Serializable { get; set; }
        public bool Identity { get; set; }
        public bool Key { get; set; }
        public bool Revision { get; set; }
        public bool From { get; set; }
        public bool To { get; set; }
        public string Alias { get; set; }

        public ArangoProperty()
        {
            Serializable = true;
            Identity = false;
            Key = false;
            Revision = false;
            From = false;
            To = false;
        }
    }
}

Add more arango specific attributes.

Add more arango specific attributes.


using System;
using System.Collections.Concurrent;
using System.Threading;

namespace Serilog.Sinks.PeriodicBatching
{
    class BoundedConcurrentQueue<T>
    {
        const int NON_BOUNDED = -1;

        readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
        readonly int _queueLimit;

        int _counter;

        public BoundedConcurrentQueue()
        {
            _queueLimit = NON_BOUNDED;
        }

        public BoundedConcurrentQueue(int queueLimit)
        {
            if (queueLimit <= 0)
                throw new ArgumentOutOfRangeException(nameof(queueLimit), "queue limit must be positive");

            _queueLimit = queueLimit;
        }

        public int Count => _queue.Count;

        public bool TryDequeue(out T item)
        {
            if (_queueLimit == NON_BOUNDED)
                return _queue.TryDequeue(out item);

            var result = false;
            try
            { }
            finally // prevent state corrupt while aborting
            {
                if (_queue.TryDequeue(out item))
                {
                    Interlocked.Decrement(ref _counter);
                    result = true;
                }
            }

            return result;
        }

        public bool TryEnqueue(T item)
        {
            if (_queueLimit == NON_BOUNDED)
            {
                _queue.Enqueue(item);
                return true;
            }

            var result = true;
            try
            { }
            finally
            {
                if (Interlocked.Increment(ref _counter) <= _queueLimit)
                {
                    _queue.Enqueue(item);
                }
                else
                {
                    Interlocked.Decrement(ref _counter);
                    result = false;
                }
            }

            return result;
        }
    }
}

using System;
using System.Collections.Concurrent;
using System.Threading;

namespace Serilog.Sinks.PeriodicBatching
{
    class BoundedConcurrentQueue<T>
    {
        const int NON_BOUNDED = -1;

        readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
        readonly int _queueLimit;

        int _counter;

        public BoundedConcurrentQueue()
            : this(NON_BOUNDED) { }

        public BoundedConcurrentQueue(int queueLimit)
        {
            if (queueLimit <= 0 && queueLimit != NON_BOUNDED)
                throw new ArgumentOutOfRangeException(nameof(queueLimit), $"Queue limit must be positive, or {NON_BOUNDED} (to indicate unlimited).");

            _queueLimit = queueLimit;
        }

        public int Count => _queue.Count;

        public bool TryDequeue(out T item)
        {
            if (_queueLimit == NON_BOUNDED)
                return _queue.TryDequeue(out item);

            var result = false;
            try
            { }
            finally // prevent state corrupt while aborting
            {
                if (_queue.TryDequeue(out item))
                {
                    Interlocked.Decrement(ref _counter);
                    result = true;
                }
            }

            return result;
        }

        public bool TryEnqueue(T item)
        {
            if (_queueLimit == NON_BOUNDED)
            {
                _queue.Enqueue(item);
                return true;
            }

            var result = true;
            try
            { }
            finally
            {
                if (Interlocked.Increment(ref _counter) <= _queueLimit)
                {
                    _queue.Enqueue(item);
                }
                else
                {
                    Interlocked.Decrement(ref _counter);
                    result = false;
                }
            }

            return result;
        }
    }
}

Allow NON_BOUNDED value to be used as constructor parameter.


using System.Linq;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

namespace Dangl.WebDocumentation.Models
{
    public static class DatabaseInitialization
    {
        public static void Initialize(ApplicationDbContext Context)
        {
            SetUpRoles(Context);
        }

        private static void SetUpRoles(ApplicationDbContext Context)
        {
            // Add Admin role if not present
            if (Context.Roles.All(Role => Role.Name != "Admin"))
            {
                Context.Roles.Add(new IdentityRole {Name = "Admin"});
                Context.SaveChanges();
            }
        }
    }
}

using System.Linq;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

namespace Dangl.WebDocumentation.Models
{
    public static class DatabaseInitialization
    {
        public static void Initialize(ApplicationDbContext Context)
        {
            SetUpRoles(Context);
        }

        private static void SetUpRoles(ApplicationDbContext Context)
        {
            // Add Admin role if not present
            if (Context.Roles.All(role => role.Name != "Admin"))
            {
                Context.Roles.Add(new IdentityRole {Name = "Admin", NormalizedName = "ADMIN"});
                Context.SaveChanges();
            }
            else if (Context.Roles.Any(role => role.Name == "Admin" && role.NormalizedName != "Admin"))
            {
                var adminRole = Context.Roles.FirstOrDefault(role => role.Name == "Admin");
                adminRole.NormalizedName = "ADMIN";
                Context.SaveChanges();
            }
        }
    }
}

Fix creation of admin role in DB initialization


using System.Web;
using System.Web.UI;

namespace Unicorn.ControlPanel
{
	public class AccessDenied : IControlPanelControl
	{
		public void Render(HtmlTextWriter writer)
		{
			writer.Write("
Access Denied
");
			writer.Write("
You need to sign in to Sitecore as an administrator to use the Unicorn control panel.
", HttpUtility.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery));
		}
	}
}

using System.Web;
using System.Web.UI;

namespace Unicorn.ControlPanel
{
	public class AccessDenied : IControlPanelControl
	{
		public void Render(HtmlTextWriter writer)
		{
			writer.Write("
Access Denied
");
			writer.Write("
You need to sign in to Sitecore as an administrator to use the Unicorn control panel.
", HttpUtility.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery));

			HttpContext.Current.Response.TrySkipIisCustomErrors = true;
			HttpContext.Current.Response.StatusCode = 401;
		}
	}
}

Send proper 401 for access denied

Send proper 401 for access denied


using System;

namespace KnckoutBindingGenerater
{
    public class KnockoutProxy
    {
        private readonly string m_ViewModelName;
        private readonly string m_PrimitiveObservables;
        private readonly string m_MethodProxies;
        private readonly string m_CollectionObservables;

        const string c_ViewModelTemplate = @"
                var {0}ProxyObject = function() {{
                    {1}

                    {2}

                    {3}
                }}

                window.{4} = new {0}ProxyObject();

                ko.applyBindings({4});
            ";

        public KnockoutProxy(string viewModelName, string primitiveObservables, string methodProxies, string collectionObservables)
        {
            m_ViewModelName = viewModelName;
            m_PrimitiveObservables = primitiveObservables;
            m_MethodProxies = methodProxies;
            m_CollectionObservables = collectionObservables;
        }

        public string KnockoutViewModel
        {
            get
            {
                return String.Format(c_ViewModelTemplate,
                                     m_ViewModelName,
                                     m_PrimitiveObservables,
                                     m_MethodProxies,
                                     m_CollectionObservables,
                                     ViewModelInstanceName);
            }
        }

        public string ViewModelInstanceName
        {
            get { return "kevin"; }
        }
    }
}

using System;

namespace KnckoutBindingGenerater
{
    public class KnockoutProxy
    {
        private readonly string m_ViewModelName;
        private readonly string m_PrimitiveObservables;
        private readonly string m_MethodProxies;
        private readonly string m_CollectionObservables;

        const string c_ViewModelTemplate = @"
                var {0}ProxyObject = function() {{
                    {1}

                    {2}

                    {3}
                }}

                window.{4} = new {0}ProxyObject();

                ko.applyBindings({4});
            ";

        public KnockoutProxy(string viewModelName, string primitiveObservables, string methodProxies, string collectionObservables)
        {
            m_ViewModelName = viewModelName;
            m_PrimitiveObservables = primitiveObservables;
            m_MethodProxies = methodProxies;
            m_CollectionObservables = collectionObservables;
        }

        public string KnockoutViewModel
        {
            get
            {
                return String.Format(c_ViewModelTemplate,
                                     m_ViewModelName,
                                     m_PrimitiveObservables,
                                     m_MethodProxies,
                                     m_CollectionObservables,
                                     ViewModelInstanceName);
            }
        }

        public string ViewModelInstanceName
        {
            get { return String.Format("{0}ProxyObjectInstance", m_ViewModelName); }
        }
    }
}

Remove this last piece of hardcodedness

Remove this last piece of hardcodedness


using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;

namespace Reni.FeatureTest.Reference
{
    [TestFixture]
    [ArrayElementType]
    [TargetSet(@"
text: 'abcdefghijklmnopqrstuvwxyz';
pointer: ((text type >>)*1) array_reference instance (text);
(pointer >> 7) dump_print;
(pointer >> 0) dump_print;
(pointer >> 11) dump_print;
(pointer >> 11) dump_print;
(pointer >> 14) dump_print;
", "hallo")]
    public sealed class ArrayReferenceByInstance : CompilerTest {}
}

using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;

namespace Reni.FeatureTest.Reference
{
    [TestFixture]
    [ArrayElementType]
    [TargetSet(@"
text: 'abcdefghijklmnopqrstuvwxyz';
pointer: ((text type item)*1) array_reference instance (text);
pointer item(7) dump_print;
pointer item(0) dump_print;
pointer item(11) dump_print;
pointer item(11) dump_print;
pointer item(14) dump_print;
", "hallo")]
    public sealed class ArrayReferenceByInstance : CompilerTest {}
}

Access operator for array is now "item"

Change: Access operator for array is now "item"


using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.CommitmentsV2.Api.Types.Requests;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;

namespace SFA.DAS.CommitmentsV2.Api.Client
{
    public interface ICommitmentsApiClient
    {
        Task<bool> HealthCheck();

        Task<AccountLegalEntityResponse> GetLegalEntity(long accountLegalEntityId, CancellationToken cancellationToken = default);

        // To be removed latter
        Task<string> SecureCheck();
        Task<string> SecureEmployerCheck();
        Task<string> SecureProviderCheck();
        Task<CreateCohortResponse> CreateCohort(CreateCohortRequest request, CancellationToken cancellationToken = default);

        Task<UpdateDraftApprenticeshipResponse> UpdateDraftApprenticeship(long cohortId, long apprenticeshipId, UpdateDraftApprenticeshipRequest request, CancellationToken cancellationToken = default);
    }
}

using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.CommitmentsV2.Api.Types.Requests;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;

namespace SFA.DAS.CommitmentsV2.Api.Client
{
    public interface ICommitmentsApiClient
    {
        Task<bool> HealthCheck();

        Task<AccountLegalEntityResponse> GetLegalEntity(long accountLegalEntityId, CancellationToken cancellationToken = default);

        // To be removed latter
        Task<string> SecureCheck();
        Task<string> SecureEmployerCheck();
        Task<string> SecureProviderCheck();
        Task<CreateCohortResponse> CreateCohort(CreateCohortRequest request, CancellationToken cancellationToken = default);
        Task<UpdateDraftApprenticeshipResponse> UpdateDraftApprenticeship(long cohortId, long apprenticeshipId, UpdateDraftApprenticeshipRequest request, CancellationToken cancellationToken = default);
        Task<GetCohortResponse> GetCohort(long cohortId, CancellationToken cancellationToken = default);
    }
}

Add missing client method to interface

Add missing client method to interface


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Threading;

namespace ProjectExtensions.Azure.ServiceBus.Tests.Unit {

    [TestFixture]
    public class SampleTest {

        [Test]
        public void Test() {
            Thread.Sleep(30000);
            Assert.IsTrue(true);
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Threading;

namespace ProjectExtensions.Azure.ServiceBus.Tests.Unit {

    [TestFixture]
    public class SampleTest {

        [Test]
        public void Test() {
            Thread.Sleep(2000);
            Assert.IsTrue(true);
        }

    }
}

Set pause to 2 seconds so we can watch the mock run


using Subtle.Model;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;

namespace Subtle.Registry
{

    [RunInstaller(true)]
    public partial class Installer : System.Configuration.Install.Installer
    {
        public Installer()
        {
            InitializeComponent();
        }

        public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);

            if (!Context.Parameters.ContainsKey("targetdir"))
            {
                throw new InstallException("Missing 'targetdir' parameter");
            }

            var targetDir = Context.Parameters["targetdir"].TrimEnd(Path.DirectorySeparatorChar);
            RegistryHelper.SetShellCommands(
                FileTypes.VideoTypes,
                Path.Combine(targetDir, "Subtle.exe"),
                Path.Combine(targetDir, "Subtle.ico"));
        }

        public override void Rollback(IDictionary savedState)
        {
            base.Rollback(savedState);
            //RegistryHelper.DeleteShellCommands(FileTypes.VideoTypes);
        }

    }
}

using Subtle.Model;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;

namespace Subtle.Registry
{
    [RunInstaller(true)]
    public partial class Installer : System.Configuration.Install.Installer
    {
        private const string TargetDirKey = "targetdir";

        public Installer()
        {
            InitializeComponent();
        }

        public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);

            if (!Context.Parameters.ContainsKey(TargetDirKey))
            {
                throw new InstallException($"Missing '{TargetDirKey}' parameter");
            }

            var targetDir = Context.Parameters[TargetDirKey].TrimEnd(Path.DirectorySeparatorChar);
            RegistryHelper.SetShellCommands(
                FileTypes.VideoTypes,
                Path.Combine(targetDir, "Subtle.exe"),
                Path.Combine(targetDir, "Subtle.ico"));
        }

        public override void Rollback(IDictionary savedState)
        {
            base.Rollback(savedState);
            //RegistryHelper.DeleteShellCommands(FileTypes.VideoTypes);
        }
    }
}

Create const for targetdir key

Create const for targetdir key


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

using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;

#nullable enable

namespace osu.Framework.Extensions
{
    public static class PopoverExtensions
    {
        /// <summary>
        /// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor.
        /// </summary>
        public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover);

        /// <summary>
        /// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor.
        /// </summary>
        public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null);

        private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target)
        {
            var popoverContainer = origin.FindClosestParent<PopoverContainer>()
                                   ?? throw new InvalidOperationException($"Cannot show or hide a popover without a parent {nameof(PopoverContainer)} in the hierarchy");

            popoverContainer.SetTarget(target);
        }
    }
}

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

using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;

#nullable enable

namespace osu.Framework.Extensions
{
    public static class PopoverExtensions
    {
        /// <summary>
        /// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor.
        /// </summary>
        public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover);

        /// <summary>
        /// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor.
        /// </summary>
        public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null);

        private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target)
        {
            var popoverContainer = origin as PopoverContainer
                                   ?? origin.FindClosestParent<PopoverContainer>()
                                   ?? throw new InvalidOperationException($"Cannot show or hide a popover without a parent {nameof(PopoverContainer)} in the hierarchy");

            popoverContainer.SetTarget(target);
        }
    }
}

Allow `HidePopover()` to be called directly on popover containers


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

namespace Roton.Emulation
{
    internal class ExecuteCodeContext : ICodeSeekable
    {
        private ICodeSeekable _instructionSource;

        public ExecuteCodeContext(int index, ICodeSeekable instructionSource, string name)
        {
            _instructionSource = instructionSource;
            this.Index = index;
            this.Name = name;
        }

        public Actor Actor
        {
            get;
            set;
        }

        public int CommandsExecuted
        {
            get;
            set;
        }

        public bool Died
        {
            get;
            set;
        }

        public bool Finished
        {
            get;
            set;
        }

        public int Index
        {
            get;
            set;
        }

        public int Instruction
        {
            get { return _instructionSource.Instruction; }
            set { _instructionSource.Instruction = value; }
        }

        public string Message
        {
            get;
            set;
        }

        public bool Moved
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public int PreviousInstruction
        {
            get;
            set;
        }

        public bool Repeat
        {
            get;
            set;
        }
    }
}

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

namespace Roton.Emulation
{
    internal class ExecuteCodeContext : ICodeSeekable
    {
        private ICodeSeekable _instructionSource;

        public ExecuteCodeContext(int index, ICodeSeekable instructionSource, string name)
        {
            _instructionSource = instructionSource;
            this.Index = index;
            this.Name = name;
        }

        public Actor Actor
        {
            get;
            set;
        }

        public int CommandsExecuted
        {
            get;
            set;
        }

        public bool Died
        {
            get;
            set;
        }

        public bool Finished
        {
            get;
            set;
        }

        public int Index
        {
            get;
            set;
        }

        public int Instruction
        {
            get { return _instructionSource.Instruction; }
            set { _instructionSource.Instruction = value; }
        }

        public string Message
        {
            get;
            set;
        }

        public bool Moved
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public bool NextLine
        {
            get;
            set;
        }

        public int PreviousInstruction
        {
            get;
            set;
        }

        public bool Repeat
        {
            get;
            set;
        }
    }
}

Add NextLine to execution context

Add NextLine to execution context


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

public class YuukaWaterController : MonoBehaviour {

    public int requiredCompletion = 3;
    int completionCounter = 0;

    public delegate void VictoryAction();
    public static event VictoryAction OnVictory;

	public void Notify() {
        completionCounter++;
        if (completionCounter >= requiredCompletion) {
            MicrogameController.instance.setVictory(true, true);
            OnVictory();
        }
    }

    private void OnDestroy() {
        OnVictory = null;
    }
}

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

public class YuukaWaterController : MonoBehaviour {

    public int requiredCompletion = 3;
    int completionCounter = 0;

    public delegate void VictoryAction();
    public static event VictoryAction OnVictory;

    private void Awake()
    {
        OnVictory = null;
    }

    public void Notify() {
        completionCounter++;
        if (completionCounter >= requiredCompletion) {
            MicrogameController.instance.setVictory(true, true);
            OnVictory();
        }
    }
}

Fix victory delegate clearing in stage

YuukaWater: Fix victory delegate clearing in stage


#r "Newtonsoft.Json"

using System;
using Red_Folder.WebCrawl;
using Red_Folder.WebCrawl.Data;
using Red_Folder.Logging;
using Newtonsoft.Json;

public static void Run(string request, out object outputDocument, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {crawlRequest.Id}");

	var azureLogger = new AzureLogger(log);

	var crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request);

    var crawler = new Crawler(crawlRequest, azureLogger);
    crawler.AddUrl("https://www.red-folder.com/sitemap.xml");
    var crawlResult = crawler.Crawl();

    outputDocument = crawlResult;
}

public class AzureLogger : ILogger
{
	private TraceWriter _log;

	public AzureLogger(TraceWriter log)
	{
		_log = log;
	}

	public void Info(string message)
	{
		_log.Info(message);
	}
}

#r "Newtonsoft.Json"

using System;
using Red_Folder.WebCrawl;
using Red_Folder.WebCrawl.Data;
using Red_Folder.Logging;
using Newtonsoft.Json;

public static void Run(string request, out object outputDocument, TraceWriter log)
{
	var crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request);
    log.Info($"C# Queue trigger function processed: {crawlRequest.Id}");

	var azureLogger = new AzureLogger(log);

    var crawler = new Crawler(crawlRequest, azureLogger);
    crawler.AddUrl($"{crawlRequest.Host}/sitemap.xml");
    var crawlResult = crawler.Crawl();

    outputDocument = crawlResult;
}

public class AzureLogger : ILogger
{
	private TraceWriter _log;

	public AzureLogger(TraceWriter log)
	{
		_log = log;
	}

	public void Info(string message)
	{
		_log.Info(message);
	}
}

Change sitemap.xml to reference requested host


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SampleProject.Domain.Products;
using SampleProject.Domain.SharedKernel;

namespace SampleProject.Application.Orders.PlaceCustomerOrder
{
    public static class ProductPriceProvider
    {
        public static async Task<List<ProductPriceData>> GetAllProductPrices(IDbConnection connection)
        {
            var productPrices = await connection.QueryAsync<ProductPriceResponse>("SELECT " +
                                                                                $"[ProductPrice].ProductId AS [{nameof(ProductPriceResponse.ProductId)}], " +
                                                                                $"[ProductPrice].Value AS [{nameof(ProductPriceResponse.Value)}], " +
                                                                                $"[ProductPrice].Currency AS [{nameof(ProductPriceResponse.Currency)}] " +
                                                                                "FROM orders.v_ProductPrices AS [ProductPrice]");

            return productPrices.AsList()
                .Select(x => new ProductPriceData(
                    new ProductId(x.ProductId),
                    MoneyValue.Of(x.Value, x.Currency)))
                .ToList();
        }

        private sealed class ProductPriceResponse
        {
            public Guid ProductId { get; set; }

            public decimal Value { get; set; }

            public string Currency { get; set; }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SampleProject.Domain.Products;
using SampleProject.Domain.SharedKernel;

namespace SampleProject.Application.Orders.PlaceCustomerOrder
{
    public static class ProductPriceProvider
    {
        public static async Task<List<ProductPriceData>> GetAllProductPrices(IDbConnection connection)
        {
            var productPrices = await connection.QueryAsync<ProductPriceResponse>("SELECT " +
                                                                                $"[ProductPrice].ProductId AS [{nameof(ProductPriceResponse.ProductId)}], " +
                                                                                $"[ProductPrice].Value AS [{nameof(ProductPriceResponse.Value)}], " +
                                                                                $"[ProductPrice].Currency AS [{nameof(ProductPriceResponse.Currency)}] " +
                                                                                "FROM orders.ProductPrices AS [ProductPrice]");

            return productPrices.AsList()
                .Select(x => new ProductPriceData(
                    new ProductId(x.ProductId),
                    MoneyValue.Of(x.Value, x.Currency)))
                .ToList();
        }

        private sealed class ProductPriceResponse
        {
            public Guid ProductId { get; set; }

            public decimal Value { get; set; }

            public string Currency { get; set; }
        }
    }
}

Fix bug with querying ProductPrices in SampleAPI case study


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

using System;
using osu.Framework.Configuration;
using osu.Framework.IO.Stores;

namespace osu.Framework.Localisation
{
    public partial class LocalisationManager
    {
        private class LocalisedBindableString : Bindable<string>, ILocalisedBindableString
        {
            private readonly IBindable<IResourceStore<string>> storage = new Bindable<IResourceStore<string>>();

            private LocalisableString text;

            public LocalisedBindableString(IBindable<IResourceStore<string>> storage)
            {
                this.storage.BindTo(storage);
                this.storage.BindValueChanged(_ => updateValue(), true);
            }

            private void updateValue()
            {
                string newText = text.Text;

                if (text.ShouldLocalise && storage.Value != null)
                    newText = storage.Value.Get(newText);

                if (text.Args != null && !string.IsNullOrEmpty(newText))
                {
                    try
                    {
                        newText = string.Format(newText, text.Args);
                    }
                    catch (FormatException)
                    {
                        // Prevent crashes if the formatting fails. The string will be in a non-formatted state.
                    }
                }

                Value = newText;
            }

            LocalisableString ILocalisedBindableString.Original
            {
                set
                {
                    text = value;
                    updateValue();
                }
            }
        }
    }
}

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

using System;
using osu.Framework.Configuration;
using osu.Framework.IO.Stores;

namespace osu.Framework.Localisation
{
    public partial class LocalisationManager
    {
        private class LocalisedBindableString : Bindable<string>, ILocalisedBindableString
        {
            private readonly IBindable<IResourceStore<string>> storage = new Bindable<IResourceStore<string>>();

            private LocalisableString text;

            public LocalisedBindableString(IBindable<IResourceStore<string>> storage)
            {
                this.storage.BindTo(storage);
                this.storage.BindValueChanged(_ => updateValue(), true);
            }

            private void updateValue()
            {
                string newText = text.Text;

                if (text.ShouldLocalise && storage.Value != null)
                    newText = storage.Value.Get(newText);

                if (text.Args != null && !string.IsNullOrEmpty(newText))
                {
                    try
                    {
                        newText = string.Format(newText, text.Args);
                    }
                    catch (FormatException)
                    {
                        // Prevent crashes if the formatting fails. The string will be in a non-formatted state.
                    }
                }

                Value = newText;
            }

            LocalisableString ILocalisedBindableString.Original
            {
                set
                {
                    if (text == value)
                        return;
                    text = value;

                    updateValue();
                }
            }
        }
    }
}

Reduce potential value updates when setting localisablestring

This won't have any effect with the current usage of ILocalisedBindableString (SpriteText only), but may have an effect if used elsewhere.


using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;

namespace Promact.Trappist.Repository.Questions
{
    public class QuestionRepository : IQuestionRepository
    {
        private readonly TrappistDbContext _dbContext;

        public QuestionRepository(TrappistDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// Get all questions
        /// </summary>
        /// <returns>Question list</returns>
        public List<SingleMultipleAnswerQuestion> GetAllQuestions()
        {
            var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
            return question;
        }
        /// <summary>
        /// Add single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <param name="singleMultipleAnswerQuestionOption"></param>
        public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
            _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
            _dbContext.SaveChanges();
        }
    }
}

using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;

namespace Promact.Trappist.Repository.Questions
{
    public class QuestionRepository : IQuestionRepository
    {
        private readonly TrappistDbContext _dbContext;

        public QuestionRepository(TrappistDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// Get all questions
        /// </summary>
        /// <returns>Question list</returns>
        public List<SingleMultipleAnswerQuestion> GetAllQuestions()
        {
            var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
            return question;
        }
        /// <summary>
        /// Add single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <param name="singleMultipleAnswerQuestionOption"></param>
        public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
            _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
            _dbContext.SaveChanges();
        }
        /// <summary>
        /// Adding single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
            _dbContext.SaveChanges();
        }

    }
}

Create server side API for single multiple answer question


namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
    using Base.Get;
    using Objects.Basic;
    using Objects.Get.Movies.Common;

    internal class TraktMoviesTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingMovie>, TraktTrendingMovie>
    {
        internal TraktMoviesTrendingRequest(TraktClient client) : base(client) { }

        protected override string UriTemplate => "movies/trending{?extended,page,limit}";

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
    using Base;
    using Base.Get;
    using Objects.Basic;
    using Objects.Get.Movies.Common;

    internal class TraktMoviesTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingMovie>, TraktTrendingMovie>
    {
        internal TraktMoviesTrendingRequest(TraktClient client) : base(client) { }

        protected override string UriTemplate => "movies/trending{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}";

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        internal TraktMovieFilter Filter { get; set; }

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

Add filter property to trending movies request.


using System;
using System.Web;

namespace Canonicalize
{
    internal static class HttpRequestBaseExtensions
    {
        public static Uri GetOriginalUrl(this HttpRequestBase request)
        {
            if (request.Url == null || request.Headers == null)
            {
                return request.Url;
            }

            var uriBuilder = new UriBuilder(request.Url);

            var forwardedProtocol = request.Headers["X-Forwarded-Proto"];
            if (forwardedProtocol != null)
            {
                uriBuilder.Scheme = forwardedProtocol;
            }

            var hostHeader = request.Headers["X-Forwarded-Host"] ?? request.Headers["Host"];
            if (hostHeader != null)
            {
                var parsedHost = new Uri(uriBuilder.Scheme + Uri.SchemeDelimiter + hostHeader);
                uriBuilder.Host = parsedHost.Host;
                uriBuilder.Port = parsedHost.Port;
            }

            return uriBuilder.Uri;
        }
    }
}

using System;
using System.Web;

namespace Canonicalize
{
    /// <summary>
    /// Adds extension methods on <see cref="HttpRequestBase"/>.
    /// </summary>
    public static class HttpRequestBaseExtensions
    {
        /// <summary>
        /// Gets the original URL requested by the client, without artifacts from proxies or load balancers.
        /// In particular HTTP headers Host, X-Forwarded-Host, X-Forwarded-Proto are applied on top of <see cref="HttpRequestBase.Url"/>.
        /// </summary>
        /// <param name="request">The request for which the original URL should be computed.</param>
        /// <returns>The original URL requested by the client.</returns>
        public static Uri GetOriginalUrl(this HttpRequestBase request)
        {
            if (request.Url == null || request.Headers == null)
            {
                return request.Url;
            }

            var uriBuilder = new UriBuilder(request.Url);

            var forwardedProtocol = request.Headers["X-Forwarded-Proto"];
            if (forwardedProtocol != null)
            {
                uriBuilder.Scheme = forwardedProtocol;
            }

            var hostHeader = request.Headers["X-Forwarded-Host"] ?? request.Headers["Host"];
            if (hostHeader != null)
            {
                var parsedHost = new Uri(uriBuilder.Scheme + Uri.SchemeDelimiter + hostHeader);
                uriBuilder.Host = parsedHost.Host;
                uriBuilder.Port = parsedHost.Port;
            }

            return uriBuilder.Uri;
        }
    }
}

Add XML documentation to extension method HttpRequestBase.GetOriginalUrl() and make the method public.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace JabberBCIT {
    public class RouteConfig {
        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

using System.Web.Mvc;
using System.Web.Routing;

namespace JabberBCIT
{
    public class RouteConfig {
        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "EditProfile",
                url: "Profile/Edit/{id}",
                defaults: new { controller = "Manage", action = "Edit" }
            );

            routes.MapRoute(
                name: "Profile",
                url: "Profile/{id}",
                defaults: new { controller = "Manage", action = "Index"}
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

Add routing rules for profile

Add routing rules for profile


namespace Htc.Vita.Core.Diagnostics
{
    public partial class LocationManager
    {
        /// <summary>
        /// Class LocationInfo.
        /// </summary>
        public class LocationInfo
        {
            /// <summary>
            /// Gets or sets the country code alpha2.
            /// </summary>
            /// <value>The country code alpha2.</value>
            public string CountryCodeAlpha2 { get; set; }
            /// <summary>
            /// Gets or sets the provider name.
            /// </summary>
            /// <value>The provider name.</value>
            public string ProviderName { get; set; }
            /// <summary>
            /// Gets or sets the provider type.
            /// </summary>
            /// <value>The provider type.</value>
            public LocationProviderType ProviderType { get; set; } = LocationProviderType.Unknown;
        }

        /// <summary>
        /// Enum LocationProviderType
        /// </summary>
        public enum LocationProviderType
        {
            /// <summary>
            /// Unknown
            /// </summary>
            Unknown,
            /// <summary>
            /// Provided by operating system
            /// </summary>
            OperatingSystem,
            /// <summary>
            /// Provided by network
            /// </summary>
            Network,
            /// <summary>
            /// Provided by user
            /// </summary>
            User
        }
    }
}

namespace Htc.Vita.Core.Diagnostics
{
    public partial class LocationManager
    {
        /// <summary>
        /// Class LocationInfo.
        /// </summary>
        public class LocationInfo
        {
            /// <summary>
            /// Gets or sets the country code alpha2.
            /// </summary>
            /// <value>The country code alpha2.</value>
            public string CountryCodeAlpha2 { get; set; }
            /// <summary>
            /// Gets or sets the provider name.
            /// </summary>
            /// <value>The provider name.</value>
            public string ProviderName { get; set; }
            /// <summary>
            /// Gets or sets the provider type.
            /// </summary>
            /// <value>The provider type.</value>
            public LocationProviderType ProviderType { get; set; } = LocationProviderType.Unknown;
        }

        /// <summary>
        /// Enum LocationProviderType
        /// </summary>
        public enum LocationProviderType
        {
            /// <summary>
            /// Unknown
            /// </summary>
            Unknown,
            /// <summary>
            /// Provided by operating system
            /// </summary>
            OperatingSystem,
            /// <summary>
            /// Provided by network
            /// </summary>
            Network,
            /// <summary>
            /// Provided by user
            /// </summary>
            User,
            /// <summary>
            /// The external application
            /// </summary>
            ExternalApplication
        }
    }
}

Add provider name and provider type into LocationInfo, part 2


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

using System.Collections.Generic;
using Xunit;

namespace System.Globalization.Tests
{
    public class DateTimeFormatInfoReadOnly
    {
        public static IEnumerable<object[]> ReadOnly_TestData()
        {
            yield return new object[] { DateTimeFormatInfo.InvariantInfo, true };
            yield return new object[] { new DateTimeFormatInfo(), false };
            yield return new object[] { new CultureInfo("en-US").DateTimeFormat, false };
        }

        [Theory]
        [MemberData(nameof(ReadOnly_TestData))]
        public void ReadOnly(DateTimeFormatInfo format, bool expected)
        {
            Assert.Equal(expected, format.IsReadOnly);

            DateTimeFormatInfo readOnlyFormat = DateTimeFormatInfo.ReadOnly(format);
            Assert.True(readOnlyFormat.IsReadOnly);
        }

        [Fact]
        public void ReadOnly_Null_ThrowsArgumentNullException()
        {
            Assert.Throws<ArgumentNullException>("dtfi", () => DateTimeFormatInfo.ReadOnly(null)); // Dtfi is null
        }
    }
}

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

using System.Collections.Generic;
using Xunit;

namespace System.Globalization.Tests
{
    public class DateTimeFormatInfoReadOnly
    {
        public static IEnumerable<object[]> ReadOnly_TestData()
        {
            yield return new object[] { DateTimeFormatInfo.InvariantInfo, true };
            yield return new object[] { DateTimeFormatInfo.ReadOnly(new DateTimeFormatInfo()), true };
            yield return new object[] { new DateTimeFormatInfo(), false };
            yield return new object[] { new CultureInfo("en-US").DateTimeFormat, false };
        }

        [Theory]
        [MemberData(nameof(ReadOnly_TestData))]
        public void ReadOnly(DateTimeFormatInfo format, bool originalFormatIsReadOnly)
        {
            Assert.Equal(originalFormatIsReadOnly, format.IsReadOnly);

            DateTimeFormatInfo readOnlyFormat = DateTimeFormatInfo.ReadOnly(format);
            if (originalFormatIsReadOnly)
            {
            	Assert.Same(format, readOnlyFormat);
            }
            else
            {
            	Assert.NotSame(format, readOnlyFormat);
            }
            Assert.True(readOnlyFormat.IsReadOnly);
        }

        [Fact]
        public void ReadOnly_Null_ThrowsArgumentNullException()
        {
            Assert.Throws<ArgumentNullException>("dtfi", () => DateTimeFormatInfo.ReadOnly(null)); // Dtfi is null
        }
    }
}

Add tests for sameness in DateTimeFormatInfo

- Fixes #6313


using System;
using FullSerializer.Internal;
using NUnit.Framework;
using System.Collections.Generic;

namespace FullSerializer.Tests {
    [fsObject(Converter = typeof(MyConverter))]
    public class MyModel {
    }

    public class MyConverter : fsConverter {
        public static bool DidSerialize = false;
        public static bool DidDeserialize = false;

        public override bool CanProcess(Type type) {
            throw new NotSupportedException();
        }

        public override object CreateInstance(fsData data, Type storageType) {
            return new MyModel();
        }

        public override fsFailure TrySerialize(object instance, out fsData serialized, Type storageType) {
            DidSerialize = true;
            serialized = new fsData();
            return fsFailure.Success;
        }

        public override fsFailure TryDeserialize(fsData data, ref object instance, Type storageType) {
            DidDeserialize = true;
            return fsFailure.Success;
        }
    }

    public class SpecifiedConverterTests {
        [Test]
        public void VerifyConversion() {
            var serializer = new fsSerializer();

            fsData result;
            serializer.TrySerialize(new MyModel(), out result);
            Assert.IsTrue(MyConverter.DidSerialize);
            Assert.IsFalse(MyConverter.DidDeserialize);

            MyConverter.DidSerialize = false;
            object resultObj = null;
            serializer.TryDeserialize(result, typeof (MyModel), ref resultObj);
            Assert.IsFalse(MyConverter.DidSerialize);
            Assert.IsTrue(MyConverter.DidDeserialize);
        }
    }
}

using System;
using FullSerializer.Internal;
using NUnit.Framework;
using System.Collections.Generic;

namespace FullSerializer.Tests {
    [fsObject(Converter = typeof(MyConverter))]
    public class MyModel {
    }

    public class MyConverter : fsConverter {
        public static bool DidSerialize = false;
        public static bool DidDeserialize = false;

        public override bool CanProcess(Type type) {
            throw new NotSupportedException();
        }

        public override object CreateInstance(fsData data, Type storageType) {
            return new MyModel();
        }

        public override fsFailure TrySerialize(object instance, out fsData serialized, Type storageType) {
            DidSerialize = true;
            serialized = new fsData();
            return fsFailure.Success;
        }

        public override fsFailure TryDeserialize(fsData data, ref object instance, Type storageType) {
            DidDeserialize = true;
            return fsFailure.Success;
        }
    }

    public class SpecifiedConverterTests {
        [Test]
        public void VerifyConversion() {
            MyConverter.DidDeserialize = false;
            MyConverter.DidSerialize = false;

            var serializer = new fsSerializer();

            fsData result;
            serializer.TrySerialize(new MyModel(), out result);
            Assert.IsTrue(MyConverter.DidSerialize);
            Assert.IsFalse(MyConverter.DidDeserialize);

            MyConverter.DidSerialize = false;
            object resultObj = null;
            serializer.TryDeserialize(result, typeof (MyModel), ref resultObj);
            Assert.IsFalse(MyConverter.DidSerialize);
            Assert.IsTrue(MyConverter.DidDeserialize);
        }
    }
}

Fix running test multiple times in same .NET runtime instance


namespace Stripe
{
    using Newtonsoft.Json;

    public class CreditNoteListOptions : ListOptions
    {
        /// <summary>
        /// ID of the invoice.
        /// </summary>
        [JsonProperty("invoice")]
        public string InvoiceId { get; set; }
    }
}

namespace Stripe
{
    using Newtonsoft.Json;

    public class CreditNoteListOptions : ListOptions
    {
        /// <summary>
        /// ID of the customer.
        /// </summary>
        [JsonProperty("customer")]
        public string CustomerId { get; set; }

        /// <summary>
        /// ID of the invoice.
        /// </summary>
        [JsonProperty("invoice")]
        public string InvoiceId { get; set; }
    }
}

Add Customer filter when listing CreditNote


using System;

namespace MQTTnet.Core.Diagnostics
{
    public static class MqttTrace
    {
        public static event EventHandler<MqttTraceMessagePublishedEventArgs> TraceMessagePublished;

        public static void Verbose(string source, string message)
        {
            Publish(source, MqttTraceLevel.Verbose, null, message);
        }

        public static void Information(string source, string message)
        {
            Publish(source, MqttTraceLevel.Information, null, message);
        }

        public static void Warning(string source, string message)
        {
            Publish(source, MqttTraceLevel.Warning, null, message);
        }

        public static void Warning(string source, Exception exception, string message)
        {
            Publish(source, MqttTraceLevel.Warning, exception, message);
        }

        public static void Error(string source, string message)
        {
            Publish(source, MqttTraceLevel.Error, null, message);
        }

        public static void Error(string source, Exception exception, string message)
        {
            Publish(source, MqttTraceLevel.Error, exception, message);
        }

        private static void Publish(string source, MqttTraceLevel traceLevel, Exception exception, string message)
        {
            TraceMessagePublished?.Invoke(null, new MqttTraceMessagePublishedEventArgs(Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
        }
    }
}

using System;

namespace MQTTnet.Core.Diagnostics
{
    public static class MqttTrace
    {
        public static event EventHandler<MqttTraceMessagePublishedEventArgs> TraceMessagePublished;

        public static void Verbose(string source, string message)
        {
            Publish(source, MqttTraceLevel.Verbose, null, message);
        }

        public static void Information(string source, string message)
        {
            Publish(source, MqttTraceLevel.Information, null, message);
        }

        public static void Warning(string source, string message)
        {
            Publish(source, MqttTraceLevel.Warning, null, message);
        }

        public static void Warning(string source, Exception exception, string message)
        {
            Publish(source, MqttTraceLevel.Warning, exception, message);
        }

        public static void Error(string source, string message)
        {
            Publish(source, MqttTraceLevel.Error, null, message);
        }

        public static void Error(string source, Exception exception, string message)
        {
            Publish(source, MqttTraceLevel.Error, exception, message);
        }

        private static void Publish(string source, MqttTraceLevel traceLevel, Exception exception, string message)
        {
            var handler = TraceMessagePublished;
            if (handler == null)
            {
                return;
            }

            message = string.Format(message, 1);
            handler.Invoke(null, new MqttTraceMessagePublishedEventArgs(Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
        }
    }
}

Make string format optional if no trace listener is attached


using System;

namespace Sep.Git.Tfs
{
    public static class GitTfsExitCodes
    {
        public const int OK = 0;
        public const int Help = 1;
        public const int InvalidArguments = 2;
        public const int ForceRequired = 3;
        public const int ExceptionThrown = Byte.MaxValue - 1;
    }
}

using System;

namespace Sep.Git.Tfs
{
    /// <summary>
    ///     Collection of exit codes used by git-tfs.
    /// </summary>
    /// <remarks>
    ///     For consistency across all running environments, both various
    ///     Windows - shells (powershell.exe, cmd.exe) and UNIX - like environments
    ///     such as bash (MinGW), sh or zsh avoid using negative exit status codes
    ///     or codes 255 or higher.
    ///
    ///     Some running environments might either modulo exit codes with 256 or clamp
    ///     them to interval [0, 255].
    ///
    ///     For more information:
    ///     http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
    ///     http://tldp.org/LDP/abs/html/exitcodes.html
    /// </remarks>
    public static class GitTfsExitCodes
    {
        public const int OK = 0;
        public const int Help = 1;
        public const int InvalidArguments = 2;
        public const int ForceRequired = 3;
        public const int ExceptionThrown = Byte.MaxValue - 1;
    }
}

Add rationale for exit status codes to comments.


using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using CroquetAustralia.Domain.Data;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;

namespace CroquetAustralia.DownloadTournamentEntries.ReadModels
{
    [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
    public class FunctionReadModel
    {
        public FunctionReadModel(EntrySubmittedReadModel entrySubmitted, Tournament tournament, SubmitEntry.LineItem lineItem)
        {
            TournamentItem = tournament.Functions.First(f => f.Id == lineItem.Id);
            EntrySubmitted = entrySubmitted;
            LineItem = lineItem;
        }

        public EntrySubmittedReadModel EntrySubmitted { get; }
        public SubmitEntry.LineItem LineItem { get; }
        public TournamentItem TournamentItem { get; }
    }
}

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using CroquetAustralia.Domain.Data;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;

namespace CroquetAustralia.DownloadTournamentEntries.ReadModels
{
    [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
    public class FunctionReadModel
    {
        public FunctionReadModel(EntrySubmittedReadModel entrySubmitted, Tournament tournament, SubmitEntry.LineItem lineItem)
        {
            TournamentItem = FindFirstFunction(tournament, lineItem);
            EntrySubmitted = entrySubmitted;
            LineItem = lineItem;
        }

        private static TournamentItem FindFirstFunction(Tournament tournament, SubmitEntry.LineItem lineItem)
        {
            try
            {
                return tournament.Functions.First(f => f.Id == lineItem.Id);
            }
            catch (Exception e)
            {
                throw new Exception($"Cannot find function '{lineItem.Id}' in tournament '{tournament.Title}'.", e);
            }
        }

        public EntrySubmittedReadModel EntrySubmitted { get; }
        public SubmitEntry.LineItem LineItem { get; }
        public TournamentItem TournamentItem { get; }
    }
}

Improve exception handling when function does not exist


using Microsoft.Extensions.Options;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.IO;

namespace Umbraco.Core.Runtime
{
    public class CoreInitialComponent : IComponent
    {
        private readonly IIOHelper _ioHelper;
        private readonly GlobalSettings _globalSettings;

        public CoreInitialComponent(IIOHelper ioHelper, IOptions<GlobalSettings> globalSettings)
        {
            _ioHelper = ioHelper;
            _globalSettings = globalSettings.Value;
        }

        public void Initialize()
        {
            // ensure we have some essential directories
            // every other component can then initialize safely
            _ioHelper.EnsurePathExists(Constants.SystemDirectories.Data);
            _ioHelper.EnsurePathExists(_globalSettings.UmbracoMediaPath);
            _ioHelper.EnsurePathExists(Constants.SystemDirectories.MvcViews);
            _ioHelper.EnsurePathExists(Constants.SystemDirectories.PartialViews);
            _ioHelper.EnsurePathExists(Constants.SystemDirectories.MacroPartials);
        }

        public void Terminate()
        { }
    }
}

using Microsoft.Extensions.Options;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;

namespace Umbraco.Core.Runtime
{
    public class CoreInitialComponent : IComponent
    {
        private readonly IIOHelper _ioHelper;
        private readonly IHostingEnvironment _hostingEnvironment;
        private readonly GlobalSettings _globalSettings;

        public CoreInitialComponent(IIOHelper ioHelper, IHostingEnvironment hostingEnvironment, IOptions<GlobalSettings> globalSettings)
        {
            _ioHelper = ioHelper;
            _hostingEnvironment = hostingEnvironment;
            _globalSettings = globalSettings.Value;
        }

        public void Initialize()
        {
            // ensure we have some essential directories
            // every other component can then initialize safely
            _ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Data));
            _ioHelper.EnsurePathExists(_hostingEnvironment.MapPathWebRoot(_globalSettings.UmbracoMediaPath));
            _ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MvcViews));
            _ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.PartialViews));
            _ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MacroPartials));
        }

        public void Terminate()
        { }
    }
}

Update Ensure calls to use full path

Update Ensure calls to use full path


namespace BlockchainSharp.Tests.Processors
{
    using System;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using BlockchainSharp.Stores;
    using BlockchainSharp.Processors;
    using BlockchainSharp.Tests.TestUtils;
    using BlockchainSharp.Core;

    [TestClass]
    public class MinerProcessorTests
    {
        [TestMethod]
        public void MineBlock()
        {
            TransactionPool transactionPool = new TransactionPool();
            MinerProcessor processor = new MinerProcessor(transactionPool);
            Block genesis = FactoryHelper.CreateGenesisBlock();

            Block block = processor.MineBlock(genesis);

            Assert.IsNotNull(block);
            Assert.AreEqual(1, block.Number);
            Assert.AreEqual(0, block.Transactions.Count);
            Assert.AreEqual(genesis.Hash, block.ParentHash);
        }

        [TestMethod]
        public void MineBlockWithTransaction()
        {
            TransactionPool transactionPool = new TransactionPool();
            Transaction transaction = FactoryHelper.CreateTransaction(1000);

            MinerProcessor processor = new MinerProcessor(transactionPool);
            Block genesis = FactoryHelper.CreateGenesisBlock();

            Block block = processor.MineBlock(genesis);

            Assert.IsNotNull(block);
            Assert.AreEqual(1, block.Number);
            Assert.AreEqual(1, block.Transactions.Count);
            Assert.AreSame(transaction, block.Transactions[0]);
            Assert.AreEqual(genesis.Hash, block.ParentHash);
        }
    }
}

namespace BlockchainSharp.Tests.Processors
{
    using System;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using BlockchainSharp.Stores;
    using BlockchainSharp.Processors;
    using BlockchainSharp.Tests.TestUtils;
    using BlockchainSharp.Core;

    [TestClass]
    public class MinerProcessorTests
    {
        [TestMethod]
        public void MineBlock()
        {
            TransactionPool transactionPool = new TransactionPool();
            MinerProcessor processor = new MinerProcessor(transactionPool);
            Block genesis = FactoryHelper.CreateGenesisBlock();

            Block block = processor.MineBlock(genesis);

            Assert.IsNotNull(block);
            Assert.AreEqual(1, block.Number);
            Assert.AreEqual(0, block.Transactions.Count);
            Assert.AreEqual(genesis.Hash, block.ParentHash);
        }

        [TestMethod]
        public void MineBlockWithTransaction()
        {
            TransactionPool transactionPool = new TransactionPool();
            Transaction transaction = FactoryHelper.CreateTransaction(1000);
            transactionPool.AddTransaction(transaction);

            MinerProcessor processor = new MinerProcessor(transactionPool);
            Block genesis = FactoryHelper.CreateGenesisBlock();

            Block block = processor.MineBlock(genesis);

            Assert.IsNotNull(block);
            Assert.AreEqual(1, block.Number);
            Assert.AreEqual(1, block.Transactions.Count);
            Assert.AreSame(transaction, block.Transactions[0]);
            Assert.AreEqual(genesis.Hash, block.ParentHash);
        }
    }
}

Fix test, mine block with transaction

Fix test, mine block with transaction


using System;
using System.Collections.Generic;
using System.Windows.Data;

namespace NuGet.Dialog.PackageManagerUI
{

    public class StringCollectionsToStringConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (targetType == typeof(string))
            {

                string stringValue = value as string;
                if (stringValue != null)
                {
                    return stringValue;
                }
                else
                {
                    IEnumerable<string> parts = (IEnumerable<string>)value;
                    return String.Join(", ", parts);
                }
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Windows.Data;

namespace NuGet.Dialog.PackageManagerUI
{
    public class StringCollectionsToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (targetType == typeof(string))
            {
                string stringValue = value as string;
                if (stringValue != null)
                {
                    return stringValue;
                }
                else if (value == null)
                {
                    return String.Empty;
                }
                {
                    IEnumerable<string> parts = (IEnumerable<string>)value;
                    return String.Join(", ", parts);
                }
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

Add a safety check for when Authors is null, which shouldn't happen in the first place. Work items: 1727, 1728

--HG--
branch : 1.6


using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Classi.Soccorso.Eventi;
using SO115App.API.Models.Servizi.CQRS.Queries.ListaEventi;
using SO115App.Models.Servizi.Infrastruttura.GetListaEventi;
using System;
using System.Collections.Generic;
using System.Text;

namespace SO115App.Persistence.MongoDB.GestioneInterventi
{
    public class GetListaEventiByCodiceRichiesta : IGetListaEventi
    {
        private readonly DbContext _dbContext;

        public GetListaEventiByCodiceRichiesta(DbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public List<Evento> Get(ListaEventiQuery query)
        {
            return (List<Evento>)_dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Eq(x => x.Id, query.IdRichiesta)).Single().Eventi;
        }
    }
}

using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Classi.Soccorso.Eventi;
using SO115App.API.Models.Servizi.CQRS.Queries.ListaEventi;
using SO115App.Models.Servizi.Infrastruttura.GetListaEventi;
using System;
using System.Collections.Generic;
using System.Text;

namespace SO115App.Persistence.MongoDB.GestioneInterventi
{
    public class GetListaEventiByCodiceRichiesta : IGetListaEventi
    {
        private readonly DbContext _dbContext;

        public GetListaEventiByCodiceRichiesta(DbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public List<Evento> Get(ListaEventiQuery query)
        {
            return (List<Evento>)_dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Eq(x => x.Codice, query.IdRichiesta)).Single().Eventi;
        }
    }
}

Fix - Cambiata chiave degli eventi da id richiesta a codice


using NUnit.Framework;
using System;

namespace Sailthru.Tests
{
    [TestFixture()]
    public class Test
    {
        [Test()]
        public void TestCase()
        {
            Assert.Fail();
        }
    }
}

using NUnit.Framework;
using System;

namespace Sailthru.Tests
{
    [TestFixture()]
    public class Test
    {
        [Test()]
        public void TestCase()
        {
        }
    }
}

Revert "[DEVOPS-245] verify test failure"

This reverts commit 11678f30528dfc2ecc5463ad693822d1af2ad1ff.


using System;

using NUnit.Framework;

namespace NHibernate.Test.NHSpecificTest.NH315
{
	/// <summary>
	/// Summary description for Fixture.
	/// </summary>
	[TestFixture]
	[Ignore("Not working, see http://jira.nhibernate.org/browse/NH-315")]
	public class Fixture : TestCase
	{
		protected override string MappingsAssembly
		{
			get { return "NHibernate.Test"; }
		}

		protected override System.Collections.IList Mappings
		{
			get
			{
				return new string[] { "NHSpecificTest.NH315.Mappings.hbm.xml" };
			}
		}

		[Test]
		public void SaveClient()
		{
			Client client = new Client();
			Person person = new Person();

			client.Contacts = new ClientPersons();

			using( ISession s = OpenSession() )
			{
				s.Save( person );

				client.Contacts.PersonId = person.Id;
				client.Contacts.Person   = person;

				s.Save( client );

				s.Flush();
			}

			using( ISession s = OpenSession() )
			{
				s.Delete( client );
				s.Delete( person );

				s.Flush();
			}
		}
	}
}

using System;

using NUnit.Framework;

namespace NHibernate.Test.NHSpecificTest.NH315
{
	/// <summary>
	/// Summary description for Fixture.
	/// </summary>
	[TestFixture]
	public class Fixture : BugTestCase
	{
		public override string BugNumber
		{
			get { return "NH315"; }
		}

		[Test]
		public void SaveClient()
		{
			Client client = new Client();
			Person person = new Person();

			client.Contacts = new ClientPersons();

			using( ISession s = OpenSession() )
			{
				s.Save( person );

				client.Contacts.PersonId = person.Id;
				client.Contacts.Person   = person;

				s.Save( client );

				s.Flush();
			}

			using( ISession s = OpenSession() )
			{
				s.Delete( client );
				s.Delete( person );

				s.Flush();
			}
		}
	}
}

Enable NH-315 fixture since it works now

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@2313