using Glimpse.Web;
using System;
using System.Text;
using System.Threading.Tasks;

namespace Glimpse.Server.Web.Resources
{
    public class HelloGlimpseResource : IRequestHandler
    {
        public bool WillHandle(IContext context)
        {
            return context.Request.Path.StartsWith("/Glimpse");
        }

        public async Task Handle(IContext context)
        {
            var response = context.Response;

            response.SetHeader("Content-Type", "text/plain");

            var data = Encoding.UTF8.GetBytes("Hello world, Glimpse!");
            await response.WriteAsync(data);
        }
    }
}

using Glimpse.Web;
using System;
using System.Text;
using System.Threading.Tasks;

namespace Glimpse.Server.Web.Resources
{
    public class HelloGlimpseResource : IRequestHandler
    {
        public bool WillHandle(IContext context)
        {
            return context.Request.Path == "/Glimpse";
        }

        public async Task Handle(IContext context)
        {
            var response = context.Response;

            response.SetHeader("Content-Type", "text/plain");

            var data = Encoding.UTF8.GetBytes("Hello world, Glimpse!");
            await response.WriteAsync(data);
        }
    }
}

Make test resource more specific

Make test resource more specific


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

[assembly: AssemblyCompany("lozanotek")]
[assembly: AssemblyProduct("MvcTurbine")]
[assembly: AssemblyCopyright("Copyright © lozanotek, inc. 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

[assembly: ComVisible(false)]

[assembly: AssemblyVersion("3.2.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

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

[assembly: AssemblyCompany("lozanotek")]
[assembly: AssemblyProduct("MvcTurbine")]
[assembly: AssemblyCopyright("Copyright © lozanotek, inc. 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

[assembly: ComVisible(false)]

[assembly: AssemblyVersion("3.2.1.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Update the version to 3.2.1.

Update the version to 3.2.1.


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

namespace NMaier.SimpleDlna.Utilities
{
  using Attribute = KeyValuePair<string, string>;
  using System;

  public sealed class AttributeCollection : IEnumerable<Attribute>
  {
    private readonly IList<Attribute> list = new List<Attribute>();

    public int Count
    {
      get
      {
        return list.Count;
      }
    }
    public ICollection<string> Keys
    {
      get
      {
        return (from i in list
                select i.Key).ToList();
      }
    }
    public ICollection<string> Values
    {
      get
      {
        return (from i in list
                select i.Value).ToList();
      }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
      return list.GetEnumerator();
    }

    public void Add(Attribute item)
    {
      list.Add(item);
    }

    public void Add(string key, string value)
    {
      list.Add(new Attribute(key, value));
    }

    public void Clear()
    {
      list.Clear();
    }

    public bool Contains(Attribute item)
    {
      return list.Contains(item);
    }

    public IEnumerator<Attribute> GetEnumerator()
    {
      return list.GetEnumerator();
    }

    public IEnumerable<string> GetValuesForKey(string key)
    {
      return from i in list
             where StringComparer.CurrentCultureIgnoreCase.Equals(i.Key, key)
             select i.Value;
    }
  }
}

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

namespace NMaier.SimpleDlna.Utilities
{
  using Attribute = KeyValuePair<string, string>;

  public sealed class AttributeCollection : IEnumerable<Attribute>
  {
    private readonly IList<Attribute> list = new List<Attribute>();

    public int Count
    {
      get
      {
        return list.Count;
      }
    }
    public ICollection<string> Keys
    {
      get
      {
        return (from i in list
                select i.Key).ToList();
      }
    }
    public ICollection<string> Values
    {
      get
      {
        return (from i in list
                select i.Value).ToList();
      }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
      return list.GetEnumerator();
    }

    public void Add(Attribute item)
    {
      list.Add(item);
    }

    public void Add(string key, string value)
    {
      list.Add(new Attribute(key, value));
    }

    public void Clear()
    {
      list.Clear();
    }

    public bool Contains(Attribute item)
    {
      return list.Contains(item);
    }

    public IEnumerator<Attribute> GetEnumerator()
    {
      return list.GetEnumerator();
    }

    public IEnumerable<string> GetValuesForKey(string key)
    {
      return from i in list
             where StringComparer.CurrentCultureIgnoreCase.Equals(i.Key, key)
             select i.Value;
    }
  }
}

Move using where it belongs

Move using where it belongs


namespace TraktOAuthAuthenticationExample
{
    class Program
    {
        static void Main(string[] args)
        {

        }
    }
}

namespace TraktOAuthAuthenticationExample
{
    using System;
    using System.Threading.Tasks;
    using TraktApiSharp;
    using TraktApiSharp.Authentication;
    using TraktApiSharp.Exceptions;

    class Program
    {
        private const string CLIENT_ID = "ENTER_CLIENT_ID_HERE";
        private const string CLIENT_SECRET = "ENTER_CLIENT_SECRET_HERE";

        private static TraktClient _client = null;

        static void Main(string[] args)
        {
            try
            {
                SetupClient();
                TryToOAuthAuthenticate().Wait();

                var authorization = _client.Authorization;

                if (authorization == null || !authorization.IsValid)
                    throw new InvalidOperationException("Trakt Client not authenticated for requests, that require OAuth");
            }
            catch (TraktException ex)
            {
                Console.WriteLine("-------------- Trakt Exception --------------");
                Console.WriteLine($"Exception message: {ex.Message}");
                Console.WriteLine($"Status code: {ex.StatusCode}");
                Console.WriteLine($"Request URL: {ex.RequestUrl}");
                Console.WriteLine($"Request message: {ex.RequestBody}");
                Console.WriteLine($"Request response: {ex.Response}");
                Console.WriteLine($"Server Reason Phrase: {ex.ServerReasonPhrase}");
                Console.WriteLine("---------------------------------------------");
            }
            catch (Exception ex)
            {
                Console.WriteLine("-------------- Exception --------------");
                Console.WriteLine($"Exception message: {ex.Message}");
                Console.WriteLine("---------------------------------------");
            }

            Console.ReadLine();
        }

        static void SetupClient()
        {
            if (_client == null)
            {
                _client = new TraktClient(CLIENT_ID, CLIENT_SECRET);

                if (!_client.IsValidForAuthenticationProcess)
                    throw new InvalidOperationException("Trakt Client not valid for authentication");
            }
        }

        static async Task TryToOAuthAuthenticate()
        {
            var authorizationUrl = _client.OAuth.CreateAuthorizationUrl();

            if (!string.IsNullOrEmpty(authorizationUrl))
            {
                Console.WriteLine("You have to authenticate this application.");
                Console.WriteLine("Please visit the following webpage:");
                Console.WriteLine($"{authorizationUrl}\n");
                Console.Write("Enter the PIN code from Trakt.tv: ");

                var code = Console.ReadLine();

                if (!string.IsNullOrEmpty(code))
                {
                    TraktAuthorization authorization = await _client.OAuth.GetAuthorizationAsync(code);

                    if (authorization != null && authorization.IsValid)
                    {
                        Console.WriteLine("-------------- Authentication successful --------------");
                        Console.WriteLine($"Created (UTC): {authorization.Created}");
                        Console.WriteLine($"Access Scope: {authorization.AccessScope.DisplayName}");
                        Console.WriteLine($"Refresh Possible: {authorization.IsRefreshPossible}");
                        Console.WriteLine($"Valid: {authorization.IsValid}");
                        Console.WriteLine($"Token Type: {authorization.TokenType.DisplayName}");
                        Console.WriteLine($"Access Token: {authorization.AccessToken}");
                        Console.WriteLine($"Refresh Token: {authorization.RefreshToken}");
                        Console.WriteLine($"Token Expired: {authorization.IsExpired}");
                        Console.WriteLine($"Expires in {authorization.ExpiresIn / 3600 / 24} days");
                        Console.WriteLine("-------------------------------------------------------");
                    }
                }
            }
        }
    }
}

Add implementation for oauth authentication example.


namespace NBench.VisualStudio.TestAdapter
{
    using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
    using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
    using System;
    using System.Collections.Generic;
using System.Linq;

    public class NBenchTestDiscoverer : ITestDiscoverer
    {
        public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
        {
            if (sources == null)
            {
                throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
            }
            else if (!sources.Any())
            {
                throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources");
            }
            else if (discoveryContext == null)
            {
                throw new ArgumentNullException("discoveryContext", "The discovery context you have passed in is null. The discovery context must not be null.");
            }
            else if (logger == null)
            {
                throw new ArgumentNullException("logger", "The message logger you have passed in is null. The message logger must not be null.");
            }
            else if (discoverySink == null)
            {
                throw new ArgumentNullException(
                    "discoverySink",
                    "The test case discovery sink you have passed in is null. The test case discovery sink must not be null.");
            }

            throw new NotImplementedException();
        }
    }
}

namespace NBench.VisualStudio.TestAdapter
{
    using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
    using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
    using System;
    using System.Collections.Generic;
using System.Linq;

    public class NBenchTestDiscoverer : ITestDiscoverer
    {
        public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
        {
            if (sources == null)
            {
                throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
            }
            else if (!sources.Any())
            {
                throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources");
            }
            else if (discoveryContext == null)
            {
                throw new ArgumentNullException("discoveryContext", "The discovery context you have passed in is null. The discovery context must not be null.");
            }
            else if (logger == null)
            {
                throw new ArgumentNullException("logger", "The message logger you have passed in is null. The message logger must not be null.");
            }
            else if (discoverySink == null)
            {
                throw new ArgumentNullException("discoverySink", "The test case discovery sink you have passed in is null. The test case discovery sink must not be null.");
            }

            throw new NotImplementedException();
        }
    }
}

Remove the test for the situation whree all the parameters are valid.


using System;
using ColossalFramework;
using ICities;

namespace ModTools
{
    public class LoadingExtension : LoadingExtensionBase
    {
        public override void OnCreated(ILoading loading)
        {
            base.OnCreated(loading);
            ModToolsBootstrap.inMainMenu = false;
            ModToolsBootstrap.Bootstrap();
        }

        public override void OnLevelLoaded(LoadMode mode)
        {
            base.OnLevelLoaded(mode);
            CustomPrefabs.Bootstrap();
            var appMode = Singleton<ToolManager>.instance.m_properties.m_mode;
            if (ModTools.Instance.config.extendGamePanels && appMode == ItemClass.Availability.Game)
            {
                ModTools.Instance.gameObject.AddComponent<GamePanelExtender>();
            }
        }

        public override void OnReleased()
        {
            base.OnReleased();
            CustomPrefabs.Revert();
            ModToolsBootstrap.inMainMenu = true;
            ModToolsBootstrap.initialized = false;
        }
    }
}

using System;
using ColossalFramework;
using ICities;

namespace ModTools
{
    public class LoadingExtension : LoadingExtensionBase
    {
        public override void OnCreated(ILoading loading)
        {
            base.OnCreated(loading);
            ModToolsBootstrap.inMainMenu = false;
            ModToolsBootstrap.initialized = false;
            ModToolsBootstrap.Bootstrap();
        }

        public override void OnLevelLoaded(LoadMode mode)
        {
            base.OnLevelLoaded(mode);
            CustomPrefabs.Bootstrap();
            var appMode = Singleton<ToolManager>.instance.m_properties.m_mode;
            if (ModTools.Instance.config.extendGamePanels && appMode == ItemClass.Availability.Game)
            {
                ModTools.Instance.gameObject.AddComponent<GamePanelExtender>();
            }
        }

        public override void OnReleased()
        {
            base.OnReleased();
            CustomPrefabs.Revert();
            ModToolsBootstrap.inMainMenu = true;
            ModToolsBootstrap.initialized = false;
        }
    }
}

Set initialized to false in OnCreated

Set initialized to false in OnCreated


namespace Qvision.Umbraco.PollIt.Controllers.ApiControllers
{
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;

    using global::Umbraco.Web.Editors;

    using Qvision.Umbraco.PollIt.Attributes;
    using Qvision.Umbraco.PollIt.CacheRefresher;
    using Qvision.Umbraco.PollIt.Models.Pocos;
    using Qvision.Umbraco.PollIt.Models.Repositories;

    [CamelCase]
    public class AnswerApiController : UmbracoAuthorizedJsonController
    {
        [HttpPost]
        public HttpResponseMessage Post(Answer answer)
        {
            var result = AnswerRepository.Current.Save(answer);

            if (result != null)
            {
                PollItCacheRefresher.ClearCache(answer.QuestionId);
                this.Request.CreateResponse(HttpStatusCode.OK, answer);
            }

            return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Can't save answer");
        }

        [HttpDelete]
        public HttpResponseMessage Delete(int id, int questionId)
        {
            using (var transaction = this.ApplicationContext.DatabaseContext.Database.GetTransaction())
            {
                if (ResponseRepository.Current.DeleteByAnswerId(id) && AnswerRepository.Current.Delete(id))
                {
                    transaction.Complete();
                    PollItCacheRefresher.ClearCache(questionId);

                    return this.Request.CreateResponse(HttpStatusCode.OK);
                }
            }

            return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Can't delete answer");
        }
    }
}

namespace Qvision.Umbraco.PollIt.Controllers.ApiControllers
{
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;

    using global::Umbraco.Web.Editors;

    using Qvision.Umbraco.PollIt.Attributes;
    using Qvision.Umbraco.PollIt.CacheRefresher;
    using Qvision.Umbraco.PollIt.Models.Pocos;
    using Qvision.Umbraco.PollIt.Models.Repositories;

    [CamelCase]
    public class AnswerApiController : UmbracoAuthorizedJsonController
    {
        [HttpPost]
        public HttpResponseMessage Post(Answer answer)
        {
            var result = AnswerRepository.Current.Save(answer);

            if (result != null)
            {
                PollItCacheRefresher.ClearCache(answer.QuestionId);
                return this.Request.CreateResponse(HttpStatusCode.OK, answer);
            }

            return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Can't save answer");
        }

        [HttpDelete]
        public HttpResponseMessage Delete(int id, int questionId)
        {
            using (var transaction = this.ApplicationContext.DatabaseContext.Database.GetTransaction())
            {
                if (ResponseRepository.Current.DeleteByAnswerId(id) && AnswerRepository.Current.Delete(id))
                {
                    transaction.Complete();
                    PollItCacheRefresher.ClearCache(questionId);

                    return this.Request.CreateResponse(HttpStatusCode.OK);
                }
            }

            return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Can't delete answer");
        }
    }
}

Add missing return when creating Answer

Add missing return when creating Answer


using System.Runtime.Serialization;

namespace GogoKit.Models.Response
{
    [DataContract]
    public class Seating
    {
        [DataMember(Name = "section")]
        public string Section { get; set; }

        [DataMember(Name = "row")]
        public string Row { get; set; }

        [DataMember(Name = "seat_from")]
        public string SeatFrom { get; set; }

        [DataMember(Name = "seat_to")]
        public string SeatTo { get; set; }

        [DataMember(Name = "mapping_status")]
        public MappingStatus MappingStatus { get; set; }
    }

    public class MappingStatus
    {
        [DataMember(Name = "status")]
        public MappingStatusEnum Status { get; set; }

        [DataMember(Name = "description")]
        public string Description { get; set; }
    }

    public enum MappingStatusEnum
    {
        Unknown = 0,
        Mapped = 1,
        Unmapped = 2,
        Ignored = 3,
        Rejected = 4
    }
}

using System.Runtime.Serialization;

namespace GogoKit.Models.Response
{
    [DataContract]
    public class Seating
    {
        [DataMember(Name = "section")]
        public string Section { get; set; }

        [DataMember(Name = "row")]
        public string Row { get; set; }

        [DataMember(Name = "seat_from")]
        public string SeatFrom { get; set; }

        [DataMember(Name = "seat_to")]
        public string SeatTo { get; set; }

        [DataMember(Name = "mapping_status")]
        public MappingStatus MappingStatus { get; set; }
    }

    public class MappingStatus
    {
        [DataMember(Name = "status")]
        public ApiMappingState Status { get; set; }
    }

    public enum ApiMappingState
    {
        Unknown = 0,
        Mapped = 1,
        Unmapped = 2,
        Ignored = 3,
        Rejected = 4
    }
}

Update status enum to match current data base setup


using System.Web.Http;
using Swashbuckle.Application;
using System;

namespace WebHost
{
    internal static class SwaggerConfig
    {

        public static void Register(HttpConfiguration httpConfigurations)
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            httpConfigurations
                .EnableSwagger(c =>
                    {
                        c.SingleApiVersion("v1", "Enttoi API");
                        c.IncludeXmlComments($"{AppDomain.CurrentDomain.BaseDirectory}\\bin\\Core.XML");
                        c.IncludeXmlComments($"{AppDomain.CurrentDomain.BaseDirectory}\\bin\\WebHost.XML");
                    })
                .EnableSwaggerUi();
        }
    }
}

using System.Web.Http;
using Swashbuckle.Application;
using System;
using System.IO;

namespace WebHost
{
    internal static class SwaggerConfig
    {

        public static void Register(HttpConfiguration httpConfigurations)
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;
            var coreXml = new FileInfo($"{AppDomain.CurrentDomain.BaseDirectory}\\bin\\Core.XML");
            var hostXml = new FileInfo($"{AppDomain.CurrentDomain.BaseDirectory}\\bin\\WebHost.XML");

            httpConfigurations
                .EnableSwagger(c =>
                    {
                        c.SingleApiVersion("v1", "Enttoi API");
                        if (coreXml.Exists) c.IncludeXmlComments(coreXml.FullName);
                        if (hostXml.Exists) c.IncludeXmlComments(hostXml.FullName);
                    })
                .EnableSwaggerUi();
        }
    }
}

Check of XML file existance

Check of XML file existance


<title>Hearts and Bones Dog Rescue - Pet Adoption - @ViewBag.Title</title>

@* Recommended meta tags for bootstrap *@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Hearts & Bones Rescue is a 501(c)3 non-profit organization dedicated to saving the lives of at-risk dogs and finding them loving, forever homes.">

<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,700|Permanent+Marker" rel="stylesheet">

<link rel="stylesheet" href="/Styles/materialize/materialize.min.css">
<link rel="stylesheet" href="/Styles/site.min.css">

<title>Hearts & Bones Dog Rescue - Pet Adoption - @ViewBag.Title</title>

@* Recommended meta tags for bootstrap *@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Hearts & Bones Rescue is a 501(c)3 non-profit organization dedicated to saving the lives of at-risk dogs and finding them loving, forever homes.">

<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,700|Permanent+Marker" rel="stylesheet">

<link rel="stylesheet" href="/Styles/materialize/materialize.min.css">
<link rel="stylesheet" href="/Styles/site.min.css">

Update page title to ampersand

Update page title to ampersand


#if !ODIN_INSPECTOR

using UnityEditor;

namespace Zenject
{
    [CanEditMultipleObjects]
    [CustomEditor(typeof(SceneContext))]
    public class SceneContextEditor : RunnableContextEditor
    {
        SerializedProperty _contractNameProperty;
        SerializedProperty _parentNamesProperty;
        SerializedProperty _parentContractNameProperty;
        SerializedProperty _parentNewObjectsUnderRootProperty;

        public override void OnEnable()
        {
            base.OnEnable();

            _contractNameProperty = serializedObject.FindProperty("_contractNames");
            _parentNamesProperty = serializedObject.FindProperty("_parentContractNames");
            _parentContractNameProperty = serializedObject.FindProperty("_parentContractName");
            _parentNewObjectsUnderRootProperty = serializedObject.FindProperty("_parentNewObjectsUnderRoot");
        }

        protected override void OnGui()
        {
            base.OnGui();

            EditorGUILayout.PropertyField(_contractNameProperty, true);
            EditorGUILayout.PropertyField(_parentNamesProperty, true);
            EditorGUILayout.PropertyField(_parentContractNameProperty);
            EditorGUILayout.PropertyField(_parentNewObjectsUnderRootProperty);
        }
    }
}

#endif

#if !ODIN_INSPECTOR

using UnityEditor;

namespace Zenject
{
    [CanEditMultipleObjects]
    [CustomEditor(typeof(SceneContext))]
    public class SceneContextEditor : RunnableContextEditor
    {
        SerializedProperty _contractNameProperty;
        SerializedProperty _parentNamesProperty;
        SerializedProperty _parentNewObjectsUnderRootProperty;

        public override void OnEnable()
        {
            base.OnEnable();

            _contractNameProperty = serializedObject.FindProperty("_contractNames");
            _parentNamesProperty = serializedObject.FindProperty("_parentContractNames");
            _parentNewObjectsUnderRootProperty = serializedObject.FindProperty("_parentNewObjectsUnderRoot");
        }

        protected override void OnGui()
        {
            base.OnGui();

            EditorGUILayout.PropertyField(_contractNameProperty, true);
            EditorGUILayout.PropertyField(_parentNamesProperty, true);
            EditorGUILayout.PropertyField(_parentNewObjectsUnderRootProperty);
        }
    }
}

#endif

Fix for scene context editor crash

Fix for scene context editor crash


using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Cimpress.Extensions.Http
{
    public static class HttpResponseMessageExtensions
    {
        public static async Task LogAndThrowIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
        {
            if (!message.IsSuccessStatusCode)
            {
                var formattedMsg = await LogMessage(message, logger);
                throw new Exception(formattedMsg);
            }
        }

        public static async Task LogIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
        {
            if (!message.IsSuccessStatusCode)
            {
                await LogMessage(message, logger);
            }
        }

        public static async Task<string> LogMessage(HttpResponseMessage message, ILogger logger)
        {
            var msg = await message.Content.ReadAsStringAsync();
            var formattedMsg = $"Error processing request. Status code was {message.StatusCode} when calling '{message.RequestMessage.RequestUri}', message was '{msg}'";
            logger.LogError(formattedMsg);
            return formattedMsg;
        }
    }
}

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Cimpress.Extensions.Http
{
    public static class HttpResponseMessageExtensions
    {
        public static async Task LogAndThrowIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
        {
            if (!message.IsSuccessStatusCode)
            {
                var formattedMsg = await LogMessage(message, logger);
                throw new Exception(formattedMsg);
            }
        }

        public static async Task LogIfNotSuccessStatusCode(this HttpResponseMessage message, ILogger logger)
        {
            if (!message.IsSuccessStatusCode)
            {
                await LogMessage(message, logger);
            }
        }

        public static async Task ThrowIfNotSuccessStatusCode(this HttpResponseMessage message)
        {
            if (!message.IsSuccessStatusCode)
            {
                var formattedMsg = await FormatErrorMessage(message);
                throw new Exception(formattedMsg);
            }
        }

        public static async Task<string> LogMessage(HttpResponseMessage message, ILogger logger)
        {
            string formattedMsg = await message.FormatErrorMessage();
            logger.LogError(formattedMsg);
            return formattedMsg;
        }

        public static async Task<string> FormatErrorMessage(this HttpResponseMessage message)
        {
            var msg = await message.Content.ReadAsStringAsync();
            var formattedMsg = $"Error processing request. Status code was {message.StatusCode} when calling '{message.RequestMessage.RequestUri}', message was '{msg}'";
            return formattedMsg;
        }
    }
}

Add option to throw an exception without logging it.


// 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.

namespace System.Data.Common
{
    public static class DbDataReaderExtension
    {
        public static System.Collections.ObjectModel.ReadOnlyCollection<DbColumn> GetColumnSchema(this DbDataReader reader)
        {
            if (reader is IDbColumnSchemaGenerator)
            {
                return ((IDbColumnSchemaGenerator)reader).GetColumnSchema();
            }
            throw new NotImplementedException();
        }
    }
}

// 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.

namespace System.Data.Common
{
    public static class DbDataReaderExtension
    {
        public static System.Collections.ObjectModel.ReadOnlyCollection<DbColumn> GetColumnSchema(this DbDataReader reader)
        {
            if (reader.CanProvideSchema())
            {
                return ((IDbColumnSchemaGenerator)reader).GetColumnSchema();
            }
            throw new NotImplementedException();
        }

        public static bool CanProvideSchema(this DbDataReader reader)
        {
            return reader is IDbColumnSchemaGenerator;
        }
    }
}

Add the query for capability

Add the query for capability


using PluginContracts;
using System;
using System.Collections.Generic;
using Xunit;

namespace PluginLoader.Tests
{
    public class Plugins_Tests
    {
        [Fact]
        public void PluginsFound()
        {
            // Arrange
            var path = @"..\..\..\..\LAN\bin\Debug\netstandard1.3";

            // Act
            var plugins = Plugins<IPluginV1>.Load(path);

            // Assert
            Assert.NotEmpty(plugins);
        }

        [Fact]
        public void PluginsNotFound()
        {
            // Arrange
            var path = @".";

            // Act
            var plugins = Plugins<IPluginV1>.Load(path);

            // Assert
            Assert.Empty(plugins);
        }
    }
}

using PluginContracts;
using System;
using System.Collections.Generic;
using Xunit;

namespace PluginLoader.Tests
{
    public class Plugins_Tests
    {
        [Fact]
        public void PluginsFoundFromLibsFolder()
        {
            // Arrange
            var path = @"..\..\..\..\LAN\bin\Debug\netstandard1.3";

            // Act
            var plugins = Plugins<IPluginV1>.Load(path);

            // Assert
            Assert.NotEmpty(plugins);
        }

        [Fact]
        public void PluginsNotFoundFromCurrentFolder()
        {
            // Arrange
            var path = @".";

            // Act
            var plugins = Plugins<IPluginV1>.Load(path);

            // Assert
            Assert.Empty(plugins);
        }
    }
}

Change test method names to follow "Feature to be tested" pattern


using System;
using Npgsql;

namespace Dotnet.Microservice.Health.Checks
{
    public class PostgresqlHealthCheck
    {
        /// <summary>
        /// Check that a connection can be established to Postgresql and return the server version
        /// </summary>
        /// <param name="connectionString">An Npgsql connection string</param>
        /// <returns>A <see cref="HealthResponse"/> object that contains the return status of this health check</returns>
        public static HealthResponse CheckHealth(string connectionString)
        {
            try
            {
                NpgsqlConnection conn = new NpgsqlConnection(connectionString);
                conn.Open();
                string host = conn.Host;
                string version = conn.PostgreSqlVersion.ToString();
                int port = conn.Port;
                conn.Close();
                conn.Dispose();
                return HealthResponse.Healthy(new { host = host, port = port , version = version});
            }
            catch (Exception e)
            {
                return HealthResponse.Unhealthy(e);
            }
        }
    }
}

using System;
using Npgsql;

namespace Dotnet.Microservice.Health.Checks
{
    public class PostgresqlHealthCheck
    {
        /// <summary>
        /// Check that a connection can be established to Postgresql and return the server version
        /// </summary>
        /// <param name="connectionString">An Npgsql connection string</param>
        /// <returns>A <see cref="HealthResponse"/> object that contains the return status of this health check</returns>
        public static HealthResponse CheckHealth(string connectionString)
        {
            try
            {
                NpgsqlConnection conn = new NpgsqlConnection(connectionString);
                NpgsqlConnection.ClearPool(conn);
                conn.Open();
                string host = conn.Host;
                string version = conn.PostgreSqlVersion.ToString();
                int port = conn.Port;
                conn.Close();
                conn.Dispose();
                return HealthResponse.Healthy(new { host = host, port = port , version = version});
            }
            catch (Exception e)
            {
                return HealthResponse.Unhealthy(e);
            }
        }
    }
}

Clear connection pool so that an actual connection is created always


using System.Collections.Generic;
using System.Threading.Tasks;
using SocialToolBox.Core.Database;
using SocialToolBox.Core.Database.Projection;
using SocialToolBox.Core.Database.Serialization;

namespace SocialToolBox.Core.Mocks.Database.Projections
{
    /// <summary>
    /// An in-memory implementation of <see cref="IWritableStore{T}"/>
    /// </summary>
    public class InMemoryStore<T> : IWritableStore<T> where T : class
    {
        public readonly Dictionary<Id, byte[]> Contents = new Dictionary<Id,byte[]>();

        public IDatabaseDriver Driver { get; private set; }

        public readonly UntypedSerializer Serializer;

        public InMemoryStore(IDatabaseDriver driver)
        {
            Driver = driver;
            Serializer = new UntypedSerializer(driver.TypeDictionary);
        }

// ReSharper disable CSharpWarnings::CS1998
        public async Task<T> Get(Id id, IReadCursor cursor)
// ReSharper restore CSharpWarnings::CS1998
        {
            byte[] value;
            if (!Contents.TryGetValue(id, out value)) return null;

            return Serializer.Unserialize<T>(value);
        }

// ReSharper disable CSharpWarnings::CS1998
        public async Task Set(Id id, T item, IProjectCursor cursor)
// ReSharper restore CSharpWarnings::CS1998
        {
            Contents.Remove(id);
            if (item == null) return;
            Contents.Add(id,Serializer.Serialize(item));
        }
    }
}

using System.Collections.Generic;
using System.Threading.Tasks;
using SocialToolBox.Core.Async;
using SocialToolBox.Core.Database;
using SocialToolBox.Core.Database.Projection;
using SocialToolBox.Core.Database.Serialization;

namespace SocialToolBox.Core.Mocks.Database.Projections
{
    /// <summary>
    /// An in-memory implementation of <see cref="IWritableStore{T}"/>
    /// </summary>
    public class InMemoryStore<T> : IWritableStore<T> where T : class
    {
        public readonly Dictionary<Id, byte[]> Contents = new Dictionary<Id,byte[]>();

        public IDatabaseDriver Driver { get; private set; }

        public readonly UntypedSerializer Serializer;

        public InMemoryStore(IDatabaseDriver driver)
        {
            Driver = driver;
            Serializer = new UntypedSerializer(driver.TypeDictionary);
        }

        /// <summary>
        /// A lock for avoiding multi-thread collisions.
        /// </summary>
        private readonly AsyncLock _lock = new AsyncLock();

        public async Task<T> Get(Id id, IReadCursor cursor)
        {
            byte[] value;

            using (await _lock.Lock())
            {
                if (!Contents.TryGetValue(id, out value)) return null;
            }

            return Serializer.Unserialize<T>(value);
        }

        public async Task Set(Id id, T item, IProjectCursor cursor)
        {
            var bytes = item == null ? null : Serializer.Serialize(item);
            using (await _lock.Lock())
            {
                Contents.Remove(id);
                if (item == null) return;
                Contents.Add(id, bytes);
            }
        }
    }
}

Use lock for in-memory store

Use lock for in-memory store


#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"

public class ContextInfo
{
    public string NugetVersion { get; set; }
    public string AssemblyVersion { get; set; }
    public GitVersion Git { get; set; }

    public string BuildVersion
    {
        get { return NugetVersion + "-" + Git.Sha; }
    }
}

ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
    get
    {
        if(_versionContext == null)
            throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");

        return _versionContext;
    }
}

public ContextInfo ReadContext(FilePath filepath)
{
    _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
    _versionContext.Git = GitVersion();
    return _versionContext;
}

public void UpdateAppVeyorBuildVersionNumber()
{
    var increment = 0;
    while(increment < 10)
    {
        try
        {
            var version = VersionContext.BuildVersion;
            if(increment > 0)
                version += "-" + increment;

            AppVeyor.UpdateBuildVersion(version);
            break;
        }
        catch
        {
            increment++;
        }
    }
}

#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"

public class ContextInfo
{
    public string NugetVersion { get; set; }
    public string AssemblyVersion { get; set; }
    public GitVersion Git { get; set; }

    public string BuildVersion
    {
        get { return NugetVersion + "-" + Git.Sha; }
    }
}

ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
    get
    {
        if(_versionContext == null)
            throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");

        return _versionContext;
    }
}

public ContextInfo ReadContext(FilePath filepath)
{
    _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
    try
    {
        _versionContext.Git = GitVersion();
    }
    catch
    {
        _versionContext.Git = new Cake.Common.Tools.GitVersion.GitVersion();
    }
    return _versionContext;
}

public void UpdateAppVeyorBuildVersionNumber()
{
    var increment = 0;
    while(increment < 10)
    {
        try
        {
            var version = VersionContext.BuildVersion;
            if(increment > 0)
                version += "-" + increment;

            AppVeyor.UpdateBuildVersion(version);
            break;
        }
        catch
        {
            increment++;
        }
    }
}

Allow to run build even if git repo informations are not available


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CertiPay.ACH")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CertiPay.ACH")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9b9b2436-3cbc-4b6a-8c68-fc1565a21dd7")]

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

[assembly: InternalsVisibleTo("CertiPay.ACH.Tests")]

Make internals visible to the test assembly


#if TFS2015u2
using System;
using System.Diagnostics.CodeAnalysis;

using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.VisualStudio.Services.Location;
using Microsoft.VisualStudio.Services.Location.Server;

namespace Aggregator.Core.Extensions
{
    public static class LocationServiceExtensions
    {
        [SuppressMessage("Maintainability", "S1172:Unused method parameters should be removed", Justification = "Required by original interface", Scope = "member", Target = "~M:Aggregator.Core.Extensions.LocationServiceExtensions.GetSelfReferenceUri(Microsoft.VisualStudio.Services.Location.Server.ILocationService,Microsoft.TeamFoundation.Framework.Server.IVssRequestContext,Microsoft.VisualStudio.Services.Location.AccessMapping)~System.Uri")]
        public static Uri GetSelfReferenceUri(this ILocationService self, IVssRequestContext context, AccessMapping mapping)
        {
            string url = self.GetSelfReferenceUrl(context, self.GetDefaultAccessMapping(context));
            return new Uri(url, UriKind.Absolute);
        }
    }
}
#endif

#if TFS2015u2
using System;
using System.Diagnostics.CodeAnalysis;

using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.VisualStudio.Services.Location;
using Microsoft.VisualStudio.Services.Location.Server;

namespace Aggregator.Core.Extensions
{
    public static class LocationServiceExtensions
    {
        public static Uri GetSelfReferenceUri(this ILocationService self, IVssRequestContext context, AccessMapping mapping)
        {
            string url = self.GetSelfReferenceUrl(context, mapping);
            return new Uri(url, UriKind.Absolute);
        }
    }
}
#endif

Use th esupplied access mappign instead of looking it up a second time.


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

using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.Rooms;
using osu.Game.Screens.OnlinePlay.Multiplayer.Match;

namespace osu.Game.Tests.Visual.Multiplayer
{
    public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene
    {
        [SetUp]
        public new void Setup() => Schedule(() =>
        {
            SelectedRoom.Value = new Room();

            Child = new Container
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                RelativeSizeAxes = Axes.X,
                Height = 50,
                Child = new MultiplayerMatchFooter()
            };
        });
    }
}

// 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Screens.OnlinePlay.Multiplayer.Match;

namespace osu.Game.Tests.Visual.Multiplayer
{
    public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene
    {
        [SetUp]
        public new void Setup() => Schedule(() =>
        {
            Child = new Container
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                RelativeSizeAxes = Axes.X,
                Height = 50,
                Child = new MultiplayerMatchFooter()
            };
        });
    }
}

Fix incorrect clearing of room

Fix incorrect clearing of room


using System.Collections.Generic;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.PropertyEditors;

namespace Umbraco.Web.PropertyEditors
{
    /// <summary>
    /// Represents a media picker property editor.
    /// </summary>
    [DataEditor(
        Constants.PropertyEditors.Aliases.MediaPicker,
        EditorType.PropertyValue | EditorType.MacroParameter,
        "Media Picker",
        "mediapicker",
        ValueType = ValueTypes.Text,
        Group = Constants.PropertyEditors.Groups.Media,
        Icon = Constants.Icons.MediaImage)]
    public class MediaPickerPropertyEditor : DataEditor
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="MediaPickerPropertyEditor"/> class.
        /// </summary>
        public MediaPickerPropertyEditor(ILogger logger)
            : base(logger)
        {
        }

        /// <inheritdoc />
        protected override IConfigurationEditor CreateConfigurationEditor() => new MediaPickerConfigurationEditor();

        protected override IDataValueEditor CreateValueEditor() => new MediaPickerPropertyValueEditor(Attribute);

        internal class MediaPickerPropertyValueEditor : DataValueEditor, IDataValueReference
        {
            public MediaPickerPropertyValueEditor(DataEditorAttribute attribute) : base(attribute)
            {
            }

            public IEnumerable<UmbracoEntityReference> GetReferences(object value)
            {
                var asString = value is string str ? str : value?.ToString();

                if (string.IsNullOrEmpty(asString)) yield break;

                if (Udi.TryParse(asString, out var udi))
                    yield return new UmbracoEntityReference(udi);
            }
        }
    }

}

using System.Collections.Generic;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.PropertyEditors;

namespace Umbraco.Web.PropertyEditors
{
    /// <summary>
    /// Represents a media picker property editor.
    /// </summary>
    [DataEditor(
        Constants.PropertyEditors.Aliases.MediaPicker,
        EditorType.PropertyValue | EditorType.MacroParameter,
        "Media Picker",
        "mediapicker",
        ValueType = ValueTypes.Text,
        Group = Constants.PropertyEditors.Groups.Media,
        Icon = Constants.Icons.MediaImage)]
    public class MediaPickerPropertyEditor : DataEditor
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="MediaPickerPropertyEditor"/> class.
        /// </summary>
        public MediaPickerPropertyEditor(ILogger logger)
            : base(logger)
        {
        }

        /// <inheritdoc />
        protected override IConfigurationEditor CreateConfigurationEditor() => new MediaPickerConfigurationEditor();

        protected override IDataValueEditor CreateValueEditor() => new MediaPickerPropertyValueEditor(Attribute);

        internal class MediaPickerPropertyValueEditor : DataValueEditor, IDataValueReference
        {
            public MediaPickerPropertyValueEditor(DataEditorAttribute attribute) : base(attribute)
            {
            }

            public IEnumerable<UmbracoEntityReference> GetReferences(object value)
            {
                var asString = value is string str ? str : value?.ToString();

                if (string.IsNullOrEmpty(asString)) yield break;

                foreach (var udiStr in asString.Split(','))
                {
                    if (Udi.TryParse(udiStr, out var udi))
                        yield return new UmbracoEntityReference(udi);
                }
            }
        }
    }

}

7879: Handle for multiple picked media relations


using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Layers;
using System.Linq;
using Windows.UI.Xaml.Controls;

namespace ArcGISRuntimeSDKDotNet_StoreSamples.Samples
{
	/// <summary>
	///
	/// </summary>
    /// <category>Mapping</category>
	public sealed partial class OverviewMap : Page
    {
        public OverviewMap()
        {
            this.InitializeComponent();

			mapView1.Map.InitialViewpoint = new Viewpoint(new Envelope(-5, 20, 50, 65, SpatialReferences.Wgs84));

        }

        private void mapView1_ExtentChanged(object sender, System.EventArgs e)
        {
            var graphicslayer = overviewMap.Map.Layers.OfType<GraphicsLayer>().FirstOrDefault();
            Graphic g = graphicslayer.Graphics.FirstOrDefault();
            if (g == null) //first time
            {
                g = new Graphic();
                graphicslayer.Graphics.Add(g);
            }
            g.Geometry = mapView1.Extent;
        }
    }
}

using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Layers;
using System.Linq;
using Windows.UI.Xaml.Controls;

namespace ArcGISRuntimeSDKDotNet_StoreSamples.Samples
{
	/// <summary>
	///
	/// </summary>
    /// <category>Mapping</category>
	public sealed partial class OverviewMap : Page
    {
        public OverviewMap()
        {
            this.InitializeComponent();

			mapView1.Map.InitialViewpoint = new Viewpoint(new Envelope(-5, 20, 50, 65, SpatialReferences.Wgs84));

        }

        private async void mapView1_ExtentChanged(object sender, System.EventArgs e)
        {
            var graphicslayer = overviewMap.Map.Layers.OfType<GraphicsLayer>().FirstOrDefault();
            Graphic g = graphicslayer.Graphics.FirstOrDefault();
            if (g == null) //first time
            {
                g = new Graphic();
                graphicslayer.Graphics.Add(g);
            }
            g.Geometry = mapView1.Extent;

            // Adjust overview map scale
            await overviewMap.SetViewAsync(mapView1.Extent.GetCenter(), mapView1.Scale * 15);
        }
    }
}

Adjust the MapOverView map scale

Adjust the MapOverView map scale


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Containers;

namespace osu.Game.Screens.Edit.Setup
{
    public class SetupScreen : EditorRoundedScreen
    {
        [Cached]
        private SectionsContainer<SetupSection> sections = new SectionsContainer<SetupSection>();

        [Cached]
        private SetupScreenHeader header = new SetupScreenHeader();

        public SetupScreen()
            : base(EditorScreenMode.SongSetup)
        {
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            AddRange(new Drawable[]
            {
                sections = new SectionsContainer<SetupSection>
                {
                    FixedHeader = header,
                    RelativeSizeAxes = Axes.Both,
                    Children = new SetupSection[]
                    {
                        new ResourcesSection(),
                        new MetadataSection(),
                        new DifficultySection(),
                        new ColoursSection(),
                        new DesignSection(),
                    }
                },
            });
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Containers;

namespace osu.Game.Screens.Edit.Setup
{
    public class SetupScreen : EditorRoundedScreen
    {
        [Cached]
        private SectionsContainer<SetupSection> sections = new SectionsContainer<SetupSection>();

        [Cached]
        private SetupScreenHeader header = new SetupScreenHeader();

        public SetupScreen()
            : base(EditorScreenMode.SongSetup)
        {
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            AddRange(new Drawable[]
            {
                sections = new SetupScreenSectionsContainer
                {
                    FixedHeader = header,
                    RelativeSizeAxes = Axes.Both,
                    Children = new SetupSection[]
                    {
                        new ResourcesSection(),
                        new MetadataSection(),
                        new DifficultySection(),
                        new ColoursSection(),
                        new DesignSection(),
                    }
                },
            });
        }

        private class SetupScreenSectionsContainer : SectionsContainer<SetupSection>
        {
            protected override UserTrackingScrollContainer CreateScrollContainer()
            {
                var scrollContainer = base.CreateScrollContainer();

                // Workaround for masking issues (see https://github.com/ppy/osu-framework/issues/1675#issuecomment-910023157)
                // Note that this actually causes the full scroll range to be reduced by 2px at the bottom, but it's not really noticeable.
                scrollContainer.Margin = new MarginPadding { Top = 2 };

                return scrollContainer;
            }
        }
    }
}

Fix pixels poking out of the top edge of editor setup screen


using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Mitternacht;
using System.Threading.Tasks;

namespace MitternachtWeb {
	public class Program {
		public static async Task Main(string[] args) {
			await new MitternachtBot(0, 0).RunAsync(args);

			await CreateHostBuilder(args).Build().RunAsync();
		}

		public static IHostBuilder CreateHostBuilder(string[] args)
			=> Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
	}
}

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Mitternacht;
using System.Threading.Tasks;

namespace MitternachtWeb {
	public class Program {
		public static MitternachtBot MitternachtBot;

		public static async Task Main(string[] args) {
			MitternachtBot = new MitternachtBot(0, 0);
			await MitternachtBot.RunAsync(args);

			await CreateHostBuilder(args).Build().RunAsync();
		}

		public static IHostBuilder CreateHostBuilder(string[] args)
			=> Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
	}
}

Move MitternachtBot instance to a static variable.


using HarryPotterUnity.Cards.BasicBehavior;
using JetBrains.Annotations;

namespace HarryPotterUnity.Cards.Quidditch.Items
{
    [UsedImplicitly]
    public class BluebottleBroom : ItemLessonProvider
    {
        public override void OnSelectedAction()
        {
            var card = Player.Discard.GetHealableCards(1);

            Player.Discard.RemoveAll(card);
            Player.Deck.AddAll(card);

            Player.UseActions();
        }
    }
}

using HarryPotterUnity.Cards.BasicBehavior;
using JetBrains.Annotations;

namespace HarryPotterUnity.Cards.Quidditch.Items
{
    [UsedImplicitly]
    public class BluebottleBroom : ItemLessonProvider
    {
        public override void OnSelectedAction()
        {
            var card = Player.Discard.GetHealableCards(1);

            Player.Discard.RemoveAll(card);
            Player.Deck.AddAll(card);

            Player.UseActions();
        }

        public override bool CanPerformInPlayAction()
        {
            return Player.CanUseActions();
        }
    }
}

Add CanPerformAction condition to bluebottle broom


using System;
using System.IO;
using System.Net.Http;
using Firestorm.Tests.Examples.Football.Web;
using Microsoft.AspNetCore.Hosting;

namespace Firestorm.Tests.Examples.Football.Tests
{
    public class FootballTestFixture : IDisposable
    {
        private readonly IWebHost _host;

        public HttpClient HttpClient { get; }

        public FootballTestFixture()
        {
            var url = "http://localhost:1337";

            _host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                //.UseIISIntegration()
                .UseStartup<Startup>()
                .UseUrls(url)
                .Build();

            HttpClient = new HttpClient
            {
                BaseAddress = new Uri(url)
            };

            _host.Start();
        }

        public void Dispose()
        {
            _host.Dispose();
            HttpClient.Dispose();
        }
    }
}

using System;
using System.IO;
using System.Net.Http;
using Firestorm.Tests.Examples.Football.Web;
using Microsoft.AspNetCore.Hosting;

namespace Firestorm.Tests.Examples.Football.Tests
{
    public class FootballTestFixture : IDisposable
    {
        private static int _startPort = 3000;

        private readonly IWebHost _host;

        public HttpClient HttpClient { get; }

        public FootballTestFixture()
        {
            var url = "http://localhost:" + _startPort++;

            _host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                //.UseIISIntegration()
                .UseStartup<Startup>()
                .UseUrls(url)
                .Build();

            HttpClient = new HttpClient
            {
                BaseAddress = new Uri(url)
            };

            _host.Start();
        }

        public void Dispose()
        {
            _host.Dispose();
            HttpClient.Dispose();
        }
    }
}

Test fixture uses incrementing ports to avoid conflicts


// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Microsoft.AspNetCore.Mvc.Formatters
{
    /// <summary>
    /// Helper class which provides <see cref="JsonSerializerSettings"/>.
    /// </summary>
    public static class JsonSerializerSettingsProvider
    {
        private const int DefaultMaxDepth = 32;

        /// <summary>
        /// Creates default <see cref="JsonSerializerSettings"/>.
        /// </summary>
        /// <returns>Default <see cref="JsonSerializerSettings"/>.</returns>
        public static JsonSerializerSettings CreateSerializerSettings()
        {
            return new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy(),
                },

                MissingMemberHandling = MissingMemberHandling.Ignore,

                // Limit the object graph we'll consume to a fixed depth. This prevents stackoverflow exceptions
                // from deserialization errors that might occur from deeply nested objects.
                MaxDepth = DefaultMaxDepth,

                // Do not change this setting
                // Setting this to None prevents Json.NET from loading malicious, unsafe, or security-sensitive types
                TypeNameHandling = TypeNameHandling.None,
            };
        }
    }
}

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Microsoft.AspNetCore.Mvc.Formatters
{
    /// <summary>
    /// Helper class which provides <see cref="JsonSerializerSettings"/>.
    /// </summary>
    public static class JsonSerializerSettingsProvider
    {
        private const int DefaultMaxDepth = 32;

        // return shared resolver by default for perf so slow reflection logic is cached once
        // developers can set their own resolver after the settings are returned if desired
        private static readonly DefaultContractResolver SharedContractResolver = new DefaultContractResolver
        {
            NamingStrategy = new CamelCaseNamingStrategy(),
        };

        /// <summary>
        /// Creates default <see cref="JsonSerializerSettings"/>.
        /// </summary>
        /// <returns>Default <see cref="JsonSerializerSettings"/>.</returns>
        public static JsonSerializerSettings CreateSerializerSettings()
        {
            return new JsonSerializerSettings
            {
                ContractResolver = SharedContractResolver,

                MissingMemberHandling = MissingMemberHandling.Ignore,

                // Limit the object graph we'll consume to a fixed depth. This prevents stackoverflow exceptions
                // from deserialization errors that might occur from deeply nested objects.
                MaxDepth = DefaultMaxDepth,

                // Do not change this setting
                // Setting this to None prevents Json.NET from loading malicious, unsafe, or security-sensitive types
                TypeNameHandling = TypeNameHandling.None,
            };
        }
    }
}

Return a shared contract resolver

Return a shared contract resolver

Return a shared contract resolver from CreateSerializerSettings for performance


using Utf8Json;

namespace Nest
{
	internal class TypeNameFormatter : IJsonFormatter<TypeName>
	{
		public TypeName Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
		{
			if (reader.GetCurrentJsonToken() == JsonToken.String)
			{
				TypeName typeName = reader.ReadString();
				return typeName;
			}
			return null;
		}

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

			var settings = formatterResolver.GetConnectionSettings();
			var typeName = settings.Inferrer.TypeName(value);
			writer.WriteString(typeName);
		}
	}
}

using Utf8Json;

namespace Nest
{
	internal class TypeNameFormatter : IJsonFormatter<TypeName>, IObjectPropertyNameFormatter<TypeName>
	{
		public TypeName Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
		{
			if (reader.GetCurrentJsonToken() == JsonToken.String)
			{
				TypeName typeName = reader.ReadString();
				return typeName;
			}

			reader.ReadNextBlock();
			return null;
		}

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

			var settings = formatterResolver.GetConnectionSettings();
			var typeName = settings.Inferrer.TypeName(value);
			writer.WriteString(typeName);
		}

		public void SerializeToPropertyName(ref JsonWriter writer, TypeName value, IJsonFormatterResolver formatterResolver) =>
			Serialize(ref writer, value, formatterResolver);

		public TypeName DeserializeFromPropertyName(ref JsonReader reader, IJsonFormatterResolver formatterResolver) =>
			Deserialize(ref reader, formatterResolver);
	}
}

Allow TypeName to be used as Dictionary key


namespace Tests
{
    using System;
    using System.IO;
    using System.Reflection;
    using System.Xml.Linq;

    using JetBrains.Annotations;

    using Tests.Properties;

    using Xunit;

    public class IntegrationTests
    {
        [NotNull]
        private readonly Assembly _assembly;

        public IntegrationTests()
        {
            var thisFolder = Path.GetDirectoryName(GetType().Assembly.Location);

            _assembly = Assembly.LoadFrom(Path.Combine(thisFolder, "AssemblyToProcess.dll"));
        }

        [Fact]
        public void CanCreateClass()
        {
            var type = _assembly.GetType("AssemblyToProcess.SimpleClass");
            // ReSharper disable once AssignNullToNotNullAttribute
            Activator.CreateInstance(type);
        }

        [Fact]
        public void ReferenceIsRemoved()
        {
            // ReSharper disable once PossibleNullReferenceException
            Assert.DoesNotContain(_assembly.GetReferencedAssemblies(), x => x.Name == "JetBrains.Annotations");
        }

        [Fact]
        public void AreExternalAnnotationsCorrect()
        {
            var annotations = XDocument.Load(Path.ChangeExtension(_assembly.Location, ".ExternalAnnotations.xml")).ToString();

            Assert.Equal(Resources.ExpectedAnnotations, annotations);
        }

        [Fact]
        public void IsDocumentationProperlyDecorated()
        {
            var _documentation = XDocument.Load(Path.ChangeExtension(_assembly.Location, ".xml")).ToString();

            Assert.Equal(Resources.ExpectedDocumentation, _documentation);
        }
    }
}

namespace Tests
{
    using System;
    using System.IO;
    using System.Reflection;
    using System.Xml.Linq;

    using JetBrains.Annotations;

    using Tests.Properties;

    using Xunit;

    public class IntegrationTests
    {
        [NotNull]
        private readonly string _targetFolder = AppDomain.CurrentDomain.BaseDirectory;
        [NotNull]
        private readonly Assembly _assembly;

        public IntegrationTests()
        {
            _assembly = Assembly.LoadFrom(Path.Combine(_targetFolder, "AssemblyToProcess.dll"));
        }

        [Fact]
        public void CanCreateClass()
        {
            var type = _assembly.GetType("AssemblyToProcess.SimpleClass");
            // ReSharper disable once AssignNullToNotNullAttribute
            Activator.CreateInstance(type);
        }

        [Fact]
        public void ReferenceIsRemoved()
        {
            // ReSharper disable once PossibleNullReferenceException
            Assert.DoesNotContain(_assembly.GetReferencedAssemblies(), x => x.Name == "JetBrains.Annotations");
        }

        [Fact]
        public void AreExternalAnnotationsCorrect()
        {
            var annotations = XDocument.Load(Path.ChangeExtension(_targetFolder, ".ExternalAnnotations.xml")).ToString();

            Assert.Equal(Resources.ExpectedAnnotations, annotations);
        }

        [Fact]
        public void IsDocumentationProperlyDecorated()
        {
            var _documentation = XDocument.Load(Path.ChangeExtension(_targetFolder, ".xml")).ToString();

            Assert.Equal(Resources.ExpectedDocumentation, _documentation);
        }
    }
}

Fix file location for build server

Fix file location for build server


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Talks.C2DF.Interfaces;

namespace Talks.C2DF.Web.Controllers
{
	public class HomeController: Controller
	{
		//ICostCalculator calculator;
		//public HomeController(ICostCalculator calculator)
		//{
		//	this.calculator = calculator;
		//}

		ISendingMicroApp sendingApp;
		public HomeController(ISendingMicroApp sendingApp)
		{
			this.sendingApp = sendingApp;
		}

		public ActionResult Index()
		{

			var result = sendingApp.Send("Hello World!!!DEAL");

			return View();
		}

		public ActionResult About()
		{
			ViewBag.Message = "Your application description page.";

			return View();
		}

		public ActionResult Contact()
		{
			ViewBag.Message = "Your contact page.";

			return View();
		}
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Talks.C2DF.BetterApp.Lib.Logging;
using Talks.C2DF.Interfaces;

namespace Talks.C2DF.Web.Controllers
{
	public class HomeController: Controller
	{

		ISendingMicroApp sendingApp;
		IAppLogger _logger;

		public HomeController(ISendingMicroApp sendingApp, IAppLogger logger)
		{
			this.sendingApp = sendingApp;
			_logger = logger;
		}

		public ActionResult Index()
		{
			_logger.Debug("Sending Message from MVC App");
			var result = sendingApp.Send("Hello World!!!DEAL");

			_logger.Debug($"Result: {result.ResultMessage} -- Price: {result.Price} -- Message: {result.Message} ");

			return View();
		}

		public ActionResult About()
		{
			ViewBag.Message = "Your application description page.";

			return View();
		}

		public ActionResult Contact()
		{
			ViewBag.Message = "Your contact page.";

			return View();
		}
	}
}

Update Home Controller to send message - and log it


using WalletWasabi.Gui.Controls.TransactionDetails.ViewModels;
using WalletWasabi.Gui.ViewModels;

namespace WalletWasabi.Gui.Controls.WalletExplorer
{
	public class TransactionInfoTabViewModel : WasabiDocumentTabViewModel
	{
		public TransactionInfoTabViewModel(TransactionDetailsViewModel transaction) : base("")
		{
			Transaction = transaction;
			Title = $"Transaction ({transaction.TransactionId[0..10]}) Details";
		}

		public TransactionDetailsViewModel Transaction { get; }
	}
}

using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using ReactiveUI;
using Splat;
using WalletWasabi.Gui.Controls.TransactionDetails.ViewModels;
using WalletWasabi.Gui.ViewModels;

namespace WalletWasabi.Gui.Controls.WalletExplorer
{
	public class TransactionInfoTabViewModel : WasabiDocumentTabViewModel
	{
		public TransactionInfoTabViewModel(TransactionDetailsViewModel transaction) : base("")
		{
			Global = Locator.Current.GetService<Global>();
			Transaction = transaction;
			Title = $"Transaction ({transaction.TransactionId[0..10]}) Details";
		}

		public override void OnOpen(CompositeDisposable disposables)
		{
			Global.UiConfig.WhenAnyValue(x => x.LurkingWifeMode)
				.ObserveOn(RxApp.MainThreadScheduler)
				.Subscribe(x => Transaction.RaisePropertyChanged(nameof(Transaction.TransactionId)))
				.DisposeWith(disposables);

			base.OnOpen(disposables);
		}

		protected Global Global { get; }

		public TransactionDetailsViewModel Transaction { get; }
	}
}

Fix lurking wife mode on transaction id in details


using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.DataFlow;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Yaml.ProjectModel;
using JetBrains.Util;

namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
  [ShellComponent]
  public class UnityTestsSpecificYamlFileExtensionMapping : IFileExtensionMapping
  {
    private static readonly string[] ourFileExtensions =
    {
#if RIDER
      // Rider doesn't register .yaml, as the frontend already provides support for it. But we need it for tests...
      ".yaml",
#endif
      ".meta",
      ".asset",
      ".unity"
    };

    public UnityTestsSpecificYamlFileExtensionMapping(Lifetime lifetime)
    {
      Changed = new SimpleSignal(lifetime, GetType().Name + "::Changed");
    }

    public IEnumerable<ProjectFileType> GetFileTypes(string extension)
    {
      if (ourFileExtensions.Contains(extension, StringComparer.InvariantCultureIgnoreCase))
        return new[] {YamlProjectFileType.Instance};
      return EmptyList<ProjectFileType>.Enumerable;
    }

    public IEnumerable<string> GetExtensions(ProjectFileType projectFileType)
    {
      if (Equals(projectFileType, YamlProjectFileType.Instance))
        return ourFileExtensions;
      return EmptyList<string>.Enumerable;
    }

    public ISimpleSignal Changed { get; }
  }
}

using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Yaml.ProjectModel;
using JetBrains.Util;

namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
  [ShellComponent]
  public class UnityTestsSpecificYamlFileExtensionMapping : FileTypeDefinitionExtensionMapping
  {
    private static readonly string[] ourFileExtensions =
    {
#if RIDER
      // Rider doesn't register .yaml, as the frontend already provides support for it. But we need it for tests...
      ".yaml",
#endif
      ".meta",
      ".asset",
      ".unity"
    };

    public UnityTestsSpecificYamlFileExtensionMapping(Lifetime lifetime, IProjectFileTypes fileTypes)
      : base(lifetime, fileTypes)
    {
    }

    public override IEnumerable<ProjectFileType> GetFileTypes(string extension)
    {
      if (ourFileExtensions.Contains(extension, StringComparer.InvariantCultureIgnoreCase))
        return new[] {YamlProjectFileType.Instance};
      return EmptyList<ProjectFileType>.Enumerable;
    }

    public override IEnumerable<string> GetExtensions(ProjectFileType projectFileType)
    {
      if (Equals(projectFileType, YamlProjectFileType.Instance))
        return ourFileExtensions;
      return base.GetExtensions(projectFileType);
    }
  }
}

Fix breaking change in SDK

Fix breaking change in SDK


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

namespace MultiMiner.Xgminer.Api.Parsers
{
    class VersionInformationParser : ResponseTextParser
    {
        public static void ParseTextForVersionInformation(string text, MultiMiner.Xgminer.Api.Data.VersionInformation versionInformation)
        {
            List<string> responseParts = text.Split('|').ToList();

            Dictionary<string, string> keyValuePairs = GetDictionaryFromTextChunk(responseParts[0]);

            versionInformation.Name = keyValuePairs["Msg"].Replace(" versions", String.Empty);
            versionInformation.Description = keyValuePairs["Description"];

            keyValuePairs = GetDictionaryFromTextChunk(responseParts[1]);

            versionInformation.MinerVersion = keyValuePairs["CGMiner"];
            versionInformation.ApiVersion = keyValuePairs["API"];
        }
    }
}

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

namespace MultiMiner.Xgminer.Api.Parsers
{
    class VersionInformationParser : ResponseTextParser
    {
        public static void ParseTextForVersionInformation(string text, MultiMiner.Xgminer.Api.Data.VersionInformation versionInformation)
        {
            List<string> responseParts = text.Split('|').ToList();

            Dictionary<string, string> keyValuePairs = GetDictionaryFromTextChunk(responseParts[0]);

            versionInformation.Name = keyValuePairs["Msg"].Replace(" versions", String.Empty);
            versionInformation.Description = keyValuePairs["Description"];

            keyValuePairs = GetDictionaryFromTextChunk(responseParts[1]);

            string key = "CGMiner";
            if (keyValuePairs.ContainsKey(key))
                versionInformation.MinerVersion = keyValuePairs[key];
            else
            {
                // SGMiner 4.0 broke compatibility with the CGMiner RPC API
                // Version 5.0 fixed the issue - this work-around is for 4.0
                // Request :"version"
                // Response:"STATUS=S,When=1415068731,Code=22,Msg=SGMiner versions,Description=sgminer 4.1.0|VERSION,SGMiner=4.1.0,API=3.1|\u0000"
                key = "SGMiner";
                if (keyValuePairs.ContainsKey(key))
                    versionInformation.MinerVersion = keyValuePairs[key];
            }

            versionInformation.ApiVersion = keyValuePairs["API"];
        }
    }
}

Work around incomatibility in SGMiner 4.0 with the CGMiner RPC API


using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

namespace DeviceHive.Setup.Actions
{
    class SqlDatabaseValidator
    {
        private SqlConnection _connection;

        public SqlDatabaseValidator(SqlConnection connection)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            _connection = connection;
        }

        public void Validate(string databaseName)
        {
            if (databaseName == null)
                throw new ArgumentNullException("databaseName");

            string sqlCommand = string.Format("SELECT CASE WHEN db_id('{0}') is null THEN 0 ELSE 1 END", databaseName);
            IDbCommand command = new SqlCommand(sqlCommand, _connection);
            if (!Convert.ToBoolean(command.ExecuteScalar()))
                throw new Exception(string.Format("Database '{0}' does not exist. Please enter a correct database name.", databaseName));
        }
    }
}

using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

namespace DeviceHive.Setup.Actions
{
    class SqlDatabaseValidator
    {
        private SqlConnection _connection;

        public SqlDatabaseValidator(SqlConnection connection)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            _connection = connection;
        }

        public void Validate(string databaseName)
        {
            if (string.IsNullOrEmpty(databaseName))
                throw new ArgumentNullException("databaseName");

            string sqlCommand = string.Format("SELECT CASE WHEN db_id('{0}') is null THEN 0 ELSE 1 END", databaseName);
            IDbCommand command = new SqlCommand(sqlCommand, _connection);
            if (!Convert.ToBoolean(command.ExecuteScalar()))
                throw new Exception(string.Format("Database '{0}' does not exist. Please enter a correct database name.", databaseName));
        }
    }
}

Check database name input parameter

Check database name input parameter


//
// MonoTouch defines for docfixer
//
using System;
using System.IO;
using System.Reflection;
using MonoTouch.Foundation;

public partial class DocGenerator {
	static Assembly assembly = typeof (MonoTouch.Foundation.NSObject).Assembly;
	const string BaseNamespace = "MonoTouch";

	static string GetMostRecentDocBase ()
	{
		var versions = new[]{"4_0", "3_2", "3_1"};
		string format = "/Developer/Platforms/iPhoneOS.platform/Developer/Documentation/DocSets/com.apple.adc.documentation.AppleiPhone{0}.iPhoneLibrary.docset/Contents/Resources/Documents/documentation";
		foreach (var v in versions) {
			var d = string.Format (format, v);
			if (Directory.Exists (d)) {
				return d;
				break;
			}
		}
		return null;
	}

	public static string GetSelector (object attr)
	{
		return ((ExportAttribute) attr).Selector;
	}
}

//
// MonoTouch defines for docfixer
//
using System;
using System.IO;
using System.Reflection;
using MonoTouch.Foundation;

public partial class DocGenerator {
	static Assembly assembly = typeof (MonoTouch.Foundation.NSObject).Assembly;
	const string BaseNamespace = "MonoTouch";

	static string GetMostRecentDocBase ()
	{
		//var versions = new[]{"4_0", "3_2", "3_1"};
		//string format = "/Developer/Platforms/iPhoneOS.platform/Developer/Documentation/DocSets/com.apple.adc.documentation.AppleiPhone{0}.iPhoneLibrary.docset/Contents/Resources/Documents/documentation";
		var versions = new [] { "5_0" };
		string format = "/Library/Developer/Documentation/DocSets/com.apple.adc.documentation.AppleiOS{0}.iOSLibrary.docset/Contents/Resources/Documents/documentation";

		foreach (var v in versions) {
			var d = string.Format (format, v);
			if (Directory.Exists (d)) {
				return d;
				break;
			}
		}
		return null;
	}

	public static string GetSelector (object attr)
	{
		return ((ExportAttribute) attr).Selector;
	}
}

Fix docfixed to work with iOS5

Fix docfixed to work with iOS5


using JetBrains.ReSharper.FeaturesTestFramework.Intentions;
using JetBrains.ReSharper.Intentions.CSharp.QuickFixes;
using JetBrains.ReSharper.TestFramework;
using NUnit.Framework;

namespace XmlDocInspections.Plugin.Tests.Integrative
{
    [TestFixture]
    [TestNetFramework4]
    public class AddDocCommentFixTest : CSharpQuickFixTestBase<AddDocCommentFix>
    {
        protected override string RelativeTestDataPath => @"QuickFixes\AddDocCommentFix";

        [Test]
        public void TestClass()
        {
            DoNamedTest2();
        }

        [Test]
        public void TestSimpleMethod()
        {
            DoNamedTest2();
        }

        [Test]
        public void TestMethodWithAdditionalElementsForDocTemplate()
        {
            DoNamedTest2();
        }

        [Test]
        public void TestField()
        {
            DoNamedTest2();
        }

        [Test]
        public void TestProperty()
        {
            DoNamedTest2();
        }
    }
}

using JetBrains.ReSharper.FeaturesTestFramework.Intentions;
using JetBrains.ReSharper.Intentions.CSharp.QuickFixes;
using JetBrains.ReSharper.TestFramework;
using NUnit.Framework;

namespace XmlDocInspections.Plugin.Tests.Integrative
{
    [TestFixture]
    [TestNetFramework4]
    public class AddDocCommentFixTest : CSharpQuickFixTestBase<AddDocCommentFix>
    {
        protected override string RelativeTestDataPath => @"QuickFixes\AddDocCommentFix";

        [Test]
        public void TestClass() => DoNamedTest2();

        [Test]
        public void TestSimpleMethod() => DoNamedTest2();

        [Test]
        public void TestMethodWithAdditionalElementsForDocTemplate() => DoNamedTest2();

        [Test]
        public void TestField() => DoNamedTest2();

        [Test]
        public void TestProperty() => DoNamedTest2();
    }
}

Refactor to expr. bodied members

Refactor to expr. bodied members


using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SFA.DAS.EAS.Domain.Configuration;
using SFA.DAS.EAS.Domain.Data.Repositories;
using SFA.DAS.EAS.Domain.Models.UserProfile;
using SFA.DAS.Sql.Client;
using SFA.DAS.NLog.Logger;

namespace SFA.DAS.EAS.Infrastructure.Data
{
    public class UserRepository : BaseRepository, IUserRepository
    {
        private readonly Lazy<EmployerAccountsDbContext> _db;

        public UserRepository(EmployerApprenticeshipsServiceConfiguration configuration, ILog logger, Lazy<EmployerAccountsDbContext> db)
            : base(configuration.DatabaseConnectionString, logger)
        {
            _db = db;
        }

        public Task Upsert(User user)
        {
            return WithConnection(c =>
            {
                var parameters = new DynamicParameters();

                parameters.Add("@email", user.Email, DbType.String);
                parameters.Add("@userRef", new Guid(user.UserRef), DbType.Guid);
                parameters.Add("@firstName", user.FirstName, DbType.String);
                parameters.Add("@lastName", user.LastName, DbType.String);

                return c.ExecuteAsync(
                    sql: "[employer_account].[UpsertUser] @userRef, @email, @firstName, @lastName",
                    param: parameters,
                    commandType: CommandType.Text);
            });
        }
    }
}

using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SFA.DAS.EAS.Domain.Configuration;
using SFA.DAS.EAS.Domain.Data.Repositories;
using SFA.DAS.EAS.Domain.Models.UserProfile;
using SFA.DAS.Sql.Client;
using SFA.DAS.NLog.Logger;

namespace SFA.DAS.EAS.Infrastructure.Data
{
    public class UserRepository : BaseRepository, IUserRepository
    {
        private readonly Lazy<EmployerAccountsDbContext> _db;

        public UserRepository(EmployerApprenticeshipsServiceConfiguration configuration, ILog logger, Lazy<EmployerAccountsDbContext> db)
            : base(configuration.DatabaseConnectionString, logger)
        {
            _db = db;
        }

        public Task Upsert(User user)
        {
            return WithConnection(c =>
            {
                var parameters = new DynamicParameters();

                parameters.Add("@email", user.Email, DbType.String);
                parameters.Add("@userRef", new Guid(user.UserRef), DbType.Guid);
                parameters.Add("@firstName", user.FirstName, DbType.String);
                parameters.Add("@lastName", user.LastName, DbType.String);
                parameters.Add("@correlationId", null, DbType.String);

                return c.ExecuteAsync(
                    sql: "[employer_account].[UpsertUser] @userRef, @email, @firstName, @lastName, @correlationId",
                    param: parameters,
                    commandType: CommandType.Text);
            });
        }
    }
}

Add correlationId to fix startup of the EAS web application. Copied from specific branch


using Amazon.Lambda.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using Amazon.Lambda.APIGatewayEvents;

namespace Amazon.Lambda.AspNetCoreServer
{
    /// <summary>
    /// Helper extensions for APIGatewayProxyFunction
    /// </summary>
    public static class APIGatewayProxyFunctionExtensions
    {

        /// <summary>
        /// An overload of FunctionHandlerAsync to allow working with the typed API Gateway event classes. Implemented as an extension
        /// method to avoid confusion of using it as the function handler for the Lambda function.
        /// </summary>
        /// <param name="function"></param>
        /// <param name="request"></param>
        /// <param name="lambdaContext"></param>
        /// <returns></returns>
        public static async Task<APIGatewayProxyResponse> FunctionHandlerAsync(this APIGatewayProxyFunction function, APIGatewayProxyRequest request, ILambdaContext lambdaContext)
        {
            ILambdaSerializer serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();

            var requestStream = new MemoryStream();
            serializer.Serialize<APIGatewayProxyRequest>(request, requestStream);
            requestStream.Position = 0;

            var responseStream = await function.FunctionHandlerAsync(requestStream, lambdaContext);

            var response = serializer.Deserialize<APIGatewayProxyResponse>(responseStream);
            return response;
        }
    }
}

using Amazon.Lambda.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.AspNetCoreServer;

namespace Amazon.Lambda.TestUtilities
{
    /// <summary>
    /// Extension methods for APIGatewayProxyFunction to make it easier to write tests
    /// </summary>
    public static class APIGatewayProxyFunctionExtensions
    {

        /// <summary>
        /// An overload of FunctionHandlerAsync to allow working with the typed API Gateway event classes. Implemented as an extension
        /// method to avoid confusion of using it as the function handler for the Lambda function.
        /// </summary>
        /// <param name="function"></param>
        /// <param name="request"></param>
        /// <param name="lambdaContext"></param>
        /// <returns></returns>
        public static async Task<APIGatewayProxyResponse> FunctionHandlerAsync(this APIGatewayProxyFunction function, APIGatewayProxyRequest request, ILambdaContext lambdaContext)
        {
            ILambdaSerializer serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();

            var requestStream = new MemoryStream();
            serializer.Serialize<APIGatewayProxyRequest>(request, requestStream);
            requestStream.Position = 0;

            var responseStream = await function.FunctionHandlerAsync(requestStream, lambdaContext);

            var response = serializer.Deserialize<APIGatewayProxyResponse>(responseStream);
            return response;
        }
    }
}

Change namespace for helper extension method to Amazon.Lambda.TestUtilities to make it more discover able when writing tests.


// 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.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.NamingStyles
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    internal sealed class CSharpNamingStyleDiagnosticAnalyzer : NamingStyleDiagnosticAnalyzerBase<SyntaxKind>
    {
        protected override ImmutableArray<SyntaxKind> SupportedSyntaxKinds { get; } =
            ImmutableArray.Create(
                SyntaxKind.VariableDeclarator,
                SyntaxKind.ForEachStatement,
                SyntaxKind.CatchDeclaration,
                SyntaxKind.SingleVariableDesignation,
                SyntaxKind.LocalFunctionStatement,
                SyntaxKind.Parameter,
                SyntaxKind.TypeParameter);

        // Parameters of positional record declarations should be ignored because they also
        // considered properties, and that naming style makes more sense
        protected override bool ShouldIgnore(ISymbol symbol)
            => (symbol.IsKind(SymbolKind.Parameter)
            && IsParameterOfRecordDeclaration(symbol.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax()))
            || !symbol.CanBeReferencedByName;

        private static bool IsParameterOfRecordDeclaration(SyntaxNode? node)
            => node is ParameterSyntax
            {
                Parent: ParameterListSyntax
                {
                    Parent: RecordDeclarationSyntax
                }
            };
    }
}

// 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.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.NamingStyles
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    internal sealed class CSharpNamingStyleDiagnosticAnalyzer : NamingStyleDiagnosticAnalyzerBase<SyntaxKind>
    {
        protected override ImmutableArray<SyntaxKind> SupportedSyntaxKinds { get; } =
            ImmutableArray.Create(
                SyntaxKind.VariableDeclarator,
                SyntaxKind.ForEachStatement,
                SyntaxKind.CatchDeclaration,
                SyntaxKind.SingleVariableDesignation,
                SyntaxKind.LocalFunctionStatement,
                SyntaxKind.Parameter,
                SyntaxKind.TypeParameter);

        protected override bool ShouldIgnore(ISymbol symbol)
        {
            if (symbol.IsKind(SymbolKind.Parameter)
                && symbol.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is ParameterSyntax
                {
                    Parent: ParameterListSyntax
                    {
                        Parent: RecordDeclarationSyntax
                    }
                })
            {
                // Parameters of positional record declarations should be ignored because they also
                // considered properties, and that naming style makes more sense
                return true;
            }

            if (!symbol.CanBeReferencedByName)
            {
                // Explicit interface implementation falls into here, as they don't own their names
                // Two symbols are involved here, and symbol.ExplicitInterfaceImplementations only applies for one
                return true;
            }

            return false;
        }
    }
}

Expand and add comment for ShouldIgnore.


using System;

namespace FractionCalculator.Class
{
    public struct Fraction
    {
        private long numerator;
        private long denominator;

        public Fraction(long numerator, long denominator) : this()
        {
            this.Numerator = numerator;
            this.Denominator = denominator;
        }

        public long Denominator
        {
            get { return this.denominator; }
            set
            {
                if (value <= 0)
                    throw new DivideByZeroException("Denominator cannot be zero or negative");
                this.denominator = value;
            }
        }

        public long Numerator
        {
            get { return this.numerator; }
            set
            {
                if (value <= 0)
                    throw new ArgumentException("numerator", "Numerator cannot be zero or negative!");
                this.numerator = value;
            }
        }

        public override string ToString()
        {
            return string.Format();
        }
    }
}

using System;

namespace FractionCalculator.Class
{
    public struct Fraction
    {
        private long numerator;
        private long denominator;

        public Fraction(long numerator, long denominator) : this()
        {
            this.Numerator = numerator;
            this.Denominator = denominator;
        }

        public long Denominator
        {
            get { return this.denominator; }
            set
            {
                if (value <= 0)
                    throw new DivideByZeroException("Denominator cannot be zero or negative");
                this.denominator = value;
            }
        }

        public long Numerator
        {
            get { return this.numerator; }
            set
            {
                if (value <= 0)
                    throw new ArgumentException("numerator", "Numerator cannot be zero or negative!");
                this.numerator = value;
            }
        }

        public static Fraction operator +(Fraction fraction1, Fraction fraction2)
        {
            return new Fraction(fraction1.Numerator + fraction2.Numerator, fraction1.Denominator + fraction2.Denominator);
        }

        public static Fraction operator -(Fraction fraction1, Fraction fraction2)
        {
            return new Fraction(fraction1.Numerator - fraction2.Numerator, fraction1.Denominator - fraction2.Denominator);
        }

        //public override string ToString()
        //{
        //    return string.Format();
        //}
    }
}

Create method for overload operator + and -


// 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.
/*=============================================================================
**
** File: ExceptionNotification.cs
**
**
** Purpose: Contains definitions for supporting Exception Notifications.
**
** Created: 10/07/2008
**
** <owner>gkhanna</owner>
**
=============================================================================*/
#if FEATURE_EXCEPTION_NOTIFICATIONS
namespace System.Runtime.ExceptionServices {
    using System;

    // Definition of the argument-type passed to the FirstChanceException event handler
    public class FirstChanceExceptionEventArgs : EventArgs
    {
        // Constructor
        public FirstChanceExceptionEventArgs(Exception exception)
        {
            m_Exception = exception;
        }

        // Returns the exception object pertaining to the first chance exception
        public Exception Exception
        {
            get { return m_Exception; }
        }

        // Represents the FirstChance exception instance
        private Exception m_Exception;
    }
}
#endif // FEATURE_EXCEPTION_NOTIFICATIONS

// 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.
/*=============================================================================
**
** File: ExceptionNotification.cs
**
**
** Purpose: Contains definitions for supporting Exception Notifications.
**
** Created: 10/07/2008
**
** <owner>gkhanna</owner>
**
=============================================================================*/
#if FEATURE_EXCEPTION_NOTIFICATIONS
namespace System.Runtime.ExceptionServices {
    using System;
    using System.Runtime.ConstrainedExecution;

    // Definition of the argument-type passed to the FirstChanceException event handler
    public class FirstChanceExceptionEventArgs : EventArgs
    {
        // Constructor
        public FirstChanceExceptionEventArgs(Exception exception)
        {
            m_Exception = exception;
        }

        // Returns the exception object pertaining to the first chance exception
        public Exception Exception
        {
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            get { return m_Exception; }
        }

        // Represents the FirstChance exception instance
        private Exception m_Exception;
    }
}
#endif // FEATURE_EXCEPTION_NOTIFICATIONS

Remove FirstChanceExceptionEventArgs from BCL folder. The file has been moved into mscorlib folder

[tfs-changeset: 1630635]