using System;
using System.IO;
using System.Linq;

namespace AutoHeader.Options
{
    public class RemoveHeaderOption : Option
    {
        public override void Execute()
        {
            Console.WriteLine("Execute \'RemoveHeaderOption\': {0}", Arg);

            if (!Directory.Exists(Arg))
            {
                throw new ExecutionException(string.Format("Directory does not exist: {0}", Arg));
            }

            RemoveHeaderFromFilesInDirectory(Arg);
        }

        private void RemoveHeaderFromFilesInDirectory(string directory)
        {
            foreach (var filePath in Directory.GetFiles(directory).Where(f => f.EndsWith(".cs")))
            {
                RemoveHeaderFromFile(filePath);
            }
            foreach (var subDir in Directory.GetDirectories(directory))
            {
                RemoveHeaderFromFilesInDirectory(subDir);
            }
        }

        private void RemoveHeaderFromFile(string filePath)
        {
            var tempFilePath = GetTempFileName(filePath);
            File.Move(filePath, tempFilePath);

            string header;
            using (var streamReader = new StreamReader("HeaderTemplate.txt"))
            {
                header = streamReader.ReadToEnd();
            }

            string fileContent;
            using (var streamReader = new StreamReader(tempFilePath))
            {
                fileContent = streamReader.ReadToEnd();
            }

            fileContent = fileContent.Substring(header.Length);

            using (var stream = new StreamWriter(filePath, false))
            {
                stream.Write(fileContent);
            }
            File.Delete(tempFilePath);
        }

        private static string GetTempFileName(string filePath)
        {
            var fileName = Path.GetFileName(filePath);
            var path = Path.GetDirectoryName(filePath) ?? string.Empty;
            var tempFilePath = Path.Combine(path, string.Format("~{0}", fileName));
            return tempFilePath;
        }

    }
}

using System;
using System.IO;
using System.Linq;

namespace AutoHeader.Options
{
    public class RemoveHeaderOption : Option
    {
        public override void Execute()
        {
            Console.WriteLine("Execute \'RemoveHeaderOption\': {0}", Arg);

            if (!Directory.Exists(Arg))
            {
                throw new ExecutionException(string.Format("Directory does not exist: {0}", Arg));
            }

            RemoveHeaderFromFilesInDirectory(Arg);
        }

        private void RemoveHeaderFromFilesInDirectory(string directory)
        {
            foreach (var filePath in Directory.GetFiles(directory).Where(f => f.EndsWith(".cs")))
            {
                RemoveHeaderFromFile(filePath);
            }
            foreach (var subDir in Directory.GetDirectories(directory))
            {
                RemoveHeaderFromFilesInDirectory(subDir);
            }
        }

        private void RemoveHeaderFromFile(string filePath)
        {
            string header;
            using (var streamReader = new StreamReader("HeaderTemplate.txt"))
            {
                header = streamReader.ReadToEnd();
            }

            string fileContent;
            using (var streamReader = new StreamReader(filePath))
            {
                fileContent = streamReader.ReadToEnd();
            }

            if (fileContent.Length >= header.Length)
            {
                var fileHeader = fileContent.Substring(0, header.Length);
                if (fileHeader == header)
                {
                    fileContent = fileContent.Substring(header.Length);
                    using (var stream = new StreamWriter(filePath, false))
                    {
                        stream.Write(fileContent);
                    }
                }
            }
        }
    }
}

Check for header before removing it

Check for header before removing it


using System.Drawing;
using MonoHaven.Graphics;
using MonoHaven.Graphics.Text;

namespace MonoHaven.UI.Widgets
{
	public class Progress : Widget
	{
		private readonly TextLine textLine;
		private int value;

		public Progress(Widget parent) : base(parent)
		{
			textLine = new TextLine(Fonts.LabelText);
			textLine.TextColor = Color.DeepPink;
			textLine.TextAlign = TextAlign.Center;
			textLine.SetWidth(75);
			Resize(textLine.Width, 20);
		}

		public int Value
		{
			get { return value; }
			set
			{
				this.value = value;
				textLine.Clear();
				textLine.Append(string.Format("{0}%", value));
			}
		}

		protected override void OnDraw(DrawingContext dc)
		{
			dc.Draw(textLine, 0, 0);
		}

		protected override void OnDispose()
		{
			if (textLine != null)
				textLine.Dispose();
		}
	}
}

using System.Drawing;
using MonoHaven.Graphics;
using MonoHaven.Graphics.Text;

namespace MonoHaven.UI.Widgets
{
	public class Progress : Widget
	{
		private readonly TextLine textLine;
		private int value;

		public Progress(Widget parent) : base(parent)
		{
			textLine = new TextLine(Fonts.LabelText);
			textLine.TextColor = Color.Yellow;
			textLine.TextAlign = TextAlign.Center;
			textLine.SetWidth(75);
			Resize(textLine.Width, 20);
		}

		public int Value
		{
			get { return value; }
			set
			{
				this.value = value;
				textLine.Clear();
				textLine.Append(string.Format("{0}%", value));
			}
		}

		protected override void OnDraw(DrawingContext dc)
		{
			dc.Draw(textLine, 0, 0);
		}

		protected override void OnDispose()
		{
			if (textLine != null)
				textLine.Dispose();
		}
	}
}

Change color to be more visible

Change color to be more visible


using System;
using SQLite;

namespace Amica.vNext.SimpleCache
{
    class CacheElement
    {
	[PrimaryKey]
	public string Key { get; set; }
	[Indexed]
	public string TypeName { get; set; }
        public byte[] Value { get; set; }
	public DateTime? Expiration { get; set; }
	public DateTimeOffset CreatedAt { get; set; }
    }
}

using System;
using SQLite;

namespace Amica.vNext.SimpleCache
{
    class CacheElement
    {
	[PrimaryKey]
	public string Key { get; set; }
	[Indexed]
	public string TypeName { get; set; }
        public byte[] Value { get; set; }
	[Indexed]
	public DateTime? Expiration { get; set; }
	public DateTimeOffset CreatedAt { get; set; }
    }
}

Make sure Expiration field is also indexed in the db


namespace Sitecore.FakeDb.Tests.Data
{
    using System;
    using FluentAssertions;
    using NSubstitute;
    using global::AutoFixture.Xunit2;
    using Sitecore.Data;
    using Sitecore.Data.Fields;
    using Sitecore.FakeDb.Data;
    using Sitecore.FakeDb.Data.Engines;
    using Sitecore.FakeDb.Data.Items;
    using Xunit;

    public class FakeStandardValuesProviderTest
    {
        [Theory, DefaultAutoData]
        public void ShouldReturnEmptyStringIfNoTemplateFound(
            FakeStandardValuesProvider sut,
            [Greedy] Field field,
            DataStorage dataStorage)
        {
            using (new DataStorageSwitcher(dataStorage))
            {
                sut.GetStandardValue(field).Should().BeEmpty();
            }
        }

        [Fact]
        public void ShouldThrowIfNoDataStorageSet()
        {
            // arrange
            var sut = Substitute.ForPartsOf<FakeStandardValuesProvider>();
            sut.DataStorage(Arg.Any<Database>()).Returns((DataStorage)null);

            var field = new Field(ID.NewID, ItemHelper.CreateInstance());

            // act
            Action action = () => sut.GetStandardValue(field);

            // assert
            action.ShouldThrow<InvalidOperationException>()
                .WithMessage("DataStorage cannot be null.");
        }
    }
}

namespace Sitecore.FakeDb.Tests.Data
{
    using System;
    using FluentAssertions;
    using NSubstitute;
    using global::AutoFixture.Xunit2;
    using Sitecore.Abstractions;
    using Sitecore.Data;
    using Sitecore.Data.Fields;
    using Sitecore.FakeDb.Data;
    using Sitecore.FakeDb.Data.Engines;
    using Sitecore.FakeDb.Data.Items;
    using Xunit;

    public class FakeStandardValuesProviderTest
    {
        [Theory, DefaultSubstituteAutoData]
        public void ShouldReturnEmptyStringIfNoTemplateFound(
            FakeStandardValuesProvider sut,
            [Greedy] Field field,
            DataStorage dataStorage)
        {
            using (new DataStorageSwitcher(dataStorage))
            {
                sut.GetStandardValue(field).Should().BeEmpty();
            }
        }

        [Theory, DefaultSubstituteAutoData]
        public void ShouldThrowIfNoDataStorageSet(
            BaseItemManager itemManager,
            BaseTemplateManager templateManager,
            BaseFactory factory)
        {
            // arrange
            var sut = Substitute.ForPartsOf<FakeStandardValuesProvider>(itemManager, templateManager, factory);
            sut.DataStorage(Arg.Any<Database>()).Returns((DataStorage)null);
            var field = new Field(ID.NewID, ItemHelper.CreateInstance());

            // act
            Action action = () => sut.GetStandardValue(field);

            // assert
            action.ShouldThrow<InvalidOperationException>()
                .WithMessage("DataStorage cannot be null.");
        }
    }
}

Fix FakeStandardValuesProvider instatiation in tests


using Hangfire.Mongo.Database;
using MongoDB.Driver;
using System;
using Hangfire.Mongo.Helpers;
using MongoDB.Bson;

namespace Hangfire.Mongo.MongoUtils
{
    /// <summary>
    /// Helper utilities to work with Mongo database
    /// </summary>
    public static class MongoExtensions
    {
        /// <summary>
        /// Retreives server time in UTC zone
        /// </summary>
        /// <param name="database">Mongo database</param>
        /// <returns>Server time</returns>
        public static DateTime GetServerTimeUtc(this IMongoDatabase database)
        {
            try
            {
                dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1)));
                return ((DateTime)serverStatus.localTime).ToUniversalTime();
            }
            catch (MongoException)
            {
                return DateTime.UtcNow;
			}
			catch (FormatException)
			{
				return DateTime.UtcNow;
			}
        }

        /// <summary>
        /// Retreives server time in UTC zone
        /// </summary>
        /// <param name="dbContext">Hangfire database context</param>
        /// <returns>Server time</returns>
        public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext)
        {
            return GetServerTimeUtc(dbContext.Database);
        }
    }
}

using Hangfire.Mongo.Database;
using MongoDB.Driver;
using System;
using Hangfire.Mongo.Helpers;
using MongoDB.Bson;

namespace Hangfire.Mongo.MongoUtils
{
    /// <summary>
    /// Helper utilities to work with Mongo database
    /// </summary>
    public static class MongoExtensions
    {
        /// <summary>
        /// Retreives server time in UTC zone
        /// </summary>
        /// <param name="database">Mongo database</param>
        /// <returns>Server time</returns>
        public static DateTime GetServerTimeUtc(this IMongoDatabase database)
        {
            try
            {
                dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1)));
                return ((DateTime)serverStatus.localTime).ToUniversalTime();
            }
            catch (MongoException)
            {
                return DateTime.UtcNow;
            }
        }

        /// <summary>
        /// Retreives server time in UTC zone
        /// </summary>
        /// <param name="dbContext">Hangfire database context</param>
        /// <returns>Server time</returns>
        public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext)
        {
            return GetServerTimeUtc(dbContext.Database);
        }
    }
}

Revert "Ignore FormatException, that can be caused by an error in the MongoDb.Driver"

This reverts commit 7667a1ee529db168fd58590e94e3992cdc389dc8.


using Xamarin.UITest;

namespace Xtc101.UITest
{
    public class AppInitializer
    {
        public static IApp StartApp(Platform platform)
        {
            if (platform == Platform.Android)
            {
                return ConfigureApp
                    .Android
                    .PreferIdeSettings()
                    .StartApp();
            }

            return ConfigureApp
                .iOS
                .PreferIdeSettings()
                .StartApp();
        }
    }
}

using Xamarin.UITest;

namespace Xtc101.UITest
{
    public class AppInitializer
    {
        public static IApp StartApp(Platform platform)
        {
            if (platform == Platform.Android)
            {
                return ConfigureApp
                    .Android
                    // Run Release Android project on Simulator and then uncomment line bellow (you can run the tests under the debug config)
                    //.ApkFile("../../../Xtc101/bin/Release/com.companyname.xtc101.apk")
                    .PreferIdeSettings()
                    .StartApp();
            }

            return ConfigureApp
                .iOS
                .PreferIdeSettings()
                .StartApp();
        }
    }
}

Add App Package location sample code

Add App Package location sample code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using MundlTransit.WP8.ViewModels.LineInfo;

namespace MundlTransit.WP8.StorageHandlers
{
    public class LineInfoPageViewModelStorage : StorageHandler<LineInfoPageViewModel>
    {
        public override void Configure()
        {
            Property(vm => vm.NavigationLineId)
                .InPhoneState()
                .RestoreAfterViewLoad();

            Property(vm => vm.NavigationLineName)
                .InPhoneState()
                .RestoreAfterViewLoad();

            Property(vm => vm.Richtung)
                .InPhoneState()
                .RestoreAfterViewLoad();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using MundlTransit.WP8.ViewModels.LineInfo;

namespace MundlTransit.WP8.StorageHandlers
{
    public class LineInfoPageViewModelStorage : StorageHandler<LineInfoPageViewModel>
    {
        public override void Configure()
        {
            // No need to store navigation properties

            Property(vm => vm.Richtung)
                .InPhoneState()
                .RestoreAfterActivation();  // this property is needed in OnActivate
        }
    }
}

Fix storage handler for Richtung property and remove unnecessary navigation properties


using System.Net;
using LtiLibrary.Core.Outcomes.v2;

namespace LtiLibrary.AspNet.Outcomes.v2
{
    public class PutResultContext
    {
        public PutResultContext(LisResult result)
        {
            Result = result;
            StatusCode = HttpStatusCode.OK;
        }

        public LisResult Result { get; private set; }
        public HttpStatusCode StatusCode { get; set; }
    }
}

using System.Net;
using LtiLibrary.Core.Outcomes.v2;

namespace LtiLibrary.AspNet.Outcomes.v2
{
    public class PutResultContext
    {
        public PutResultContext(string contextId, string lineItemId, string id, LisResult result)
        {
            ContextId = contextId;
            LineItemId = lineItemId;
            Id = id;
            Result = result;
            StatusCode = HttpStatusCode.OK;
        }

        public string ContextId { get; set; }
        public string LineItemId { get; set; }
        public string Id { get; set; }
        public LisResult Result { get; private set; }
        public HttpStatusCode StatusCode { get; set; }
    }
}

Add ids from service endpoint

Add ids from service endpoint


using System;
using SevenDigital.Api.Wrapper.Exceptions;

namespace SevenDigital.Api.Wrapper.Utility.Serialization
{
	public class ApiXmlDeSerializer<T> : IDeSerializer<T> where T : class
	{
		private readonly IDeSerializer<T> _deSerializer;
		private readonly IXmlErrorHandler _xmlErrorHandler;

		public ApiXmlDeSerializer(IDeSerializer<T> deSerializer, IXmlErrorHandler xmlErrorHandler) {
			_deSerializer = deSerializer;
			_xmlErrorHandler = xmlErrorHandler;
		}

		public T DeSerialize(string response)
		{
			try
			{
				var responseNode = _xmlErrorHandler.GetResponseAsXml(response);
				_xmlErrorHandler.AssertError(responseNode);
				var resourceNode = responseNode.FirstNode.ToString();
				return _deSerializer.DeSerialize(resourceNode);
			}
			catch (Exception e)
			{
				if (e is ApiXmlException)
					throw;
				throw new ApplicationException("Internal error while deserializing response " + response, e);
			}
		}
	}
}

namespace SevenDigital.Api.Wrapper.Utility.Serialization
{
	public class ApiXmlDeSerializer<T> : IDeSerializer<T> where T : class
	{
		private readonly IDeSerializer<T> _deSerializer;
		private readonly IXmlErrorHandler _xmlErrorHandler;

		public ApiXmlDeSerializer(IDeSerializer<T> deSerializer, IXmlErrorHandler xmlErrorHandler) {
			_deSerializer = deSerializer;
			_xmlErrorHandler = xmlErrorHandler;
		}

		public T DeSerialize(string response)
		{
			var responseNode = _xmlErrorHandler.GetResponseAsXml(response);
			_xmlErrorHandler.AssertError(responseNode);
			var resourceNode = responseNode.FirstNode.ToString();
			return _deSerializer.DeSerialize(resourceNode);
		}
	}
}

Stop wrapping exceptions we don't know about and let them throw at the point of error.


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

using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;

namespace osu.Game.Users
{
    /// <summary>
    /// An avatar which can update to a new user when needed.
    /// </summary>
    public class UpdateableAvatar : Container
    {
        private Container displayedAvatar;

        private User user;

        public User User
        {
            get { return user; }
            set
            {
                if (user?.Id == value?.Id)
                    return;

                user = value;

                if (IsLoaded)
                    updateAvatar();
            }
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();
            updateAvatar();
        }

        private void updateAvatar()
        {
            displayedAvatar?.FadeOut(300);
            displayedAvatar?.Expire();
            Add(displayedAvatar = new AsyncLoadWrapper(new Avatar(user)
            {
                RelativeSizeAxes = Axes.Both,
                OnLoadComplete = d => d.FadeInFromZero(200),
            }));
        }
    }
}

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

using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;

namespace osu.Game.Users
{
    /// <summary>
    /// An avatar which can update to a new user when needed.
    /// </summary>
    public class UpdateableAvatar : Container
    {
        private Container displayedAvatar;

        private User user;

        public User User
        {
            get { return user; }
            set
            {
                if (user?.Id == value?.Id)
                    return;

                user = value;

                if (IsLoaded)
                    updateAvatar();
            }
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();
            updateAvatar();
        }

        private void updateAvatar()
        {
            displayedAvatar?.FadeOut(300);
            displayedAvatar?.Expire();
            Add(displayedAvatar = new DelayedLoadWrapper(new Avatar(user)
            {
                RelativeSizeAxes = Axes.Both,
                OnLoadComplete = d => d.FadeInFromZero(200),
            }));
        }
    }
}

Make avatars use a delayed load wrapper

Make avatars use a delayed load wrapper


using System.Linq;
using UnityEngine;
using UnityEditor;

namespace EasyButtons
{
    /// <summary>
    /// Custom inspector for Object including derived classes.
    /// </summary>
    [CanEditMultipleObjects]
    [CustomEditor(typeof(Object), true)]
    public class ObjectEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            // Loop through all methods with the Button attribute and no arguments
            foreach (var method in target.GetType().GetMethods()
                .Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0)
                .Where(m => m.GetParameters().Length == 0))
            {
                // Draw a button which invokes the method
                if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name)))
                {
                    foreach (var target in targets)
                    {
                        method.Invoke(target, null);
                    }
                }
            }
            // Draw the rest of the inspector as usual
            DrawDefaultInspector();
        }
    }
}

using System.Linq;
using UnityEngine;
using UnityEditor;

namespace EasyButtons
{
    /// <summary>
    /// Custom inspector for Object including derived classes.
    /// </summary>
    [CanEditMultipleObjects]
    [CustomEditor(typeof(Object), true)]
    public class ObjectEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            // Loop through all methods with the Button attribute and no arguments
            foreach (var method in target.GetType().GetMethods()
                .Where(m => System.Attribute.IsDefined(m, typeof(ButtonAttribute), true))
                .Where(m => m.GetParameters().Length == 0))
            {
                // Draw a button which invokes the method
                if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name)))
                {
                    foreach (var target in targets)
                    {
                        method.Invoke(target, null);
                    }
                }
            }
            // Draw the rest of the inspector as usual
            DrawDefaultInspector();
        }
    }
}

Make attribute search more to the point

Make attribute search more to the point


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

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

        public IConfigurationRoot Configuration { get; }

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

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

            app.UseDeveloperExceptionPage();
            app.UseMvc();

        }
    }
}

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

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

        public IConfigurationRoot Configuration { get; }

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

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

            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();

            app.UseMvc();

        }
    }
}

Use DeveloperExceptionPage only in DEV Enviroment


using Glimpse.Core.Extensibility;

namespace Glimpse.Knockout
{
    public sealed class ClientScript : IStaticClientScript
    {
        public ScriptOrder Order { get { return ScriptOrder.IncludeAfterClientInterfaceScript; } }
        public string GetUri(string version)
        {
            return "/Scripts/glimpse-knockout.js";
        }
    }
}

using Glimpse.Core.Extensibility;

namespace Glimpse.Knockout
{
    public sealed class ClientScript : IStaticClientScript
    {
        public ScriptOrder Order { get { return ScriptOrder.IncludeAfterClientInterfaceScript; } }
        public string GetUri(string version)
        {
            return System.Web.VirtualPathUtility.ToAbsolute("~/Scripts/glimpse-knockout.js");
        }
    }
}

Fix to support virtual directories/folders in IIS.


namespace Microsoft.eShopOnContainers.WebMVC.Controllers
{
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.eShopOnContainers.WebMVC.Services;
    using Microsoft.eShopOnContainers.WebMVC.ViewModels;
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;

    [Authorize]
    public class CampaignsController : Controller
    {
        private ICampaignService _campaignService;

        public CampaignsController(ICampaignService campaignService) =>
            _campaignService = campaignService;

        public async Task<IActionResult> Index()
        {
            var campaignList = await _campaignService.GetCampaigns();

            return View(campaignList);
        }

        public async Task<IActionResult> Details(int id)
        {
            var campaignDto = await _campaignService.GetCampaignById(id);

            var campaign = new Campaign
            {
                Id = campaignDto.Id,
                Name = campaignDto.Name,
                Description = campaignDto.Description,
                From = campaignDto.From,
                To = campaignDto.To,
                PictureUri = campaignDto.PictureUri
            };

            return View(campaign);
        }
    }
}

namespace Microsoft.eShopOnContainers.WebMVC.Controllers
{
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.eShopOnContainers.WebMVC.Models;
    using Microsoft.eShopOnContainers.WebMVC.Services;
    using Microsoft.eShopOnContainers.WebMVC.ViewModels;
    using System.Collections.Generic;
    using System.Threading.Tasks;

    [Authorize]
    public class CampaignsController : Controller
    {
        private ICampaignService _campaignService;

        public CampaignsController(ICampaignService campaignService) =>
            _campaignService = campaignService;

        public async Task<IActionResult> Index()
        {
            var campaignDtoList = await _campaignService.GetCampaigns();

            if(campaignDtoList is null)
            {
                return View();
            }

            var campaignList = MapCampaignModelListToDtoList(campaignDtoList);

            return View(campaignList);
        }

        public async Task<IActionResult> Details(int id)
        {
            var campaignDto = await _campaignService.GetCampaignById(id);

            if (campaignDto is null)
            {
                return NotFound();
            }

            var campaign = new Campaign
            {
                Id = campaignDto.Id,
                Name = campaignDto.Name,
                Description = campaignDto.Description,
                From = campaignDto.From,
                To = campaignDto.To,
                PictureUri = campaignDto.PictureUri
            };

            return View(campaign);
        }

        private List<Campaign> MapCampaignModelListToDtoList(IEnumerable<CampaignDTO> campaignDtoList)
        {
            var campaignList = new List<Campaign>();

            foreach(var campaignDto in campaignDtoList)
            {
                campaignList.Add(MapCampaignDtoToModel(campaignDto));
            }

            return campaignList;
        }

        private Campaign MapCampaignDtoToModel(CampaignDTO campaign)
        {
            return new Campaign
            {
                Id = campaign.Id,
                Name = campaign.Name,
                Description = campaign.Description,
                From = campaign.From,
                To = campaign.To,
                PictureUri = campaign.PictureUri
            };
        }
    }
}

Check when list is null and campaign details doesn't exist


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

namespace Mycroft.Cmd.App
{
    class AppCommand : Command
    {
        /// <summary>
        /// Parses JSON into App command objects
        /// </summary>
        /// <param name="messageType">The message type that determines the command to create</param>
        /// <param name="json">The JSON body of the message</param>
        /// <returns>Returns a command object for the parsed message</returns>
        public static Command Parse(String type, String json, AppInstance instance)
        {
            switch (type)
            {
                case "APP_UP":
                    return new DependencyChange(instance, Status.up);
                case "APP_DOWN":
                    return new DependencyChange(instance, Status.down);
                case "APP_MANIFEST":
                    return Manifest.Parse(json, instance);
                default:
                    //data is incorrect - can't do anything with it
                    // TODO notify that is wrong
                    break;
            }
            return null ;
        }
    }
}

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

namespace Mycroft.Cmd.App
{
    class AppCommand : Command
    {
        /// <summary>
        /// Parses JSON into App command objects
        /// </summary>
        /// <param name="messageType">The message type that determines the command to create</param>
        /// <param name="json">The JSON body of the message</param>
        /// <returns>Returns a command object for the parsed message</returns>
        public static Command Parse(String type, String json, AppInstance instance)
        {
            switch (type)
            {
                case "APP_UP":
                    return new DependencyChange(instance, Status.up);
                case "APP_DOWN":
                    return new DependencyChange(instance, Status.down);
                case "APP_IN_USE":
                    return new DependencyChange(instance, Status.in_use);
                case "APP_MANIFEST":
                    return Manifest.Parse(json, instance);
                default:
                    //data is incorrect - can't do anything with it
                    // TODO notify that is wrong
                    break;
            }
            return null ;
        }
    }
}

Add support for APP_IN_USE dependency change


using UnityEngine;
using System;

namespace Starstrider42.CustomAsteroids {
	/// Standard implementation of <see cref="ReferencePlane"/>.
	internal class SimplePlane : ReferencePlane {
		public string name { get; private set; }

		/// Rotation used to implement toDefaultFrame.
		private readonly Quaternion xform;

		///
		/// Creates a new ReferencePlane with the given name and rotation.
		///
		/// <param name="id">A unique identifier for this object. Initialises the <see cref="name"/> property.</param>
		/// <param name="thisToDefault">A rotation that transforms vectors from this reference frame
		/// to the KSP default reference frame.</param>
		internal SimplePlane(string id, Quaternion thisToDefault) {
			this.name = id;
			this.xform = thisToDefault;
		}

		public Vector3d toDefaultFrame(Vector3d inFrame) {
			Quaternion frameCorrection = Planetarium.Rotation;
			return frameCorrection * xform * Quaternion.Inverse(frameCorrection) * inFrame;
		}
	}
}

using UnityEngine;

namespace Starstrider42.CustomAsteroids {
	/// Standard implementation of <see cref="ReferencePlane"/>.
	internal class SimplePlane : ReferencePlane {
		public string name { get; private set; }

		/// Rotation used to implement toDefaultFrame.
		private readonly Quaternion xform;

		///
		/// Creates a new ReferencePlane with the given name and rotation.
		///
		/// <param name="id">A unique identifier for this object. Initialises the <see cref="name"/> property.</param>
		/// <param name="thisToDefault">A rotation that transforms vectors from this reference frame
		/// to the KSP default reference frame.</param>
		internal SimplePlane(string id, Quaternion thisToDefault) {
			this.name = id;
			this.xform = thisToDefault;
		}

		public Vector3d toDefaultFrame(Vector3d inFrame) {
			Quaternion frameCorrection = Planetarium.Zup.Rotation;
			return Quaternion.Inverse(frameCorrection) * xform * frameCorrection * inFrame;
		}
	}
}

Fix reference plane rotation bug.

Fix reference plane rotation bug.

Fixes a regression of #26 caused by the API changes in KSP 1.2.


using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Webkit;
using Uri = Android.Net.Uri;

namespace MonoDroid.Dialog
{
    public class HtmlElement : StringElement
    {
        // public string Value;

        public HtmlElement(string caption, string url)
            : base(caption)
        {
            Url = Uri.Parse(url);
        }

        public HtmlElement(string caption, Uri uri)
            : base(caption)
        {
            Url = uri;
        }

        public Uri Url { get; set; }

		void OpenUrl(Context context)
		{
			Intent intent = new Intent(context, typeof(HtmlActivity));
			intent.PutExtra("URL",this.Url.ToString());
			intent.AddFlags(ActivityFlags.NewTask);
			context.StartActivity(intent);
		}

        public override View GetView(Context context, View convertView, ViewGroup parent)
		{
			View view = base.GetView (context, convertView, parent);

            this.Click = (o, e) => OpenUrl(context);

			return view;
		}
    }

	[Activity]
	public class HtmlActivity : Activity
	{
		protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

			Intent i = this.Intent;
			string url = i.GetStringExtra("URL");

			WebView webview = new WebView(this);
			webview.Settings.JavaScriptEnabled = true;
 			SetContentView(webview);
			webview.LoadUrl(url);
		}
	}
}

using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Webkit;
using Uri = Android.Net.Uri;

namespace MonoDroid.Dialog
{
    public class HtmlElement : StringElement
    {
        // public string Value;

        public HtmlElement(string caption, string url)
            : base(caption)
        {
            Url = Uri.Parse(url);
        }

        public HtmlElement(string caption, Uri uri)
            : base(caption)
        {
            Url = uri;
        }

        public Uri Url { get; set; }

		void OpenUrl(Context context)
		{
			Intent intent = new Intent(context, typeof(HtmlActivity));
			intent.PutExtra("URL",this.Url.ToString());
			intent.PutExtra("Title",Caption);
			intent.AddFlags(ActivityFlags.NewTask);
			context.StartActivity(intent);
		}

        public override View GetView(Context context, View convertView, ViewGroup parent)
		{
			View view = base.GetView (context, convertView, parent);

            this.Click = (o, e) => OpenUrl(context);

			return view;
		}
    }

	[Activity]
	public class HtmlActivity : Activity
	{
		protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

			Intent i = this.Intent;
			string url = i.GetStringExtra("URL");
			this.Title = i.GetStringExtra("Title");

			WebView webview = new WebView(this);
			webview.Settings.JavaScriptEnabled = true;
 			SetContentView(webview);
			webview.LoadUrl(url);
		}
	}
}

Fix to ensure HTMLElement uses the Caption when loading up the actual HTML page.


using System;
using System.IO;
using System.Timers;
using Shell.Execute;

namespace PiDashcam
{
	public class StillCam
	{
		Timer timer;
		int imgcounter;
		string folder;

		public StillCam(string imageFolder)
		{
			folder = imageFolder;
			if (!Directory.Exists(folder))
			{
				Directory.CreateDirectory(folder);
			}
			foreach (var file in Directory.EnumerateFiles(folder))
			{
				int count = Int32.Parse(file.Remove(file.IndexOf('.')).Substring(file.LastIndexOf('/') + 1));
				if (imgcounter <= count)
				{
					imgcounter = count + 1;
				}
			}
			timer = new Timer(6000);
			timer.Elapsed += Timer_Elapsed;
			timer.Start();
			imgcounter = 1;
		}

		public void Stop()
		{
			timer.Stop();
		}

		void Timer_Elapsed(object sender, ElapsedEventArgs e)
		{
			ProgramLauncher.Execute("raspistill", String.Format("-h 1080 -w 1920 -n -o {0}/{1}.jpg", folder, imgcounter.ToString("D8")));
			imgcounter++;
		}
	}
}

using System;
using System.IO;
using System.Timers;
using Shell.Execute;

namespace PiDashcam
{
	public class StillCam
	{
		Timer timer;
		int imgcounter;
		string folder;

		public StillCam(string imageFolder)
		{
			imgcounter = 1;
			folder = imageFolder;
			if (!Directory.Exists(folder))
			{
				Directory.CreateDirectory(folder);
			}
			foreach (var file in Directory.EnumerateFiles(folder))
			{
				int count = Int32.Parse(file.Remove(file.IndexOf('.')).Substring(file.LastIndexOf('/') + 1));
				if (imgcounter <= count)
				{
					imgcounter = count + 1;
				}
			}
			timer = new Timer(6000);
			timer.Elapsed += Timer_Elapsed;
			timer.Start();
		}

		public void Stop()
		{
			timer.Stop();
		}

		void Timer_Elapsed(object sender, ElapsedEventArgs e)
		{
			ProgramLauncher.Execute("raspistill", String.Format("-h 1080 -w 1920 -n -o {0}/{1}.jpg", folder, imgcounter.ToString("D8")));
			imgcounter++;
		}
	}
}

Fix a image naming bug.

Fix a image naming bug.


using LiteNetLib.Utils;

namespace LiteNetLibHighLevel
{
    public abstract class LiteNetLibMessageBase
    {
        public virtual void Deserialize(NetDataReader reader) { }
        public virtual void Serialize(NetDataWriter writer) { }
    }
}

using LiteNetLib.Utils;

namespace LiteNetLibHighLevel
{
    public abstract class LiteNetLibMessageBase
    {
        public abstract void Deserialize(NetDataReader reader);
        public abstract void Serialize(NetDataWriter writer);
    }
}

Change serialize/deserialize functions to abstract


// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details

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

//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]

[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]

// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details

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

//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]

[assembly: InternalsVisibleTo ("dbus-sharp-glib")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]

Add dbus-sharp-glib to friend assemblies


using System.Runtime.Serialization;

namespace PushbulletSharp.Models.Requests
{
    [DataContract]
    public abstract class PushRequestBase
    {
        /// <summary>
        /// Gets or sets the device iden.
        /// </summary>
        /// <value>
        /// The device iden.
        /// </value>
        [DataMember(Name = "device_iden")]
        public string DeviceIden { get; set; }

        /// <summary>
        /// Gets or sets the email.
        /// </summary>
        /// <value>
        /// The email.
        /// </value>
        [DataMember(Name = "email")]
        public string Email { get; set; }

        /// <summary>
        /// Gets or sets the type.
        /// </summary>
        /// <value>
        /// The type.
        /// </value>
        [DataMember(Name = "type")]
        public string Type { get; protected set; }

        /// <summary>
        /// Gets or sets the source_device_iden.
        /// </summary>
        /// <value>
        /// The source_device_iden.
        /// </value>
        [DataMember(Name = "source_device_iden")]
        public string SourceDeviceIden { get; set; }

        /// <summary>
        /// Gets or sets the channel tag
        /// </summary>
        /// <value>
        /// The channel_tag.
        /// </value>
        [DataMember(Name = "channel_tag")]
        public string ChannelTag { get; set; }
    }
}

using System.Runtime.Serialization;

namespace PushbulletSharp.Models.Requests
{
    [DataContract]
    public abstract class PushRequestBase
    {
        /// <summary>
        /// Gets or sets the device iden.
        /// </summary>
        /// <value>
        /// The device iden.
        /// </value>
        [DataMember(Name = "device_iden")]
        public string DeviceIden { get; set; }

        /// <summary>
        /// Gets or sets the email.
        /// </summary>
        /// <value>
        /// The email.
        /// </value>
        [DataMember(Name = "email")]
        public string Email { get; set; }

        /// <summary>
        /// Gets or sets the type.
        /// </summary>
        /// <value>
        /// The type.
        /// </value>
        [DataMember(Name = "type")]
        public string Type { get; protected set; }

        /// <summary>
        /// Gets or sets the source_device_iden.
        /// </summary>
        /// <value>
        /// The source_device_iden.
        /// </value>
        [DataMember(Name = "source_device_iden")]
        public string SourceDeviceIden { get; set; }

        /// <summary>
        /// Gets or sets the client_iden
        /// </summary>
        /// <value>
        /// The client_iden.
        /// </value>
        [DataMember(Name = "client_iden")]
        public string ClientIden { get; set; }

        /// <summary>
        /// Gets or sets the channel tag
        /// </summary>
        /// <value>
        /// The channel_tag.
        /// </value>
        [DataMember(Name = "channel_tag")]
        public string ChannelTag { get; set; }
    }
}

Add client_iden field to push requests

Add client_iden field to push requests


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

using System;
using System.Linq;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mania.Scoring;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Mania.Tests.Skinning
{
    public class TestSceneDrawableJudgement : ManiaSkinnableTestScene
    {
        public TestSceneDrawableJudgement()
        {
            var hitWindows = new ManiaHitWindows();

            foreach (HitResult result in Enum.GetValues(typeof(HitResult)).OfType<HitResult>().Skip(1))
            {
                if (hitWindows.IsHitResultAllowed(result))
                {
                    AddStep("Show " + result.GetDescription(), () => SetContents(_ =>
                        new DrawableManiaJudgement(new JudgementResult(new HitObject { StartTime = Time.Current }, new Judgement())
                        {
                            Type = result
                        }, null)
                        {
                            Anchor = Anchor.Centre,
                            Origin = Anchor.Centre,
                        }));
                }
            }
        }
    }
}

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

using System;
using System.Linq;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mania.Scoring;
using osu.Game.Rulesets.Mania.Skinning.Legacy;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Mania.Tests.Skinning
{
    public class TestSceneDrawableJudgement : ManiaSkinnableTestScene
    {
        public TestSceneDrawableJudgement()
        {
            var hitWindows = new ManiaHitWindows();

            foreach (HitResult result in Enum.GetValues(typeof(HitResult)).OfType<HitResult>().Skip(1))
            {
                if (hitWindows.IsHitResultAllowed(result))
                {
                    AddStep("Show " + result.GetDescription(), () =>
                    {
                        SetContents(_ =>
                            new DrawableManiaJudgement(new JudgementResult(new HitObject { StartTime = Time.Current }, new Judgement())
                            {
                                Type = result
                            }, null)
                            {
                                Anchor = Anchor.Centre,
                                Origin = Anchor.Centre,
                            });

                        // for test purposes, undo the Y adjustment related to the `ScorePosition` legacy positioning config value
                        // (see `LegacyManiaJudgementPiece.load()`).
                        // this prevents the judgements showing somewhere below or above the bounding box of the judgement.
                        foreach (var legacyPiece in this.ChildrenOfType<LegacyManiaJudgementPiece>())
                            legacyPiece.Y = 0;
                    });
                }
            }
        }
    }
}

Fix drawable mania judgement scene looking broken


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

namespace Snowflake.Scraping
{
    internal class GameScrapeContextAsyncEnumerator : IAsyncEnumerator<IEnumerable<ISeed>>
    {
        public GameScrapeContextAsyncEnumerator(GameScrapeContext context, CancellationToken token)
        {
            this.Current = Enumerable.Empty<ISeed>();
            this.Context = context;
            this.Token = token;
        }

        public IEnumerable<ISeed> Current { get; private set; }

        private GameScrapeContext Context { get; }
        public CancellationToken Token { get; }

        public ValueTask DisposeAsync()
        {
            // what do i do here? there's nothing to dispose!
            return new ValueTask();
        }

        public async ValueTask<bool> MoveNextAsync()
        {
            // is this the correct value for this?
            if (this.Token.IsCancellationRequested) return false;

            bool retVal = await this.Context.Proceed();
            this.Current = this.Context.Context.GetUnculled();
            return retVal;
        }
    }
}

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

namespace Snowflake.Scraping
{
    internal class GameScrapeContextAsyncEnumerator : IAsyncEnumerator<IEnumerable<ISeed>>
    {
        public GameScrapeContextAsyncEnumerator(GameScrapeContext context, CancellationToken token)
        {
            this.Current = Enumerable.Empty<ISeed>();
            this.Context = context;
            this.Token = token;
            this.CullersRun = false;
        }

        public IEnumerable<ISeed> Current { get; private set; }

        private GameScrapeContext Context { get; }
        public CancellationToken Token { get; }
        private bool CullersRun { get; set; }

        public ValueTask DisposeAsync()
        {
            // what do i do here? there's nothing to dispose!
            return new ValueTask();
        }

        public async ValueTask<bool> MoveNextAsync()
        {
            // is this the correct value for this?
            if (this.Token.IsCancellationRequested) return false;

            bool retVal = await this.Context.Proceed();
            this.Current = this.Context.Context.GetUnculled();

            if (!retVal && !this.CullersRun)
            {
                this.Context.Cull();
                this.CullersRun = true;
                return true;
            }
            return retVal;
        }
    }
}

Add cull as final step

GameScrapeContext: Add cull as final step


using System;
using System.Reflection;

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Data.HashFunction Developers")]
[assembly: AssemblyCopyright("Copyright 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: CLSCompliant(false)]

[assembly: AssemblyVersion("1.1.1")]

using System;
using System.Reflection;

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Data.HashFunction Developers")]
[assembly: AssemblyCopyright("Copyright 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: CLSCompliant(false)]

[assembly: AssemblyVersion("1.2.1")]

Bump version to v1.2.1, breaking change for Data.HashFunction.CRC only.


using System;
using System.Linq.Expressions;
using RimDev.Descriptor.Generic;

namespace RimDev.Descriptor
{
    public class HttpDescriptor<TClass> : Descriptor<TClass>
        where TClass : class, new()
    {
        public HttpDescriptor<TClass> Action<TModel>(
            Expression<Func<TClass, Func<TModel, object>>> method,
            string description = null,
            string rel = null,
            string uri = null,
            Action<HttpMethodDescriptorContainer<TModel>> model = null)
        {
            var methodInfo = ExtractMemberInfoFromExpression<TModel>(method);
            var methodName = methodInfo.Name;
            var methodContainer = HydrateMethodDescriptionContainer<HttpMethodDescriptorContainer<TModel>, TModel>(
                methodName,
                description,
                Convert<HttpMethodDescriptorContainer<TModel>>(model));

            methodContainer.Rel =
                methodContainer.Rel
                    ?? rel
                    ?? "n/a";

            methodContainer.Uri =
                methodContainer.Uri
                    ?? uri
                    ?? "n/a";

            Methods.Add(methodContainer);

            return this;
        }
    }
}

using System;
using System.Linq.Expressions;
using RimDev.Descriptor.Generic;

namespace RimDev.Descriptor
{
    public class HttpDescriptor<TClass> : Descriptor<TClass>
        where TClass : class, new()
    {
        public HttpDescriptor(
            string name = null,
            string description = null,
            string type = null)
            :base(name, description, type)
        {
        }

        public HttpDescriptor<TClass> Action<TModel>(
            Expression<Func<TClass, Func<TModel, object>>> method,
            string description = null,
            string rel = null,
            string uri = null,
            Action<HttpMethodDescriptorContainer<TModel>> model = null)
        {
            var methodInfo = ExtractMemberInfoFromExpression<TModel>(method);
            var methodName = methodInfo.Name;
            var methodContainer = HydrateMethodDescriptionContainer<HttpMethodDescriptorContainer<TModel>, TModel>(
                methodName,
                description,
                Convert<HttpMethodDescriptorContainer<TModel>>(model));

            methodContainer.Rel =
                methodContainer.Rel
                    ?? rel
                    ?? "n/a";

            methodContainer.Uri =
                methodContainer.Uri
                    ?? uri
                    ?? "n/a";

            Methods.Add(methodContainer);

            return this;
        }

        public new HttpDescriptor<TClass> SetDescription(string description)
        {
            base.SetDescription(description);

            return this;
        }

        public new HttpDescriptor<TClass> SetName(string name)
        {
            base.SetName(name);

            return this;
        }

        public new HttpDescriptor<TClass> SetType(string type)
        {
            base.SetType(type);

            return this;
        }
    }
}

Add helper methods to http descriptor. This provides a more fluent interface between setting name and description with actions.


using System.ComponentModel;
using System.Windows;

namespace DesktopWidgets.Actions
{
    internal class PopupAction : ActionBase
    {
        [DisplayName("Text")]
        public string Text { get; set; }

        [DisplayName("Title")]
        public string Title { get; set; }

        [DisplayName("Image")]
        public MessageBoxImage Image { get; set; }

        public override void ExecuteAction()
        {
            base.ExecuteAction();
            MessageBox.Show(Text, Title, MessageBoxButton.OK, Image);
        }
    }
}

using System.ComponentModel;
using System.Windows;

namespace DesktopWidgets.Actions
{
    internal class PopupAction : ActionBase
    {
        [DisplayName("Text")]
        public string Text { get; set; } = "";

        [DisplayName("Title")]
        public string Title { get; set; } = "";

        [DisplayName("Image")]
        public MessageBoxImage Image { get; set; }

        public override void ExecuteAction()
        {
            base.ExecuteAction();
            MessageBox.Show(Text, Title, MessageBoxButton.OK, Image);
        }
    }
}

Fix "Popup" action "Text", "Title" default values


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Security.Cryptography;
using GistClient.FileSystem;
using RestSharp;
using RestSharp.Deserializers;

namespace GistClient.Client
{
    public static class GistClient
    {
        private static readonly RestClient Client;

        static GistClient(){
            Client =  new RestClient("https://api.github.com");
        }

        public static Dictionary<String,String> SendRequest(RestRequest request){
            var response = Client.Execute(request);
            HandleResponse(response);
            var jsonResponse = TrySerializeResponse(response);
            return jsonResponse;
        }

        public static void SetAuthentication(String username, String password){
            Client.Authenticator = new HttpBasicAuthenticator(username,password.Decrypt());
        }

        public static void HandleResponse(IRestResponse response){
            var statusHeader = response.Headers.FirstOrDefault(x => x.Name == "Status");
            var statusValue = statusHeader.Value.ToString();
            if (!statusValue.Contains("201")){
                String message = TrySerializeResponse(response)["message"];
                throw new Exception(statusValue + ", "+message);
            }
        }

        private static Dictionary<string, string> TrySerializeResponse(IRestResponse response)
        {
            var deserializer = new JsonDeserializer();
            var jsonResponse = deserializer.Deserialize<Dictionary<String, String>>(response);
            return jsonResponse;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Security.Cryptography;
using GistClient.FileSystem;
using RestSharp;
using RestSharp.Deserializers;

namespace GistClient.Client
{
    public static class GistClient
    {
        private static readonly RestClient Client;

        static GistClient(){
            Client =  new RestClient("https://api.github.com");
        }

        public static Dictionary<String,String> SendRequest(RestRequest request){
            var response = Client.Execute(request);
            HandleResponse(response);
            var jsonResponse = TrySerializeResponse(response);
            return jsonResponse;
        }

        public static void SetAuthentication(String username, String password){
            Client.Authenticator = new HttpBasicAuthenticator(username,password.Decrypt());
        }

        public static void HandleResponse(IRestResponse response){
            var statusHeader = response.Headers.FirstOrDefault(x => x.Name == "Status");
            if (statusHeader != null){
                var statusValue = statusHeader.Value.ToString();
                if (!statusValue.Contains("201")){
                    String message = TrySerializeResponse(response)["message"];
                    throw new Exception(statusValue + ", " + message);
                }
            }
            else{
                throw new Exception("Github could not be reached. Verify your connection.");
            }
        }

        private static Dictionary<string, string> TrySerializeResponse(IRestResponse response)
        {
            var deserializer = new JsonDeserializer();
            var jsonResponse = deserializer.Deserialize<Dictionary<String, String>>(response);
            return jsonResponse;
        }
    }
}

Improve error if github can't be reached.


/*
 * 由SharpDevelop创建。
 * 用户： imknown
 * 日期: 2015/12/3 周四
 * 时间: 上午 11:22
 *
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Windows.Forms;

namespace KeyFingerprintLooker
{
	/// <summary>
	/// Class with program entry point.
	/// </summary>
	internal sealed class Program
	{
		/// <summary>
		/// Program entry point.
		/// </summary>
		[STAThread]
		private static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new MainForm());
		}
	}
}

/*
 * 由SharpDevelop创建。
 * 用户： imknown
 * 日期: 2015/12/3 周四
 * 时间: 上午 11:22
 *
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Windows.Forms;

namespace KeyFingerprintLooker
{
	/// <summary>
	/// Class with program entry point.
	/// </summary>
	internal sealed class Program
	{
		/// <summary>
		/// Program entry point.
		/// </summary>
		[STAThread]
		private static void Main(string[] args)
		{
			if (Environment.OSVersion.Version.Major >= 6)
			{
				SetProcessDPIAware();
			}

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new MainForm());
		}

		[System.Runtime.InteropServices.DllImport("user32.dll")]
		private static extern bool SetProcessDPIAware();
	}
}

Support high DPI (96DPI, 120DPI tested)

Support high DPI (96DPI, 120DPI tested)


namespace AgileObjects.AgileMapper.UnitTests.Configuration
{
    using System;
    using TestClasses;
    using Xunit;

    public class WhenConfiguringStringFormatting
    {
        // See https://github.com/agileobjects/AgileMapper/issues/23
        [Fact]
        public void ShouldFormatDateTimesGlobally()
        {
            using (var mapper = Mapper.CreateNew())
            {
                mapper.WhenMapping
                    .StringsFrom<DateTime>(c => c.FormatUsing("o"));

                var source = new PublicProperty<DateTime> { Value = DateTime.Now };
                var result = mapper.Map(source).ToANew<PublicField<string>>();

                result.Value.ShouldBe(source.Value.ToString("o"));
            }
        }
    }
}

namespace AgileObjects.AgileMapper.UnitTests.Configuration
{
    using System;
    using TestClasses;
    using Xunit;

    public class WhenConfiguringStringFormatting
    {
        // See https://github.com/agileobjects/AgileMapper/issues/23
        [Fact]
        public void ShouldFormatDateTimesMapperWide()
        {
            using (var mapper = Mapper.CreateNew())
            {
                mapper.WhenMapping
                    .StringsFrom<DateTime>(c => c.FormatUsing("o"));

                var source = new PublicProperty<DateTime> { Value = DateTime.Now };
                var result = mapper.Map(source).ToANew<PublicField<string>>();

                result.Value.ShouldBe(source.Value.ToString("o"));
            }
        }

        [Fact]
        public void ShouldFormatDecimalsMapperWide()
        {
            using (var mapper = Mapper.CreateNew())
            {
                mapper.WhenMapping
                    .StringsFrom<decimal>(c => c.FormatUsing("C"));

                var source = new PublicProperty<decimal> { Value = 1.99m };
                var result = mapper.Map(source).ToANew<PublicField<string>>();

                result.Value.ShouldBe(source.Value.ToString("C"));
            }
        }

        [Fact]
        public void ShouldFormatDoublesMapperWideUsingDecimalPlaces()
        {
            using (var mapper = Mapper.CreateNew())
            {
                mapper.WhenMapping
                    .StringsFrom<double>(c => c.FormatUsing("0.00"));

                var source = new PublicProperty<double> { Value = 1 };
                var result = mapper.Map(source).ToANew<PublicField<string>>();

                result.Value.ShouldBe("1.00");
            }
        }
    }
}

Test coverage for configured, mapper-wide decimal and double ToString formatting


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

namespace CodeGeneration.Debugging
{
    class Program
    {
        static void Main(string[] args)
        {
            // This app is a dummy. But when it is debugged within VS, it builds the Tests
            // allowing VS to debug into the build/code generation process.
        }
    }
}

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

namespace CodeGeneration.Debugging
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    internal class Program
    {
        private static void Main(string[] args)
        {
            // This app is a dummy. But when it is debugged within VS, it builds the Tests
            // allowing VS to debug into the build/code generation process.
        }
    }
}

Fix stylecop issues in debugging project


using ColorProvider;
using Common;

namespace BoxBuilder
{
    public sealed class BoxBuilderFactory
    {
        internal static IBoxPointGenerator GetBoxPointGenerator(ILogger Logger)
        {
            IPiecePointGenerator piecePointGen = new PiecePointGenerator();
            IBoxPointGenerator pointGen = new BoxPointGenerator(piecePointGen, Logger);

            return pointGen;
        }

        public static IBoxBuilderSVG GetBoxHandler(ILogger Logger)
        {
            IColorProvider colorProvider = new ColorProviderAllDifferent();
            IBoxPointRendererSVG pointRender = new BoxPointRendererSVG(colorProvider);
            IBoxPointGenerator pointGen = GetBoxPointGenerator(Logger);

            IBoxBuilderSVG handler = new BoxBuilderSVG(pointGen,
                pointRender,
                Logger);

            return handler;
        }
    }
}

using ColorProvider;
using Common;

namespace BoxBuilder
{
    public sealed class BoxBuilderFactory
    {
        internal static IBoxPointGenerator GetBoxPointGenerator(ILogger Logger)
        {
            IPiecePointGenerator piecePointGen = new PiecePointGenerator();
            IBoxPointGenerator pointGen = new BoxPointGenerator(piecePointGen, Logger);

            return pointGen;
        }

        public static IBoxBuilderSVG GetBoxHandler(ILogger Logger)
        {
            IColorProvider colorProvider = new ColorProviderAllDifferent();
            IBoxPointRendererSVG pointRender = new BoxPointRendererSVG(colorProvider, true);
            IBoxPointGenerator pointGen = GetBoxPointGenerator(Logger);

            IBoxBuilderSVG handler = new BoxBuilderSVG(pointGen,
                pointRender,
                Logger);

            return handler;
        }
    }
}

Test even and odd tab settings.

Test even and odd tab settings.


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        Hello people!
    </div>
</body>
</html>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        Hello people!<br />
        Now I'm in the CLOUDDDD
    </div>
</body>
</html>

Add "now im in the cloud"

Add "now im in the cloud"


@model QuestionIndexViewModel

@{
    ViewBag.Title = "Question Index";
}

Question Index

@if (Model.Questions.SafeAny())
{

                ID
                Photo ID
                Question
                Sentence Starters

            @foreach (var question in Model.Questions)
            {

                    @question.ID
                    @question.PhotoID
                    @question.Text
                    @question.SentenceStarters

                        @if (Model.DisplayAdminLinks)
                        {

                                @Html.ActionLink("Details", MVC.Questions.QuestionDetails(question.ID)) |
                                @Html.ActionLink("Edit", MVC.Questions.QuestionEdit(question.ID)) |
                                @Html.ActionLink("Delete", MVC.Questions.QuestionDelete(question.ID))

                        }

            }

}
else
{
    @:No questions found.
}

@model QuestionIndexViewModel

@{
    ViewBag.Title = "Question Index";
}

Question Index

@if (Model.Questions.SafeAny())
{

                ID
                Photo ID
                Question
                Sentence Starters

            @foreach (var question in Model.Questions)
            {

                    @question.ID
                    @Html.ActionLink(question.PhotoID.ToString(), MVC.Photos.PhotoDetails(question.PhotoID))
                    @Html.ActionLink(question.Text, MVC.Questions.QuestionDetails(question.ID))
                    @question.SentenceStarters

                        @if (Model.DisplayAdminLinks)
                        {

                                @Html.ActionLink("Details", MVC.Questions.QuestionDetails(question.ID)) |
                                @Html.ActionLink("Edit", MVC.Questions.QuestionEdit(question.ID)) |
                                @Html.ActionLink("Delete", MVC.Questions.QuestionDelete(question.ID))

                        }

            }

}
else
{
    @:No questions found.
}

Add links to photo details and question details views.


using System.Data;

namespace NHibernate.Engine.Transaction
{
	/// <summary>
	/// Represents work that needs to be performed in a manner
	/// which isolates it from any current application unit of
	/// work transaction.
	/// </summary>
	public interface IIsolatedWork
	{
		/// <summary>
		/// Perform the actual work to be done.
		/// </summary>
		/// <param name="connection">The ADP connection to use.</param>
		void DoWork(IDbConnection connection, IDbTransaction transaction);

		// 2009-05-04 Another time we need a TransactionManager to manage isolated
		// work for a given connection.
	}
}

using System.Data;

namespace NHibernate.Engine.Transaction
{
	/// <summary>
	/// Represents work that needs to be performed in a manner
	/// which isolates it from any current application unit of
	/// work transaction.
	/// </summary>
	public interface IIsolatedWork
	{
		/// <summary>
		/// Perform the actual work to be done.
		/// </summary>
		/// <param name="connection">The ADP connection to use.</param>
		void DoWork(IDbConnection connection, IDbTransaction transaction);
	}
}

Comment is no longer reqired

Comment is no longer reqired

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@4365


using System.Xml;

namespace UDBase.EditorTools {
	public static class CSProjUpdater {

		public static void UpdateCsprojFile(string fileName) {
			var doc = new XmlDocument();
			doc.Load(fileName);

			// <PropertyGroup>
			//    <DocumentationFile>$(OutputPath)Assembly-CSharp.xml</DocumentationFile>
			// </PropertyGroup>
			var namespaceUri = doc.LastChild.Attributes["xmlns"].Value;
			var group = doc.CreateElement("PropertyGroup", namespaceUri);
			var docFile = doc.CreateElement("DocumentationFile", namespaceUri);
			docFile.InnerText = "$(OutputPath)Assembly-CSharp.xml";
			group.AppendChild(docFile);

			doc.LastChild.AppendChild(group);

			doc.Save(fileName);

			UnityEngine.Debug.Log($"Xml documentation generation added to project '{fileName}'");
		}
	}
}

using System.Xml;

namespace UDBase.EditorTools {
	public static class CSProjUpdater {

		public static void UpdateCsprojFile(string fileName) {
			var doc = new XmlDocument();
			doc.Load(fileName);

			// <PropertyGroup>
			//    <DocumentationFile>$(OutputPath)Assembly-CSharp.xml</DocumentationFile>
			// </PropertyGroup>
			var namespaceUri = doc.LastChild.Attributes["xmlns"].Value;
			var group = doc.CreateElement("PropertyGroup", namespaceUri);
			var docFile = doc.CreateElement("DocumentationFile", namespaceUri);
			docFile.InnerText = "$(OutputPath)Assembly-CSharp.xml";
			group.AppendChild(docFile);

			doc.LastChild.AppendChild(group);

			UnityEngine.Debug.Log($"Xml documentation generation added to project '{fileName}'");

			// <Target Name="PostBuild" AfterTargets="PostBuildEvent">
			//    <Exec Command="call cd $(SolutionDir)Tools\
call "$(SolutionDir)Tools\GenerateDocs.bat"" />
			// </Target>
			var target = doc.CreateElement("Target", namespaceUri);
			{
				var nameAttr = doc.CreateAttribute("Name");
				nameAttr.Value = "PostBuild";
				target.Attributes.Append(nameAttr);

				var targetAttr = doc.CreateAttribute("AfterTargets");
				targetAttr.Value = "PostBuildEvent";
				target.Attributes.Append(targetAttr);

				var exec = doc.CreateElement("Exec", namespaceUri);
				{

					var commandAttr = doc.CreateAttribute("Command");
					commandAttr.Value = "call cd $(SolutionDir)Tools\ncall \"$(SolutionDir)Tools\\GenerateDocs.bat\"";
					exec.Attributes.Append(commandAttr);
				}
				target.AppendChild(exec);
			}
			doc.LastChild.AppendChild(target);

			UnityEngine.Debug.Log($"Markdown post-process added to project '{fileName}'");

			doc.Save(fileName);

		}
	}
}

Add post-build event to update docs;

Add post-build event to update docs;


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

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

[assembly: AssemblyTitle ("CartoMobileSDK.iOS")]
[assembly: AssemblyDescription ("Carto Mobile SDK for iOS")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("CartoDB")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("(c) CartoDB 2016, All rights reserved")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]

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

[assembly: AssemblyVersion ("1.0.*")]
[assembly: LinkWith("libcarto_mobile_sdk.a", LinkTarget.ArmV7|LinkTarget.ArmV7s|LinkTarget.Arm64|LinkTarget.Simulator|LinkTarget.Simulator64, ForceLoad=true, IsCxx=true, Frameworks="OpenGLES GLKit UIKit CoreGraphics CoreText Foundation")]

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

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

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

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

[assembly: AssemblyTitle ("CartoMobileSDK.iOS")]
[assembly: AssemblyDescription ("Carto Mobile SDK for iOS")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("CartoDB")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("(c) CartoDB 2016, All rights reserved")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]

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

[assembly: AssemblyVersion ("1.0.*")]
[assembly: LinkWith("libcarto_mobile_sdk.a", LinkTarget.ArmV7|LinkTarget.ArmV7s|LinkTarget.Arm64|LinkTarget.Simulator|LinkTarget.Simulator64, ForceLoad=true, IsCxx=true, Frameworks="OpenGLES GLKit UIKit CoreGraphics CoreText CFNetwork Foundation")]

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

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

Add CFNetwork to list of Xamarin iOS dependencies, should fix Xamarin/iOS linking issues


using System;
using System.Net;

namespace Arango.Client
{
    public class ArangoException : Exception
    {
        /// <summary>
        /// HTTP status code which caused the exception.
        /// </summary>
        public HttpStatusCode HttpStatusCode { get; set; }

        /// <summary>
        /// Exception message of the web request object.
        /// </summary>
        public string WebExceptionMessage { get; set; }

        public ArangoException()
        {
        }

        public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage)
            : base(message)
        {
            HttpStatusCode = httpStatusCode;
            WebExceptionMessage = webExceptionMessage;
        }

        public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage, Exception inner)
            : base(message, inner)
        {
            HttpStatusCode = httpStatusCode;
            WebExceptionMessage = webExceptionMessage;
        }
    }
}

using System;
using System.Net;

namespace Arango.Client
{
    public class ArangoException : Exception
    {
        /// <summary>
        /// HTTP status code which caused the exception.
        /// </summary>
        public HttpStatusCode HttpStatusCode { get; set; }

        /// <summary>
        /// Exception message of the web request object.
        /// </summary>
        public string WebExceptionMessage { get; set; }

        public ArangoException()
        {
        }

        public ArangoException(string message)
            : base(message)
        {
        }

        public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage)
            : base(message)
        {
            HttpStatusCode = httpStatusCode;
            WebExceptionMessage = webExceptionMessage;
        }

        public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage, Exception inner)
            : base(message, inner)
        {
            HttpStatusCode = httpStatusCode;
            WebExceptionMessage = webExceptionMessage;
        }
    }
}

Create arango exception which consists only of message.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aggregates.Contracts;
using Aggregates.Extensions;
using EventStore.ClientAPI;
using Newtonsoft.Json;
using NServiceBus;
using NServiceBus.Features;
using NServiceBus.Logging;
using NServiceBus.MessageInterfaces;
using NServiceBus.ObjectBuilder;
using NServiceBus.Settings;
using Aggregates.Internal;

namespace Aggregates.GetEventStore
{
    public class Feature : NServiceBus.Features.Feature
    {
        public Feature()
        {
            RegisterStartupTask<ConsumerRunner>();

            Defaults(s =>
            {
                s.SetDefault("SetEventStoreMaxDegreeOfParallelism", Environment.ProcessorCount);
                s.SetDefault("SetEventStoreCapacity", 10000);
            });
        }

        protected override void Setup(FeatureConfigurationContext context)
        {
            context.Container.ConfigureComponent<StoreEvents>(DependencyLifecycle.InstancePerCall);
            context.Container.ConfigureComponent<StoreSnapshots>(DependencyLifecycle.InstancePerCall);
            context.Container.ConfigureComponent<NServiceBusDispatcher>(DependencyLifecycle.SingleInstance);
            context.Container.ConfigureComponent<DomainSubscriber>(DependencyLifecycle.SingleInstance);

            context.Container.ConfigureComponent(y =>
                {
                    return new JsonSerializerSettings
                    {
                        Binder = new EventSerializationBinder(y.Build<IMessageMapper>()),
                        ContractResolver = new EventContractResolver(y.Build<IMessageMapper>(), y.Build<IMessageCreator>())
                    };
                }, DependencyLifecycle.SingleInstance);
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aggregates.Contracts;
using Aggregates.Extensions;
using EventStore.ClientAPI;
using Newtonsoft.Json;
using NServiceBus;
using NServiceBus.Features;
using NServiceBus.Logging;
using NServiceBus.MessageInterfaces;
using NServiceBus.ObjectBuilder;
using NServiceBus.Settings;
using Aggregates.Internal;

namespace Aggregates.GetEventStore
{
    public class Feature : NServiceBus.Features.Feature
    {
        public Feature()
        {
            RegisterStartupTask<ConsumerRunner>();

            Defaults(s =>
            {
                s.SetDefault("SetEventStoreMaxDegreeOfParallelism", Environment.ProcessorCount);
                s.SetDefault("ParallelHandlers", true);
                s.SetDefault("ReadSize", 500);
            });
        }

        protected override void Setup(FeatureConfigurationContext context)
        {
            context.Container.ConfigureComponent<StoreEvents>(DependencyLifecycle.InstancePerCall);
            context.Container.ConfigureComponent<StoreSnapshots>(DependencyLifecycle.InstancePerCall);
            context.Container.ConfigureComponent<NServiceBusDispatcher>(DependencyLifecycle.SingleInstance);
            context.Container.ConfigureComponent<DomainSubscriber>(DependencyLifecycle.SingleInstance);

            context.Container.ConfigureComponent(y =>
                {
                    return new JsonSerializerSettings
                    {
                        Binder = new EventSerializationBinder(y.Build<IMessageMapper>()),
                        ContractResolver = new EventContractResolver(y.Build<IMessageMapper>(), y.Build<IMessageCreator>())
                    };
                }, DependencyLifecycle.SingleInstance);
        }

    }
}

Add correct defaults to domain subscriber


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

namespace TestObjectBuilderTests
{
    public class ProductTestObjectBuilder : TestObjBuilder<Product>
    {
        public ProductTestObjectBuilder()
        {
            this.FirstDependency = new DummyDependency1();
            this.SecondDependency = new DummyDependency2();
            this.ConstructorArgumentPropertyNames = new List<string>() { "FirstDependency" };
        }

        public List<string> ConstructorArgumentPropertyNames { get; set; }

        public IDependency1 FirstDependency { get; set; }
        public IDependency2 SecondDependency { get; set; }
    }
}

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

namespace TestObjectBuilderTests
{
    public class ProductTestObjectBuilder : TestObjBuilder<Product>
    {
        public ProductTestObjectBuilder()
        {
            this.FirstDependency = new DummyDependency1();
            this.SecondDependency = new DummyDependency2();
            this.PropertiesUsedByProductConstructor = new List<string>() { "FirstDependency" };
        }

        public IDependency1 FirstDependency { get; set; }
        public IDependency2 SecondDependency { get; set; }
    }
}

Remove property from ProductTestObjetBuilder that is left over from move of building with constructor feature to TestObjectBuilder class.


using System;
using System.Collections.Generic;
using Owin;

namespace JabbR.Infrastructure
{
    public static class AppBuilderExtensions
    {
        private static readonly string SystemWebHostName = "System.Web 4.5, Microsoft.Owin.Host.SystemWeb 1.0.0.0";

        public static bool IsRunningUnderSystemWeb(this IAppBuilder app)
        {
            var capabilities = (IDictionary<string, object>)app.Properties["server.Capabilities"];

            // Not hosing on system web host? Bail out.
            object serverName;
            if (capabilities.TryGetValue("server.Name", out serverName) &&
                !SystemWebHostName.Equals((string)serverName, StringComparison.Ordinal))
            {
                return false;
            }

            return true;
        }
    }
}

using System;
using System.Collections.Generic;
using Owin;

namespace JabbR.Infrastructure
{
    public static class AppBuilderExtensions
    {
        private static readonly string SystemWebHostName = "System.Web 4.5, Microsoft.Owin.Host.SystemWeb 1.0.0.0";

        public static bool IsRunningUnderSystemWeb(this IAppBuilder app)
        {
            var capabilities = (IDictionary<string, object>)app.Properties["server.Capabilities"];

            // Not hosing on system web host? Bail out.
            object serverName;
            if (capabilities.TryGetValue("server.Name", out serverName) &&
                SystemWebHostName.Equals((string)serverName, StringComparison.Ordinal))
            {
                return true;
            }

            return false;
        }
    }
}

Fix system web detection logic.

Fix system web detection logic.


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

using osu.Framework.Configuration;
using osu.Framework.Platform;

namespace osu.Framework.Testing
{
    internal class TestBrowserConfig : IniConfigManager<TestBrowserSetting>
    {
        protected override string Filename => @"visualtests.cfg";

        public TestBrowserConfig(Storage storage) : base(storage)
        {
        }
    }

    internal enum TestBrowserSetting
    {
        LastTest,
    }
}

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

using osu.Framework.Configuration;
using osu.Framework.Platform;

namespace osu.Framework.Testing
{
    internal class TestBrowserConfig : IniConfigManager<TestBrowserSetting>
    {
        protected override string Filename => @"visualtests.cfg";

        public TestBrowserConfig(Storage storage) : base(storage)
        {
        }

        protected override void InitialiseDefaults()
        {
            base.InitialiseDefaults();
            Set(TestBrowserSetting.LastTest, string.Empty);
        }
    }

    internal enum TestBrowserSetting
    {
        LastTest,
    }
}

Fix VisualTests crashing on first startup due to incorrect configuration


using System;
using System.IO;

using NUnit.Framework;

namespace Mango.Server.Tests
{
	[TestFixture()]
	public class HttpHeadersTest
	{

		[Test()]
		public void TestMultilineParse ()
		{
			//
			// multiline values are acceptable if the next
			// line starts with spaces
			//
			string header = @"HeaderName: Some multiline
  								value";

			HttpHeaders headers = new HttpHeaders ();

			headers.Parse (new StringReader (header));

			Assert.AreEqual ("some multiline value", headers ["HeaderName"], "a1");
		}
	}
}

using System;
using System.IO;

using NUnit.Framework;

namespace Mango.Server.Tests
{
	[TestFixture()]
	public class HttpHeadersTest
	{

		[Test()]
		public void TestMultilineParse ()
		{
			//
			// multiline values are acceptable if the next
			// line starts with spaces
			//
			string header = @"HeaderName: Some multiline
  								value";

			HttpHeaders headers = new HttpHeaders ();

			headers.Parse (new StringReader (header));

			Assert.AreEqual ("some multiline value", headers ["HeaderName"], "a1");

			header = @"HeaderName: Some multiline
  								value
	that spans
	a bunch of lines";

			headers = new HttpHeaders ();
			headers.Parse (new StringReader (header));

			Assert.AreEqual ("Some multiline value that spans a bunch of lines", headers ["HeaderName"], "a2");
		}
	}
}

Make sure we test across more than two lines.


namespace CypherTwo.Tests
{
    using System;
    using System.Net.Http;

    using CypherTwo.Core;

    using NUnit.Framework;

    [TestFixture]
    public class IntegrationTests
    {
        private INeoClient neoClient;

        private ISendRestCommandsToNeo neoApi;

        private IJsonHttpClientWrapper httpClientWrapper;

        [SetUp]
        public void SetupBeforeEachTest()
        {
            this.httpClientWrapper = new JsonHttpClientWrapper(new HttpClient());
            this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:7474/");
            this.neoClient = new NeoClient(this.neoApi);
            this.neoClient.Initialise();
        }

        [Test]
        public void InitialiseThrowsExecptionWithInvalidUrl()
        {
            this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:1111/");
            this.neoClient = new NeoClient(this.neoApi);
            Assert.Throws<InvalidOperationException>(() => this.neoClient.Initialise());
        }

        [Test]
        public async void CreateAndSelectNode()
        {
            var reader = await this.neoClient.QueryAsync("CREATE (n:Person  { name : 'Andres', title : 'Developer' }) RETURN Id(n)");

            Assert.That(reader.Read(), Is.EqualTo(true));
            Assert.That(reader.Get<int>(0), Is.EqualTo(1));
        }
    }
}

namespace CypherTwo.Tests
{
    using System;
    using System.Net.Http;

    using CypherTwo.Core;

    using NUnit.Framework;

    [TestFixture]
    public class IntegrationTests
    {
        private INeoClient neoClient;

        private ISendRestCommandsToNeo neoApi;

        private IJsonHttpClientWrapper httpClientWrapper;

        [SetUp]
        public void SetupBeforeEachTest()
        {
            this.httpClientWrapper = new JsonHttpClientWrapper(new HttpClient());
            this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:7474/db/data");
            this.neoClient = new NeoClient(this.neoApi);
            this.neoClient.Initialise();
        }

        [Test]
        public void InitialiseThrowsExecptionWithInvalidUrl()
        {
            this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:1111/");
            this.neoClient = new NeoClient(this.neoApi);
            Assert.Throws<InvalidOperationException>(() => this.neoClient.Initialise());
        }

        [Test]
        public async void CreateAndSelectNode()
        {
            var reader = await this.neoClient.QueryAsync("CREATE (n:Person  { name : 'Andres', title : 'Developer' }) RETURN Id(n)");

            Assert.That(reader.Read(), Is.EqualTo(true));
            Assert.That(reader.Get<int>(0), Is.EqualTo(1));
        }
    }
}

Change URL of initialization in integration tests


using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;

namespace Template10.Samples.SearchSample
{
    sealed partial class App : Template10.Common.BootStrapper
    {
        public App()
        {
            InitializeComponent();
        }

        public override Task OnInitializeAsync(IActivatedEventArgs args)
        {
            var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include, null);
            Window.Current.Content = new Views.Shell(nav);
			return Task.CompletedTask;
		}

        public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            NavigationService.Navigate(typeof(Views.MainPage));
			return Task.CompletedTask;
		}
    }
}

using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;

namespace Template10.Samples.SearchSample
{
    sealed partial class App : Template10.Common.BootStrapper
    {
        public App()
        {
            InitializeComponent();
        }

        public override Task OnInitializeAsync(IActivatedEventArgs args)
        {
            var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
            Window.Current.Content = new Views.Shell(nav);
			return Task.CompletedTask;
		}

        public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            NavigationService.Navigate(typeof(Views.MainPage));
			return Task.CompletedTask;
		}
    }
}

Fix Object reference not set to an instance of an object.


using Glimpse.Web;
using System;

namespace Glimpse.Agent.Web
{
    public class AgentRuntime : IRequestRuntime
    {
        private readonly IMessagePublisher _messagePublisher;

        public AgentRuntime(IMessagePublisher messagePublisher)
        {
            _messagePublisher = messagePublisher;
        }

        public void Begin(IContext newContext)
        {
            var message = new BeginRequestMessage();

            // TODO: Full out message more

            _messagePublisher.PublishMessage(message);
        }

        public void End(IContext newContext)
        {
            var message = new EndRequestMessage();

            // TODO: Full out message more

            _messagePublisher.PublishMessage(message);
        }
    }
}

using Glimpse.Web;
using System;

namespace Glimpse.Agent.Web
{
    public class AgentRuntime : IRequestRuntime
    {
        private readonly IMessageAgentBus _messageBus;

        public AgentRuntime(IMessageAgentBus messageBus)
        {
            _messageBus = messageBus;
        }

        public void Begin(IContext newContext)
        {
            var message = new BeginRequestMessage();

            // TODO: Full out message more

            _messageBus.SendMessage(message);
        }

        public void End(IContext newContext)
        {
            var message = new EndRequestMessage();

            // TODO: Full out message more

            _messageBus.SendMessage(message);
        }
    }
}

Switch over agent to using Agent bus

Switch over agent to using Agent bus

Instead of pushing to the publisher directly


using System;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Wangkanai.Detection.Models;
using Wangkanai.Detection.Services;

namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
    [HtmlTargetElement(ElementName, Attributes = OnlyAttributeName, TagStructure = TagStructure.NormalOrSelfClosing)]
    public class PreferenceTagHelper : TagHelper
    {
        private const    string             ElementName       = "preference";
        private const    string             OnlyAttributeName = "only";
        protected        IHtmlGenerator     Generator { get; }
        private readonly IResponsiveService _responsive;
        private readonly IDeviceService     _device;

        [HtmlAttributeName(OnlyAttributeName)] public string? Only { get; set; }

        public PreferenceTagHelper(IHtmlGenerator generator, IResponsiveService responsive, IDeviceService device)
        {
            Generator   = generator ?? throw new ArgumentNullException(nameof(generator));
            _responsive = responsive ?? throw new ArgumentNullException(nameof(responsive));
            _device     = device ?? throw new ArgumentNullException(nameof(device));
        }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));
            if (output == null)
                throw new ArgumentNullException(nameof(output));

            output.TagName = null;

            if (string.IsNullOrWhiteSpace(Only))
                return;

            if (!_responsive.HasPreferred() && !DisplayOnlyDevice)
                output.SuppressOutput();
        }

        private bool DisplayOnlyDevice => _device.Type == OnlyDevice;

        private Device OnlyDevice => Enum.Parse<Device>(Only, true);
    }
}

using System;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Wangkanai.Detection.Models;
using Wangkanai.Detection.Services;

namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
    [HtmlTargetElement(ElementName, Attributes = OnlyAttributeName, TagStructure = TagStructure.NormalOrSelfClosing)]
    public class PreferenceTagHelper : TagHelper
    {
        private const    string             ElementName       = "preference";
        private const    string             OnlyAttributeName = "only";
        protected        IHtmlGenerator     Generator { get; }
        private readonly IResponsiveService _responsive;
        private readonly IDeviceService     _device;

        [HtmlAttributeName(OnlyAttributeName)] public string? Only { get; set; }

        public PreferenceTagHelper(IHtmlGenerator generator, IResponsiveService responsive, IDeviceService device)
        {
            Generator   = generator ?? throw new ArgumentNullException(nameof(generator));
            _responsive = responsive ?? throw new ArgumentNullException(nameof(responsive));
            _device     = device ?? throw new ArgumentNullException(nameof(device));
        }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));
            if (output == null)
                throw new ArgumentNullException(nameof(output));

            output.TagName = null;

            if (string.IsNullOrWhiteSpace(Only))
                return;

            if (_responsive.HasPreferred())
                return;

            if (DisplayOnlyDevice)
                return;

            output.SuppressOutput();
        }

        private bool DisplayOnlyDevice => _device.Type == OnlyDevice;

        private Device OnlyDevice => Enum.Parse<Device>(Only, true);
    }
}

Use positive statement and let it return as soon as possible


@{
    ViewBag.Title = "Search";
}

    <form asp-controller="Lab" asp-action="Search">

                Search By Id, Request Num, or Share Identifier

                    <input id="term" class="form-control" name="term" />

            <button type="submit" class="btn btn-danger"> Search</button>

    </form>

@{
    ViewBag.Title = "Search";
}

    <form asp-controller="Lab" asp-action="Search">

                Search By Id, Request Num, or Share Identifier

                    <input id="term" class="form-control" name="term" autofocus />

            <button type="submit" class="btn btn-danger"> Search</button>

    </form>

Put auto focus on search too

Put auto focus on search too