using MediatR;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using System;
using System.Collections.Generic;
using System.Text;

namespace Ordering.Domain.Events
{
    /// <summary>
    /// Event used when an order is created
    /// </summary>
    public class OrderStartedDomainEvent : INotification
    {
        public string UserId { get; private set; }
        public int CardTypeId { get; private set; }
        public string CardNumber { get; private set; }
        public string CardSecurityNumber { get; private set; }
        public string CardHolderName { get; private set; }
        public DateTime CardExpiration { get; private set; }
        public Order Order { get; private set; }

        public OrderStartedDomainEvent(Order order, string userId,
                                       int cardTypeId, string cardNumber,
                                       string cardSecurityNumber, string cardHolderName,
                                       DateTime cardExpiration)
        {
            Order = order;
            UserId = userId;
            CardTypeId = cardTypeId;
            CardNumber = cardNumber;
            CardSecurityNumber = cardSecurityNumber;
            CardHolderName = cardHolderName;
            CardExpiration = cardExpiration;
        }
    }
}

using MediatR;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using System;
using System.Collections.Generic;
using System.Text;

namespace Ordering.Domain.Events
{
    /// <summary>
    /// Event used when an order is created
    /// </summary>
    public class OrderStartedDomainEvent : INotification
    {
        public string UserId { get; }
        public int CardTypeId { get; }
        public string CardNumber { get; }
        public string CardSecurityNumber { get; }
        public string CardHolderName { get; }
        public DateTime CardExpiration { get; }
        public Order Order { get; }

        public OrderStartedDomainEvent(Order order, string userId,
                                       int cardTypeId, string cardNumber,
                                       string cardSecurityNumber, string cardHolderName,
                                       DateTime cardExpiration)
        {
            Order = order;
            UserId = userId;
            CardTypeId = cardTypeId;
            CardNumber = cardNumber;
            CardSecurityNumber = cardSecurityNumber;
            CardHolderName = cardHolderName;
            CardExpiration = cardExpiration;
        }
    }
}

Remove private setters to make class immutable

Remove private setters to make a class truly immutable. Otherwise, properties can be updated outside of constructor. This also makes code cleaner. Same in docs https://github.com/dotnet/docs/pull/4755


using System;

namespace Hlpr
{
	class WarpHelp
	{
		public static double Distance(double x1, double y1, double z1, double x2, double y2, double z2)
		{
			double dis;
			dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
			dis = Math.Pow(dis,0.5);
			return dis;
		}
		public static double Distance(Vector3d v1, Vector3d v2)
		{
			double dis, x1, x2, y1, y2, z1, z2;
			ConvertVector3dToXYZCoords(v1, x1, y1, z1);
			ConvertVector3dToXYZCoords(v2, x2, y2, z2);
			dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
			dis = Math.Pow(dis,0.5);
			return dis;
		}
	}
}

using System;

namespace Hlpr
{
	class WarpHelp
	{
		public static double Distance(double x1, double y1, double z1, double x2, double y2, double z2)
		{
			double dis;
			dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
			dis = Math.Pow(dis,0.5);
			return dis;
		}
		public static double Distance(Vector3d v1, Vector3d v2)
		{
			double dis, x1, x2, y1, y2, z1, z2;
			ConvertVector3dToXYZCoords(v1, ref x1, ref y1, ref z1);
			ConvertVector3dToXYZCoords(v2, ref x2, ref y2, ref z2);
			dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
			dis = Math.Pow(dis,0.5);
			return dis;
		}
	}
}

Fix non-existant ref vars in function calls.


using System;

namespace Umbraco.Web.Models.ContentEditing
{
    public class RollbackVersion
    {
        public int VersionId { get; set; }

        public DateTime VersionDate { get; set; }

        public string VersionAuthorName { get; set; }
    }
}

using System;
using System.Runtime.Serialization;

namespace Umbraco.Web.Models.ContentEditing
{
    [DataContract(Name = "rollbackVersion", Namespace = "")]
    public class RollbackVersion
    {
        [DataMember(Name = "versionId")]
        public int VersionId { get; set; }

        [DataMember(Name = "versionDate")]
        public DateTime VersionDate { get; set; }

        [DataMember(Name = "versionAuthorName")]
        public string VersionAuthorName { get; set; }
    }
}

Make the JSON model over the API control be the correct casing & make Mads happy :)


using System;
using log4net;
using Quartz;

namespace DCS.Core.Scheduler
{
    public sealed class CronTask : IJob
    {
        private readonly string _cronConfig;
        private readonly ILog _logger = LogManager.GetLogger(typeof(CronTask));
        private readonly Action _task;
        private readonly string _taskName;

        public CronTask()
        {
        }

        public CronTask(string taskName, string cronConfig, Action action)
        {
            _taskName = taskName;
            _task = action;
            _cronConfig = cronConfig;
        }

        public string TaskName
        {
            get { return _taskName; }
        }

        public string CronConfig
        {
            get { return _cronConfig; }
        }

        public void Execute(IJobExecutionContext context)
        {
            var task = (CronTask)context.MergedJobDataMap.Get("task");

            // executes the task
            _logger.Info("Executing task : " + task.TaskName);
            task._task();
        }
    }
}

using System;
using log4net;
using Quartz;

namespace DCS.Core.Scheduler
{
    public sealed class CronTask : IJob
    {
        private readonly string _cronConfig;
        private readonly ILog _logger = LogManager.GetLogger(typeof(CronTask));
        private readonly Action _task;
        private readonly string _taskName;

        public CronTask()
        {
        }

        public CronTask(string taskName, string cronConfig, Action action)
        {
            _taskName = taskName;
            _task = action;
            _cronConfig = cronConfig;
        }

        public string TaskName
        {
            get { return _taskName; }
        }

        public string CronConfig
        {
            get { return _cronConfig; }
        }

        public void Execute(IJobExecutionContext context)
        {
            var task = (CronTask)context.MergedJobDataMap.Get("task");

            // executes the task
            _logger.Debug("Executing task : " + task.TaskName);
            task._task();
        }
    }
}

Set Datawriter executing logs to debug level


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zermelo.API.Interfaces;
using Zermelo.API.Services.Interfaces;

namespace Zermelo.API.Services
{
    internal class UrlBuilder : IUrlBuilder
    {
        const string _https = "https://";
        const string _baseUrl = "zportal.nl/api";
        const string _apiVersion = "v2";
        const string _accessToken = "access_token";

        public string GetAuthenticatedUrl(IAuthentication auth, string endpoint, Dictionary<string, string> options = null)
        {
            string url = GetUrl(auth.Host, endpoint, options);

            if (url.Contains("?"))
                url += "&";
            else
                url += "?";

            url += $"{_accessToken}={auth.Token}";

            return url;
        }

        public string GetUrl(string host, string endpoint, Dictionary<string, string> options = null)
        {
            string url = $"{_https}{host}.{_baseUrl}/{_apiVersion}/{endpoint}";

            if (options != null)
            {
                url += "?";

                foreach (var x in options)
                {
                    url += $"{x.Key}={x.Value}&";
                }

                url = url.TrimEnd('&');
            }

            return url;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zermelo.API.Interfaces;
using Zermelo.API.Services.Interfaces;

namespace Zermelo.API.Services
{
    internal class UrlBuilder : IUrlBuilder
    {
        const string _https = "https://";
        const string _baseUrl = "zportal.nl/api";
        const string _apiVersion = "v3";
        const string _accessToken = "access_token";

        public string GetAuthenticatedUrl(IAuthentication auth, string endpoint, Dictionary<string, string> options = null)
        {
            string url = GetUrl(auth.Host, endpoint, options);

            if (url.Contains("?"))
                url += "&";
            else
                url += "?";

            url += $"{_accessToken}={auth.Token}";

            return url;
        }

        public string GetUrl(string host, string endpoint, Dictionary<string, string> options = null)
        {
            string url = $"{_https}{host}.{_baseUrl}/{_apiVersion}/{endpoint}";

            if (options != null)
            {
                url += "?";

                foreach (var x in options)
                {
                    url += $"{x.Key}={x.Value}&";
                }

                url = url.TrimEnd('&');
            }

            return url;
        }
    }
}

Update REST API version to v3

Update REST API version to v3

Issue #2


using InfluxDB.LineProtocol.Collector;
using System;

namespace InfluxDB.LineProtocol
{
    public class CollectorConfiguration
    {
        readonly IPointEmitter _parent;
        readonly PipelinedCollectorTagConfiguration _tag;
        readonly PipelinedCollectorEmitConfiguration _emitter;
        readonly PipelinedCollectorBatchConfiguration _batcher;

        public CollectorConfiguration()
            : this(null)
        {
        }

        internal CollectorConfiguration(IPointEmitter parent = null)
        {
            _parent = parent;
            _tag = new PipelinedCollectorTagConfiguration(this);
            _emitter = new PipelinedCollectorEmitConfiguration(this);
            _batcher = new PipelinedCollectorBatchConfiguration(this);
        }

        public CollectorTagConfiguration Tag
        {
            get { return _tag; }
        }

        public CollectorEmitConfiguration WriteTo
        {
            get { return _emitter; }
        }

        public CollectorBatchConfiguration Batch
        {
            get { return _batcher; }
        }

        public MetricsCollector CreateCollector()
        {
            Action disposeEmitter;
            Action disposeBatcher;

            var emitter = _parent;
            emitter = _emitter.CreateEmitter(emitter, out disposeEmitter);
            emitter = _batcher.CreateEmitter(emitter, out disposeBatcher);

            return new PipelinedMetricsCollector(emitter, _tag.CreateEnricher(), () =>
            {
                if (disposeBatcher != null)
                    disposeBatcher();

                if (disposeEmitter != null)
                    disposeBatcher();
            });
        }
    }
}

using InfluxDB.LineProtocol.Collector;
using System;

namespace InfluxDB.LineProtocol
{
    public class CollectorConfiguration
    {
        readonly IPointEmitter _parent;
        readonly PipelinedCollectorTagConfiguration _tag;
        readonly PipelinedCollectorEmitConfiguration _emitter;
        readonly PipelinedCollectorBatchConfiguration _batcher;

        public CollectorConfiguration()
            : this(null)
        {
        }

        internal CollectorConfiguration(IPointEmitter parent = null)
        {
            _parent = parent;
            _tag = new PipelinedCollectorTagConfiguration(this);
            _emitter = new PipelinedCollectorEmitConfiguration(this);
            _batcher = new PipelinedCollectorBatchConfiguration(this);
        }

        public CollectorTagConfiguration Tag
        {
            get { return _tag; }
        }

        public CollectorEmitConfiguration WriteTo
        {
            get { return _emitter; }
        }

        public CollectorBatchConfiguration Batch
        {
            get { return _batcher; }
        }

        public MetricsCollector CreateCollector()
        {
            Action disposeEmitter;
            Action disposeBatcher;

            var emitter = _parent;
            emitter = _emitter.CreateEmitter(emitter, out disposeEmitter);
            emitter = _batcher.CreateEmitter(emitter, out disposeBatcher);

            return new PipelinedMetricsCollector(emitter, _tag.CreateEnricher(), () =>
            {
                if (disposeBatcher != null)
                    disposeBatcher();

                if (disposeEmitter != null)
                    disposeEmitter();
            });
        }
    }
}

Call the disposeEmitter action on dispose


////////////////////////////////////////////////////////////////
//
// (c) 2009, 2010 Careminster Limited and Melanie Thielker
//
// All rights reserved
//
using System;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;

namespace OpenSim.Services.Interfaces
{
    public interface IBakedTextureModule
    {
        WearableCacheItem[] Get(UUID id);
        void Store(UUID id, WearableCacheItem[] data);
    }
}

/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;

namespace OpenSim.Services.Interfaces
{
    public interface IBakedTextureModule
    {
        WearableCacheItem[] Get(UUID id);
        void Store(UUID id, WearableCacheItem[] data);
    }
}

Replace proprietary file header with BSD one


@model HeadRaceTimingSite.Models.Competition
@{
    ViewData["Title"] = Model.Name;
}

<results-list competition-id="@Model.CompetitionId" first-intermediate-name="Barnes" second-intermediate-name="Hammersmith" search-value="{{searchValue}}" show-first-intermediate show-second-intermediate></results-list>

@section titleBar{
        <div main-title>@ViewData["Title"]</div>
        <paper-icon-button icon="search" id="searchButton"></paper-icon-button>
        <paper-icon-button icon="cloud-download" id="downloadButton"></paper-icon-button>
        <paper-icon-button class="searchTools" icon="arrow-back" id="backButton"></paper-icon-button>
        <paper-input class="searchTools" id="searchBox" value="{{searchValue}}" no-label-float="true"></paper-input>
}

@section scripts{
    <script>
        window.addEventListener('WebComponentsReady', function (e) {
            document.querySelector("#searchButton").addEventListener("click", function (e) {
                $("#searchButton").css("display", "none");
                $("#downloadButton").css("display", "none");
                $("#backButton").css("display", "block");
                $("#searchBox").css("display", "block");
                $("#searchBox").focus();
                $("[main-title]").css("display", "none");
            });
            document.querySelector("#backButton").addEventListener("click", function (e) {
                $("#searchButton").css("display", "inline-block");
                $("#downloadButton").css("display", "inline-block");
                $("#backButton").css("display", "none");
                $("#searchBox").css("display", "none");
                $("[main-title]").css("display", "block");
            });
            document.querySelector("#downloadButton").addEventListener("click", function (e) {
                location.href = '/Competition/DetailsAsCsv/@Model.CompetitionId'
            });
        });
    </script>
}

@model HeadRaceTimingSite.Models.Competition
@{
    ViewData["Title"] = Model.Name;
}

<results-list competition-id="@Model.CompetitionId" first-intermediate-name="Barnes" second-intermediate-name="Hammersmith" search-value="{{searchValue}}" show-first-intermediate show-second-intermediate></results-list>

@section titleBar{
        <div main-title>@ViewData["Title"]</div>
}

Remove future features from UI

Remove future features from UI


using System;
using NUnit.Framework;

namespace nunit.v3
{
    [TestFixture]
    public class FlakyTest
    {
        [Test]
        [Retry(5)]
        public void TestFlakyMethod()
        {
            int result = 0;
            try
            {
                result = FlakyAdd(2, 2);
            }
            catch(Exception ex)
            {
                Assert.Fail($"Test failed with unexpected exception, {ex.Message}");
            }
            Assert.That(result, Is.EqualTo(4));
        }

        int FlakyAdd(int x, int y)
        {
            var rand = new Random();
            if (rand.NextDouble() > 0.5)
                throw new ArgumentOutOfRangeException();

            return x + y;
        }

        [Test]
        [Retry(2)]
        public void TestFlakySubtract()
        {
            Assert.That(FlakySubtract(4, 2), Is.EqualTo(2));
        }

        int count = 0;

        int FlakySubtract(int x, int y)
        {
            count++;
            return count == 1 ? 42 : x - y;
        }
    }
}

using System;
using NUnit.Framework;

namespace nunit.v3
{
    [TestFixture]
    public class FlakyTest
    {
        [Test]
        [Retry(5)]
        public void TestFlakyMethod()
        {
            int result = 0;
            try
            {
                result = FlakyAdd(2, 2);
            }
            catch(Exception ex)
            {
                Assert.Fail($"Test failed with unexpected exception, {ex.Message}");
            }
            Assert.That(result, Is.EqualTo(4));
        }

        int count2 = 0;

        int FlakyAdd(int x, int y)
        {
            if(count2++ == 2)
                throw new ArgumentOutOfRangeException();

            return x + y;
        }

        [Test]
        [Retry(2)]
        public void TestFlakySubtract()
        {
            Assert.That(FlakySubtract(4, 2), Is.EqualTo(2));
        }

        int count = 0;

        int FlakySubtract(int x, int y)
        {
            count++;
            return count == 1 ? 42 : x - y;
        }
    }
}

Make flaky tests a bit less flaky

Make flaky tests a bit less flaky


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

namespace Snowflake.Information.MediaStore
{
    public class MediaStoreSection
    {
        public string SectionName { get; set; }
        public Dictionary<string, string> MediaStoreItems;
        private string mediaStoreRoot;
        public MediaStoreSection(string sectionName, MediaStore mediaStore)
        {
            this.mediaStoreRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Snowflake", "mediastores", mediaStore.MediaStoreKey, sectionName);
            this.SectionName = sectionName;
        }

        private void LoadMediaStore()
        {
            try
            {
                JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Path.Combine(mediaStoreRoot, ".mediastore")));
            }
            catch
            {
                return;
            }
        }

    }
}

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

namespace Snowflake.Information.MediaStore
{
    public class MediaStoreSection
    {
        public string SectionName { get; set; }
        public Dictionary<string, string> MediaStoreItems;
        private string mediaStoreRoot;
        public MediaStoreSection(string sectionName, MediaStore mediaStore)
        {
            this.mediaStoreRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Snowflake", "mediastores", mediaStore.MediaStoreKey, sectionName);
            this.SectionName = sectionName;
            this.MediaStoreItems = this.LoadMediaStore();
        }

        private Dictionary<string, string> LoadMediaStore()
        {
            try
            {
                return JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Path.Combine(mediaStoreRoot, ".mediastore")));
            }
            catch
            {
                return new Dictionary<string, string>();
            }
        }
        public void Add(string key, string fileName){
            File.Copy(fileName, Path.Combine(this.mediaStoreRoot, Path.GetFileName(fileName));
            this.MediaStoreItems.Add(key, Path.GetFileName(fileName));
            this.UpdateMediaStoreRecord();
        }
        public void Remove(string key){
            File.Delete(Path.Combine(this.mediaStoreRoot, Path.GetFileName(fileName));
            this.MediaStoreItems.Remove(key);
            this.UpdateMediaStoreRecord();
        }
        private void UpdateMediaStoreRecord(){
            string record = JsonConvert.SerializeObject(this.MediaStoreItems);
            File.WriteAllText(Path.Combine(mediaStoreRoot, ".mediastore"));
        }
    }
}

Add methods to manipulate MediaStoreItems


/*
 JustMock Lite
 Copyright © 2019 Progress Software Corporation

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

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

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

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

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

/*
 JustMock Lite
 Copyright © 2019 Progress Software Corporation

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

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

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

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

        public static void CaptureContext()
        {
            ProfilerInterceptor.GuardInternal(() =>
                resolver.CaptureContext()
            );
        }
    }
}

Add ProfilerInterceptor.GuardInternal() for public APIs even if they are hidden.


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IHaveInitializationStrategiesExtensionMethods.cs" company="Naos">
//   Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Naos.Deployment.Core
{
    using System.Collections.Generic;
    using System.Linq;

    using Naos.Deployment.Contract;

    /// <summary>
    /// Additional behavior to add on IHaveInitializationStrategies.
    /// </summary>
    public static class IHaveInitializationStrategiesExtensionMethods
    {
        /// <summary>
        /// Retrieves the initialization strategies matching the specified type.
        /// </summary>
        /// <typeparam name="T">Type of initialization strategy to look for.</typeparam>
        /// <param name="objectWithInitializationStrategies">Object to operate on.</param>
        /// <returns>Collection of initialization strategies matching the type specified.</returns>
        public static ICollection<T> GetInitializationStrategiesOf<T>(
            this IHaveInitializationStrategies objectWithInitializationStrategies) where T : InitializationStrategyBase
        {
            var ret = objectWithInitializationStrategies.InitializationStrategies.Select(strat => strat as T).Where(_ => _ != null).ToList();

            return ret;
        }
    }
}

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IHaveInitializationStrategiesExtensionMethods.cs" company="Naos">
//   Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Naos.Deployment.Core
{
    using System.Collections.Generic;
    using System.Linq;

    using Naos.Deployment.Contract;

    /// <summary>
    /// Additional behavior to add on IHaveInitializationStrategies.
    /// </summary>
    public static class IHaveInitializationStrategiesExtensionMethods
    {
        /// <summary>
        /// Retrieves the initialization strategies matching the specified type.
        /// </summary>
        /// <typeparam name="T">Type of initialization strategy to look for.</typeparam>
        /// <param name="objectWithInitializationStrategies">Object to operate on.</param>
        /// <returns>Collection of initialization strategies matching the type specified.</returns>
        public static ICollection<T> GetInitializationStrategiesOf<T>(
            this IHaveInitializationStrategies objectWithInitializationStrategies) where T : InitializationStrategyBase
        {
            var ret =
                (objectWithInitializationStrategies.InitializationStrategies ?? new List<InitializationStrategyBase>())
                    .Select(strat => strat as T).Where(_ => _ != null).ToList();

            return ret;
        }
    }
}

Fix potential null ref exception.

Fix potential null ref exception.


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

namespace osu.Game.Overlays.Settings
{
    public class SettingsTextBox : SettingsItem<string>
    {
        protected override Drawable CreateControl() => new OutlinedTextBox
        {
            Margin = new MarginPadding { Top = 5 },
            RelativeSizeAxes = Axes.X,
            CommitOnFocusLost = true
        };
    }
}

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

using System;
using osu.Framework.Bindables;
using osu.Framework.Graphics;

namespace osu.Game.Overlays.Settings
{
    public class SettingsTextBox : SettingsItem<string>
    {
        protected override Drawable CreateControl() => new OutlinedTextBox
        {
            Margin = new MarginPadding { Top = 5 },
            RelativeSizeAxes = Axes.X,
            CommitOnFocusLost = true
        };

        public override Bindable<string> Current
        {
            get => base.Current;
            set
            {
                if (value.Default == null)
                    throw new InvalidOperationException($"Bindable settings of type {nameof(Bindable<string>)} should have a non-null default value.");

                base.Current = value;
            }
        }
    }
}

Add exception to catch any incorrect defaults of `Bindable<string>`


using System.Threading.Tasks;

namespace osu.Game.Online.RealtimeMultiplayer
{
    /// <summary>
    /// An interface defining the spectator server instance.
    /// </summary>
    public interface IMultiplayerServer
    {
        /// <summary>
        /// Request to join a multiplayer room.
        /// </summary>
        /// <param name="roomId">The databased room ID.</param>
        /// <exception cref="UserAlreadyInMultiplayerRoom">If the user is already in the requested (or another) room.</exception>
        Task<MultiplayerRoom> JoinRoom(long roomId);

        /// <summary>
        /// Request to leave the currently joined room.
        /// </summary>
        Task LeaveRoom();
    }
}

using System.Threading.Tasks;

namespace osu.Game.Online.RealtimeMultiplayer
{
    /// <summary>
    /// An interface defining the spectator server instance.
    /// </summary>
    public interface IMultiplayerServer
    {
        /// <summary>
        /// Request to join a multiplayer room.
        /// </summary>
        /// <param name="roomId">The databased room ID.</param>
        /// <exception cref="UserAlreadyInMultiplayerRoom">If the user is already in the requested (or another) room.</exception>
        Task<MultiplayerRoom> JoinRoom(long roomId);

        /// <summary>
        /// Request to leave the currently joined room.
        /// </summary>
        Task LeaveRoom();

        /// <summary>
        /// Transfer the host of the currently joined room to another user in the room.
        /// </summary>
        /// <param name="userId">The new user which is to become host.</param>
        Task TransferHost(long userId);

        /// <summary>
        /// As the host, update the settings of the currently joined room.
        /// </summary>
        /// <param name="settings">The new settings to apply.</param>
        Task ChangeSettings(MultiplayerRoomSettings settings);
    }
}

Add missing methods to server interface

Add missing methods to server interface


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

using System;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
    internal static class DocumentationCommentExtensions
    {
        public static bool IsMultilineDocComment(this DocumentationCommentTriviaSyntax documentationComment)
        {
            return documentationComment.ToFullString().StartsWith("/**", StringComparison.Ordinal);
        }
    }
}

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

using System;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
    internal static class DocumentationCommentExtensions
    {
        public static bool IsMultilineDocComment(this DocumentationCommentTriviaSyntax documentationComment)
        {
            if (documentationComment == null)
            {
                return false;
            }
            return documentationComment.ToFullString().StartsWith("/**", StringComparison.Ordinal);
        }
    }
}

Handle null values in IsMultilineDocComment


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

namespace WikipediaAvsAnTrieExtractor {
    public partial class RegexTextUtils {
        //Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
        //This code is bottlenecked by regexes, so this really matters, here.

        readonly Regex followingAn = new Regex(@"\b(?<article>[Aa]n?) [""()‘’“”$'-]*(?<word>[^\s""()‘’“”$'-]+)", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
        public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) {
            return
                from Match m in followingAn.Matches(text)
                select new AvsAnSighting { Word = m.Groups["word"].Value + " ", PrecededByAn = m.Groups["article"].Value.Length == 2 };
        }
    }
}

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

namespace WikipediaAvsAnTrieExtractor {
    public partial class RegexTextUtils {
        //Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
        //This code is bottlenecked by regexes, so this really matters, here.

        readonly Regex followingAn = new Regex(@"(^|[\s""()‘’“”'])(?<article>[Aa]n?) [""()‘’“”$']*(?<word>[^\s""()‘’“”$'-]+)", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
        //watch out for dashes before "A" because of things like "Triple-A annotation"

        public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) {
            return
                from Match m in followingAn.Matches(text)
                select new AvsAnSighting { Word = m.Groups["word"].Value + " ", PrecededByAn = m.Groups["article"].Value.Length == 2 };
        }
    }
}

Improve a/an word extraction to avoid problematic cases like "Triple-A classification"


using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;

namespace MiX.Integrate.Shared.Entities.Messages
{
	public class SendJobMessageCarrier
	{
		public SendJobMessageCarrier() { }

		public short VehicleId { get; set; }
		public string Description { get; set; }
		public string UserDescription { get; set; }
		public string Body { get; set; }
		public DateTime? StartDate { get; set; }
		public DateTime? ExpiryDate { get; set; }
		public bool RequiresAddress { get; set; }
		public bool AddAddressSummary { get; set; }
		public bool UseFirstAddressForSummary { get; set; }
		public JobMessageActionNotifications NotificationSettings { get; set; }
		public int[] AddressList { get; set; }
		public long[] LocationList { get; set; }
		public CommsTransports Transport { get; set; }
		public bool Urgent { get; set; }
	}
}

using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;

namespace MiX.Integrate.Shared.Entities.Messages
{
	public class SendJobMessageCarrier
	{
		public SendJobMessageCarrier() { }

		public short VehicleId { get; set; }
		public string Description { get; set; }
		public string UserDescription { get; set; }
		public string Body { get; set; }
		public DateTime? StartDate { get; set; }
		public DateTime? ExpiryDate { get; set; }
		public bool RequiresAddress { get; set; }
		public bool AddAddressSummary { get; set; }
		public bool UseFirstAddressForSummary { get; set; }
		public JobMessageActionNotifications NotificationSettings { get; set; }
		public long[] AddressList { get; set; }
		public CommsTransports Transport { get; set; }
		public bool Urgent { get; set; }
	}
}

Revert "FLEET-9992: Add extra property to use new long Id's"

This reverts commit c4eecf2480fa0cb1924df562024c4a3d580333de.


using UnityEngine;
using NPBehave;

public class NPBehaveExampleHelloBlackboardsAI : MonoBehaviour
{
    private Root behaviorTree;

    void Start()
    {
        behaviorTree = new Root(

            // toggle the 'toggled' blackboard boolean flag around every 500 milliseconds
            new Service(0.5f, () => { behaviorTree.Blackboard.Set("foo", !behaviorTree.Blackboard.GetBool("foo")); },

                new Selector(

                    // Check the 'toggled' flag. Stops.IMMEDIATE_RESTART means that the Blackboard will be observed for changes
                    // while this or any lower priority branches are executed. If the value changes, the corresponding branch will be
                    // stopped and it will be immediately jump to the branch that now matches the condition.
                    new BlackboardCondition("foo", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART,

                        // when 'toggled' is true, this branch will get executed.
                        new Sequence(

                            // print out a message ...
                            new Action(() => Debug.Log("foo")),

                            // ... and stay here until the `BlackboardValue`-node stops us because the toggled flag went false.
                            new WaitUntilStopped()
                        )
                    ),

                    // when 'toggled' is false, we'll eventually land here
                    new Sequence(
                        new Action(() => Debug.Log("bar")),
                        new WaitUntilStopped()
                    )
                )
            )
        );
        behaviorTree.Start();
    }
}

using UnityEngine;
using NPBehave;

public class NPBehaveExampleHelloBlackboardsAI : MonoBehaviour
{
    private Root behaviorTree;

    void Start()
    {
        behaviorTree = new Root(

            // toggle the 'toggled' blackboard boolean flag around every 500 milliseconds
            new Service(0.5f, () => { behaviorTree.Blackboard.Set("foo", !behaviorTree.Blackboard.GetBool("foo")); },

                new Selector(

                    // Check the 'toggled' flag. Stops.IMMEDIATE_RESTART means that the Blackboard will be observed for changes
                    // while this or any lower priority branches are executed. If the value changes, the corresponding branch will be
                    // stopped and it will be immediately jump to the branch that now matches the condition.
                    new BlackboardCondition("foo", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART,

                        // when 'toggled' is true, this branch will get executed.
                        new Sequence(

                            // print out a message ...
                            new Action(() => Debug.Log("foo")),

                            // ... and stay here until the `BlackboardValue`-node stops us because the toggled flag went false.
                            new WaitUntilStopped()
                        )
                    ),

                    // when 'toggled' is false, we'll eventually land here
                    new Sequence(
                        new Action(() => Debug.Log("bar")),
                        new WaitUntilStopped()
                    )
                )
            )
        );
        behaviorTree.Start();

        // attach the debugger component if executed in editor (helps to debug in the inspector)
#if UNITY_EDITOR
        Debugger debugger = (Debugger)this.gameObject.AddComponent(typeof(Debugger));
        debugger.BehaviorTree = behaviorTree;
#endif
    }
}

Add debugger to HelloWorldBlacksboardAI example


// Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using AuthServer.Attributes;
using AuthServer.Constants.Net;
using Framework.Database;
using Framework.Database.Auth;

namespace AuthServer.Network.Packets.Handler
{
    class AuthHandler
    {
        [AuthPacket(ClientMessage.State1)]
        public static void HandleState1(Packet packet, AuthSession session)
        {
            // Send same data back for now.
            session.SendRaw(packet.Data);
        }

        [AuthPacket(ClientMessage.State2)]
        public static void HandleState2(Packet packet, AuthSession session)
        {
            // Send same data back for now.
            session.SendRaw(packet.Data);
        }

        [AuthPacket(ClientMessage.AuthRequest)]
        public static void HandleAuthRequest(Packet packet, AuthSession session)
        {
            packet.Read<uint>(32);
            packet.Read<ulong>(64);

            var loginName = packet.ReadString();

            Console.WriteLine($"Account '{loginName}' tries to connect.");

            var account = DB.Auth.Single<Account>(a => a.Email == loginName);

            if (account != null && account.Online)
            {
                var authComplete = new Packet(ServerMessage.AuthComplete);

                authComplete.Write(0, 32);

                session.Send(authComplete);

                var connectToRealm = new Packet(ServerMessage.ConnectToRealm);

                // Data...

                session.Send(connectToRealm);
            }
        }
    }
}

// Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using AuthServer.Attributes;
using AuthServer.Constants.Net;
using Framework.Database;
using Framework.Database.Auth;

namespace AuthServer.Network.Packets.Handler
{
    class AuthHandler
    {
        [AuthPacket(ClientMessage.State1)]
        public static void HandleState1(Packet packet, AuthSession session)
        {
            // Send same data back for now.
            session.SendRaw(packet.Data);
        }

        [AuthPacket(ClientMessage.State2)]
        public static void HandleState2(Packet packet, AuthSession session)
        {
            // Send same data back for now.
            session.SendRaw(packet.Data);
        }

        [AuthPacket(ClientMessage.AuthRequest)]
        public static void HandleAuthRequest(Packet packet, AuthSession session)
        {
            packet.Read<uint>(32);
            packet.Read<ulong>(64);

            var loginName = packet.ReadString();

            Console.WriteLine($"Account '{loginName}' tries to connect.");

            //var account = DB.Auth.Single<Account>(a => a.Email == loginName);

            //if (account != null && account.Online)
            {
                var authComplete = new Packet(ServerMessage.AuthComplete);

                authComplete.Write(0, 32);

                session.Send(authComplete);

                var connectToRealm = new Packet(ServerMessage.ConnectToRealm);

                // Data...

                session.Send(connectToRealm);
            }
        }
    }
}

Disable account online check for now.

Disable account online check for now.


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

public class DropdownLanguageFontUpdater : MonoBehaviour
{
    [SerializeField]
    private Text textComponent;

	void Start ()
    {
        var language = LocalizationManager.instance.getAllLanguages()[transform.GetSiblingIndex() - 1];
        if (language.overrideFont != null)
        {
            textComponent.font = language.overrideFont;
            if (language.forceUnbold)
                textComponent.fontStyle = FontStyle.Normal;
        }
	}

	void Update ()
    {

	}
}

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

public class DropdownLanguageFontUpdater : MonoBehaviour
{
    [SerializeField]
    private Text textComponent;

	void Start ()
    {
        var languages = LocalizationManager.instance.getAllLanguages();
        LocalizationManager.Language language = languages[0];

        //Determine langauge index based on sibling position and selectable languages
        int index = 0;
        int objectIndex = transform.GetSiblingIndex() - 1;
        for (int i = 0; i < languages.Length; i++)
        {
            if (!languages[i].disableSelect)
            {
                if (index >= objectIndex)
                {
                    language = languages[i];
                    Debug.Log(textComponent.text + " is " + language.getLanguageID());
                    break;
                }
                index++;
            }

        }

        if (language.overrideFont != null)
        {
            textComponent.font = language.overrideFont;
            if (language.forceUnbold)
                textComponent.fontStyle = FontStyle.Normal;
        }
	}

	void Update ()
    {

	}
}

Fix incorrect font indexing in language dropdown


#if !NETCOREAPP
using System.ComponentModel;
#endif
using System.IO;
#if !NETCOREAPP
using System.Runtime.InteropServices;
#endif

namespace winsw.Util
{
    public static class FileHelper
    {
        public static void MoveOrReplaceFile(string sourceFileName, string destFileName)
        {
#if NETCOREAPP
            File.Move(sourceFileName, destFileName, true);
#else
            string sourceFilePath = Path.GetFullPath(sourceFileName);
            string destFilePath = Path.GetFullPath(destFileName);

            if (!NativeMethods.MoveFileEx(sourceFilePath, destFilePath, NativeMethods.MOVEFILE_REPLACE_EXISTING | NativeMethods.MOVEFILE_COPY_ALLOWED))
            {
                throw new Win32Exception();
            }
#endif
        }
#if !NETCOREAPP

        private static class NativeMethods
        {
            internal const uint MOVEFILE_REPLACE_EXISTING = 0x01;
            internal const uint MOVEFILE_COPY_ALLOWED = 0x02;

            [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW")]
            internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, uint dwFlags);
        }
#endif
    }
}

#if !NETCOREAPP
using System;
#endif
using System.IO;
#if !NETCOREAPP
using System.Runtime.InteropServices;
#endif

namespace winsw.Util
{
    public static class FileHelper
    {
        public static void MoveOrReplaceFile(string sourceFileName, string destFileName)
        {
#if NETCOREAPP
            File.Move(sourceFileName, destFileName, true);
#else
            string sourceFilePath = Path.GetFullPath(sourceFileName);
            string destFilePath = Path.GetFullPath(destFileName);

            if (!NativeMethods.MoveFileEx(sourceFilePath, destFilePath, NativeMethods.MOVEFILE_REPLACE_EXISTING | NativeMethods.MOVEFILE_COPY_ALLOWED))
            {
                throw GetExceptionForLastWin32Error(sourceFilePath);
            }
#endif
        }
#if !NETCOREAPP

        private static Exception GetExceptionForLastWin32Error(string path) => Marshal.GetLastWin32Error() switch
        {
            2 => new FileNotFoundException(null, path), // ERROR_FILE_NOT_FOUND
            3 => new DirectoryNotFoundException(), // ERROR_PATH_NOT_FOUND
            5 => new UnauthorizedAccessException(), // ERROR_ACCESS_DENIED
            _ => new IOException()
        };

        private static class NativeMethods
        {
            internal const uint MOVEFILE_REPLACE_EXISTING = 0x01;
            internal const uint MOVEFILE_COPY_ALLOWED = 0x02;

            [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW")]
            internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, uint dwFlags);
        }
#endif
    }
}

Throw correct exceptions for IO errors

Throw correct exceptions for IO errors


using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autofac;
using Crane.Core.Configuration.Modules;
using Crane.Core.IO;
using log4net;

namespace Crane.Integration.Tests.TestUtilities
{
    public static class ioc
    {
        private static IContainer _container;

        public static T Resolve<T>() where T : class
        {
            if (_container == null)
            {
                _container = BootStrap.Start();
            }

            if (_container.IsRegistered<T>())
            {
                return _container.Resolve<T>();
            }

            return ResolveUnregistered(_container, typeof(T)) as T;
        }

        public static object ResolveUnregistered(IContainer container, Type type)
        {
            var constructors = type.GetConstructors();
            foreach (var constructor in constructors)
            {
                try
                {
                    var parameters = constructor.GetParameters();
                    var parameterInstances = new List<object>();
                    foreach (var parameter in parameters)
                    {
                        var service = container.Resolve(parameter.ParameterType);
                        if (service == null) throw new Exception("Unkown dependency");
                        parameterInstances.Add(service);
                    }
                    return Activator.CreateInstance(type, parameterInstances.ToArray());
                }
                catch (Exception)
                {

                }
            }

            Debugger.Launch();
            throw new Exception("No contructor was found that had all the dependencies satisfied.");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autofac;
using Crane.Core.Configuration.Modules;
using Crane.Core.IO;
using log4net;

namespace Crane.Integration.Tests.TestUtilities
{
    public static class ioc
    {
        private static IContainer _container;

        private static readonly ILog _log = LogManager.GetLogger(typeof(Run));

        public static T Resolve<T>() where T : class
        {
            if (_container == null)
            {
                _container = BootStrap.Start();
            }

            if (_container.IsRegistered<T>())
            {
                return _container.Resolve<T>();
            }

            return ResolveUnregistered(_container, typeof(T)) as T;
        }

        public static object ResolveUnregistered(IContainer container, Type type)
        {
            var constructors = type.GetConstructors();
            foreach (var constructor in constructors)
            {
                try
                {
                    var parameters = constructor.GetParameters();
                    var parameterInstances = new List<object>();
                    foreach (var parameter in parameters)
                    {
                        var service = container.Resolve(parameter.ParameterType);
                        if (service == null) throw new Exception("Unkown dependency");
                        parameterInstances.Add(service);
                    }
                    return Activator.CreateInstance(type, parameterInstances.ToArray());
                }
                catch (Exception exception)
                {
                    _log.ErrorFormat("Error trying to create an instance of {0}. {1}{2}", type.FullName, Environment.NewLine, exception.ToString());
                }
            }

            throw new Exception("No contructor was found that had all the dependencies satisfied.");
        }
    }
}

Add better error logging to see why mono build is failing


using System.Web;
using System.Web.Mvc;
using Pelasoft.AspNet.Mvc.Slack;
using System.Configuration;

namespace Pelasoft.AspNet.Mvc.Slack.TestWeb
{
	public class FilterConfig
	{
		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new HandleErrorAttribute());

			var slackReport =
				new WebHookErrorReportFilter(
					new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"])
					{
						ChannelName = ConfigurationManager.AppSettings["slack:channel"],
						UserName = ConfigurationManager.AppSettings["slack:username"],
						IconEmoji = ConfigurationManager.AppSettings["slack:iconEmoji"],
						AttachmentColor = ConfigurationManager.AppSettings["slack:color"],
						AttachmentTitle = ConfigurationManager.AppSettings["slack:title"],
						AttachmentTitleLink = ConfigurationManager.AppSettings["slack:link"],
						Text = ConfigurationManager.AppSettings["slack:text"],
					}
			)
			{
				IgnoreHandled = true,
				IgnoreExceptionTypes = new[] { typeof(System.ApplicationException) },
			};
			filters.Add(slackReport, 1);
		}
	}
}

using System.Web;
using System.Web.Mvc;
using Pelasoft.AspNet.Mvc.Slack;
using System.Configuration;

namespace Pelasoft.AspNet.Mvc.Slack.TestWeb
{
	public class FilterConfig
	{
		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new HandleErrorAttribute());

			var slackReport =
				new WebHookErrorReportFilter(
					new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"])
					{
						ChannelName = ConfigurationManager.AppSettings["slack:channel"],
						UserName = ConfigurationManager.AppSettings["slack:username"],
						IconEmoji = ConfigurationManager.AppSettings["slack:iconEmoji"],
						AttachmentColor = ConfigurationManager.AppSettings["slack:color"],
						AttachmentTitle = ConfigurationManager.AppSettings["slack:title"],
						AttachmentTitleLink = ConfigurationManager.AppSettings["slack:link"],
						Text = ConfigurationManager.AppSettings["slack:text"],
					}
			)
			{
				IgnoreHandled = true,
				IgnoreExceptionTypes = new[] { typeof(System.ApplicationException) },
			};
			filters.Add(slackReport, 1);

			var slackReportEvented = new WebHookErrorReportFilter();
			slackReportEvented.OnExceptionReporting += slackReportEvented_OnExceptionReporting;
			filters.Add(slackReportEvented);
		}

		static void slackReportEvented_OnExceptionReporting(ExceptionReportingEventArgs args)
		{
			args.Options = new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"])
			{
				Text = "Options reported via the event.",
				ChannelName = ConfigurationManager.AppSettings["slack:channel"],
			};
//			args.CancelReport = true;
		}
	}
}

Add tests for new eventing behavior.

Add tests for new eventing behavior.


using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;

namespace SevenDigital.Api.Schema.ReleaseEndpoint
{
	[XmlRoot("editorial")]
	[ApiEndpoint("release/editorial")]
	[Serializable]
	public class ReleaseEditorial : HasReleaseIdParameter
	{
		[XmlElement("review")]
		public Review Review { get; set; }

		[XmlElement("staffRecommendation")]
		public Review StaffRecommendation { get; set; }

		[XmlElement("promotionalText")]
		public string PromotionalText { get; set; }
	}

	public class Review
	{
		[XmlElement("text")]
		public string Text { get; set; }
	}
}

using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;

namespace SevenDigital.Api.Schema.ReleaseEndpoint
{
	[XmlRoot("editorial")]
	[ApiEndpoint("release/editorial")]
	[Serializable]
	public class ReleaseEditorial : HasReleaseIdParameter
	{
		[XmlElement("review")]
		public TextItem Review { get; set; }

		[XmlElement("promotionalText")]
		public TextItem PromotionalText { get; set; }
	}

	public class TextItem
	{
		[XmlElement("text")]
		public string Text { get; set; }
	}
}

Update the release/editorial endpoint schema

- Remove staff reviews, which isn't actually implemented yet
- Change promotionalText from a string to a TextItem object, so it can be modified easier


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Core.CrossDomainImagesWeb
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            Uri redirectUrl;
            switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
            {
                case RedirectionStatus.Ok:
                    return;
                case RedirectionStatus.ShouldRedirect:
                    Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
                    break;
                case RedirectionStatus.CanNotRedirect:
                    Response.Write("An error occurred while processing your request.");
                    Response.End();
                    break;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
            using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
            {
                //set access token in hidden field for client calls
                hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb;

                //set images
                Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png";
                Services.ImgService svc = new Services.ImgService();
                Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png");
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Core.CrossDomainImagesWeb
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            Uri redirectUrl;
            switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
            {
                case RedirectionStatus.Ok:
                    return;
                case RedirectionStatus.ShouldRedirect:
                    Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
                    break;
                case RedirectionStatus.CanNotRedirect:
                    Response.Write("An error occurred while processing your request.");
                    Response.End();
                    break;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
                using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
                {
                    //set access token in hidden field for client calls
                    hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb;

                    //set images
                    Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png";
                    Services.ImgService svc = new Services.ImgService();
                    Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}

Revert "Revert "added try catch, test commit""

This reverts commit 9478cd97486e0e1a2ff1759161b29d53ec3c2014.


using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Mitternacht.Modules.Games.Common;
using Mitternacht.Services;

namespace Mitternacht.Modules.Games.Services {
	public class GamesService : IMService {
		private readonly IBotConfigProvider _bc;

		public readonly ConcurrentDictionary<ulong, GirlRating> GirlRatings = new ConcurrentDictionary<ulong, GirlRating>();
		public readonly ImmutableArray<string> EightBallResponses;

		public readonly string TypingArticlesPath = "data/typing_articles2.json";

		public GamesService(IBotConfigProvider bc) {
			_bc = bc;

			EightBallResponses = _bc.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray();

			var timer = new Timer(_ => {
				GirlRatings.Clear();
			}, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1));

		}
	}
}

using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Mitternacht.Modules.Games.Common;
using Mitternacht.Services;

namespace Mitternacht.Modules.Games.Services {
	public class GamesService : IMService {
		private readonly IBotConfigProvider _bcp;

		public readonly ConcurrentDictionary<ulong, GirlRating> GirlRatings = new ConcurrentDictionary<ulong, GirlRating>();
		public readonly ImmutableArray<string> EightBallResponses;

		public readonly string TypingArticlesPath = "data/typing_articles2.json";

		public GamesService(IBotConfigProvider bcp) {
			_bcp = bcp;

			EightBallResponses = _bcp.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray();

			var timer = new Timer(_ => {
				GirlRatings.Clear();
			}, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1));

		}
	}
}

Rename field to better match type.

Rename field to better match type.


using System;
using System.Reflection;

namespace NuGet {
    public static class ExceptionUtility {
        public static Exception Unwrap(Exception exception) {
            if (exception == null) {
                throw new ArgumentNullException("exception");
            }

            if (exception.InnerException == null) {
                return exception;
            }

            // Always return the inner exception from a target invocation exception
            if (exception.GetType() == typeof(TargetInvocationException)) {
                return exception.InnerException;
            }

            // Flatten the aggregate before getting the inner exception
            if (exception.GetType() == typeof(AggregateException)) {
                return ((AggregateException)exception).Flatten().InnerException;
            }

            return exception;
        }
    }
}

using System;
using System.Reflection;

namespace NuGet {
    public static class ExceptionUtility {
        public static Exception Unwrap(Exception exception) {
            if (exception == null) {
                throw new ArgumentNullException("exception");
            }

            if (exception.InnerException == null) {
                return exception;
            }

            // Always return the inner exception from a target invocation exception
            if (exception is AggregateException ||
                exception is TargetInvocationException) {
                return exception.GetBaseException();
            }

            return exception;
        }
    }
}

Call GetBaseException instead of manually unwrapping exception types.


using System.ComponentModel;
using System.Text;
using SharpLab.Runtime.Internal;

public static class SharpLabObjectExtensions {
    // LinqPad/etc compatibility only
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static T Dump<T>(this T value)
        => value.Inspect(title: "Dump");

    public static void Inspect<T>(this T value, string title = "Inspect") {
        var builder = new StringBuilder();
        ObjectAppender.Append(builder, value);
        var data = new SimpleInspectionResult(title, builder);
        Output.Write(data);
    }
}

using System.ComponentModel;
using System.Text;
using SharpLab.Runtime.Internal;

public static class SharpLabObjectExtensions {
    // LinqPad/etc compatibility only
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static T Dump<T>(this T value) {
        value.Inspect(title: "Dump");
        return value;
    }

    public static void Inspect<T>(this T value, string title = "Inspect") {
        var builder = new StringBuilder();
        ObjectAppender.Append(builder, value);
        var data = new SimpleInspectionResult(title, builder);
        Output.Write(data);
    }
}

Return value in Dump ext. method.

Return value in Dump ext. method.


using Alensia.Core.Input;
using UnityEngine.Assertions;

namespace Alensia.Core.Locomotion
{
    public abstract class LocomotionControl<T> : Control.Control, ILocomotionControl<T>
        where T : class, ILocomotion
    {
        public T Locomotion { get; }

        public override bool Valid => base.Valid && Locomotion.Active;

        protected LocomotionControl(T locomotion, IInputManager inputManager) : base(inputManager)
        {
            Assert.IsNotNull(locomotion, "locomotion != null");

            Locomotion = locomotion;
        }
    }
}

using Alensia.Core.Input;

namespace Alensia.Core.Locomotion
{
    public abstract class LocomotionControl<T> : Control.Control, ILocomotionControl<T>
        where T : class, ILocomotion
    {
        public abstract T Locomotion { get; }

        public override bool Valid => base.Valid && Locomotion != null && Locomotion.Active;

        protected LocomotionControl(IInputManager inputManager) : base(inputManager)
        {
        }
    }
}

Allow overriding of locomotion implementation


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

namespace ArcMapAddinVisibility
{
    public class MapPointTool : ESRI.ArcGIS.Desktop.AddIns.Tool
    {
        public MapPointTool()
        {
        }

        protected override void OnUpdate()
        {
            Enabled = ArcMap.Application != null;
        }
    }

}

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ArcMapAddinVisibility.Helpers;

namespace ArcMapAddinVisibility
{
    public class MapPointTool : ESRI.ArcGIS.Desktop.AddIns.Tool
    {
        public MapPointTool()
        {
        }

        protected override void OnUpdate()
        {
            Enabled = ArcMap.Application != null;
        }

        protected override void OnMouseDown(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg)
        {
            if (arg.Button != System.Windows.Forms.MouseButtons.Left)
                return;

            try
            {
                //Get the active view from the ArcMap static class.
                IActiveView activeView = ArcMap.Document.FocusMap as IActiveView;

                var point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y) as IPoint;

                Mediator.NotifyColleagues(Constants.NEW_MAP_POINT, point);
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }
        }

        protected override void OnMouseMove(MouseEventArgs arg)
        {
            IActiveView activeView = ArcMap.Document.FocusMap as IActiveView;

            var point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y) as IPoint;

            Mediator.NotifyColleagues(Constants.MOUSE_MOVE_POINT, point);
        }
    }

}

Implement Map Point Tool Mouse events

Implement Map Point Tool Mouse events


using System;

namespace AppHarbor.Commands
{
	public class AddConfigCommand : ICommand
	{
		private readonly IApplicationConfiguration _applicationConfiguration;

		public AddConfigCommand(IApplicationConfiguration applicationConfiguration)
		{
			_applicationConfiguration = applicationConfiguration;
		}

		public void Execute(string[] arguments)
		{
			throw new NotImplementedException();
		}
	}
}

using System;

namespace AppHarbor.Commands
{
	public class AddConfigCommand : ICommand
	{
		private readonly IApplicationConfiguration _applicationConfiguration;
		private readonly IAppHarborClient _appharborClient;

		public AddConfigCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient)
		{
			_applicationConfiguration = applicationConfiguration;
			_appharborClient = appharborClient;
		}

		public void Execute(string[] arguments)
		{
			throw new NotImplementedException();
		}
	}
}

Initialize AppConfigCommand with an IAppHarborClient


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

namespace DocFunctions.Lib.Models.Github
{
    public abstract class AbstractAction
    {
        public string FullFilename { get; set; }
        public string CommitSha { get; set; }
        public string CommitShaForRead { get; set; }

        public string Path
        {
            get
            {
                if (FullFilename.Contains("/"))
                {
                    return FullFilename.Replace("/" + Filename, "");
                }
                else
                {
                    return FullFilename.Replace(Filename, "");
                }
            }
        }

        public string Filename
        {
            get
            {
                return System.IO.Path.GetFileName(FullFilename);
            }
        }

        public bool IsBlogFile
        {
            get
            {
                return (Extension == ".md" || Extension == ".json");
            }
        }

        public bool IsImageFile
        {
            get
            {
                return (Extension == ".png" || Extension == ".jpg" || Extension == ".gif");
            }
        }

        private string Extension
        {
            get
            {
                return System.IO.Path.GetExtension(FullFilename);
            }
        }
    }
}

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

namespace DocFunctions.Lib.Models.Github
{
    public abstract class AbstractAction
    {
        public string FullFilename { get; set; }
        public string CommitSha { get; set; }
        public string CommitShaForRead { get; set; }

        public string Path
        {
            get
            {
                if (FullFilename.Contains("/"))
                {
                    return FullFilename.Replace("/" + Filename, "");
                }
                else
                {
                    return FullFilename.Replace(Filename, "");
                }
            }
        }

        public string Filename
        {
            get
            {
                return System.IO.Path.GetFileName(FullFilename);
            }
        }

        public bool IsBlogFile
        {
            get
            {
                return (Extension.ToLower() == ".md" || Extension.ToLower() == ".json");
            }
        }

        public bool IsImageFile
        {
            get
            {
                return (Extension.ToLower() == ".png" || Extension.ToLower() == ".jpg" || Extension.ToLower() == ".gif");
            }
        }

        private string Extension
        {
            get
            {
                return System.IO.Path.GetExtension(FullFilename);
            }
        }
    }
}

Fix for filename lowercase matches - to fix missing .PNG images


// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.

namespace PInvoke
{
    using System;

    /// <content>
    /// Contains the <see cref="FindFirstFileExFlags"/> nested enum.
    /// </content>
    public partial class Kernel32
    {
        /// <summary>
        /// Optional flags to pass to the <see cref="FindFirstFileEx"/> method.
        /// </summary>
        [Flags]
        public enum FindFirstFileExFlags
        {
            /// <summary>
            /// Searches are case-sensitive.
            /// </summary>
            CaseSensitive,

            /// <summary>
            /// Uses a larger buffer for directory queries, which can increase performance of the find operation.
            /// </summary>
            LargeFetch,
        }
    }
}

// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.

namespace PInvoke
{
    using System;

    /// <content>
    /// Contains the <see cref="FindFirstFileExFlags"/> nested enum.
    /// </content>
    public partial class Kernel32
    {
        /// <summary>
        /// Optional flags to pass to the <see cref="FindFirstFileEx"/> method.
        /// </summary>
        [Flags]
        public enum FindFirstFileExFlags
        {
            /// <summary>
            /// No flags.
            /// </summary>
            None = 0x0,

            /// <summary>
            /// Searches are case-sensitive.
            /// </summary>
            CaseSensitive = 0x1,

            /// <summary>
            /// Uses a larger buffer for directory queries, which can increase performance of the find operation.
            /// </summary>
            LargeFetch = 0x2,
        }
    }
}

Apply fixes to duplicate file

Apply fixes to duplicate file

The files shouldn't be duplicated (tracked by #32). But this change is defensive so that whichever one is selected as winner won't regress the fix for #28.


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

namespace Test
{
    using System;

    struct AA
    {
        static float[] m_afStatic1;

        static void Main1()
        {
            ulong[] param2 = new ulong[10];
            uint[] local5 = new uint[7];
            try
            {
                try
                {
                    int[] local8 = new int[7];
                    try
                    {
                        //.......
                    }
                    catch (Exception)
                    {
                        do
                        {
                            //.......
                        } while (m_afStatic1[233] > 0.0);
                    }
                    while (0 != local5[205])
                        return;
                }
                catch (IndexOutOfRangeException)
                {
                    float[] local10 = new float[7];
                    while ((int)param2[168] != 1)
                    {
                        float[] local11 = new float[7];
                    }
                }
            }
            catch (NullReferenceException) { }
        }
        static int Main()
        {
            try
            {
                Main1();
                return -1;
            }
            catch (IndexOutOfRangeException)
            {
                return 100;
            }
        }
    }
}

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

namespace Test
{
    using System;

    struct AA
    {
        static float[] m_afStatic1;

        static void Main1()
        {
            ulong[] param2 = new ulong[10];
            uint[] local5 = new uint[7];
            try
            {
                try
                {
                    int[] local8 = new int[7];
                    try
                    {
                        //.......
                    }
                    catch (Exception)
                    {
                        do
                        {
                            //.......
                        } while (m_afStatic1[233] > 0.0);
                    }
                    while (0 != local5[205])
                        return;
                }
                catch (IndexOutOfRangeException)
                {
                    float[] local10 = new float[7];
                    while ((int)param2[168] != 1)
                    {
                        float[] local11 = new float[7];
                    }
                }
            }
            catch (NullReferenceException) { }
        }
        static int Main()
        {
            try
            {
                // Issue #1421 RyuJIT generates incorrect exception handling scopes for IL generated by Roslyn
#if false
                Main1();
                return -1;
#endif
                return 100;
            }
            catch (IndexOutOfRangeException)
            {
                return 100;
            }
        }
    }
}

Disable test failing on VS2015

Disable test failing on VS2015

Failure tracked by #1421 RyuJIT generates incorrect exception handling scopes for IL generated by Roslyn


using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
    public class AndreasBittner : IAmACommunityMember
    {
        public string FirstName => "Andreas";
        public string LastName => "Bittner";
        public string ShortBioOrTagLine => "DevOp and MCSE Server 2012R2";
        public string StateOrRegion => "Saxony, Germany";
        public string EmailAddress => "";
        public string TwitterHandle => "Andreas_Bittner";
        public string GitHubHandle => "bobruhny";
        public string GravatarHash => "9e94e1e9014ad138df3f5281f814d755";
        public GeoPosition Position => new GeoPosition(49,4833, 10,7167);
        public Uri WebSite => new Uri("http://joinpowershell.de/de/new/");
        public IEnumerable<Uri> FeedUris { get { yield return new Uri(""); } }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
    public class AndreasBittner : IAmACommunityMember
    {
        public string FirstName => "Andreas";
        public string LastName => "Bittner";
        public string ShortBioOrTagLine => "DevOp and MCSE Server 2012R2";
        public string StateOrRegion => "Saxony, Germany";
        public string EmailAddress => "";
        public string TwitterHandle => "Andreas_Bittner";
        public string GitHubHandle => "bobruhny";
        public string GravatarHash => "9e94e1e9014ad138df3f5281f814d755";
        public GeoPosition Position => new GeoPosition(49,4833, 10,7167);
        public Uri WebSite => new Uri("http://joinpowershell.de/de/new/");
        public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://joinpowershell.de/de/feed/"); } }

    }
}

Add RSS Infomation for Andreas Bittner

Add RSS Infomation for Andreas Bittner


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

// 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)]

//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>.  For example, if you are using US english
//in your source files, set the <UICulture> to en-US.  Then uncomment
//the NeutralResourceLanguage attribute below.  Update the "en-US" in
//the line below to match the UICulture setting in the project file.

//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
                                     //(used if a resource is not found in the page,
                                     // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
                                              //(used if a resource is not found in the page,
                                              // app, or any theme specific resource dictionaries)
)]
[assembly: AssemblyTitle("Certify The Web (UI)")]

Set UI exe assembly title

Set UI exe assembly title


using StackExchange.Elastic;

namespace StackExchange.Opserver
{
    public class OpserverCore
    {
        // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so.
        public static void Init()
        {
            try
            {
                ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix;
                // We're going to get errors - that's kinda the point of monitoring
                // No need to log every one here unless for crazy debugging
                //ElasticException.ExceptionOccurred += e => Current.LogException(e);
            }
            catch { }
        }
    }
}

using System.Net;
using StackExchange.Elastic;

namespace StackExchange.Opserver
{
    public class OpserverCore
    {
        // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so.
        public static void Init()
        {
            try
            {
                ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix;
                // We're going to get errors - that's kinda the point of monitoring
                // No need to log every one here unless for crazy debugging
                //ElasticException.ExceptionOccurred += e => Current.LogException(e);
            }
            catch { }

            // Enable TLS only for SSL negotiation, SSL has been broken for some time.
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        }
    }
}

Enable TLS 1.1 and 1.2 and disable SSLv3 for external calls.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Mirage.Urbanization.WinForms
{
    public abstract class ToolstripMenuInitializer<TOption>
        where TOption : IToolstripMenuOption
    {
        protected ToolstripMenuInitializer(ToolStripMenuItem targetToopToolStripMenuItem, IEnumerable<TOption> options)
        {
            foreach (var option in options)
            {
                var localOption = option;
                var item = new ToolStripMenuItem(option.Name);
                item.Click += (sender, e) =>
                {
                    foreach (var x in targetToopToolStripMenuItem.DropDownItems.Cast<ToolStripMenuItem>())
                        x.Checked = false;
                    item.Checked = true;
                    _currentOption = localOption;
                    if (OnSelectionChanged != null)
                        OnSelectionChanged(this, new ToolstripMenuOptionChangedEventArgs<TOption>(_currentOption));
                };

                targetToopToolStripMenuItem.DropDownItems.Add(item);
                item.PerformClick();
            }
        }

        public event EventHandler<ToolstripMenuOptionChangedEventArgs<TOption>> OnSelectionChanged;

        private TOption _currentOption;

        public TOption GetCurrentOption() { return _currentOption; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Mirage.Urbanization.WinForms
{
    public abstract class ToolstripMenuInitializer<TOption>
        where TOption : IToolstripMenuOption
    {
        protected ToolstripMenuInitializer(ToolStripMenuItem targetToopToolStripMenuItem, IEnumerable<TOption> options)
        {
            ToolStripMenuItem first = null;
            foreach (var option in options)
            {
                var localOption = option;
                var item = new ToolStripMenuItem(option.Name);
                item.Click += (sender, e) =>
                {
                    foreach (var x in targetToopToolStripMenuItem.DropDownItems.Cast<ToolStripMenuItem>())
                        x.Checked = false;
                    item.Checked = true;
                    _currentOption = localOption;
                    if (OnSelectionChanged != null)
                        OnSelectionChanged(this, new ToolstripMenuOptionChangedEventArgs<TOption>(_currentOption));
                };

                targetToopToolStripMenuItem.DropDownItems.Add(item);
                if (first == null)
                    first = item;
            }
            first.PerformClick();
        }

        public event EventHandler<ToolstripMenuOptionChangedEventArgs<TOption>> OnSelectionChanged;

        private TOption _currentOption;

        public TOption GetCurrentOption() { return _currentOption; }
    }
}

Implement unconditional toggle of the first item when a toolstrip menu is initialized.


using System.Reflection;

[assembly: AssemblyTitle("Affecto.IdentityManagement.Store.Mocking")]
[assembly: AssemblyDescription("Identity Management store layer using Effort mock database.")]
[assembly: AssemblyProduct("Affecto.IdentityManagement")]
[assembly: AssemblyCompany("Affecto")]

[assembly: AssemblyVersion("8.0.3.0")]
[assembly: AssemblyFileVersion("8.0.3.0")]

// This version is used by NuGet:
[assembly: AssemblyInformationalVersion("8.0.3")]

using System.Reflection;

[assembly: AssemblyTitle("Affecto.IdentityManagement.Store.Mocking")]
[assembly: AssemblyDescription("Identity Management store layer using Effort mock database.")]
[assembly: AssemblyProduct("Affecto.IdentityManagement")]
[assembly: AssemblyCompany("Affecto")]

[assembly: AssemblyVersion("8.0.4.0")]
[assembly: AssemblyFileVersion("8.0.4.0")]

// This version is used by NuGet:
[assembly: AssemblyInformationalVersion("8.0.4-prerelease01")]

Raise store mocking project version.

Raise store mocking project version.


using System.Diagnostics;
using UnityEngine;

namespace Finegamedesign.Utils
{
    /// <summary>
    /// Wrapper of logging.
    /// Conditionally compiles if in debug mode or editor.
    /// </summary>
    public sealed class DebugUtil
    {
        [Conditional("DEBUG")]
        [Conditional("UNITY_EDITOR")]
        public static void Log(string message)
        {
            UnityEngine.Debug.Log(message);
        }

        [Conditional("DEBUG")]
        [Conditional("UNITY_EDITOR")]
        public static void LogWarning(string message)
        {
            UnityEngine.Debug.LogWarning(message);
        }

        [Conditional("DEBUG")]
        [Conditional("UNITY_EDITOR")]
        public static void Assert(bool condition, string message = "")
        {
            UnityEngine.Debug.Assert(condition, message);
        }
    }
}

using System.Diagnostics;
using UnityEngine;

namespace Finegamedesign.Utils
{
    /// <summary>
    /// Wrapper of logging.
    /// Conditionally compiles if in debug mode or editor.
    /// </summary>
    public sealed class DebugUtil
    {
        [Conditional("DEBUG")]
        [Conditional("UNITY_EDITOR")]
        public static void Log(string message)
        {
            UnityEngine.Debug.Log(message);
        }

        [Conditional("DEBUG")]
        [Conditional("UNITY_EDITOR")]
        public static void LogWarning(string message)
        {
            UnityEngine.Debug.LogWarning(message);
        }

        public static void LogError(string message)
        {
            UnityEngine.Debug.LogError(message);
        }

        [Conditional("DEBUG")]
        [Conditional("UNITY_EDITOR")]
        public static void Assert(bool condition, string message = "")
        {
            UnityEngine.Debug.Assert(condition, message);
        }
    }
}

Debug Util: Wraps log error.

Debug Util: Wraps log error.


using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
    internal class ProductInformation
    {
        public const string Author = "amay077";
        public const string Name = "Xamarin.Forms.GoogleMaps";
        public const string Copyright = "Copyright © amay077. 2016 - 2018";
        public const string Trademark = "";
        public const string Version = "3.0.3.0";
    }
}

using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
    internal class ProductInformation
    {
        public const string Author = "amay077";
        public const string Name = "Xamarin.Forms.GoogleMaps";
        public const string Copyright = "Copyright © amay077. 2016 - 2018";
        public const string Trademark = "";
        public const string Version = "3.0.4.0";
    }
}

Update file version to 3.0.4.0

Update file version to 3.0.4.0


using System;
using System.Xml.Serialization;

namespace XeroApi.Model
{
    public class ManualJournal : ModelBase
    {
        [ItemUpdatedDate]
        public DateTime? UpdatedDateUTC { get; set; }

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

        public DateTime? Date { get; set; }

        public string Status { get; set; }

        public LineAmountType LineAmountTypes { get; set; }

        public string Narration { get; set; }

        [XmlArrayItem("JournalLine")]
        public ManualJournalLineItems JournalLines { get; set; }
    }

    public class ManualJournals : ModelList<ManualJournal>
    {
    }
}

using System;
using System.Xml.Serialization;

namespace XeroApi.Model
{
    public class ManualJournal : ModelBase
    {
        [ItemUpdatedDate]
        public DateTime? UpdatedDateUTC { get; set; }

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

        public DateTime? Date { get; set; }

        public string Status { get; set; }

        public LineAmountType LineAmountTypes { get; set; }

        public string Narration { get; set; }

        public string Url { get; set; }

        public bool? ShowOnCashBasisReports { get; set; }

        [XmlArrayItem("JournalLine")]
        public ManualJournalLineItems JournalLines { get; set; }
    }

    public class ManualJournals : ModelList<ManualJournal>
    {
    }
}

Add optional Url and ShowOnCashBasisReports fields for MJs [v2.15]


// 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.ComponentModel;
using System.Security;
using System.Security.Principal;

namespace System
{
    internal static class EnvironmentHelpers
    {
        private static volatile bool s_isAppContainerProcess;
        private static volatile bool s_isAppContainerProcessInitalized;
        internal const int TokenIsAppContainer = 29;

        public static bool IsAppContainerProcess
        {
            get
            {
                if (!s_isAppContainerProcessInitalized)
                {
                    s_isAppContainerProcess = HasAppContainerToken();
                    s_isAppContainerProcessInitalized = true;
                }

                return s_isAppContainerProcess;
            }
        }

        [SecuritySafeCritical]
        private static unsafe bool HasAppContainerToken()
        {
            int* dwIsAppContainerPtr = stackalloc int[1];
            uint dwLength = 0;

            using (WindowsIdentity wi = WindowsIdentity.GetCurrent(TokenAccessLevels.Query))
            {
                if (!Interop.Advapi32.GetTokenInformation(wi.Token, TokenIsAppContainer, new IntPtr(dwIsAppContainerPtr), sizeof(int), out dwLength))
                {
                    throw new Win32Exception();
                }
            }

            return (*dwIsAppContainerPtr != 0);
        }
    }
}

// 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.ComponentModel;
using System.Security;
using System.Security.Principal;

namespace System
{
    internal static class EnvironmentHelpers
    {
        private static volatile bool s_isAppContainerProcess;
        private static volatile bool s_isAppContainerProcessInitalized;
        internal const int TokenIsAppContainer = 29;

        public static bool IsAppContainerProcess
        {
            get
            {
                if(!s_IsAppContainerProcessInitalized) {
                   if(Environment.OSVersion.Platform != PlatformID.Win32NT) {
                       s_IsAppContainerProcess = false;
                   } else if(Environment.OSVersion.Version.Major < 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor <= 1)) {
                       // Windows 7 or older.
                       s_IsAppContainerProcess = false;
                   } else {
                       s_IsAppContainerProcess = HasAppContainerToken();
                   }

                    s_IsAppContainerProcessInitalized = true;
                }

                return s_IsAppContainerProcess;
            }
        }

        [SecuritySafeCritical]
        private static unsafe bool HasAppContainerToken()
        {
            int* dwIsAppContainerPtr = stackalloc int[1];
            uint dwLength = 0;

            using (WindowsIdentity wi = WindowsIdentity.GetCurrent(TokenAccessLevels.Query))
            {
                if (!Interop.Advapi32.GetTokenInformation(wi.Token, TokenIsAppContainer, new IntPtr(dwIsAppContainerPtr), sizeof(int), out dwLength))
                {
                    throw new Win32Exception();
                }
            }

            return (*dwIsAppContainerPtr != 0);
        }
    }
}

Fix IsAppContainerProcess for Windows 7

Fix IsAppContainerProcess for Windows 7


using System.Linq;
using System.Xml.Linq;
using WebDav.Helpers;

namespace WebDav.Request
{
    internal static class PropfindRequestBuilder
    {
        public static string BuildRequestBody(string[] customProperties)
        {
            XNamespace webDavNs = "DAV:";
            var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
            var propfind = new XElement(webDavNs + "propfind", new XAttribute(XNamespace.Xmlns + "D", webDavNs));
            propfind.Add(new XElement(webDavNs + "allprop"));
            if (customProperties.Any())
            {
                var include = new XElement(webDavNs + "include");
                foreach (var prop in customProperties)
                {
                    include.Add(new XElement(webDavNs + prop));
                }
                propfind.Add(include);
            }
            doc.Add(propfind);
            return doc.ToStringWithDeclaration();
        }
    }
}

using System.Linq;
using System.Xml.Linq;
using WebDav.Helpers;

namespace WebDav.Request
{
    internal static class PropfindRequestBuilder
    {
        public static string BuildRequestBody(string[] customProperties)
        {
            var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
            var propfind = new XElement("{DAV:}propfind", new XAttribute(XNamespace.Xmlns + "D", "DAV:"));
            propfind.Add(new XElement("{DAV:}allprop"));
            if (customProperties.Any())
            {
                var include = new XElement("{DAV:}include");
                foreach (var prop in customProperties)
                {
                    include.Add(new XElement(XName.Get(prop, "DAV:")));
                }
                propfind.Add(include);
            }
            doc.Add(propfind);
            return doc.ToStringWithDeclaration();
        }
    }
}

Use standard syntax to build propfind requests


using MaterialColor.Common.Data;
using System.Collections.Generic;
using UnityEngine;

namespace MaterialColor.Core
{
    public static class State
    {
        public static Dictionary<string, Color32> TypeColorOffsets = new Dictionary<string, Color32>();
        public static Dictionary<SimHashes, ElementColorInfo> ElementColorInfos = new Dictionary<SimHashes, ElementColorInfo>();

        public static ConfiguratorState ConfiguratorState = new ConfiguratorState();

        public static bool Disabled = false;

        public static readonly List<string> TileNames = new List<string>
        {
            "Tile", "MeshTile", "InsulationTile", "GasPermeableMembrane"
        };
    }
}

using MaterialColor.Common.Data;
using System.Collections.Generic;
using UnityEngine;

namespace MaterialColor.Core
{
    public static class State
    {
        public static Dictionary<string, Color32> TypeColorOffsets = new Dictionary<string, Color32>();
        public static Dictionary<SimHashes, ElementColorInfo> ElementColorInfos = new Dictionary<SimHashes, ElementColorInfo>();

        public static ConfiguratorState ConfiguratorState = new ConfiguratorState();

        public static bool Disabled = false;

        public static readonly List<string> TileNames = new List<string>
        {
            "Tile", "MeshTile", "InsulationTile", "GasPermeableMembrane", "TilePOI"
        };
    }
}

Add TilePOI to list of tile names

Add TilePOI to list of tile names