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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Graphics.UserInterface;

namespace osu.Game.Overlays.Settings.Sections.Audio
{
    public class OffsetSettings : SettingsSubsection
    {
        protected override LocalisableString Header => "Offset Adjustment";

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsSlider<double, OffsetSlider>
                {
                    LabelText = "Audio offset",
                    Current = config.GetBindable<double>(OsuSetting.AudioOffset),
                    KeyboardStep = 1f
                },
                new SettingsButton
                {
                    Text = "Offset wizard"
                }
            };
        }

        private class OffsetSlider : OsuSliderBar<double>
        {
            public override LocalisableString TooltipText => Current.Value.ToString(@"0ms");
        }
    }
}

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

using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Graphics.UserInterface;

namespace osu.Game.Overlays.Settings.Sections.Audio
{
    public class OffsetSettings : SettingsSubsection
    {
        protected override LocalisableString Header => "Offset Adjustment";

        public override IEnumerable<string> FilterTerms => base.FilterTerms.Concat(new[] { "universal", "uo", "timing" });

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsSlider<double, OffsetSlider>
                {
                    LabelText = "Audio offset",
                    Current = config.GetBindable<double>(OsuSetting.AudioOffset),
                    KeyboardStep = 1f
                },
                new SettingsButton
                {
                    Text = "Offset wizard"
                }
            };
        }

        private class OffsetSlider : OsuSliderBar<double>
        {
            public override LocalisableString TooltipText => Current.Value.ToString(@"0ms");
        }
    }
}

Add keywords to make finding audio offset adjustments easier in settings


using System;
using Microsoft.Deployment.WindowsInstaller;

namespace Wix.CustomActions
{
    using System.IO;

    public class CustomActions
    {
        [CustomAction]
        public static ActionResult CloseIt(Session session)
        {
            try
            {
                const string fileFullPath = @"c:\KensCustomAction.txt";

                if (!File.Exists(fileFullPath))
                    File.Create(fileFullPath);

                File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now));

                session.Log("Close DotTray!");
            }
            catch (Exception ex)
            {
                session.Log("ERROR in custom action CloseIt {0}", ex.ToString());
                return ActionResult.Failure;
            }

            return ActionResult.Success;
        }
    }
}

using System;
using Microsoft.Deployment.WindowsInstaller;

namespace Wix.CustomActions
{
    using System.IO;
    using System.Diagnostics;

    public class CustomActions
    {
        [CustomAction]
        public static ActionResult CloseIt(Session session)
        {
            try
            {

                Debugger.Launch();

                const string fileFullPath = @"c:\KensCustomAction.txt";

                if (!File.Exists(fileFullPath))
                    File.Create(fileFullPath);

                File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now));

                session.Log("Close DotTray!");
            }
            catch (Exception ex)
            {
                session.Log("ERROR in custom action CloseIt {0}", ex.ToString());
                return ActionResult.Failure;
            }

            return ActionResult.Success;
        }
    }
}

Add more logic to the custom action.

Add more logic to the custom action.


namespace FlatFile.FixedLength.Attributes.Infrastructure
{
    using System;
    using System.Linq;
    using FlatFile.Core;
    using FlatFile.Core.Attributes.Extensions;
    using FlatFile.Core.Attributes.Infrastructure;
    using FlatFile.Core.Base;

    public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>>
    {
        public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>()
        {
            var container = new FieldsContainer<FixedFieldSettings>();

            var fileMappingType = typeof(T);

            var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>();

            if (fileAttribute == null)
            {
                throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute",
                    fileMappingType.Name,
                    typeof(FixedLengthFileAttribute).Name));
            }

            var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>();

            foreach (var p in properties)
            {
                var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute;

                if (attribute != null)
                {
                    var fieldSettings = attribute.GetFieldSettings(p.Property);

                    container.AddOrUpdate(fieldSettings, false);
                }
            }

            var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container);

            return descriptor;
        }
    }
}

namespace FlatFile.FixedLength.Attributes.Infrastructure
{
    using System;
    using System.Linq;
    using FlatFile.Core;
    using FlatFile.Core.Attributes.Extensions;
    using FlatFile.Core.Attributes.Infrastructure;
    using FlatFile.Core.Base;

    public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>>
    {
        public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>()
        {
            var container = new FieldsContainer<FixedFieldSettings>();

            var fileMappingType = typeof(T);

            var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>();

            if (fileAttribute == null)
            {
                throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute",
                    fileMappingType.Name,
                    typeof(FixedLengthFileAttribute).Name));
            }

            var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>();

            foreach (var p in properties)
            {
                var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute;

                if (attribute != null)
                {
                    var fieldSettings = attribute.GetFieldSettings(p.Property);

                    container.AddOrUpdate(fieldSettings, false);
                }
            }

            var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container)
            {
                HasHeader = false
            };

            return descriptor;
        }
    }
}

Fix header behavior for the fixed length types


using UnityEngine;

namespace com.adjust.sdk.test
{
    public class TestFactoryAndroid : ITestFactory
    {
        private string _baseUrl;
        private AndroidJavaObject ajoTestLibrary;
        private CommandListenerAndroid onCommandReceivedListener;

        public TestFactoryAndroid(string baseUrl)
        {
            _baseUrl = baseUrl;
            CommandExecutor commandExecutor = new CommandExecutor(this, baseUrl);
            onCommandReceivedListener = new CommandListenerAndroid(commandExecutor);
        }

        public void StartTestSession()
        {
            TestApp.Log("TestFactory -> StartTestSession()");

            if (ajoTestLibrary == null)
            {
                ajoTestLibrary = new AndroidJavaObject(
                    "com.adjust.testlibrary.TestLibrary",
                    _baseUrl,
                    onCommandReceivedListener);
            }

            TestApp.Log("TestFactory -> calling testLib.startTestSession()");
            ajoTestLibrary.Call("startTestSession", TestApp.CLIENT_SDK);
        }

        public void AddInfoToSend(string key, string paramValue)
        {
            if (ajoTestLibrary == null)
            {
                return;
            }
            ajoTestLibrary.Call("addInfoToSend", key, paramValue);
        }

        public void SendInfoToServer(string basePath)
        {
            if (ajoTestLibrary == null)
            {
                return;
            }
            ajoTestLibrary.Call("sendInfoToServer", basePath);
        }

		public void AddTest(string testName)
		{
			if (ajoTestLibrary == null) {
                return;
            }
			ajoTestLibrary.Call("addTest", testName);
		}

		public void AddTestDirectory(string testDirectory)
		{
			if (ajoTestLibrary == null)
            {
                return;
            }
			ajoTestLibrary.Call("addTestDirectory", testDirectory);
		}
    }
}

using UnityEngine;

namespace com.adjust.sdk.test
{
    public class TestFactoryAndroid : ITestFactory
    {
        private string _baseUrl;
        private AndroidJavaObject ajoTestLibrary;
        private CommandListenerAndroid onCommandReceivedListener;

        public TestFactoryAndroid(string baseUrl)
        {
            _baseUrl = baseUrl;
            CommandExecutor commandExecutor = new CommandExecutor(this, baseUrl);
            onCommandReceivedListener = new CommandListenerAndroid(commandExecutor);
			ajoTestLibrary = new AndroidJavaObject(
				"com.adjust.testlibrary.TestLibrary",
				_baseUrl,
				onCommandReceivedListener);

        }

        public void StartTestSession()
        {
            ajoTestLibrary.Call("startTestSession", TestApp.CLIENT_SDK);
        }

        public void AddInfoToSend(string key, string paramValue)
        {
            ajoTestLibrary.Call("addInfoToSend", key, paramValue);
        }

        public void SendInfoToServer(string basePath)
        {
            ajoTestLibrary.Call("sendInfoToServer", basePath);
        }

		public void AddTest(string testName)
		{
			ajoTestLibrary.Call("addTest", testName);
		}

		public void AddTestDirectory(string testDirectory)
		{
			ajoTestLibrary.Call("addTestDirectory", testDirectory);
		}
    }
}

Initialize android test library on contructor


#addin "Cake.FileHelpers"

var TARGET = Argument ("target", Argument ("t", "Default"));

var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");

Task ("Default").Does (() =>
{

    const string sln = "./../Vibrate.sln";
    const string cfg = "Release";

	NuGetRestore (sln);

    if (!IsRunningOnWindows ())
        DotNetBuild (sln, c => c.Configuration = cfg);
    else
        MSBuild (sln, c => {
            c.Configuration = cfg;
            c.MSBuildPlatform = MSBuildPlatform.x86;
        });
});

Task ("NuGetPack")
	.IsDependentOn ("Default")
	.Does (() =>
{
	NuGetPack ("./../Vibrate.nuspec", new NuGetPackSettings {
		Version = version,
		Verbosity = NuGetVerbosity.Detailed,
		OutputDirectory = "./",
		BasePath = "./",
	});
});

RunTarget (TARGET);

#addin "Cake.FileHelpers"

var TARGET = Argument ("target", Argument ("t", "Default"));

var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");

Task ("Default").Does (() =>
{

    const string sln = "./../Vibrate.sln";
    const string cfg = "Release";

	NuGetRestore (sln);

    if (!IsRunningOnWindows ())
        DotNetBuild (sln, c => c.Configuration = cfg);
    else
        MSBuild (sln, c => {
            c.Configuration = cfg;
            c.MSBuildPlatform = MSBuildPlatform.x86;
        });
});

Task ("NuGetPack")
	.IsDependentOn ("Default")
	.Does (() =>
{
	NuGetPack ("./../Vibrate.nuspec", new NuGetPackSettings {
		Version = version,
		Verbosity = NuGetVerbosity.Detailed,
		OutputDirectory = "./../",
		BasePath = "./",
	});
});

RunTarget (TARGET);

Adjust output directory in script

Adjust output directory in script


using System.Collections.Generic;

namespace CertiPay.Payroll.Common
{
    /// <summary>
    /// Describes how an employee pay is calculated
    /// </summary>
    public enum EmployeePayType : byte
    {
        /// <summary>
        /// Employee earns a set salary per period of time, i.e. $70,000 yearly
        /// </summary>
        Salary = 1,

        /// <summary>
        /// Employee earns a given amount per hour of work, i.e. $10 per hour
        /// </summary>
        Hourly = 2
    }

    public static class EmployeePayTypes
    {
        public static IEnumerable<EmployeePayType> Values()
        {
            yield return EmployeePayType.Salary;
            yield return EmployeePayType.Hourly;
        }
    }
}

using System.Collections.Generic;

namespace CertiPay.Payroll.Common
{
    /// <summary>
    /// Describes how an employee pay is calculated
    /// </summary>
    public enum EmployeePayType : byte
    {
        /// <summary>
        /// Employee earns a set salary per period of time, i.e. $70,000 yearly
        /// </summary>
        Salary = 1,

        /// <summary>
        /// Employee earns a given amount per hour of work, i.e. $10 per hour
        /// </summary>
        Hourly = 2,

        /// <summary>
        /// Employee earns a flat rate based on sales or project completion
        /// </summary>
        Commission = 3
    }

    public static class EmployeePayTypes
    {
        public static IEnumerable<EmployeePayType> Values()
        {
            yield return EmployeePayType.Salary;
            yield return EmployeePayType.Hourly;
            yield return EmployeePayType.Commission;
        }
    }
}

Add commission as Employee Pay Type

Add commission as Employee Pay Type


using System.Web.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;
using ValidateRequestExample.Filters;

namespace ValidateRequestExample.Controllers
{
    public class IncomingController : TwilioController
    {
        [ValidateTwilioRequest]
        public ActionResult Voice(string from)
        {
            var response = new TwilioResponse();
            const string message = "Thanks for calling! " +
                "Your phone number is {0}. I got your call because of Twilio's webhook. " +
                "Goodbye!";

            response.Say(string.Format(message, from));
            response.Hangup();

            return TwiML(response);
        }

        [ValidateTwilioRequest]
        public ActionResult Message(string body)
        {
            var response = new TwilioResponse();

            response.Say($"Your text to me was {body.Length} characters long. Webhooks are neat :)");
            response.Hangup();

            return TwiML(response);
        }
    }
}

using System.Web.Mvc;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;
using ValidateRequestExample.Filters;

namespace ValidateRequestExample.Controllers
{
    public class IncomingController : TwilioController
    {
        [ValidateTwilioRequest]
        public ActionResult Voice(string from)
        {
            var message = "Thanks for calling! " +
                $"Your phone number is {from}. " +
                "I got your call because of Twilio's webhook. " +
                "Goodbye!";

            var response = new VoiceResponse();
            response.Say(string.Format(message, from));
            response.Hangup();

            return TwiML(response);
        }

        [ValidateTwilioRequest]
        public ActionResult Message(string body)
        {
            var message = $"Your text to me was {body.Length} characters long. " +
                "Webhooks are neat :)";

            var response = new MessagingResponse();
            response.Message(new Message(message));

            return TwiML(response);
        }
    }
}

Update controller for request validation


using System;
using NUnit.Framework;

using DevTyr.Gullap;

namespace DevTyr.Gullap.Tests.With_Guard.For_NotNullOrEmpty
{
	[TestFixture]
	public class When_argument_is_not_null
	{
		[Test]
		public void Should_pass ()
		{
			Guard.NotNullOrEmpty ("", null);
			Assert.Pass ();
		}
	}
}

using System;
using NUnit.Framework;

using DevTyr.Gullap;

namespace DevTyr.Gullap.Tests.With_Guard.For_NotNullOrEmpty
{
	[TestFixture]
	public class When_argument_is_not_null_or_empty
	{
		[Test]
		public void Should_pass ()
		{
			Guard.NotNullOrEmpty ("Test", null);
			Assert.Pass ();
		}
	}
}

Fix test for NotNullOrEmpty passing check.


using BankService.Domain.Contracts;
using BankService.Domain.Models;
using Microsoft.AspNet.Cors;
using Microsoft.AspNet.Mvc;
using System.Collections.Generic;

namespace BankService.Api.Controllers
{
    [EnableCors("MyPolicy")]
    [Route("api/accountHolders")]
    public class AccountHolderController : Controller
    {
        private readonly IAccountHolderRepository accountHolderRepository;
        private readonly ICachedAccountHolderRepository cachedAccountHolderRepository;

        public AccountHolderController(IAccountHolderRepository repository, ICachedAccountHolderRepository cachedRepository)
        {
            this.accountHolderRepository = repository;
            this.cachedAccountHolderRepository = cachedRepository;
        }

        [HttpGet]
        public IEnumerable<AccountHolder> Get()
        {
            return this.accountHolderRepository.GetWithLimit(100);
        }

        [HttpGet("{id}")]
        public AccountHolder Get(string id)
        {
            var accountHolder = this.cachedAccountHolderRepository.Get(id);

            if (accountHolder != null)
            {
                return accountHolder;
            }

            accountHolder = this.accountHolderRepository.GetById(id);

            this.cachedAccountHolderRepository.Set(accountHolder);

            return accountHolder;
        }
    }
}

using BankService.Domain.Contracts;
using BankService.Domain.Models;
using Microsoft.AspNet.Mvc;
using System.Collections.Generic;

namespace BankService.Api.Controllers
{
    [Route("api/accountHolders")]
    public class AccountHolderController : Controller
    {
        private readonly IAccountHolderRepository accountHolderRepository;
        private readonly ICachedAccountHolderRepository cachedAccountHolderRepository;

        public AccountHolderController(IAccountHolderRepository repository, ICachedAccountHolderRepository cachedRepository)
        {
            this.accountHolderRepository = repository;
            this.cachedAccountHolderRepository = cachedRepository;
        }

        [HttpGet]
        public IEnumerable<AccountHolder> Get()
        {
            return this.accountHolderRepository.GetWithLimit(100);
        }

        [HttpGet("{id}")]
        public AccountHolder Get(string id)
        {
            var accountHolder = this.cachedAccountHolderRepository.Get(id);

            if (accountHolder != null)
            {
                return accountHolder;
            }

            accountHolder = this.accountHolderRepository.GetById(id);

            this.cachedAccountHolderRepository.Set(accountHolder);

            return accountHolder;
        }
    }
}

Remove EnableCors attribute from controller


namespace VotingSystem.Web.Areas.User.ViewModels
{
    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;

    using VotingSystem.Models;
    using VotingSystem.Web.Infrastructure.Mapping;

    using AutoMapper;

    public class UserPollsViewModel : IMapFrom<Poll>, IHaveCustomMappings
    {
        [HiddenInput(DisplayValue = false)]
        public int Id { get; set; }

        public string Title { get; set; }

        public string Description { get; set; }

        [HiddenInput(DisplayValue = false)]
        public string Author { get; set; }

        public bool IsPublic { get; set; }

        public DateTime StartDate { get; set; }

        public DateTime EndDate { get; set; }

        public string UserId { get; set; }

        public void CreateMappings(AutoMapper.IConfiguration configuration)
        {
            configuration.CreateMap<Poll, UserPollsViewModel>()
                .ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName));
        }
    }
}

namespace VotingSystem.Web.Areas.User.ViewModels
{
    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;

    using VotingSystem.Models;
    using VotingSystem.Web.Infrastructure.Mapping;

    using AutoMapper;

    public class UserPollsViewModel : IMapFrom<Poll>, IHaveCustomMappings
    {
        [HiddenInput(DisplayValue = false)]
        public int Id { get; set; }

        public string Title { get; set; }

        public string Description { get; set; }

        [HiddenInput(DisplayValue = false)]
        public string Author { get; set; }

        public bool IsPublic { get; set; }

        public DateTime StartDate { get; set; }

        public DateTime EndDate { get; set; }

        [HiddenInput(DisplayValue = false)]
        public string UserId { get; set; }

        public void CreateMappings(AutoMapper.IConfiguration configuration)
        {
            configuration.CreateMap<Poll, UserPollsViewModel>()
                .ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName));
        }
    }
}

Hide UserId by Editing in KendoGrid PopUp


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VVVV.DX11.Internals.Effects.Pins;
using VVVV.PluginInterfaces.V2;
using SlimDX.Direct3D11;
using VVVV.PluginInterfaces.V1;
using VVVV.Hosting.Pins;
using VVVV.DX11.Lib.Effects.Pins;
using FeralTic.DX11;

namespace VVVV.DX11.Internals.Effects.Pins
{
    public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription>
    {
        private SamplerState state;

        protected override void ProcessAttribute(InputAttribute attr, EffectVariable var)
        {
            attr.IsSingle = true;
            attr.CheckIfChanged = true;
        }

        protected override bool RecreatePin(EffectVariable var)
        {
            return false;
        }

        public override void SetVariable(DX11ShaderInstance shaderinstance, int slice)
        {
            if (this.pin.PluginIO.IsConnected)
            {
                using (var state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[slice]))
                {
                    shaderinstance.SetByName(this.Name, state);
                }
            }
            else
            {
                shaderinstance.Effect.GetVariableByName(this.Name).AsConstantBuffer().UndoSetConstantBuffer();
            }

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VVVV.DX11.Internals.Effects.Pins;
using VVVV.PluginInterfaces.V2;
using SlimDX.Direct3D11;
using VVVV.PluginInterfaces.V1;
using VVVV.Hosting.Pins;
using VVVV.DX11.Lib.Effects.Pins;
using FeralTic.DX11;

namespace VVVV.DX11.Internals.Effects.Pins
{
    public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription>
    {
        private SamplerState state;

        protected override void ProcessAttribute(InputAttribute attr, EffectVariable var)
        {
            attr.IsSingle = true;
            attr.CheckIfChanged = true;
        }

        protected override bool RecreatePin(EffectVariable var)
        {
            return false;
        }

        public override void SetVariable(DX11ShaderInstance shaderinstance, int slice)
        {
            if (this.pin.PluginIO.IsConnected)
            {
                using (var state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[slice]))
                {
                    shaderinstance.SetByName(this.Name, state);
                }
            }
            else
            {
                shaderinstance.Effect.GetVariableByName(this.Name).AsSampler().UndoSetSamplerState(0);
            }

        }
    }
}

Fix error in sampler state pin connection


using Harvest.Net.Models;
using System;
using System.Linq;
using Xunit;

namespace Harvest.Net.Tests
{
    public class TimeTrackingFacts : FactBase, IDisposable
    {
        DayEntry _todelete = null;

        [Fact]
        public void Daily_ReturnsResult()
        {
            var result = Api.Daily();

            Assert.NotNull(result);
            Assert.NotNull(result.DayEntries);
            Assert.NotNull(result.Projects);
            Assert.Equal(DateTime.Now.Date, result.ForDay);
        }

        [Fact]
        public void Daily_ReturnsCorrectResult()
        {
            var result = Api.Daily(286857409);

            Assert.NotNull(result);
            Assert.Equal(1m, result.DayEntry.Hours);
            Assert.Equal(new DateTime(2014, 12, 19), result.DayEntry.SpentAt);
        }

        [Fact]
        public void CreateDaily_CreatesAnEntry()
        {
            var result = Api.CreateDaily(DateTime.Now.Date, GetTestId(TestId.ProjectId), GetTestId(TestId.TaskId), 2);
            _todelete = result.DayEntry;

            Assert.Equal(2m, result.DayEntry.Hours);
            Assert.Equal(GetTestId(TestId.ProjectId), result.DayEntry.ProjectId);
            Assert.Equal(GetTestId(TestId.TaskId), result.DayEntry.TaskId);
        }

        public void Dispose()
        {
            if (_todelete != null)
                Api.DeleteDaily(_todelete.Id);
        }
    }
}

using Harvest.Net.Models;
using System;
using System.Linq;
using Xunit;

namespace Harvest.Net.Tests
{
    public class TimeTrackingFacts : FactBase, IDisposable
    {
        DayEntry _todelete = null;

        [Fact]
        public void Daily_ReturnsResult()
        {
            var result = Api.Daily();

            Assert.NotNull(result);
            Assert.NotNull(result.DayEntries);
            Assert.NotNull(result.Projects);

            // The test harvest account is in EST, but Travis CI runs in different timezones
            Assert.Equal(TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Utc, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")).Date, result.ForDay);
        }

        [Fact]
        public void Daily_ReturnsCorrectResult()
        {
            var result = Api.Daily(286857409);

            Assert.NotNull(result);
            Assert.Equal(1m, result.DayEntry.Hours);
            Assert.Equal(new DateTime(2014, 12, 19), result.DayEntry.SpentAt);
        }

        [Fact]
        public void CreateDaily_CreatesAnEntry()
        {
            var result = Api.CreateDaily(DateTime.Now.Date, GetTestId(TestId.ProjectId), GetTestId(TestId.TaskId), 2);
            _todelete = result.DayEntry;

            Assert.Equal(2m, result.DayEntry.Hours);
            Assert.Equal(GetTestId(TestId.ProjectId), result.DayEntry.ProjectId);
            Assert.Equal(GetTestId(TestId.TaskId), result.DayEntry.TaskId);
        }

        public void Dispose()
        {
            if (_todelete != null)
                Api.DeleteDaily(_todelete.Id);
        }
    }
}

Fix test to work in any timezone

Fix test to work in any timezone


using System;
using Microsoft.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters;
using ProtoBuf.Meta;

namespace Infrastructure
{
    public class ProtobufOutputFormatter :  OutputFormatter
    {
        private static Lazy<RuntimeTypeModel> model = new Lazy<RuntimeTypeModel>(CreateTypeModel);

        public string ContentType { get; private set; }

        public static RuntimeTypeModel Model
        {
            get { return model.Value; }
        }

        public ProtobufOutputFormatter()
        {
            ContentType = "application/x-protobuf";
            SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/x-protobuf"));
            //SupportedEncodings.Add(Encoding.GetEncoding("utf-8"));
        }

        private static RuntimeTypeModel CreateTypeModel()
        {
            var typeModel = TypeModel.Create();
            typeModel.UseImplicitZeroDefaults = false;
            return typeModel;
        }

        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
        {
            var response = context.HttpContext.Response;

            Model.Serialize(response.Body, context.Object);
            return Task.FromResult(response);
        }
    }
}

using System;
using Microsoft.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters;
using ProtoBuf.Meta;

namespace Infrastructure
{
    public class ProtobufOutputFormatter :  OutputFormatter
    {
        private static Lazy<RuntimeTypeModel> model = new Lazy<RuntimeTypeModel>(CreateTypeModel);

        public string ContentType { get; private set; }

        public static RuntimeTypeModel Model
        {
            get { return model.Value; }
        }

        public ProtobufOutputFormatter()
        {
            ContentType = "application/x-protobuf";
            var mediaTypeHeader = MediaTypeHeaderValue.Parse(ContentType);
            mediaTypeHeader.Encoding = System.Text.Encoding.UTF8;
            SupportedMediaTypes.Add(mediaTypeHeader);
        }

        private static RuntimeTypeModel CreateTypeModel()
        {
            var typeModel = TypeModel.Create();
            typeModel.UseImplicitZeroDefaults = false;
            return typeModel;
        }

        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
        {
            var response = context.HttpContext.Response;

            Model.Serialize(response.Body, context.Object);
            return Task.FromResult(response);
        }
    }
}

Add encoding header to protobuf content

Add encoding header to protobuf content


using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using System.Text;

namespace Abp.AspNetCore.EntityHistory
{
    /// <summary>
    /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
    /// </summary>
    public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
    {
        [CanBeNull]
        public override string Reason
        {
            get
            {
                if (OverridedValue != null)
                {
                    return OverridedValue.Reason;
                }

                // TODO: Use back HttpContextAccessor.HttpContext?.Request.GetDisplayUrl()
                // after moved to net core 3.0
                // see https://github.com/aspnet/AspNetCore/issues/2718#issuecomment-482347489
                return GetDisplayUrl(HttpContextAccessor.HttpContext?.Request);
            }
        }

        protected IHttpContextAccessor HttpContextAccessor { get; }

        private const string SchemeDelimiter = "://";

        public HttpRequestEntityChangeSetReasonProvider(
            IHttpContextAccessor httpContextAccessor,

            IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
            ) : base(reasonOverrideScopeProvider)
        {
            HttpContextAccessor = httpContextAccessor;
        }

        private string GetDisplayUrl(HttpRequest request)
        {
            if (request == null)
            {
                Logger.Debug("Unable to get URL from HttpRequest, fallback to null");
                return null;
            }

            var scheme = request.Scheme ?? string.Empty;
            var host = request.Host.Value ?? string.Empty;
            var pathBase = request.PathBase.Value ?? string.Empty;
            var path = request.Path.Value ?? string.Empty;
            var queryString = request.QueryString.Value ?? string.Empty;

            // PERF: Calculate string length to allocate correct buffer size for StringBuilder.
            var length = scheme.Length + SchemeDelimiter.Length + host.Length
                + pathBase.Length + path.Length + queryString.Length;

            return new StringBuilder(length)
                .Append(scheme)
                .Append(SchemeDelimiter)
                .Append(host)
                .Append(pathBase)
                .Append(path)
                .Append(queryString)
                .ToString();
        }
    }
}

using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using System.Text;
using Microsoft.AspNetCore.Http.Extensions;

namespace Abp.AspNetCore.EntityHistory
{
    /// <summary>
    /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
    /// </summary>
    public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
    {
        [CanBeNull]
        public override string Reason => OverridedValue != null
            ? OverridedValue.Reason
            : HttpContextAccessor.HttpContext?.Request.GetDisplayUrl();

        protected IHttpContextAccessor HttpContextAccessor { get; }

        private const string SchemeDelimiter = "://";

        public HttpRequestEntityChangeSetReasonProvider(
            IHttpContextAccessor httpContextAccessor,

            IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
            ) : base(reasonOverrideScopeProvider)
        {
            HttpContextAccessor = httpContextAccessor;
        }
    }
}

Use the aspnet core built-in GetDisplayUrl method.

Resolve #4946


using System;
using System.Data.Entity;
using PhotoLife.Data.Contracts;

namespace PhotoLife.Data
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly DbContext dbContext;

        public UnitOfWork(DbContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("Context cannot be null");
            }

            this.dbContext = context;
        }

        public void Dispose()
        {
        }

        public void Commit()
        {
            this.dbContext.SaveChanges();
        }
    }
}

using System;
using PhotoLife.Data.Contracts;

namespace PhotoLife.Data
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly IPhotoLifeEntities dbContext;

        public UnitOfWork(IPhotoLifeEntities context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("Context cannot be null");
            }

            this.dbContext = context;
        }

        public void Dispose()
        {
        }

        public void Commit()
        {
            this.dbContext.SaveChanges();
        }
    }
}

Fix unit of work ctor param

Fix unit of work ctor param


namespace Worker.Scalable
{
    using King.Service;
    using System.Diagnostics;
    using System.Threading.Tasks;

    public class ScalableTask : IDynamicRuns
    {
        public int MaximumPeriodInSeconds
        {
            get { return 30; }
        }

        public int MinimumPeriodInSeconds
        {
            get { return 20; }
        }

        public Task<bool> Run()
        {
            Trace.TraceInformation("Scalable Task Running.");
            return Task.FromResult(true);
        }
    }
}

namespace Worker.Scalable
{
    using King.Service;
    using System;
    using System.Diagnostics;
    using System.Threading.Tasks;

    public class ScalableTask : IDynamicRuns
    {
        public int MaximumPeriodInSeconds
        {
            get
            {
                return 30;
            }
        }

        public int MinimumPeriodInSeconds
        {
            get
            {
                return 20;
            }
        }

        public Task<bool> Run()
        {
            var random = new Random();
            var workWasDone = (random.Next() % 2) == 0;

            Trace.TraceInformation("Work was done: {0}", workWasDone);
            return Task.FromResult(workWasDone);
        }
    }
}

Scale up and down in demo

Scale up and down in demo


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

    internal class TraktShowsTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingShow>, TraktTrendingShow>
    {
        internal TraktShowsTrendingRequest(TraktClient client) : base(client) { }

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

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

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

    internal class TraktShowsTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingShow>, TraktTrendingShow>
    {
        internal TraktShowsTrendingRequest(TraktClient client) : base(client) { }

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

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        internal TraktShowFilter Filter { get; set; }

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

Add filter property to trending shows request.


using System;
using System.Linq;

using LinqToDB;

using NUnit.Framework;

namespace Tests.UserTests
{
	[TestFixture]
	public class Issue1556Tests : TestBase
	{
		[Test]
		public void Issue1556Test([DataSources(ProviderName.Sybase, ProviderName.OracleNative)] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in db.Parent
					from c in db.Child
					where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID)
					select new { p, c }
					,
					db.Parent
						.InnerJoin(db.Child,
							(p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID),
							(p,c) => new { p, c }));
			}
		}
	}
}

using System;
using System.Linq;

using LinqToDB;

using NUnit.Framework;

namespace Tests.UserTests
{
	[TestFixture]
	public class Issue1556Tests : TestBase
	{
		[Test]
		public void Issue1556Test(
			[DataSources(ProviderName.Sybase, ProviderName.OracleNative, ProviderName.Access)] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in db.Parent
					from c in db.Child
					where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID)
					select new { p, c }
					,
					db.Parent
						.InnerJoin(db.Child,
							(p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID),
							(p,c) => new { p, c }));
			}
		}
	}
}

Access dos not support such join syntax.

(cherry picked from commit 8d08686469e98c88d2d4594c32a91dfd5c0f3892)


using System.Net.Http;
using System.Threading.Tasks;
using Anemonis.MicrosoftOffice.AddinHost.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Anemonis.MicrosoftOffice.AddinHost.IntegrationTests
{
    [TestClass]
    public sealed class RequestTracingMiddlewareTests
    {
        [TestMethod]
        public async Task Trace()
        {
            var loggerMock = new Mock<Serilog.ILogger>(MockBehavior.Strict);

            loggerMock.Setup(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<object[]>()));

            var builder = new WebHostBuilder()
                .ConfigureServices(sc => sc
                    .AddSingleton(loggerMock.Object)
                    .AddSingleton<RequestTracingMiddleware, RequestTracingMiddleware>())
                .Configure(ab => ab
                    .UseMiddleware<RequestTracingMiddleware>());

            using (var server = new TestServer(builder))
            {
                using (var client = server.CreateClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Get, server.BaseAddress);
                    var response = await client.SendAsync(request);
                }
            }

            loggerMock.Verify(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<object[]>()), Times.Exactly(1));
        }
    }
}

using System.Net.Http;
using System.Threading.Tasks;
using Anemonis.MicrosoftOffice.AddinHost.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Anemonis.MicrosoftOffice.AddinHost.IntegrationTests
{
    [TestClass]
    public sealed class RequestTracingMiddlewareTests
    {
        [TestMethod]
        public async Task Trace()
        {
            var loggerMock = new Mock<Serilog.ILogger>(MockBehavior.Strict);

            loggerMock.Setup(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>()));

            var builder = new WebHostBuilder()
                .ConfigureServices(sc => sc
                    .AddSingleton(loggerMock.Object)
                    .AddSingleton<RequestTracingMiddleware, RequestTracingMiddleware>())
                .Configure(ab => ab
                    .UseMiddleware<RequestTracingMiddleware>());

            using (var server = new TestServer(builder))
            {
                using (var client = server.CreateClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Get, server.BaseAddress);
                    var response = await client.SendAsync(request);
                }
            }

            loggerMock.Verify(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(1));
        }
    }
}

Fix integration tests for tracing

Fix integration tests for tracing


using GRA.Domain.Service;
using GRA.Controllers.ViewModel.ParticipatingBranches;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace GRA.Controllers
{
    public class ParticipatingBranchesController : Base.UserController
    {
        private readonly SiteService _siteService;

        public static string Name { get { return "ParticipatingBranches"; } }

        public ParticipatingBranchesController(ServiceFacade.Controller context,
            SiteService siteService)
            : base(context)
        {
            _siteService = siteService ?? throw new ArgumentNullException(nameof(siteService));
        }

        public async Task<IActionResult> Index()
        {
            var site = await GetCurrentSiteAsync();
            if(await _siteLookupService.GetSiteSettingBoolAsync(site.Id,
                    SiteSettingKey.Users.ShowLinkToParticipatingBranches))
            {
                var viewModel = new ParticipatingBranchesViewModel
                {
                    Systems = await _siteService.GetSystemList()
                };
                return View(nameof(Index), viewModel);
            }
            else
            {
                return StatusCode(404);
            }
        }
    }
}

using GRA.Domain.Service;
using GRA.Controllers.ViewModel.ParticipatingBranches;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace GRA.Controllers
{
    public class ParticipatingBranchesController : Base.UserController
    {
        private readonly SiteService _siteService;

        public static string Name { get { return "ParticipatingBranches"; } }

        public ParticipatingBranchesController(ServiceFacade.Controller context,
            SiteService siteService)
            : base(context)
        {
            _siteService = siteService ?? throw new ArgumentNullException(nameof(siteService));
        }

        public async Task<IActionResult> Index()
        {
            var site = await GetCurrentSiteAsync();
            var viewModel = new ParticipatingBranchesViewModel
            {
                Systems = await _siteService.GetSystemList()
            };
            return View(nameof(Index), viewModel);
        }
    }
}

Access always to list of branches

Access always to list of branches


using System;

namespace OpenWeatherMap.Standard.Models
{
    /// <summary>
    /// wind model
    /// </summary>
    [Serializable]
    public class Wind : BaseModel
    {
        private float speed, gust;
        private int deg;

        /// <summary>
        /// wind speed
        /// </summary>
        public float Speed
        {
            get => speed;
            set => SetProperty(ref speed, value);
        }

        /// <summary>
        /// wind degree
        /// </summary>
        public int Degree
        {
            get => deg;
            set => SetProperty(ref deg, value);
        }

        /// <summary>
        /// gust
        /// </summary>
        public float Gust
        {
            get => gust;
            set => SetProperty(ref gust, value);
        }
    }

}

using Newtonsoft.Json;
using System;

namespace OpenWeatherMap.Standard.Models
{
    /// <summary>
    /// wind model
    /// </summary>
    [Serializable]
    public class Wind : BaseModel
    {
        private float speed, gust;
        private int deg;

        /// <summary>
        /// wind speed
        /// </summary>
        public float Speed
        {
            get => speed;
            set => SetProperty(ref speed, value);
        }

        /// <summary>
        /// wind degree
        /// </summary>
        [JsonProperty("deg")]
        public int Degree
        {
            get => deg;
            set => SetProperty(ref deg, value);
        }

        /// <summary>
        /// gust
        /// </summary>
        public float Gust
        {
            get => gust;
            set => SetProperty(ref gust, value);
        }
    }

}

Fix wind Degree not using the right name for the json file


using RepoZ.Api.IO;
using System;
using System.Linq;

namespace RepoZ.Api.Mac.IO
{
    public class MacDriveEnumerator : IPathProvider
    {
        public string[] GetPaths()
        {
            return System.IO.DriveInfo.GetDrives()
                .Where(d => d.DriveType == System.IO.DriveType.Fixed)
                .Where(p => !p.RootDirectory.FullName.StartsWith("/private", StringComparison.OrdinalIgnoreCase))
                .Select(d => d.RootDirectory.FullName)
                .ToArray();
        }
    }
}

using RepoZ.Api.IO;
using System;
using System.Linq;

namespace RepoZ.Api.Mac.IO
{
    public class MacDriveEnumerator : IPathProvider
    {
        public string[] GetPaths()
        {
            return new string[] { Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) };
        }
    }
}

Use the user profile as scan entry point instead of drives like in Windows


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sprache;
using System.Text.RegularExpressions;
using KVLib.KeyValues;

namespace KVLib
{
    /// <summary>
    /// Parser entry point for reading Key Value strings
    /// </summary>
    public static class KVParser
    {
        public static IKVParser KV1 = new KeyValues.SpracheKVParser();

        /// <summary>
        /// Reads a line of text and returns the first Root key in the text
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        ///
        [Obsolete("Please use KVParser.KV1.Parse()")]
        public static KeyValue ParseKeyValueText(string text)
        {
            return KV1.Parse(text);

        }
        /// <summary>
        /// Reads a blob of text and returns an array of all root keys in the text
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        ///
        [Obsolete("Please use KVParser.KV1.ParseAll()")]
        public static KeyValue[] ParseAllKVRootNodes(string text)
        {
            return KV1.ParseAll(text);
        }

    }

    public class KeyValueParsingException : Exception
    {
        public KeyValueParsingException(string message, Exception inner)
            : base(message, inner)
        {

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sprache;
using System.Text.RegularExpressions;
using KVLib.KeyValues;

namespace KVLib
{
    /// <summary>
    /// Parser entry point for reading Key Value strings
    /// </summary>
    public static class KVParser
    {
        public static IKVParser KV1 = new KeyValues.PenguinParser();

        /// <summary>
        /// Reads a line of text and returns the first Root key in the text
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        ///
        [Obsolete("Please use KVParser.KV1.Parse()")]
        public static KeyValue ParseKeyValueText(string text)
        {
            return KV1.Parse(text);

        }
        /// <summary>
        /// Reads a blob of text and returns an array of all root keys in the text
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        ///
        [Obsolete("Please use KVParser.KV1.ParseAll()")]
        public static KeyValue[] ParseAllKVRootNodes(string text)
        {
            return KV1.ParseAll(text);
        }

    }

    public class KeyValueParsingException : Exception
    {
        public KeyValueParsingException(string message, Exception inner)
            : base(message, inner)
        {

        }
    }
}

Set the default parser to the Penguin Parser as it has better error reporting and is faster


using System;
using System.Linq;

using HtmlAgilityPack;

namespace ReverseMarkdown.Converters
{
	public class Li
		: ConverterBase
	{
		public Li(Converter converter)
			: base(converter)
		{
			this.Converter.Register("li", this);
		}

		public override string Convert(HtmlNode node)
		{
			string content = this.TreatChildren(node);
			string indentation = IndentationFor(node);
			string prefix = PrefixFor(node);

			return string.Format("{0}{1}{2}" + Environment.NewLine, indentation, prefix, content.Chomp());
		}

		private string PrefixFor(HtmlNode node)
		{
			if (node.ParentNode != null && node.ParentNode.Name == "ol")
			{
				// index are zero based hence add one
				int index = node.ParentNode.SelectNodes("./li").IndexOf(node) + 1;
				return string.Format("{0}. ",index);
			}
			else
			{
				return "- ";
			}
		}

		private string IndentationFor(HtmlNode node)
		{
			int length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count();
			return new string(' ', Math.Max(length-1,0));
		}
	}
}

using System;
using System.Linq;

using HtmlAgilityPack;

namespace ReverseMarkdown.Converters
{
	public class Li
		: ConverterBase
	{
		public Li(Converter converter)
			: base(converter)
		{
			this.Converter.Register("li", this);
		}

		public override string Convert(HtmlNode node)
		{
			string content = this.TreatChildren(node);
			string indentation = IndentationFor(node);
			string prefix = PrefixFor(node);

			return string.Format("{0}{1}{2}" + Environment.NewLine, indentation, prefix, content.Chomp());
		}

		private string PrefixFor(HtmlNode node)
		{
			if (node.ParentNode != null && node.ParentNode.Name == "ol")
			{
				// index are zero based hence add one
				int index = node.ParentNode.SelectNodes("./li").IndexOf(node) + 1;
				return string.Format("{0}. ",index);
			}
			else
			{
				return "- ";
			}
		}

		private string IndentationFor(HtmlNode node)
		{
			int length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count();
			return new string(' ', Math.Max(length-1,0)*2);
		}
	}
}

Fix nested list item space before to 2 characters GH-14


namespace DungeonsAndDragons.DOF
{
    public class Character
    {
        public int Level { get; set; }
        public int Strength { get; set; }
        public int Dexterity { get; set; }
        public IWeapon CurrentWeapon { get; set; }

        public int StrengthModifier
        {
            get { return Strength / 2 - 5; }
        }

        public int DexterityModifier
        {
            get { return Dexterity / 2 - 5; }
        }

        public int BaseMeleeAttack
        {
            get { return Level / 2 + StrengthModifier; }
        }

        public int BaseRangedAttack
        {
            get { return Level / 2 + DexterityModifier; }
        }

        public int CurrentAttack
        {
            get
            {
                if (CurrentWeapon.IsMelee)
                    return BaseMeleeAttack + CurrentWeapon.AttackBonus;
                else
                    return BaseRangedAttack + CurrentWeapon.AttackBonus;
            }
        }

        public void Equip(IWeapon weapon)
        {
            CurrentWeapon = weapon;
        }

        public bool Attack(Creature creature, int roll)
        {
            return CurrentAttack + roll >= creature.ArmorClass;
        }
    }
}

namespace DungeonsAndDragons.DOF
{
    public class Character
    {
        public int Level { get; set; }
        public int Strength { get; set; }
        public int Dexterity { get; set; }
        public IWeapon CurrentWeapon { get; set; }

        public int StrengthModifier
        {
            get { return Strength / 2 - 5; }
        }

        public int DexterityModifier
        {
            get { return Dexterity / 2 - 5; }
        }

        public int BaseMeleeAttack
        {
            get { return Level / 2 + StrengthModifier; }
        }

        public int BaseRangedAttack
        {
            get { return Level / 2 + DexterityModifier; }
        }

        public int GetCurrentAttack(Creature creature)
        {
            if (CurrentWeapon.IsMelee)
                return BaseMeleeAttack + CurrentWeapon.RacialAttackBonus(creature.Race);
            else
                return BaseRangedAttack + CurrentWeapon.RacialAttackBonus(creature.Race);
        }

        public void Equip(IWeapon weapon)
        {
            CurrentWeapon = weapon;
        }

        public bool Attack(Creature creature, int roll)
        {
            return GetCurrentAttack(creature) + roll >= creature.ArmorClass;
        }
    }
}

Use racial attack bonus to compute current attack.


namespace Stripe.Issuing
{
    using Newtonsoft.Json;

    public class VerificationData : StripeEntity<VerificationData>
    {
        /// <summary>
        /// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
        /// </summary>
        [JsonProperty("address_line1_check")]
        public string AddressLine1Check { get; set; }

        /// <summary>
        /// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
        /// </summary>
        [JsonProperty("address_zip_check")]
        public string AddressZipCheck { get; set; }

        /// <summary>
        /// One of <c>success</c>, <c>failure</c>, <c>exempt</c>, or <c>none</c>.
        /// </summary>
        [JsonProperty("authentication")]
        public string Authentication { get; set; }

        /// <summary>
        /// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
        /// </summary>
        [JsonProperty("cvc_check")]
        public string CvcCheck { get; set; }
    }
}

namespace Stripe.Issuing
{
    using Newtonsoft.Json;

    public class VerificationData : StripeEntity<VerificationData>
    {
        /// <summary>
        /// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
        /// </summary>
        [JsonProperty("address_line1_check")]
        public string AddressLine1Check { get; set; }

        /// <summary>
        /// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
        /// </summary>
        [JsonProperty("address_zip_check")]
        public string AddressZipCheck { get; set; }

        /// <summary>
        /// One of <c>success</c>, <c>failure</c>, <c>exempt</c>, or <c>none</c>.
        /// </summary>
        [JsonProperty("authentication")]
        public string Authentication { get; set; }

        /// <summary>
        /// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
        /// </summary>
        [JsonProperty("cvc_check")]
        public string CvcCheck { get; set; }

        /// <summary>
        /// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
        /// </summary>
        [JsonProperty("expiry_check")]
        public string ExpiryCheck { get; set; }
    }
}

Add support for `ExpiryCheck` on Issuing `Authorization`


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

namespace Requests
{
    public class Schema
    {
        public string Url { get; private set; }
        public string Base { get; private set; }
        public string Path { get; private set; }

        public Schema(string url)
        {
            Url = url.TrimEnd(new char[] { '/' });
            var baseAndPath = url.Split('#');
            Base = baseAndPath[0];
            if (baseAndPath.Length == 2)
            {
                Path = baseAndPath[1];
            }
        }
    }
}

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

namespace Requests
{
    public class Schema
    {
        public string Url { get; private set; }
        public string Base { get; private set; }
        public string Path { get; private set; }

        public Schema(string url)
        {
            Url = url.TrimEnd(new char[] { '/' });
            var baseAndPath = Url.Split('#');
            Base = baseAndPath[0];
            if (baseAndPath.Length == 2)
            {
                Path = baseAndPath[1];
            }
        }
    }
}

Fix trailing slash in Url

Fix trailing slash in Url


using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = ClassLibrary1.Class1.ReturnFive();
            Console.WriteLine("Hello World!");
        }
    }
}

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Quick little demo of using a function from the shared class library
            int x = ClassLibrary1.Class1.ReturnFive();
            System.Diagnostics.Debug.Assert(x == 5);

            Console.WriteLine("Hello World!");
        }
    }
}

Add a quick little demo of using a function from the shared class library to ConsoleApp1


@model IEnumerable<Unit>

Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default" })

            @Html.DisplayNameFor(_ => _.FirstOrDefault().Name)
            @Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)

        @foreach (var unit in Model)
            {

                @Html.DisplayFor(s => unit)
                @Html.DisplayFor(s => unit.UIC)

                    @Html.ActionLink("Edit", "Edit", new { unit.Id })
                    @Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id })

        }

@model IEnumerable<Unit>

Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default" })

            @Html.DisplayNameFor(_ => _.FirstOrDefault().Name)
            @Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)

        @foreach (var unit in Model)
            {

                @Html.DisplayFor(s => unit)
                @Html.DisplayFor(s => unit.UIC)

                    @Html.ActionLink("Edit", "Edit", new { unit.Id })
                    @Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id })
                    @Html.ActionLink("Org Chart", "Details", new { unit.Id })

        }

Add link to org chart

Add link to org chart


using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Meraki {
    public partial class MerakiClient {
        private readonly HttpClient _client;
        private readonly UrlFormatProvider _formatter = new UrlFormatProvider();

        public MerakiClient(IOptions<MerakiClientSettings> options) {
            _client = new HttpClient(new HttpClientHandler()) {
                BaseAddress = new Uri(options.Value.Address)
            };
            _client.DefaultRequestHeaders.Add("X-Cisco-Meraki-API-Key", options.Value.Key);
            _client.DefaultRequestHeaders.Add("Accept-Type", "application/json");
        }

        private string Url(FormattableString formattable) => formattable.ToString(_formatter);

        public Task<HttpResponseMessage> SendAsync(HttpMethod method, string uri) {
            return SendAsync(new HttpRequestMessage(method, uri));
        }

        internal Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) {
            return _client.SendAsync(request);
        }

        internal async Task<T> GetAsync<T>(string uri) {
            var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
            var content = await response.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<T>(content);
        }

        public async Task<string> GetAsync(string uri) {
            var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
            var content = await response.Content.ReadAsStringAsync();

            return content;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Meraki {
    public partial class MerakiClient {
        private readonly HttpClient _client;
        private readonly UrlFormatProvider _formatter = new UrlFormatProvider();

        public MerakiClient(IOptions<MerakiClientSettings> options)
            : this(options.Value) {
        }

        public MerakiClient(MerakiClientSettings settings) {
            _client = new HttpClient(new HttpClientHandler()) {
                BaseAddress = new Uri(settings.Address)
            };
            _client.DefaultRequestHeaders.Add("X-Cisco-Meraki-API-Key", settings.Key);
            _client.DefaultRequestHeaders.Add("Accept-Type", "application/json");
        }

        private string Url(FormattableString formattable) => formattable.ToString(_formatter);

        public Task<HttpResponseMessage> SendAsync(HttpMethod method, string uri) => SendAsync(new HttpRequestMessage(method, uri));

        internal Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) => _client.SendAsync(request);

        internal async Task<T> GetAsync<T>(string uri) {
            var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
            var content = await response.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<T>(content);
        }

        public async Task<string> GetAsync(string uri) {
            var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
            var content = await response.Content.ReadAsStringAsync();

            return content;
        }
    }
}

Allow settings to be passed as well

Allow settings to be passed as well


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

using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;

using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;

using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Duality.Editor;

namespace RockyTV.Duality.Plugins.IronPython
{
    [EditorHintCategory(Properties.ResNames.CategoryScripts)]
    [EditorHintImage(Properties.ResNames.IconScriptGo)]
    public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
    {
        public ContentRef<PythonScript> Script { get; set; }

        [DontSerialize]
        private PythonExecutionEngine _engine;
        protected PythonExecutionEngine Engine
        {
            get { return _engine; }
        }

        protected virtual float Delta
        {
            get { return Time.MsPFMult * Time.TimeMult; }
        }

        public void OnInit(InitContext context)
        {
            if (!Script.IsAvailable) return;

            _engine = new PythonExecutionEngine(Script.Res.Content);
            _engine.SetVariable("gameObject", GameObj);

            if (_engine.HasMethod("start"))
                _engine.CallMethod("start");
        }

        public void OnUpdate()
        {
            if (_engine.HasMethod("update"))
                _engine.CallMethod("update", Delta);
        }

        public void OnShutdown(ShutdownContext context)
        {
            if (context == ShutdownContext.Deactivate)
            {
                GameObj.DisposeLater();
            }
        }
    }
}

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

using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;

using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;

using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Duality.Editor;

namespace RockyTV.Duality.Plugins.IronPython
{
    [EditorHintCategory(Properties.ResNames.CategoryScripts)]
    [EditorHintImage(Properties.ResNames.IconScriptGo)]
    public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
    {
        public ContentRef<PythonScript> Script { get; set; }

        [DontSerialize]
        private PythonExecutionEngine _engine;
        protected PythonExecutionEngine Engine
        {
            get { return _engine; }
        }

        protected virtual float Delta
        {
            get { return Time.MsPFMult * Time.TimeMult; }
        }

        public void OnInit(InitContext context)
        {
            if (!Script.IsAvailable) return;
            if (context == InitContext.Loaded)
            {
                _engine = new PythonExecutionEngine(Script.Res.Content);
                _engine.SetVariable("gameObject", GameObj);
            }

            if (_engine.HasMethod("start"))
                _engine.CallMethod("start", context);
        }

        public void OnUpdate()
        {
            if (_engine.HasMethod("update"))
                _engine.CallMethod("update", Delta);
        }

        public void OnShutdown(ShutdownContext context)
        {
            if (context == ShutdownContext.Deactivate)
            {
                GameObj.DisposeLater();
            }
        }
    }
}

Create exec engine on load and pass context to script


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SFA.DAS.EmployerUsers.Api.Controllers
{

    [RoutePrefix("api/status")]
    public class StatusController : ApiController
    {
        [Route("")]
        public IHttpActionResult Index()
        {
            // Do some Infrastructre work here to smoke out any issues.
            return Ok();
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using SFA.DAS.EmployerUsers.Api.Orchestrators;

namespace SFA.DAS.EmployerUsers.Api.Controllers
{

    [RoutePrefix("api/status")]
    public class StatusController : ApiController
    {
        private readonly UserOrchestrator _orchestrator;

        public StatusController(UserOrchestrator orchestrator)
        {
            _orchestrator = orchestrator;
        }

        [Route("")]
        public async Task <IHttpActionResult> Index()
        {
            try
            {
                // Do some Infrastructre work here to smoke out any issues.
                var users = await _orchestrator.UsersIndex(1, 1);
                return Ok();
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }
        }

    }
}

Add smoke test to Status controller

Add smoke test to Status controller


namespace Siftables
{
    public partial class MainWindowView
    {
        public MainWindowView()
        {
            InitializeComponent();
        }
    }
}

namespace Siftables
{
    public partial class MainWindowView
    {
        public MainWindowView()
        {
            InitializeComponent();
            DoSomething();
        }
    }
}

Break build to test TeamCity.

Break build to test TeamCity.

Signed-off-by: Alexander J Mullans <60c6d277a8bd81de7fdde19201bf9c58a3df08f4@alexmullans.com>


namespace Fixie
{
    using Internal;
    using Internal.Expressions;

    /// <summary>
    /// Subclass Discovery to customize test discovery rules.
    ///
    /// The default discovery rules are applied to a test assembly whenever the test
    /// assembly includes no such subclass.
    ///
    /// By defualt,
    ///
    /// <para>A class is a test class if its name ends with "Tests".</para>
    ///
    /// <para>All public methods in a test class are test methods.</para>
    /// </summary>
    public class Discovery
    {
        public Discovery()
        {
            Config = new Configuration();

            Classes = new ClassExpression(Config);
            Methods = new MethodExpression(Config);
            Parameters = new ParameterSourceExpression(Config);
        }

        /// <summary>
        /// The current state describing the discovery rules. This state can be manipulated through
        /// the other properties on Discovery.
        /// </summary>
        internal Configuration Config { get; }

        /// <summary>
        /// Defines the set of conditions that describe which classes are test classes.
        /// </summary>
        public ClassExpression Classes { get; }

        /// <summary>
        /// Defines the set of conditions that describe which test class methods are test methods,
        /// and what order to run them in.
        /// </summary>
        public MethodExpression Methods { get; }

        /// <summary>
        /// Defines the set of parameter sources, which provide inputs to parameterized test methods.
        /// </summary>
        public ParameterSourceExpression Parameters { get; }
    }
}

namespace Fixie
{
    using Internal;
    using Internal.Expressions;

    /// <summary>
    /// Subclass Discovery to customize test discovery rules.
    ///
    /// The default discovery rules are applied to a test assembly whenever the test
    /// assembly includes no such subclass.
    ///
    /// By default,
    ///
    /// <para>A class is a test class if its name ends with "Tests".</para>
    ///
    /// <para>All public methods in a test class are test methods.</para>
    /// </summary>
    public class Discovery
    {
        public Discovery()
        {
            Config = new Configuration();

            Classes = new ClassExpression(Config);
            Methods = new MethodExpression(Config);
            Parameters = new ParameterSourceExpression(Config);
        }

        /// <summary>
        /// The current state describing the discovery rules. This state can be manipulated through
        /// the other properties on Discovery.
        /// </summary>
        internal Configuration Config { get; }

        /// <summary>
        /// Defines the set of conditions that describe which classes are test classes.
        /// </summary>
        public ClassExpression Classes { get; }

        /// <summary>
        /// Defines the set of conditions that describe which test class methods are test methods,
        /// and what order to run them in.
        /// </summary>
        public MethodExpression Methods { get; }

        /// <summary>
        /// Defines the set of parameter sources, which provide inputs to parameterized test methods.
        /// </summary>
        public ParameterSourceExpression Parameters { get; }
    }
}

Fix spelling error in summary comment.

Fix spelling error in summary comment.


using System.Web.UI;
using IntelliFactory.WebSharper;

namespace IntelliFactory.WebSharper.JQuery.Mobile.Resources
{
    [IntelliFactory.WebSharper.Core.Attributes.Require(typeof(IntelliFactory.WebSharper.JQuery.Resources.JQuery))]
    public class JQueryMobile : IntelliFactory.WebSharper.Core.Resources.BaseResource
    {
        public JQueryMobile() : base("http://code.jquery.com/mobile/1.2.0-alpha.1",
            "/jquery.mobile-1.2.0-alpha.1.min.js",
            "/jquery.mobile-1.2.0-alpha.1.min.css") {}
    }
}

using System.Web.UI;
using IntelliFactory.WebSharper;

namespace IntelliFactory.WebSharper.JQuery.Mobile.Resources
{
    [IntelliFactory.WebSharper.Core.Attributes.Require(typeof(IntelliFactory.WebSharper.JQuery.Resources.JQuery))]
    public class JQueryMobile : IntelliFactory.WebSharper.Core.Resources.BaseResource
    {
        public JQueryMobile() : base("http://code.jquery.com/mobile/1.1.1",
            "/jquery.mobile-1.1.1.min.js",
            "/jquery.mobile-1.1.1.min.css") {}
    }
}

Use stable version of JQueryMobile.

Use stable version of JQueryMobile.


using System;

using Moq;
using Xunit;

namespace MarcinHoppe.LangtonsAnts.Tests
{
    public class AntTests
    {
        [Fact]
        public void AntTurnsRightOnWhiteSquare()
        {
            // Arrange
            var ant = AntAt(10, 7);
            var board = Mock.Of<Board>(b => b.ColorAt(PositionAt(10, 7)) == Colors.White);

            // Act
            ant.MoveOn(board);

            // Assert
            Assert.Equal(PositionAt(10, 8), ant.Position);
        }

        [Fact]
        public void AndTurnsLeftOnBlackSquare()
        {
            // Arrange
            var ant = AntAt(10, 7);
            var board = Mock.Of<Board>(b => b.ColorAt(PositionAt(10, 7)) == Colors.Black);

            // Act
            ant.MoveOn(board);

            // Assert
            Assert.Equal(PositionAt(10, 6), ant.Position);
        }

        private Ant AntAt(int row, int column)
        {
            return new Ant()
            {
                Position = new Position { Row = row, Column = column }
            };
        }

        private Position PositionAt(int row, int column)
        {
            return new Position
            {
                Row = row, Column = column
            };
        }
    }
}

using System;

using Moq;
using Xunit;

namespace MarcinHoppe.LangtonsAnts.Tests
{
    public class AntTests
    {
        [Fact]
        public void AntTurnsRightOnWhiteSquare()
        {
            // Arrange
            var ant = AntAt(10, 7);
            var board = Mock.Of<Board>(b => b.ColorAt(PositionAt(10, 7)) == Colors.White);

            // Act
            ant.MoveOn(board);

            // Assert
            Assert.Equal(PositionAt(10, 8), ant.Position);
        }

        [Fact]
        public void AntTurnsLeftOnBlackSquare()
        {
            // Arrange
            var ant = AntAt(10, 7);
            var board = Mock.Of<Board>(b => b.ColorAt(PositionAt(10, 7)) == Colors.Black);

            // Act
            ant.MoveOn(board);

            // Assert
            Assert.Equal(PositionAt(10, 6), ant.Position);
        }

        private Ant AntAt(int row, int column)
        {
            return new Ant()
            {
                Position = new Position { Row = row, Column = column }
            };
        }

        private Position PositionAt(int row, int column)
        {
            return new Position
            {
                Row = row, Column = column
            };
        }
    }
}

Fix typo in unit test name

Fix typo in unit test name


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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bdcb2164-56db-4f8c-8e7d-58c36a7408ca")]

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

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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bdcb2164-56db-4f8c-8e7d-58c36a7408ca")]

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

Disable parallel execution for tests

Disable parallel execution for tests

Tests for `FakeHostEnvironment` and `FakeHttpContext` can't be executed
in parallel as they are changing state of static classes.

I used to run tests with NCrunch with disabled parallel execution,
thats why I didn't see a problem.


#region Usings

using NUnit.Framework;

#endregion

namespace UnitTests
{
    [TestFixture]
    public class UnitTest1
    {
        [Test]
        public void TestMethod1()
        {
            Assert.True(true);
        }
    }
}

#region Usings

using NUnit.Framework;
using WebApplication.Controllers;

#endregion

namespace UnitTests
{
    [TestFixture]
    public class UnitTest1
    {
        [Test]
        public void TestMethod1()
        {
            var controller = new HabitController();
            Assert.True(true);
        }
    }
}

Replace test with test stub

Replace test with test stub


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

using Microsoft.WindowsAzure.MobileServices;

namespace MyDriving.AzureClient
{
    public class AzureClient : IAzureClient
    {
        const string DefaultMobileServiceUrl = "https://mydriving.azurewebsites.net";
        IMobileServiceClient client;
        string mobileServiceUrl;
        public IMobileServiceClient Client => client ?? (client = CreateClient());

        IMobileServiceClient CreateClient()
        {
            client = new MobileServiceClient(DefaultMobileServiceUrl, new AuthHandler())
            {
                SerializerSettings = new MobileServiceJsonSerializerSettings()
                {
                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
                    CamelCasePropertyNames = true
                }
            };
            return client;
        }
    }
}

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

using Microsoft.WindowsAzure.MobileServices;

namespace MyDriving.AzureClient
{
    public class AzureClient : IAzureClient
    {
        const string DefaultMobileServiceUrl = "https://mydriving.azurewebsites.net";
        static IMobileServiceClient client;

        public IMobileServiceClient Client => client ?? (client = CreateClient());

        IMobileServiceClient CreateClient()
        {
            client = new MobileServiceClient(DefaultMobileServiceUrl, new AuthHandler())
            {
                SerializerSettings = new MobileServiceJsonSerializerSettings()
                {
                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
                    CamelCasePropertyNames = true
                }
            };
            return client;
        }
    }
}

Make sure there is only one MobileServiceClient


using Lombiq.HelpfulExtensions.Extensions.SiteTexts.Services;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Data.Migration;
using OrchardCore.Modules;

namespace Lombiq.HelpfulExtensions.Extensions.SiteTexts;

[Feature(FeatureIds.SiteTexts)]
public class Startup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<IDataMigration, Migrations>();
        services.AddScoped<ISiteTextService, SiteTextService>();
    }
}

[Feature("OrchardCore.ContentLocalization")]
public class ContentLocalizationStartup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.RemoveImplementations<ISiteTextService>();
        services.AddScoped<ISiteTextService, ContentLocalizationSiteTextService>();
    }
}

using Lombiq.HelpfulExtensions.Extensions.SiteTexts.Services;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Data.Migration;
using OrchardCore.Modules;

namespace Lombiq.HelpfulExtensions.Extensions.SiteTexts;

[Feature(FeatureIds.SiteTexts)]
public class Startup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<IDataMigration, Migrations>();
        services.AddScoped<ISiteTextService, SiteTextService>();
    }
}

[RequireFeatures("OrchardCore.ContentLocalization")]
public class ContentLocalizationStartup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.RemoveImplementations<ISiteTextService>();
        services.AddScoped<ISiteTextService, ContentLocalizationSiteTextService>();
    }
}

Correct feature attribute to indicate dependency.


using Newtonsoft.Json;

namespace Clubhouse.io.net.Entities.Labels
{
    public class ClubhouseCreateLabelParams
    {
        [JsonProperty(PropertyName = "color")]
        public string Color { get; set; }

        [JsonProperty(PropertyName = "external_id")]
        public string ExternalID { get; set; }

        [JsonProperty(PropertyName = "name", Required = Required.Always)]
        public string Name { get; set; }
    }
}

using Newtonsoft.Json;

namespace Clubhouse.io.net.Entities.Labels
{
    public class ClubhouseCreateLabelParams
    {
        [JsonProperty(PropertyName = "color", NullValueHandling = NullValueHandling.Ignore)]
        public string Color { get; set; }

        [JsonProperty(PropertyName = "external_id", NullValueHandling = NullValueHandling.Ignore)]
        public string ExternalID { get; set; }

        [JsonProperty(PropertyName = "name", Required = Required.Always)]
        public string Name { get; set; }
    }
}

Create Label failing due to null Color & ExternalID being sent to API


using System.Collections.Generic;

namespace KotoriCore.Configuration
{
    /// <summary>
    /// Kotori main configuration.
    /// </summary>
    public class Kotori
    {
        /// <summary>
        /// Gets or sets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public string Instance { get; set; }

        /// <summary>
        /// GEts or sets the version of kotori server.
        /// </summary>
        /// <value>The version.</value>
        public string Version { get; set; }

        /// <summary>
        /// Gets or sets the master keys.
        /// </summary>
        /// <value>The master keys.</value>
        public IEnumerable<MasterKey> MasterKeys { get; set; }
    }
}

using System.Collections.Generic;

namespace KotoriCore.Configuration
{
    /// <summary>
    /// Kotori main configuration.
    /// </summary>
    public class Kotori
    {
        /// <summary>
        /// Gets or sets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public string Instance { get; set; }

        /// <summary>
        /// GEts or sets the version of kotori server.
        /// </summary>
        /// <value>The version.</value>
        public string Version { get; set; }

        /// <summary>
        /// Gets or sets the master keys.
        /// </summary>
        /// <value>The master keys.</value>
        public IEnumerable<MasterKey> MasterKeys { get; set; }

        /// <summary>
        /// Gets or sets the document db connection string.
        /// </summary>
        /// <value>The document db.</value>
        public DocumentDb DocumentDb { get; set; }
    }
}

Add DocumentDb connection to main kotori config


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

namespace Magick.NET.Tests
{
    public partial class MagickNETTests
    {
        [TestClass]
        public class TheDelegatesProperty
        {
            [TestMethod]
            public void ShouldReturnAllDelegates()
            {
                var delegates = MagickNET.Delegates; // Cannot detect difference between macOS and Linux build at the moment

#if WINDOWS_BUILD
                Assert.AreEqual("cairo flif freetype gslib heic jng jp2 jpeg lcms lqr openexr pangocairo png ps raw rsvg tiff webp xml zlib", delegates);
#else
                Assert.AreEqual("fontconfig freetype heic jng jp2 jpeg lcms openexr png raw tiff webp xml zlib", delegates);
#endif
            }
        }
    }
}

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

namespace Magick.NET.Tests
{
    public partial class MagickNETTests
    {
        [TestClass]
        public class TheDelegatesProperty
        {
            [TestMethod]
            public void ShouldReturnAllDelegates()
            {
                var delegates = MagickNET.Delegates; // Cannot detect difference between macOS and Linux build at the moment

#if WINDOWS_BUILD
                Assert.AreEqual("cairo flif freetype gslib heic jng jp2 jpeg lcms lqr openexr pangocairo png ps raw rsvg tiff webp xml zlib", delegates);
#else
                Assert.AreEqual("fontconfig freetype heic jng jp2 jpeg lcms lqr openexr png raw tiff webp xml zlib", delegates);
#endif
            }
        }
    }
}

Change because lqr support was added to the Linux and macOS build.


using System;
using System.Drawing;
using NUnit.Framework;
using Palaso.UI.WindowsForms;

namespace PalasoUIWindowsForms.Tests.FontTests
{
	[TestFixture]
	public class FontHelperTests
	{

		[SetUp]
		public void SetUp()
		{
			// setup code goes here
		}

		[TearDown]
		public void TearDown()
		{
			// tear down code goes here
		}

		[Test]
		public void MakeFont_FontName_ValidFont()
		{
			Font sourceFont = SystemFonts.DefaultFont;
			Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
			Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
		}

	}
}

using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;

namespace PalasoUIWindowsForms.Tests.FontTests
{
	[TestFixture]
	public class FontHelperTests
	{
		[Test]
		public void MakeFont_FontName_ValidFont()
		{
			using (var sourceFont = SystemFonts.DefaultFont)
			{
				using (var returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name))
				{
					Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
				}
			}
		}

		[Test]
		public void MakeFont_FontNameAndStyle_ValidFont()
		{
			// use Times New Roman
			foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
			{
				using (var sourceFont = new Font(family, 10f, FontStyle.Regular))
				{
					using (var returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold))
					{
						Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
						Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
					}
				}
				break;
			}
		}
	}
}

Fix mono bug in the FontHelper class

Fix mono bug in the FontHelper class


using CrossStitch.Core.Configuration;

namespace CrossStitch.Core.Modules.Stitches
{
    public class StitchesConfiguration : IModuleConfiguration
    {
        public static StitchesConfiguration GetDefault()
        {
            return ConfigurationLoader.GetConfiguration<StitchesConfiguration>("stitches.json");
        }

        public string DataBasePath { get; set; }
        public string AppLibraryBasePath { get; set; }
        public string RunningAppBasePath { get; set; }

        public void ValidateAndSetDefaults()
        {
        }
    }
}

using CrossStitch.Core.Configuration;

namespace CrossStitch.Core.Modules.Stitches
{
    public class StitchesConfiguration : IModuleConfiguration
    {
        public static StitchesConfiguration GetDefault()
        {
            return ConfigurationLoader.GetConfiguration<StitchesConfiguration>("stitches.json");
        }

        public string DataBasePath { get; set; }
        public string AppLibraryBasePath { get; set; }
        public string RunningAppBasePath { get; set; }

        public void ValidateAndSetDefaults()
        {
            if (string.IsNullOrEmpty(DataBasePath))
                DataBasePath = ".\\StitchData";
            if (string.IsNullOrEmpty(AppLibraryBasePath))
                AppLibraryBasePath = ".\\StitchLibrary";
            if (string.IsNullOrEmpty(RunningAppBasePath))
                RunningAppBasePath = ".\\RunningStitches";
        }
    }
}

[Stitches] Add some default values for StitchConfiguration


// 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.Threading;
using NUnit.Framework;
using osu.Framework.Audio;

namespace osu.Framework.Tests.Audio
{
    [TestFixture]
    public class AudioCollectionManagerTest
    {
        [Test]
        public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
        {
            var manager = new TestAudioCollectionManager();

            var threadExecutionFinished = new ManualResetEventSlim();
            var updateLoopStarted = new ManualResetEventSlim();

            // add a huge amount of items to the queue
            for (int i = 0; i < 10000; i++)
                manager.AddItem(new TestingAdjustableAudioComponent());

            // in a separate thread start processing the queue
            var thread = new Thread(() =>
            {
                while (!manager.IsDisposed)
                {
                    manager.Update();
                    updateLoopStarted.Set();
                }

                threadExecutionFinished.Set();
            });

            thread.Start();

            Assert.IsTrue(updateLoopStarted.Wait(1000));

            Assert.DoesNotThrow(() => manager.Dispose());

            Assert.IsTrue(threadExecutionFinished.Wait(1000));
        }

        private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent>
        {
            public new bool IsDisposed => base.IsDisposed;
        }

        private class TestingAdjustableAudioComponent : AdjustableAudioComponent
        {
        }
    }
}

// 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.Threading;
using NUnit.Framework;
using osu.Framework.Audio;

namespace osu.Framework.Tests.Audio
{
    [TestFixture]
    public class AudioCollectionManagerTest
    {
        [Test]
        public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
        {
            var manager = new TestAudioCollectionManager();

            var threadExecutionFinished = new ManualResetEventSlim();
            var updateLoopStarted = new ManualResetEventSlim();

            // add a huge amount of items to the queue
            for (int i = 0; i < 10000; i++)
                manager.AddItem(new TestingAdjustableAudioComponent());

            // in a separate thread start processing the queue
            var thread = new Thread(() =>
            {
                while (!manager.IsDisposed)
                {
                    manager.Update();
                    updateLoopStarted.Set();
                }

                threadExecutionFinished.Set();
            });

            thread.Start();

            Assert.IsTrue(updateLoopStarted.Wait(10000));

            Assert.DoesNotThrow(() => manager.Dispose());

            Assert.IsTrue(threadExecutionFinished.Wait(10000));
        }

        private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent>
        {
            public new bool IsDisposed => base.IsDisposed;
        }

        private class TestingAdjustableAudioComponent : AdjustableAudioComponent
        {
        }
    }
}

Increase test wait times (appveyor be slow)


using NUnit.Framework;
using SecretSplitting;

namespace ElectronicCash.Tests
{
    [TestFixture]
    class SecretSplittingTests
    {
        private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
        private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
        private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);

        [Test]
        public void OnSplit_OriginalMessageShouldBeRecoverable()
        {
            _splitter.SplitSecretBetweenTwoPeople();

            var r = _splitter.R;
            var s = _splitter.S;

            var m = Helpers.ExclusiveOr(r, s);

            Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message));
        }

        [Test]
        public void OnSecretSplit_FlagsShouldBeTrue()
        {
            var splitter = new SecretSplittingProvider(Message, RandBytes);
            splitter.SplitSecretBetweenTwoPeople();

            Assert.IsTrue(splitter.IsRProtected);
            Assert.IsTrue(splitter.IsSProtected);
            Assert.IsTrue(splitter.IsSecretMessageProtected);
        }
    }
}

using NUnit.Framework;
using SecretSplitting;

namespace ElectronicCash.Tests
{
    [TestFixture]
    class SecretSplittingTests
    {
        private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
        private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
        private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);
        private const int Padding = 16;

        [Test]
        public void OnSplit_OriginalMessageShouldBeRecoverable()
        {
            _splitter.SplitSecretBetweenTwoPeople();
            Helpers.ToggleMemoryProtection(_splitter);
            var r = _splitter.R;
            var s = _splitter.S;

            var m = Helpers.ExclusiveOr(r, s);
            var toPad = Message;

            Helpers.PadArrayToMultipleOf(ref toPad, Padding);

            Helpers.ToggleMemoryProtection(_splitter);

            Assert.AreEqual(Helpers.GetString(toPad), Helpers.GetString(m));
        }

        [Test]
        public void OnSecretSplit_FlagsShouldBeTrue()
        {
            var splitter = new SecretSplittingProvider(Message, RandBytes);
            splitter.SplitSecretBetweenTwoPeople();

            Assert.IsTrue(splitter.IsRProtected);
            Assert.IsTrue(splitter.IsSProtected);
            Assert.IsTrue(splitter.IsSecretMessageProtected);
        }
    }
}

Fix unit test so it does unprotecting and padding