using System.Reflection;

[assembly: AssemblyTitle("Logo en español para Xamarin Workbooks")]
[assembly: AssemblyDescription("Aprende a programar con Xamarin Workbooks, C# y la legendaria Tortuga!")]
[assembly: AssemblyCulture("es")]

// NuGet package metadata
[assembly: AssemblyMetadata("id", "Logo.es")]
[assembly: AssemblyMetadata("authors", "Daniel Cazzulino")]

using System.Reflection;

[assembly: AssemblyTitle("Logo en español para Xamarin Workbooks")]
[assembly: AssemblyDescription("Aprende a programar con Xamarin Workbooks, C# y la legendaria Tortuga!")]

// NuGet package metadata
[assembly: AssemblyMetadata("id", "Logo.es")]
[assembly: AssemblyMetadata("authors", "Daniel Cazzulino")]

Remove Culture since that causes issues for Workbooks


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

[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyProduct("NuGet")]
[assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]

[assembly: ComVisible(false)]

#if !FIXED_ASSEMBLY_VERSION
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0")]
#endif

[assembly: NeutralResourcesLanguage("en-US")]

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

[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyProduct("NuGet")]
[assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]

[assembly: ComVisible(false)]

#if !FIXED_ASSEMBLY_VERSION
[assembly: AssemblyVersion("2.2.0.0")]
[assembly: AssemblyInformationalVersion("2.2.0")]
#endif

[assembly: NeutralResourcesLanguage("en-US")]

Update assembly version to 2.2

Update assembly version to 2.2


using NUnit.Framework;

namespace InterFAX.Api.Test.Integration
{
    [TestFixture]
    public class AccountTests
    {
        [Test]
        public void can_get_balance()
        {
            var interfax = new FaxClient();
            var actual = interfax.Account.GetBalance().Result;
            Assert.IsTrue(actual > 0);
        }
    }
}

using NUnit.Framework;

namespace InterFAX.Api.Test.Integration
{
    [TestFixture]
    public class AccountTests
    {
        [Test]
        public void can_get_balance()
        {
            var interfax = new FaxClient();
            var actual = interfax.Account.GetBalance().Result;
            //Assert.IsTrue(actual > 0);
        }
    }
}

Update account balance check, account can have zero balance and still be valid.


using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using IntelliTect.Coalesce;
using IntelliTect.Coalesce.DataAnnotations;
using IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext;

#nullable enable

namespace IntelliTect.Coalesce.Tests.TargetClasses
{
    [Coalesce]
    public class CaseDtoStandalone : IClassDto<Case, TestDbContext.TestDbContext>
    {
        [Key]
        public int CaseId { get; set; }

        public string? Title { get; set; }

        public void MapTo(Case obj, IMappingContext context)
        {
            obj.Title = Title;
        }

        public void MapFrom(Case obj, IMappingContext context, IncludeTree? tree = null)
        {
            CaseId = obj.CaseKey;
            Title = obj.Title;
        }
    }

    public class ExternalTypeWithDtoProp
    {
        public CaseDtoStandalone Case { get; set; }
    }
}

using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using IntelliTect.Coalesce;
using IntelliTect.Coalesce.DataAnnotations;
using IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext;

#nullable enable

namespace IntelliTect.Coalesce.Tests.TargetClasses
{
    [Coalesce]
    public class CaseDtoStandalone : IClassDto<Case, TestDbContext.TestDbContext>
    {
        [Key]
        public int CaseId { get; set; }

        public string? Title { get; set; }

        public void MapTo(Case obj, IMappingContext context)
        {
            obj.Title = Title;
        }

        public void MapFrom(Case obj, IMappingContext context, IncludeTree? tree = null)
        {
            CaseId = obj.CaseKey;
            Title = obj.Title;
        }
    }

    public class ExternalTypeWithDtoProp
    {
        public CaseDtoStandalone Case { get; set; }
        public ICollection<CaseDtoStandalone> Cases { get; set; }
        public List<CaseDtoStandalone> CasesList { get; set; }
        public CaseDtoStandalone[] CasesArray { get; set; }
    }
}

Add additional code gen smoke test cases


using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace HardwareSensorSystem.SensorTechnology.Controllers
{
    public class OwServerEnet2LogController : Controller
    {
        [AllowAnonymous]
        [HttpPost("api/devices/{deviceId}/log")]
        public async Task<IActionResult> Log([FromRoute]int deviceId)
        {
            XDocument file = XDocument.Load(HttpContext.Request.Body);

            var romIdName = XName.Get("ROMId", file.Root.Name.NamespaceName);
            var dataSensors = file.Root.Elements().Select(sensor => new
            {
                SerialNumber = sensor.Element(romIdName).Value,
                Data = sensor.Elements().Where(element => element != sensor.Element(romIdName))
            });

            return Ok();
        }
    }
}

using HardwareSensorSystem.SensorTechnology.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace HardwareSensorSystem.SensorTechnology.Controllers
{
    public class OwServerEnet2LogController : Controller
    {
        private SensorTechnologyDbContext _context;

        public OwServerEnet2LogController(SensorTechnologyDbContext context)
        {
            _context = context;
        }

        [AllowAnonymous]
        [HttpPost("api/devices/{deviceId}/log/ow-server-enet")]
        public async Task<IActionResult> Log([FromRoute]int deviceId)
        {
            XDocument file = XDocument.Load(HttpContext.Request.Body);

            var romIdName = XName.Get("ROMId", file.Root.Name.NamespaceName);
            var dataSensors = file.Root.Elements().Select(sensor => new
            {
                SerialNumber = sensor.Element(romIdName).Value,
                Data = sensor.Elements().Where(element => element != sensor.Element(romIdName))
            });

            var groupedProperties = await _context.Sensors.Where(sensor => sensor.DeviceId.Equals(deviceId))
                .Join(_context.SensorProperties
                          .Where(property => property.Name.Equals("SENSOR_ID"))
                          .Where(property => dataSensors.Any(e => e.SerialNumber.Equals(property.Value))),
                      sensor => sensor.Id,
                      property => property.SensorId,
                      (sensor, _) => sensor)
                .GroupJoin(_context.SensorProperties,
                           sensor => sensor.Id,
                           property => property.SensorId,
                           (_, properties) => properties)
                .ToListAsync();

            foreach (var properties in groupedProperties)
            {
                var serialNumber = properties.Single(property => property.Name.Equals("SENSOR_ID")).Value;

                try
                {
                    var data = dataSensors.Single(e => e.SerialNumber.Equals(serialNumber)).Data;
                }
                catch
                {

                }
            }

            return Ok();
        }
    }
}

Update log controller for ow-server-enet


/*
 * Copyright 2012-2015 Aerospike, Inc.
 *
 * Portions may be licensed to Aerospike, Inc. under one or more contributor
 * license agreements.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
using System;

namespace Aerospike.Client
{
	/// <summary>
	/// Lua static configuration variables. These variables apply to all AerospikeClient instances
	/// in a single process.
	/// </summary>
	public sealed class LuaConfig
	{
		/// <summary>
		/// Directory location which contains user defined Lua source files.
		/// </summary>
		public static string PackagePath = "udf/?.lua";

		/// <summary>
		/// Maximum number of Lua runtime instances to cache at any point in time.
		/// Each query with an aggregation function requires a Lua instance.
		/// If the number of concurrent queries exceeds the Lua pool size, a new Lua
		/// instance will still be created, but it will not be returned to the pool.
		/// </summary>
		public static int InstancePoolSize = 5;
	}
}

/*
 * Copyright 2012-2015 Aerospike, Inc.
 *
 * Portions may be licensed to Aerospike, Inc. under one or more contributor
 * license agreements.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
using System;
using System.IO;

namespace Aerospike.Client
{
	/// <summary>
	/// Lua static configuration variables. These variables apply to all AerospikeClient instances
	/// in a single process.
	/// </summary>
	public sealed class LuaConfig
	{
		/// <summary>
		/// Directory location which contains user defined Lua source files.
		/// </summary>
		public static string PackagePath = "udf" + Path.DirectorySeparatorChar + "?.lua";

		/// <summary>
		/// Maximum number of Lua runtime instances to cache at any point in time.
		/// Each query with an aggregation function requires a Lua instance.
		/// If the number of concurrent queries exceeds the Lua pool size, a new Lua
		/// instance will still be created, but it will not be returned to the pool.
		/// </summary>
		public static int InstancePoolSize = 5;
	}
}

Replace more hard-coded directory separators with "Path.DirectorySeparatorChar"


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

using Xamarin.Forms;

namespace XF_TabbedPage
{
    public class Page3 : ContentPage
    {
        public Page3()
        {
            NavigationPage.SetHasNavigationBar(this, false);

            var label = new Label
            {
                Text = "Hello TabbedPage 3!",
                TextColor = Color.FromHex("#666666"),
                HorizontalTextAlignment = TextAlignment.Center
            };
            var button = new Button
            {
                Text = "GoTo NextPage",
                Command = new Command(() =>
                {
                    Navigation.PushAsync(new Page3());
                })
            };

            Title = "TabPage 3";
            BackgroundColor = Color.FromHex("#eeeeff");

            Content = new StackLayout
            {
                Padding = 8,
                VerticalOptions = LayoutOptions.CenterAndExpand,
                Children =
                    {
                        label,
                        button
                    }
            };
        }
    }
}

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

using Xamarin.Forms;

namespace XF_TabbedPage
{
    public class Page3 : ContentPage
    {
        public Page3()
        {
            NavigationPage.SetHasNavigationBar(this, false);

            var label = new Label
            {
                Text = "Hello TabbedPage 3!",
                TextColor = Color.FromHex("#666666"),
                HorizontalTextAlignment = TextAlignment.Center
            };
            var button1 = new Button
            {
                Text = "GoTo Page3",
                Command = new Command(() =>
                {
                    Navigation.PushAsync(new Page3());
                })
            };
            var button2 = new Button
            {
                Text = "GoTo Page1",
                Command = new Command(() =>
                {
                    Navigation.PushAsync(new Page1());
                })
            };

            Title = "TabPage 3";
            BackgroundColor = Color.FromHex("#eeeeff");

            Content = new StackLayout
            {
                Padding = 8,
                VerticalOptions = LayoutOptions.CenterAndExpand,
                Children =
                    {
                        label,
                        button1,
                        button2
                    }
            };
        }
    }
}

Add button to move to page1. it means both of destination page must set "HasNavigationBar=False"


using System.Collections.Generic;
using Newtonsoft.Json;

namespace TMDbLib.Objects.General
{
    public class ConfigImageTypes
    {
        [JsonProperty("base_url")]
        public string BaseUrl { get; set; }

        [JsonProperty("secure_base_url")]
        public string SecureBaseUrl { get; set; }

        [JsonProperty("poster_sizes")]
        public List<string> PosterSizes { get; set; }

        [JsonProperty("backdrop_sizes")]
        public List<string> BackdropSizes { get; set; }

        [JsonProperty("profile_sizes")]
        public List<string> ProfileSizes { get; set; }

        [JsonProperty("logo_sizes")]
        public List<string> LogoSizes { get; set; }
    }
}

using System.Collections.Generic;
using Newtonsoft.Json;

namespace TMDbLib.Objects.General
{
    public class ConfigImageTypes
    {
        [JsonProperty("base_url")]
        public string BaseUrl { get; set; }

        [JsonProperty("secure_base_url")]
        public string SecureBaseUrl { get; set; }

        [JsonProperty("poster_sizes")]
        public List<string> PosterSizes { get; set; }

        [JsonProperty("backdrop_sizes")]
        public List<string> BackdropSizes { get; set; }

        [JsonProperty("profile_sizes")]
        public List<string> ProfileSizes { get; set; }

        [JsonProperty("logo_sizes")]
        public List<string> LogoSizes { get; set; }

        [JsonProperty("still_sizes")]
        public List<string> StillSizes { get; set; }
    }
}

Add missing field to config

Add missing field to config


using System;
using System.Collections.Generic;

namespace MonsterClicker
{
    using Interfaces;
    using System.Numerics;
    using System.Windows.Forms;
    public class Monster : IMonster
    {
        private BigInteger health;
        private static BigInteger startHealth = 10;
        private BigInteger nextLevelHealth = startHealth;
        //private List<string> photosPaths;
        private Random randomGenerator;

        //TODO: exp and money - every next monster must have more money and exp
        //TODO: exp must be part of health
        //TODO: make class Boss
        //TODO: make homework
        //TODO: Timer

        public Monster()
        {
            this.Health = startHealth;
            //this.photosPaths = new List<string>();
            this.randomGenerator = new System.Random();
        }

        public BigInteger Health
        {
            get { return this.health; }
            set { this.health = value; }
        }

        public void TakeDamage(BigInteger damage)
        {
            this.Health -= damage;
        }

        public void GenerateHealth()
        {
            nextLevelHealth += (nextLevelHealth / 10);
            this.health = nextLevelHealth;
        }

        public int GetRandomNumber()
        {
            var number = randomGenerator.Next(0, 5);
            return number;
        }

    }
}

using System;
using System.Collections.Generic;

namespace MonsterClicker
{
    using Interfaces;
    using System.Numerics;
    using System.Windows.Forms;
    public class Monster : IMonster
    {
        private BigInteger health;
        private static BigInteger startHealth = 10;
        private BigInteger nextLevelHealth = startHealth;
        //private List<string> photosPaths;
        private Random randomGenerator;

        //TODO: exp and money - every next monster must have more money and exp
        //TODO: exp must be part of health
        //TODO: make class Boss
        //TODO: make homework
        //TODO: Timer

        public Monster()
        {
            this.Health = startHealth;
            //this.photosPaths = new List<string>();
            this.randomGenerator = new System.Random();
        }

        public BigInteger Health
        {
            get { return this.health; }
            set { this.health = value; }
        }

        public void TakeDamage(BigInteger damage)
        {
            this.Health -= damage;
        }

        public void GenerateHealth()
        {
            nextLevelHealth += (nextLevelHealth / 10);
            this.health = nextLevelHealth;
        }

        public int GetRandomNumber()
        {
            int firstNumber = 0;
            var number = randomGenerator.Next(0, 5);
            if (number == firstNumber)
            {
                while (number == firstNumber)
                {
                    number = randomGenerator.Next(0, 5);
                }
            }
            else
            {
                firstNumber = number;
            }
            return number;
        }

    }
}

Make a picture unque for every next level


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

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

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

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

        return _versionContext;
    }
}

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

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

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

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

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

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

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

        return _versionContext;
    }
}

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

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

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

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


using System.Diagnostics;
using System.IO;

internal class Mono50Compiler : Compiler
{
	public Mono50Compiler(Logger logger, string compilerPath) : base(logger, compilerPath, null) { }
	public override string Name => "Mono C# 5.0";

	protected override Process CreateCompilerProcess(Platform platform, string monoProfileDir, string unityEditorDataDir, string responseFile)
	{
		var systemCoreDllPath = Path.Combine(monoProfileDir, "System.Core.dll");

		string processArguments;
		if (platform == Platform.Windows)
		{
			processArguments = $"-sdk:2 -debug+ -langversion:Future -r:\"{systemCoreDllPath}\" {responseFile}";
		}
		else
		{
			processArguments = $"-sdk:2 -debug+ -langversion:Future {responseFile}";
		}

		var process = new Process();
		process.StartInfo = CreateOSDependentStartInfo(platform, ProcessRuntime.CLR40, compilerPath, processArguments, unityEditorDataDir);
		return process;
	}
}

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

internal class Mono50Compiler : Compiler
{
	public Mono50Compiler(Logger logger, string compilerPath) : base(logger, compilerPath, null) { }
	public override string Name => "Mono C# 5.0";

	protected override Process CreateCompilerProcess(Platform platform, string monoProfileDir, string unityEditorDataDir, string responseFile)
	{
		var systemCoreDllPath = Path.Combine(monoProfileDir, "System.Core.dll");

		string processArguments;
		if (platform == Platform.Windows && GetSdkValue(responseFile) == "2.0")
		{
			// -sdk:2.0 requires System.Core.dll. but -sdk:unity doesn't.
			processArguments = $"-r:\"{systemCoreDllPath}\" {responseFile}";
		}
		else
		{
			processArguments = responseFile;
		}

		var process = new Process();
		process.StartInfo = CreateOSDependentStartInfo(platform, ProcessRuntime.CLR40, compilerPath, processArguments, unityEditorDataDir);
		return process;
	}

	private string GetSdkValue(string responseFile)
	{
		var lines = File.ReadAllLines(responseFile.Substring(1));
		var sdkArg = lines.FirstOrDefault(line => line.StartsWith("-sdk:"));
		return (sdkArg != null) ? sdkArg.Substring(5) : "";
	}
}

Fix Mono 5.0 run under Unity 5.5+

Fix Mono 5.0 run under Unity 5.5+


@model ElmahDashboardHostingApp.Areas.MvcElmahDashboard.Models.Logs.ItemsModel
@{
    Layout = null;
    var dateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.Replace("yyyy", "yy").ToUpperInvariant();
}

@foreach (var item in Model.Items)
{
    @(item.Sequence)

            @(item.Sequence)

@(item.RowNum)

                @(item.TimeUtc.ToString()) (UTC)

            @(item.TimeAgoText)

        @item.Application
        @item.Host
        @item.Source
        @item.Type
        @item.Message

}

@model ElmahDashboardHostingApp.Areas.MvcElmahDashboard.Models.Logs.ItemsModel
@{
    Layout = null;
    var dateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.Replace("yyyy", "yy").ToUpperInvariant();
}

@* Disable Email obfuscation by Cloudflare (which is not compatible with this rendering) *@

@foreach (var item in Model.Items)
{
    @(item.Sequence)

            @(item.Sequence)

@(item.RowNum)

                @(item.TimeUtc.ToString()) (UTC)

            @(item.TimeAgoText)

        @item.Application
        @item.Host
        @item.Source
        @item.Type
        @item.Message

}

Fix for email obfuscator of Cloudflare

Fix for email obfuscator of Cloudflare


using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace PackageDiscovery.Finders
{
    public sealed class NuGetPackageFinder : IPackageFinder
    {
        public const string Moniker = "NuGet";

        public IReadOnlyCollection<Package> FindPackages(DirectoryInfo directory)
        {
            return directory
                .GetFiles("packages.config", SearchOption.AllDirectories)
                .Select(f => XDocument.Load(f.FullName))
                .SelectMany(x => x.Root.Elements("package"))
                .Select(x => new Package(Moniker, x.Attribute("id").Value, x.Attribute("version").Value))
                .Distinct(p => new { p.Id, p.Version, p.IsDevelopmentPackage })
                .OrderBy(p => p.Id)
                .ThenBy(p => p.Version)
                .ToList();
        }
    }
}

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace PackageDiscovery.Finders
{
    public sealed class NuGetPackageFinder : IPackageFinder
    {
        public const string Moniker = "NuGet";

        public IReadOnlyCollection<Package> FindPackages(DirectoryInfo directory)
        {
            var packagesFromRepositories = (
                from f in directory
                    .GetFiles("repositories.config", SearchOption.AllDirectories)
                let x = XDocument.Load(f.FullName)
                from r in x.Root.Elements("repository")
                select new FileInfo(Path.Combine(f.Directory.FullName, r.Attribute("path").Value))
            );

            var standalonePackages = directory
                .GetFiles("packages.config", SearchOption.AllDirectories);

            return standalonePackages.Union(packagesFromRepositories)
                .Select(f => XDocument.Load(f.FullName))
                .SelectMany(x => x.Root.Elements("package"))
                .Select(x => new Package(Moniker, x.Attribute("id").Value, x.Attribute("version").Value))
                .Distinct(p => new { p.Id, p.Version, p.IsDevelopmentPackage })
                .OrderBy(p => p.Id)
                .ThenBy(p => p.Version)
                .ToList();
        }
    }
}

Enumerate packages.config file from repositories.config files.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raven.Client.Contrib.MVC.Auth.Interfaces;

namespace Raven.Client.Contrib.MVC.Auth.Default
{
    internal class BCryptSecurityEncoder : ISecurityEncoder
    {
        /// <summary>
        /// Generates a unique token.
        /// </summary>
        /// <returns>The unique token.</returns>
        public string GenerateToken()
        {
            return new Guid().ToString()
                             .ToLowerInvariant()
                             .Replace("-", "");
        }

        /// <summary>
        /// Hashes the identifier with the provided salt.
        /// </summary>
        /// <param name="identifier">The identifier to hash.</param>
        /// <returns>The hashed identifier.</returns>
        public string Hash(string identifier)
        {
            return BCrypt.Net.BCrypt.HashPassword(identifier, workFactor: 10);
        }

        /// <summary>
        /// Verifies if the identifier matches the hash.
        /// </summary>
        /// <param name="identifier">The identifier to check.</param>
        /// <param name="hash">The hash to check against.</param>
        /// <returns>true if the identifiers match, false otherwise.</returns>
        public bool Verify(string identifier, string hash)
        {
            return BCrypt.Net.BCrypt.Verify(identifier, hash);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raven.Client.Contrib.MVC.Auth.Interfaces;

namespace Raven.Client.Contrib.MVC.Auth.Default
{
    internal class BCryptSecurityEncoder : ISecurityEncoder
    {
        /// <summary>
        /// Generates a unique token.
        /// </summary>
        /// <returns>The unique token.</returns>
        public string GenerateToken()
        {
            return new Guid().ToString()
                             .ToLowerInvariant()
                             .Replace("-", "");
        }

        /// <summary>
        /// Hashes the identifier with the provided salt.
        /// </summary>
        /// <param name="identifier">The identifier to hash.</param>
        /// <returns>The hashed identifier.</returns>
        public string Hash(string identifier)
        {
            const string pepper = "BCryptSecurityEncoder";
            string salt         = BCrypt.Net.BCrypt.GenerateSalt(workFactor: 10);

            return BCrypt.Net.BCrypt.HashPassword(identifier, salt + pepper);
        }

        /// <summary>
        /// Verifies if the identifier matches the hash.
        /// </summary>
        /// <param name="identifier">The identifier to check.</param>
        /// <param name="hash">The hash to check against.</param>
        /// <returns>true if the identifiers match, false otherwise.</returns>
        public bool Verify(string identifier, string hash)
        {
            return BCrypt.Net.BCrypt.Verify(identifier, hash);
        }
    }
}

Include a pepper in the hashing algorithm.


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

namespace Manatee.Json.Serialization.Internal.AutoRegistration
{
	internal class ListSerializationDelegateProvider : SerializationDelegateProviderBase
	{
		public override bool CanHandle(Type type)
		{
			return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>);
		}

		private static JsonValue _Encode<T>(List<T> list, JsonSerializer serializer)
		{
			var array = new JsonArray();
			array.AddRange(list.Select(serializer.Serialize));
			return array;
		}
		private static List<T> _Decode<T>(JsonValue json, JsonSerializer serializer)
		{
			var list = new List<T>();
			list.AddRange(json.Array.Select(serializer.Deserialize<T>));
			return list;
		}
	}
}

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

namespace Manatee.Json.Serialization.Internal.AutoRegistration
{
	internal class ListSerializationDelegateProvider : SerializationDelegateProviderBase
	{
		public override bool CanHandle(Type type)
		{
			return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>);
		}

		private static JsonValue _Encode<T>(List<T> list, JsonSerializer serializer)
		{
			var array = new JsonValue[list.Count];
			for (int ii = 0; ii < array.Length; ++ii)
			{
				array[ii] = serializer.Serialize(list[ii]);
			}
			return new JsonArray(array);
		}
		private static List<T> _Decode<T>(JsonValue json, JsonSerializer serializer)
		{
			var array = json.Array;
			var list = new List<T>(array.Count);
			for (int ii = 0; ii < array.Count; ++ii)
			{
				list.Add(serializer.Deserialize<T>(array[ii]));
			}
			return list;
		}
	}
}

Decrease allocations in List Serializer

Decrease allocations in List Serializer


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

[assembly: AssemblyTitle("Autofac.Extras.Moq")]
[assembly: AssemblyDescription("Autofac Moq Integration")]
[assembly: ComVisible(false)]

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

[assembly: AssemblyTitle("Autofac.Extras.Moq")]
[assembly: ComVisible(false)]

Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.


namespace MyStudio.ViewModels
{
    using Catel;
    using Catel.MVVM;

    using MyStudio.Models;
    using MyStudio.Services;

    public class RibbonViewModel : ViewModelBase
    {
        private StudioStateModel model;

        private ICommandsService commandsService;

        public RibbonViewModel(StudioStateModel model,
            ICommandsService commandsService)
        {
            Argument.IsNotNull(() => model);
            Argument.IsNotNull(() => commandsService);

            this.model = model;
            this.commandsService = commandsService;
        }

        public Command StartCommand
        {
            get
            {
                return this.commandsService != null ? this.commandsService.StartCommand : null;
            }
        }

        public Command UndoCommand
        {
            get
            {
                return this.commandsService != null ? this.commandsService.UndoCommand : null;
            }
        }

        public Command RedoCommand
        {
            get
            {
                return this.commandsService != null ? this.commandsService.RedoCommand : null;
            }
        }
    }
}

namespace MyStudio.ViewModels
{
    using System.Collections.Generic;

    using Catel;
    using Catel.MVVM;

    using MyStudio.Models;
    using MyStudio.Services;

    using Orchestra.Models;
    using Orchestra.Services;

    public class RibbonViewModel : ViewModelBase
    {
        private StudioStateModel model;

        private ICommandsService commandsService;

        private IRecentlyUsedItemsService recentlyUsedItemsService;

        public RibbonViewModel(StudioStateModel model,
            ICommandsService commandsService,
            IRecentlyUsedItemsService recentlyUsedItemsService)
        {
            Argument.IsNotNull(() => model);
            Argument.IsNotNull(() => commandsService);
            Argument.IsNotNull(() => recentlyUsedItemsService);

            this.model = model;
            this.commandsService = commandsService;
            this.recentlyUsedItemsService = recentlyUsedItemsService;

            this.RecentlyUsedItems = new List<RecentlyUsedItem>(this.recentlyUsedItemsService.Items);
            this.PinnedItems = new List<RecentlyUsedItem>(this.recentlyUsedItemsService.PinnedItems);
        }

        public Command StartCommand
        {
            get
            {
                return this.commandsService != null ? this.commandsService.StartCommand : null;
            }
        }

        public Command UndoCommand
        {
            get
            {
                return this.commandsService != null ? this.commandsService.UndoCommand : null;
            }
        }

        public Command RedoCommand
        {
            get
            {
                return this.commandsService != null ? this.commandsService.RedoCommand : null;
            }
        }

        public List<RecentlyUsedItem> RecentlyUsedItems { get; private set; }

        public List<RecentlyUsedItem> PinnedItems { get; private set; }
    }
}

Add recently used items data

Add recently used items data


using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using Spectre.Console;

namespace Spectre.Cli.Internal
{
    [Description("Displays the CLI library version")]
    [SuppressMessage("Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Injected")]
    internal sealed class VersionCommand : Command<VersionCommand.Settings>
    {
        private readonly IAnsiConsole _writer;

        public VersionCommand(IConfiguration configuration)
        {
            _writer = configuration?.Settings?.Console ?? AnsiConsole.Console;
        }

        public sealed class Settings : CommandSettings
        {
        }

        public override int Execute(CommandContext context, Settings settings)
        {
            var version = typeof(VersionCommand)?.Assembly?.GetName()?.Version?.ToString();
            version ??= "?";

            _writer.Write($"Spectre.Cli version {version}");

            return 0;
        }
    }
}

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Spectre.Console;

namespace Spectre.Cli.Internal
{
    [Description("Displays the CLI library version")]
    [SuppressMessage("Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Injected")]
    internal sealed class VersionCommand : Command<VersionCommand.Settings>
    {
        private readonly IAnsiConsole _writer;

        public VersionCommand(IConfiguration configuration)
        {
            _writer = configuration?.Settings?.Console ?? AnsiConsole.Console;
        }

        public sealed class Settings : CommandSettings
        {
        }

        public override int Execute(CommandContext context, Settings settings)
        {
            _writer.MarkupLine(
                "[yellow]Spectre.Cli[/] version [aqua]{0}[/]",
                GetVersion(typeof(VersionCommand)?.Assembly));

            _writer.MarkupLine(
                "[yellow]Spectre.Console[/] version [aqua]{0}[/]",
                GetVersion(typeof(IAnsiConsole)?.Assembly));

            return 0;
        }

        [SuppressMessage("Design", "CA1031:Do not catch general exception types")]
        private static string GetVersion(Assembly? assembly)
        {
            if (assembly == null)
            {
                return "?";
            }

            try
            {
                var info = FileVersionInfo.GetVersionInfo(assembly.Location);
                return info.ProductVersion ?? "?";
            }
            catch
            {
                return "?";
            }
        }
    }
}

Fix displayed version in built-in version command


using System.Reflection;

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

using System.Reflection;

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

Set the version to 1.3 since we're releasing.


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

namespace Navigation.Mvc
{
	public class RouteConfig
	{
		public static void AddStateRoutes()
		{
			if (StateInfoConfig.Dialogs == null)
				return;
			string controller, action;
			Route route;
			using (RouteTable.Routes.GetWriteLock())
			{
				foreach (Dialog dialog in StateInfoConfig.Dialogs)
				{
					foreach (State state in dialog.States)
					{
						controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty;
						action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty;
						if (controller.Length != 0 && action.Length != 0 && state.Route.Length != 0)
						{
							state.StateHandler = new MvcStateHandler();
							route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route);
							route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route);
							route.Defaults["controller"] = controller;
							route.Defaults["action"] = action;
							route.RouteHandler = new MvcStateRouteHandler(state);
						}
					}
				}
			}
		}
	}
}

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

namespace Navigation.Mvc
{
	public class RouteConfig
	{
		public static void AddStateRoutes()
		{
			if (StateInfoConfig.Dialogs == null)
				return;
			string controller, action;
			Route route;
			using (RouteTable.Routes.GetWriteLock())
			{
				foreach (Dialog dialog in StateInfoConfig.Dialogs)
				{
					foreach (State state in dialog.States)
					{
						controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty;
						action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty;
						if (controller.Length != 0 && action.Length != 0 && state.Route.Length != 0)
						{
							state.StateHandler = new MvcStateHandler();
							route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route);
							route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route);
							route.Defaults["controller"] = controller;
							route.Defaults["action"] = action;
							route.DataTokens = new RouteValueDictionary() { { NavigationSettings.Config.StateIdKey, state.Id } };
							route.RouteHandler = new MvcStateRouteHandler(state);
						}
					}
				}
			}
		}
	}
}

Set StateId in DataTokens so ShieldDecode works because StateId was in the data when ShieldEncode was called


using System.Reflection;

[assembly: AssemblyCompany("Picoe Software Solutions Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: AssemblyVersion("1.99.0.0")]
[assembly: AssemblyFileVersion("1.99.0.0")]
[assembly: AssemblyInformationalVersion("1.99.0")]

using System.Reflection;

[assembly: AssemblyCompany("Picoe Software Solutions Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: AssemblyVersion("1.99.0.0")]
[assembly: AssemblyFileVersion("1.99.*")]
[assembly: AssemblyInformationalVersion("1.99.0")]

Use auto-version for AssemblyFileVersion in develop builds to facilitate installers


using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;

namespace PersonalWebApp.Middleware {
	public class StripWhitespaceMiddleware {
		private readonly RequestDelegate _next;

		public StripWhitespaceMiddleware(RequestDelegate next) {
			_next = next;
		}

		public async Task Invoke(HttpContext context) {
			var body = context.Response.Body;
			using (var intercept = new MemoryStream()) {
				context.Response.Body = intercept;

				await _next.Invoke(context);

				var contentType = context.Response.ContentType ?? "";
				if (contentType.StartsWith("text/html")) {
					intercept.Seek(0, SeekOrigin.Begin);
					using (var reader = new StreamReader(intercept)) {
						var responseBody = await reader.ReadToEndAsync();
						var stripped = Regex.Replace(responseBody, @">\s+<", "><");
						var bytes = Encoding.UTF8.GetBytes(stripped);
						await body.WriteAsync(bytes, 0, bytes.Length);
					}
				} else {
					await intercept.CopyToAsync(body);
				}
			}
		}
	}
}

using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;

namespace PersonalWebApp.Middleware {
	public class StripWhitespaceMiddleware {
		private readonly RequestDelegate _next;

		public StripWhitespaceMiddleware(RequestDelegate next) {
			_next = next;
		}

		public async Task Invoke(HttpContext context) {
			var body = context.Response.Body;
			using (var intercept = new MemoryStream()) {
				context.Response.Body = intercept;

				await _next.Invoke(context);

				var contentType = context.Response.ContentType ?? "";
				if (contentType.StartsWith("text/html")) {
					intercept.Seek(0, SeekOrigin.Begin);
					using (var reader = new StreamReader(intercept)) {
						var responseBody = await reader.ReadToEndAsync();
						var stripped = Regex.Replace(responseBody, @">\s+<", "><");
						var bytes = Encoding.UTF8.GetBytes(stripped);
						await body.WriteAsync(bytes, 0, bytes.Length);
					}
				} else {
					intercept.Seek(0, SeekOrigin.Begin);
					await intercept.CopyToAsync(body);
				}
			}
		}
	}
}

Fix bug with non-HTML responses

Fix bug with non-HTML responses


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

namespace SvNaum.Web
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //filters.Add(new HandleErrorAttribute());
        }
    }
}

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

namespace SvNaum.Web
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
}

Include missing views AddNews and EditNews in project.


namespace C42A
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    using System.Xml.Serialization;

    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        private static int Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            using (var f = new global::C42A.CAB42.Windows.Forms.CAB42())
            {
                if (args != null && args.Length > 0)
                {
                    if (args.Length == 1)
                    {
                        f.OpenFileOnShow = args[0];
                    }
                }

                Application.Run(f);
            }

            return 0;
        }
    }
}

namespace C42A
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    using System.Xml.Serialization;

    using C42A.CAB42;

    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        private static int Main(string[] args)
        {
            if (args.Length > 0 && args[0] == "build")
            {
                AllocConsole();

                if (args.Length != 2) Console.WriteLine("cab42.exe build PATH");

                try
                {
                    Build(args[1]);
                }
                catch (Exception error)
                {
                    Console.Error.WriteLine(error.ToString());
                    return 1;
                }

                return 0;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            using (var f = new global::C42A.CAB42.Windows.Forms.CAB42())
            {
                if (args != null && args.Length > 0)
                {
                    if (args.Length == 1)
                    {
                        f.OpenFileOnShow = args[0];
                    }
                }

                Application.Run(f);
            }

            return 0;
        }

        private static void Build(string file)
        {
            var buildProject = ProjectInfo.Open(file);
            using (var buildContext = new CabwizBuildContext())
            {
                var tasks = buildProject.CreateBuildTasks();

                var feedback = new BuildFeedbackBase(Console.Out);
                buildContext.Build(tasks, feedback);
            }
        }

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

Add support for building from the command line.


using System;
using compiler.frontend;

namespace Program
{
    class Program
    {
        //TODO: adjust main to use the parser when it is complete
        static void Main(string[] args)
        {
            using (Lexer l = new Lexer(@"../../testdata/big.txt"))
            {
                Token t;
                do
                {
                    t = l.GetNextToken();
                    Console.WriteLine(TokenHelper.PrintToken(t));

                } while (t != Token.EOF);

                // necessary when testing on windows with visual studio
                //Console.WriteLine("Press 'enter' to exit ....");
                //Console.ReadLine();
            }
        }
    }
}

using System;
using compiler.frontend;

namespace Program
{
    class Program
    {
        //TODO: adjust main to use the parser when it is complete
        static void Main(string[] args)
        {
//            using (Lexer l = new Lexer(@"../../testdata/big.txt"))
//            {
//                Token t;
//                do
//                {
//                    t = l.GetNextToken();
//                    Console.WriteLine(TokenHelper.PrintToken(t));
//
//                } while (t != Token.EOF);
//
//                // necessary when testing on windows with visual studio
//                //Console.WriteLine("Press 'enter' to exit ....");
//                //Console.ReadLine();
//            }

            using (Parser p = new Parser(@"../../testdata/test002.txt"))
            {
                p.Parse();
                p.FlowCfg.GenerateDOTOutput();

                using (System.IO.StreamWriter file = new System.IO.StreamWriter("graph.txt"))
                {
                    file.WriteLine( p.FlowCfg.DOTOutput);
                }

            }

        }
    }
}

Update Main to print the graph

Update Main to print the graph


namespace System.Net.Http
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;

    static class HttpHelper
    {
        public static string ValidatePath(string path)
        {
            if (path == null) throw new ArgumentNullException(nameof(path));
            if (path == "" || path == "/") return "";
            if (path[0] != '/' || path[path.Length - 1] == '/') throw new ArgumentException(nameof(path));

            return path;
        }

        public static DelegatingHandler Combine(this IEnumerable<DelegatingHandler> handlers)
        {
            var result = handlers.FirstOrDefault();
            var last = result;

            foreach (var handler in handlers.Skip(1))
            {
                last.InnerHandler = handler;
                last = handler;
            }

            return result;
        }

        [Conditional("DEBUG")]
        public static void DumpErrors(HttpResponseMessage message)
        {
            if (!message.IsSuccessStatusCode && message.StatusCode != HttpStatusCode.Unauthorized)
            {
                var dump = (Action)(async () =>
                {
                    var error = await message.Content.ReadAsStringAsync();
                    Debug.WriteLine(error);
                });
                dump();
            }
        }

        public static int TryGetContentLength(HttpResponseMessage response)
        {
            int result;
            IEnumerable<string> value;
            if (response.Headers.TryGetValues("Content-Length", out value) &&
                value.Any() && int.TryParse(value.First(), out result))
            {
                return result;
            }
            return 0;
        }
    }
}

namespace System.Net.Http
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading.Tasks;

    static class HttpHelper
    {
        public static string ValidatePath(string path)
        {
            if (path == null) throw new ArgumentNullException(nameof(path));
            if (path == "" || path == "/") return "";
            if (path[0] != '/' || path[path.Length - 1] == '/') throw new ArgumentException(nameof(path));

            return path;
        }

        public static DelegatingHandler Combine(this IEnumerable<DelegatingHandler> handlers)
        {
            var result = handlers.FirstOrDefault();
            var last = result;

            foreach (var handler in handlers.Skip(1))
            {
                last.InnerHandler = handler;
                last = handler;
            }

            return result;
        }

        [Conditional("DEBUG")]
        public static void DumpErrors(HttpResponseMessage message)
        {
            if (!message.IsSuccessStatusCode && message.StatusCode != HttpStatusCode.Unauthorized)
            {
                var dump = (Action)(async () =>
                {
                    var error = await message.Content.ReadAsStringAsync();
                    Debug.WriteLine(error);
                });
                dump();
            }
        }

        public static HttpResponseMessage EnsureSuccess(this HttpResponseMessage message)
        {
            if (message.IsSuccessStatusCode) return message;

            throw new HttpRequestException($"Http {message.StatusCode}: {message.Content.ReadAsStringAsync().Result}");
        }

        public static int TryGetContentLength(HttpResponseMessage response)
        {
            int result;
            IEnumerable<string> value;
            if (response.Headers.TryGetValues("Content-Length", out value) &&
                value.Any() && int.TryParse(value.First(), out result))
            {
                return result;
            }
            return 0;
        }
    }
}

Add HttpResponseMessage.EnsureSuccess that include response content in the exception.


using System;
using System.Collections.Generic;
using System.Data;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
using Orchard.Environment.Extensions;

namespace LccNetwork.Migrations
{
    [OrchardFeature("fea")]
    public class NavigationMigrations : DataMigrationImpl
    {
        public int Create()
        {
            return 1;
        }

        public int UpdateFrom1()
        {
            return 2;
        }

        public int UpdateFrom2()
        {
            ContentDefinitionManager.AlterTypeDefinition("SectionMenu",
                    cfg => cfg
                    .WithPart("CommonPart")
                    .WithPart("IdentityPart")
                    .WithPart("WidgetPart")
                    .WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI?
                    .WithSetting("Stereotype", "Widget")
                );

            return 3;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
using Orchard.Environment.Extensions;

namespace LccNetwork.Migrations
{
    [OrchardFeature("SectionNavigation")]
    public class NavigationMigrations : DataMigrationImpl
    {
        public int Create()
        {
            return 1;
        }

        public int UpdateFrom1()
        {
            return 2;
        }

        public int UpdateFrom2()
        {
            ContentDefinitionManager.AlterTypeDefinition("SectionMenu",
                    cfg => cfg
                    .WithPart("CommonPart")
                    .WithPart("IdentityPart")
                    .WithPart("WidgetPart")
                    .WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI?
                    .WithSetting("Stereotype", "Widget")
                );

            return 4;
        }

        public int UpdateFrom4()
        {
            ContentDefinitionManager.AlterTypeDefinition("FooterMenu",
                    cfg => cfg
                    .WithPart("CommonPart")
                    .WithPart("IdentityPart")
                    .WithPart("WidgetPart")
                    .WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI?
                    .WithSetting("Stereotype", "Widget")
                );

            return 5;
        }
    }
}

Add a footer navigation widget.

Add a footer navigation widget.


// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using System.Reflection;

namespace NodaTime.Benchmarks.Framework
{
    /// <summary>
    /// The results of running a single test.
    /// </summary>
    internal class BenchmarkResult
    {
        private const long TicksPerPicosecond = 100 * 1000L;
        private const long TicksPerNanosecond = 100;

        private readonly MethodInfo method;
        private readonly int iterations;
        private readonly Duration duration;

        internal BenchmarkResult(MethodInfo method, int iterations, Duration duration)
        {
            this.method = method;
            this.iterations = iterations;
            this.duration = duration;
        }

        internal MethodInfo Method { get { return method; } }
        internal long Iterations { get { return iterations; } }
        internal Duration Duration { get { return duration; } }
        internal long CallsPerSecond { get { return iterations * NodaConstants.TicksPerSecond / duration.Ticks; } }
        internal long TicksPerCall { get { return Duration.Ticks / iterations; } }
        internal long PicosecondsPerCall { get { return (Duration.Ticks * TicksPerPicosecond) / iterations; } }
        internal long NanosecondsPerCall { get { return (Duration.Ticks * TicksPerNanosecond) / iterations; } }
    }
}

// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using System.Reflection;

namespace NodaTime.Benchmarks.Framework
{
    /// <summary>
    /// The results of running a single test.
    /// </summary>
    internal class BenchmarkResult
    {
        private const long TicksPerPicosecond = 100 * 1000L;
        private const long TicksPerNanosecond = 100;

        private readonly MethodInfo method;
        private readonly int iterations;
        private readonly Duration duration;

        internal BenchmarkResult(MethodInfo method, int iterations, Duration duration)
        {
            this.method = method;
            this.iterations = iterations;
            this.duration = duration;
        }

        internal MethodInfo Method { get { return method; } }
        internal long Iterations { get { return iterations; } }
        internal Duration Duration { get { return duration; } }
        // Use ticks here rather than nanoseconds, as otherwise the multiplication could easily overflow. As an alternative,
        // we could use decimal arithmetic or BigInteger...
        internal long CallsPerSecond { get { return iterations * NodaConstants.TicksPerSecond / duration.Ticks; } }
        internal long NanosecondsPerCall { get { return Duration.ToInt64Nanoseconds() / iterations; } }
    }
}

Tweak to use the fact that we now have nanosecond precision in Duration.


using Newtonsoft.Json;

namespace Nest
{
	[JsonConverter(typeof(ReadAsTypeJsonConverter<TtlField>))]
	public interface ITtlField : IFieldMapping
	{
		[JsonProperty("enabled")]
		bool? Enabled { get; set; }

		[JsonProperty("default")]
		Time Default { get; set; }
	}

	public class TtlField : ITtlField
	{
		public bool? Enabled { get; set; }
		public Time Default { get; set; }
	}

	public class TtlFieldDescriptor
		: DescriptorBase<TtlFieldDescriptor, ITtlField>, ITtlField
	{
		bool? ITtlField.Enabled { get; set; }
		Time ITtlField.Default { get; set; }

		public TtlFieldDescriptor Enable(bool enable = true) => Assign(a => a.Enabled = enable);

		public TtlFieldDescriptor Default(Time defaultTtl) => Assign(a => a.Default = defaultTtl);
	}
}

using Newtonsoft.Json;

namespace Nest
{
	[JsonConverter(typeof(ReadAsTypeJsonConverter<TtlField>))]
	public interface ITtlField : IFieldMapping
	{
		[JsonProperty("enabled")]
		bool? Enabled { get; set; }

		[JsonProperty("default")]
		Time Default { get; set; }
	}

	public class TtlField : ITtlField
	{
		public bool? Enabled { get; set; }
		public Time Default { get; set; }
	}

	public class TtlFieldDescriptor
		: DescriptorBase<TtlFieldDescriptor, ITtlField>, ITtlField
	{
		bool? ITtlField.Enabled { get; set; }
		Time ITtlField.Default { get; set; }

		public TtlFieldDescriptor Enabled(bool enabled = true) => Assign(a => a.Enabled = enabled);

		public TtlFieldDescriptor Default(Time defaultTtl) => Assign(a => a.Default = defaultTtl);
	}
}

Make enable method name consistent on TTL field


using Xunit;

namespace PlayerRank.UnitTests
{
    public class PlayerTests
    {
        [Fact]
        public void CanIncreasePlayersScore()
        {
            var player = new PlayerScore("Foo");
            player.AddPoints(new Points(100));

            Assert.Equal(new Points(100), player.Points);
            Assert.Equal(100, player.Score);
        }

        [Fact]
        public void CanReducePlayersScore()
        {
            var player = new PlayerScore("Foo");
            player.AddPoints(new Points(-100));

            Assert.Equal(new Points(-100), player.Points);
            Assert.Equal(-100, player.Score);
        }
    }
}

using Xunit;

namespace PlayerRank.UnitTests
{
    public class PlayerTests
    {
        [Fact]
        public void CanIncreasePlayersScore()
        {
            var player = new PlayerScore("Foo");
            player.AddPoints(new Points(100));

            Assert.Equal(new Points(100), player.Points);
            Assert.Equal(100, player.Score);
        }

        [Fact]
        public void CanReducePlayersScore()
        {
            var player = new PlayerScore("Foo");
            player.SubtractPoints(new Points(100));

            Assert.Equal(new Points(-100), player.Points);
            Assert.Equal(-100, player.Score);
        }
    }
}

Change test to use new subtract method

Change test to use new subtract method


using System;
using System.Reactive.Linq;
using static LanguageExt.Prelude;
using static LanguageExt.Process;

namespace LanguageExt
{
    internal class ActorDispatchNotExist : IActorDispatch
    {
        public readonly ProcessId ProcessId;

        public ActorDispatchNotExist(ProcessId pid)
        {
            ProcessId = pid;
        }

        private T Raise<T>() =>
            raise<T>(new ProcessException($"Doesn't exist ({ProcessId})", Self.Path, Sender.Path, null));

        public Map<string, ProcessId> GetChildren() =>
            Map.empty<string, ProcessId>();

        public IObservable<T> Observe<T>() =>
            Observable.Empty<T>();

        public IObservable<T> ObserveState<T>() =>
            Observable.Empty<T>();

        public Unit Tell(object message, ProcessId sender, Message.TagSpec tag) =>
            Raise<Unit>();

        public Unit TellSystem(SystemMessage message, ProcessId sender) =>
            Raise<Unit>();

        public Unit TellUserControl(UserControlMessage message, ProcessId sender) =>
            Raise<Unit>();

        public Unit Ask(object message, ProcessId sender) =>
            Raise<Unit>();

        public Unit Publish(object message) =>
            Raise<Unit>();

        public Unit Kill() =>
            unit;

        public int GetInboxCount() =>
            0;

        public Unit Watch(ProcessId pid) =>
            Raise<Unit>();

        public Unit UnWatch(ProcessId pid) =>
            Raise<Unit>();

        public Unit DispatchWatch(ProcessId pid) =>
            Raise<Unit>();

        public Unit DispatchUnWatch(ProcessId pid) =>
            Raise<Unit>();
    }
}

using System;
using System.Reactive.Linq;
using static LanguageExt.Prelude;
using static LanguageExt.Process;

namespace LanguageExt
{
    internal class ActorDispatchNotExist : IActorDispatch
    {
        public readonly ProcessId ProcessId;

        public ActorDispatchNotExist(ProcessId pid)
        {
            ProcessId = pid;
        }

        private T Raise<T>() =>
            raise<T>(new ProcessException($"Doesn't exist ({ProcessId})", Self.Path, Sender.Path, null));

        public Map<string, ProcessId> GetChildren() =>
            Map.empty<string, ProcessId>();

        public IObservable<T> Observe<T>() =>
            Observable.Empty<T>();

        public IObservable<T> ObserveState<T>() =>
            Observable.Empty<T>();

        public Unit Tell(object message, ProcessId sender, Message.TagSpec tag) =>
            Raise<Unit>();

        public Unit TellSystem(SystemMessage message, ProcessId sender) =>
            Raise<Unit>();

        public Unit TellUserControl(UserControlMessage message, ProcessId sender) =>
            Raise<Unit>();

        public Unit Ask(object message, ProcessId sender) =>
            Raise<Unit>();

        public Unit Publish(object message) =>
            Raise<Unit>();

        public Unit Kill() =>
            unit;

        public int GetInboxCount() =>
            0;

        public Unit Watch(ProcessId pid) =>
            Raise<Unit>();

        public Unit UnWatch(ProcessId pid) =>
            unit;

        public Unit DispatchWatch(ProcessId pid) =>
            Raise<Unit>();

        public Unit DispatchUnWatch(ProcessId pid) =>
            unit;
    }
}

Stop unwatch from failing on shutdown

Stop unwatch from failing on shutdown


using System.Configuration;

namespace Signatory
{
    public static class Settings
    {
        public static string Authority = ConfigurationManager.AppSettings["Authority"];
        public static string GitHubKey = ConfigurationManager.AppSettings["GitHubKey"];
        public static string GitHubSecret = ConfigurationManager.AppSettings["GitHubSecret"];
    }
}

using System.Configuration;

namespace Signatory
{
    public static class Settings
    {
        public static readonly string Authority = ConfigurationManager.AppSettings["Authority"];
        public static readonly string GitHubKey = ConfigurationManager.AppSettings["GitHubKey"];
        public static readonly string GitHubSecret = ConfigurationManager.AppSettings["GitHubSecret"];
    }
}

Mark settings as read only

Mark settings as read only


using NUnit.Framework;
using System;
using System.Collections;
using Symbooglix;
using Microsoft.Boogie;
using Microsoft.Basetypes;

namespace ExprBuilderTests
{
    [TestFixture()]
    public class ConstantFoldingExprBuilderTests : SimpleExprBuilderTestBase
    {
        protected Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder> GetSimpleAndConstantFoldingBuilder()
        {
            var simpleBuilder = GetSimpleBuilder();
            var constantFoldingBuilder = new ConstantFoldingExprBuilder(simpleBuilder);
            return new Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder>(simpleBuilder, constantFoldingBuilder);
        }

        protected ConstantFoldingExprBuilder GetConstantFoldingBuilder()
        {
            return new ConstantFoldingExprBuilder(GetSimpleBuilder());
        }
    }
}

using NUnit.Framework;
using System;
using System.Collections;
using Symbooglix;
using Microsoft.Boogie;
using Microsoft.Basetypes;

namespace ExprBuilderTests
{
    public class ConstantFoldingExprBuilderTests : SimpleExprBuilderTestBase
    {
        protected Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder> GetSimpleAndConstantFoldingBuilder()
        {
            var simpleBuilder = GetSimpleBuilder();
            var constantFoldingBuilder = new ConstantFoldingExprBuilder(simpleBuilder);
            return new Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder>(simpleBuilder, constantFoldingBuilder);
        }

        protected ConstantFoldingExprBuilder GetConstantFoldingBuilder()
        {
            return new ConstantFoldingExprBuilder(GetSimpleBuilder());
        }
    }
}

Remove NUnit attribute accidently left on a class. The attribute is pointless because the class has no tests.


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

namespace Contract.Models
{
    public class FfmpegJobModel
    {
        public FfmpegJobModel()
        {
            Tasks = new List<FfmpegTaskModel>();
        }

        public Guid JobCorrelationId { get; set; }

        public TranscodingJobState State
        {
            get
            {
                if (Tasks.All(x => x.State == TranscodingJobState.Done))
                    return TranscodingJobState.Done;

                if (Tasks.Any(j => j.State == TranscodingJobState.Failed))
                    return TranscodingJobState.Failed;

                if (Tasks.Any(j => j.State == TranscodingJobState.Paused))
                    return TranscodingJobState.Paused;

                if (Tasks.Any(j => j.State == TranscodingJobState.InProgress))
                    return TranscodingJobState.InProgress;

                if (Tasks.Any(j => j.State == TranscodingJobState.Queued))
                    return TranscodingJobState.Queued;

                return TranscodingJobState.Unknown;
            }
        }

        public DateTimeOffset Created { get; set; }

        public DateTimeOffset Needed { get; set; }

        public IEnumerable<FfmpegTaskModel> Tasks { get; set; }
    }
}

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

namespace Contract.Models
{
    public class FfmpegJobModel
    {
        public FfmpegJobModel()
        {
            Tasks = new List<FfmpegTaskModel>();
        }

        public Guid JobCorrelationId { get; set; }

        public TranscodingJobState State
        {
            get
            {
                if (Tasks.All(x => x.State == TranscodingJobState.Done))
                    return TranscodingJobState.Done;

                if (Tasks.Any(j => j.State == TranscodingJobState.Failed))
                    return TranscodingJobState.Failed;

                if (Tasks.Any(j => j.State == TranscodingJobState.Paused))
                    return TranscodingJobState.Paused;

                if (Tasks.Any(j => j.State == TranscodingJobState.InProgress))
                    return TranscodingJobState.InProgress;

                if (Tasks.Any(j => j.State == TranscodingJobState.Queued))
                    return TranscodingJobState.Queued;

                if (Tasks.Any(j => j.State == TranscodingJobState.Canceled))
                    return TranscodingJobState.Canceled;

                return TranscodingJobState.Unknown;
            }
        }

        public DateTimeOffset Created { get; set; }

        public DateTimeOffset Needed { get; set; }

        public IEnumerable<FfmpegTaskModel> Tasks { get; set; }
    }
}

Fix job cancelled showing up as State = Unknown


using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using VRGIN.Core;
using VRGIN.Helpers;

namespace HoneySelectVR
{
    internal class HoneyInterpreter : GameInterpreter
    {
        public HScene Scene;
        private IList<IActor> _Actors = new List<IActor>();

        protected override void OnLevel(int level)
        {
            base.OnLevel(level);

            Scene = InitScene(GameObject.FindObjectOfType<HScene>());
        }

        protected override void OnUpdate()
        {
            base.OnUpdate();
        }

        private HScene InitScene(HScene scene)
        {
            _Actors.Clear();
            if(scene)
            {
                StartCoroutine(DelayedInit());
            }
            return scene;
        }

        IEnumerator DelayedInit()
        {
            yield return null;
            yield return null;
            var charFemaleField = typeof(HScene).GetField("chaFemale", BindingFlags.NonPublic | BindingFlags.Instance);
            var charMaleField = typeof(HScene).GetField("chaMale", BindingFlags.NonPublic | BindingFlags.Instance);

            var female = charFemaleField.GetValue(Scene) as CharFemale;
            var male = charMaleField.GetValue(Scene) as CharMale;

            if (male)
            {
                _Actors.Add(new HoneyActor(male));
            }
            if (female)
            {
                _Actors.Add(new HoneyActor(female));
            }

            VRLog.Info("Found {0} chars", _Actors.Count);
        }

        public override IEnumerable<IActor> Actors
        {
            get
            {
                return _Actors;
            }
        }

    }
}

using Manager;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using VRGIN.Core;
using VRGIN.Helpers;
using System.Linq;

namespace HoneySelectVR
{
    internal class HoneyInterpreter : GameInterpreter
    {
        public HScene Scene;
        private IList<HoneyActor> _Actors = new List<HoneyActor>();

        protected override void OnLevel(int level)
        {
            base.OnLevel(level);

            Scene = GameObject.FindObjectOfType<HScene>();
            StartCoroutine(DelayedInit());
        }

        protected override void OnUpdate()
        {
            base.OnUpdate();
        }

        IEnumerator DelayedInit()
        {
            var scene = Singleton<Scene>.Instance;
            if (!scene)
                VRLog.Error("No scene");

            while(scene.IsNowLoading)
            {
                yield return null;
            }

            foreach(var actor in GameObject.FindObjectsOfType<CharInfo>())
            {
                _Actors.Add(new HoneyActor(actor));
            }

            _Actors = _Actors.OrderBy(a => a.Actor.Sex).ToList();

            VRLog.Info("Found {0} chars", _Actors.Count);
        }

        public override IEnumerable<IActor> Actors
        {
            get
            {
                return _Actors.Cast<IActor>();
            }
        }

    }
}

Change the way characters are recognized.


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18033
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

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

[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18033
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

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

[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]

Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.


using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Queries;

namespace MyTrips.UITests
{
    [TestFixture(Platform.iOS)]
    public class Tests
    {
        IApp app;
        Platform platform;

        public Tests(Platform platform)
        {
            this.platform = platform;
        }

		[SetUp]
		public void BeforeEachTest()
		{
			app = AppInitializer.StartApp(platform);
		}

		[Test]
		public void Repl()
		{
			app.Repl ();
		}
    }
}

using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Queries;

namespace MyTrips.UITests
{
    [TestFixture(Platform.iOS)]
    public class Tests
    {
        IApp app;
        Platform platform;

        public Tests(Platform platform)
        {
            this.platform = platform;
        }

		[SetUp]
		public void BeforeEachTest()
		{
			app = AppInitializer.StartApp(platform);
		}

		// If you would like to play around with the Xamarin.UITest REPL
		// uncomment out this method, and run this test with the NUnit test runner.

//		[Test]
//		public void Repl()
//		{
//			app.Repl ();
//		}
    }
}

Add instructions for using UITest REPL.

[Test] Add instructions for using UITest REPL.


using System;
using System.Collections.Generic;

namespace Arkivverket.Arkade.Core
{
    public class ArchiveMetadata
    {
        public string ArchiveDescription { get; set; }
        public string AgreementNumber { get; set; }
        public List<MetadataEntityInformationUnit> ArchiveCreators { get; } = new List<MetadataEntityInformationUnit>();
        public MetadataEntityInformationUnit Transferer { get; set; }
        public MetadataEntityInformationUnit Producer { get; set; }
        public List<MetadataEntityInformationUnit> Owners { get; } = new List<MetadataEntityInformationUnit>();
        public string Recipient { get; set; }
        public MetadataSystemInformationUnit System { get; set; }
        public MetadataSystemInformationUnit ArchiveSystem { get; set; }
        public List<string> Comments { get; } = new List<string>();
        public string History { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public DateTime ExtractionDate { get; set; }
        public string IncommingSeparator { get; set; }
        public string OutgoingSeparator { get; set; }
    }

    public class MetadataEntityInformationUnit
    {
        public string Entity { get; set; }
        public string ContactPerson { get; set; }
        public string Telephone { get; set; }
        public string Email { get; set; }
    }

    public class MetadataSystemInformationUnit
    {
        public string Name { get; set; }
        public string Version { get; set; }
        public string Type { get; set; }
        public string TypeVersion { get; set; }
    }
}

using System;
using System.Collections.Generic;

namespace Arkivverket.Arkade.Core
{
    public class ArchiveMetadata
    {
        public string ArchiveDescription { get; set; }
        public string AgreementNumber { get; set; }
        public List<MetadataEntityInformationUnit> ArchiveCreators { get; set; }
        public MetadataEntityInformationUnit Transferer { get; set; }
        public MetadataEntityInformationUnit Producer { get; set; }
        public List<MetadataEntityInformationUnit> Owners { get; set; }
        public string Recipient { get; set; }
        public MetadataSystemInformationUnit System { get; set; }
        public MetadataSystemInformationUnit ArchiveSystem { get; set; }
        public List<string> Comments { get; set; }
        public string History { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public DateTime ExtractionDate { get; set; }
        public string IncommingSeparator { get; set; }
        public string OutgoingSeparator { get; set; }

        public ArchiveMetadata()
        {
            ArchiveCreators = new List<MetadataEntityInformationUnit>();
            Owners = new List<MetadataEntityInformationUnit>();
            Comments = new List<string>();
        }
    }

    public class MetadataEntityInformationUnit
    {
        public string Entity { get; set; }
        public string ContactPerson { get; set; }
        public string Telephone { get; set; }
        public string Email { get; set; }
    }

    public class MetadataSystemInformationUnit
    {
        public string Name { get; set; }
        public string Version { get; set; }
        public string Type { get; set; }
        public string TypeVersion { get; set; }
    }
}

Enable setters and initialize lists from constructor (again)


using System;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace AppHarbor
{
	public class AppHarborInstaller : IWindsorInstaller
	{
		public void Install(IWindsorContainer container, IConfigurationStore store)
		{
			container.Register(Component
				.For<AppHarborApi>());

			container.Register(Component
				.For<AuthInfo>()
				.UsingFactoryMethod(x =>
				{
					var token = Environment.GetEnvironmentVariable("AppHarborToken", EnvironmentVariableTarget.User);
					return new AuthInfo { AccessToken = token };
				}));

			container.Register(Component
				.For<CommandDispatcher>());
		}
	}
}

using System;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;

namespace AppHarbor
{
	public class AppHarborInstaller : IWindsorInstaller
	{
		public void Install(IWindsorContainer container, IConfigurationStore store)
		{
			container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));

			container.Register(Component
				.For<AppHarborApi>());

			container.Register(Component
				.For<AuthInfo>()
				.UsingFactoryMethod(x =>
				{
					var token = Environment.GetEnvironmentVariable("AppHarborToken", EnvironmentVariableTarget.User);
					return new AuthInfo { AccessToken = token };
				}));

			container.Register(Component
				.For<CommandDispatcher>());
		}
	}
}

Add collection resolver to container

Add collection resolver to container


using System;
using Conreign.Cluster;
using Microsoft.WindowsAzure.ServiceRuntime;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Host;

namespace Conreign.Host.Azure
{
    public class SiloRole : RoleEntryPoint
    {
        private AzureSilo _silo;

        public override void Run()
        {
            var env = RoleEnvironment.GetConfigurationSettingValue("Environment");
            if (string.IsNullOrEmpty(env))
            {
                throw new InvalidOperationException("Unable to determine environment.");
            }
            var config = ConreignSiloConfiguration.Load(Environment.CurrentDirectory, env);
            var orleansConfiguration = new ClusterConfiguration();
            orleansConfiguration.Globals.DeploymentId = RoleEnvironment.DeploymentId;
            var conreignSilo = ConreignSilo.Configure(orleansConfiguration, config);
            _silo = new AzureSilo();
            var started = _silo.Start(conreignSilo.OrleansConfiguration, conreignSilo.Configuration.SystemStorageConnectionString);
            if (!started)
            {
                throw new InvalidOperationException("Silo was not started.");
            }
            conreignSilo.Initialize();
            _silo.Run();
        }

        public override void OnStop()
        {
            _silo.Stop();
            base.OnStop();
        }
    }
}

using System;
using Conreign.Cluster;
using Microsoft.WindowsAzure.ServiceRuntime;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Host;

namespace Conreign.Host.Azure
{
    public class SiloRole : RoleEntryPoint
    {
        private AzureSilo _silo;

        public override void Run()
        {
            var env = RoleEnvironment.GetConfigurationSettingValue("Environment");
            if (string.IsNullOrEmpty(env))
            {
                throw new InvalidOperationException("Unable to determine environment.");
            }
            var config = ConreignSiloConfiguration.Load(Environment.CurrentDirectory, env);
            var orleansConfiguration = new ClusterConfiguration();
            orleansConfiguration.Globals.DeploymentId = RoleEnvironment.DeploymentId;
            var conreignSilo = ConreignSilo.Configure(orleansConfiguration, config);
            _silo = new AzureSilo();
            var started = _silo.Start(conreignSilo.OrleansConfiguration, conreignSilo.Configuration.SystemStorageConnectionString);
            if (!started)
            {
                throw new InvalidOperationException("Silo was not started.");
            }
            _silo.Run();
        }

        public override void OnStop()
        {
            _silo.Stop();
            base.OnStop();
        }
    }
}

Fix Azure host silo startup

Fix Azure host silo startup


#region License
/*********************************************************************************
 * CompactSettingWriter.cs
 *
 * Copyright (c) 2004-2018 Henk Nicolai
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *
 *********************************************************************************/
#endregion

using System.Text;

namespace Sandra.UI.WF.Storage
{
    /// <summary>
    /// Used by <see cref="AutoSave"/> to convert a <see cref="PMap"/> to its compact representation in JSON.
    /// </summary>
    internal class CompactSettingWriter : PValueVisitor
    {
        private readonly StringBuilder outputBuilder = new StringBuilder();

        public string Output() => outputBuilder.ToString();
    }
}

#region License
/*********************************************************************************
 * CompactSettingWriter.cs
 *
 * Copyright (c) 2004-2018 Henk Nicolai
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *
 *********************************************************************************/
#endregion

using System.Globalization;
using System.Text;

namespace Sandra.UI.WF.Storage
{
    /// <summary>
    /// Used by <see cref="AutoSave"/> to convert a <see cref="PMap"/> to its compact representation in JSON.
    /// </summary>
    internal class CompactSettingWriter : PValueVisitor
    {
        private readonly StringBuilder outputBuilder = new StringBuilder();

        public override void VisitBoolean(PBoolean value)
            => outputBuilder.Append(value.Value ? JsonValue.True : JsonValue.False);

        public override void VisitInteger(PInteger value)
            => outputBuilder.Append(value.Value.ToString(CultureInfo.InvariantCulture));

        public string Output() => outputBuilder.ToString();
    }
}

Write PBoolean and PInteger values.

Write PBoolean and PInteger values.


//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="SonarSource SA and Microsoft Corporation">
//   (c) SonarSource SA and Microsoft Corporation.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Sonar.Common;

namespace SonarProjectPropertiesGenerator
{
    public class Program
    {
        public static int Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("Expected to be called with exactly 4 arguments:");
                Console.WriteLine("  1) SonarQube Project Key");
                Console.WriteLine("  2) SonarQube Project Name");
                Console.WriteLine("  3) SonarQube Project Version");
                Console.WriteLine("  4) Dump folder path");
                return 1;
            }

            var dumpFolderPath = args[3];

            var projects = ProjectLoader.LoadFrom(dumpFolderPath);
            var contents = PropertiesWriter.ToString(new ConsoleLogger(), args[0], args[1], args[2], projects);

            File.WriteAllText(Path.Combine(dumpFolderPath, "sonar-project.properties"), contents, Encoding.ASCII);

            return 0;
        }
    }
}

//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="SonarSource SA and Microsoft Corporation">
//   (c) SonarSource SA and Microsoft Corporation.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Sonar.Common;

namespace SonarProjectPropertiesGenerator
{
    public class Program
    {
        public static int Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("Expected to be called with exactly 4 arguments:");
                Console.WriteLine("  1) SonarQube Project Key");
                Console.WriteLine("  2) SonarQube Project Name");
                Console.WriteLine("  3) SonarQube Project Version");
                Console.WriteLine("  4) Dump folder path");
                return 1;
            }

            var dumpFolderPath = args[3];

            var projects = ProjectLoader.LoadFrom(dumpFolderPath);
            var contents = PropertiesWriter.ToString(new ConsoleLogger(includeTimestamp: true), args[0], args[1], args[2], projects);

            File.WriteAllText(Path.Combine(dumpFolderPath, "sonar-project.properties"), contents, Encoding.ASCII);

            return 0;
        }
    }
}

Include timestamp in generated logs

Include timestamp in generated logs


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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")]

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

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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")]

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

Increase node agent version in preperation for the release


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AxeSoftware.Quest;

namespace EditorControllerTests
{
    [TestClass]
    public class TemplateTests
    {
        [TestMethod]
        public void TestTemplates()
        {
            string folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Substring(6).Replace("/", @"\");
            string templateFolder = System.IO.Path.Combine(folder, @"..\..\..\WorldModel\WorldModel\Core");
            Dictionary<string, string> templates = EditorController.GetAvailableTemplates(templateFolder);

            foreach (string template in templates.Values)
            {
                string tempFile = System.IO.Path.GetTempFileName();

                EditorController.CreateNewGameFile(tempFile, template, "Test");
                EditorController controller = new EditorController();
                string errorsRaised = string.Empty;

                controller.ShowMessage += (string message) =>
                {
                    errorsRaised += message;
                };

                bool result = controller.Initialise(tempFile, templateFolder);

                Assert.IsTrue(result, string.Format("Initialisation failed for template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised));
                Assert.AreEqual(0, errorsRaised.Length, string.Format("Error loading game with template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised));

                System.IO.File.Delete(tempFile);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AxeSoftware.Quest;

namespace EditorControllerTests
{
    [TestClass]
    public class TemplateTests
    {
        [TestMethod]
        public void TestTemplates()
        {
            string folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Substring(6).Replace("/", @"\");
            string templateFolder = System.IO.Path.Combine(folder, @"..\..\..\..\WorldModel\WorldModel\Core");
            Dictionary<string, string> templates = EditorController.GetAvailableTemplates(templateFolder);

            foreach (string template in templates.Values)
            {
                string tempFile = System.IO.Path.GetTempFileName();

                EditorController.CreateNewGameFile(tempFile, template, "Test");
                EditorController controller = new EditorController();
                string errorsRaised = string.Empty;

                controller.ShowMessage += (string message) =>
                {
                    errorsRaised += message;
                };

                bool result = controller.Initialise(tempFile, templateFolder);

                Assert.IsTrue(result, string.Format("Initialisation failed for template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised));
                Assert.AreEqual(0, errorsRaised.Length, string.Format("Error loading game with template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised));

                System.IO.File.Delete(tempFile);
            }
        }
    }
}

Fix unit tests, not sure why file paths have changed?


using System.IO;
using System.Threading.Tasks;

namespace TestCaseAutomator.TeamFoundation
{
	/// <summary>
	/// Represents a TFS source controlled file.
	/// </summary>
	public class TfsFile : TfsSourceControlledItem
	{
		/// <summary>
		/// Initializes a new <see cref="TfsFile"/>.
		/// </summary>
		/// <param name="fileItem">The source controlled file</param>
		/// <param name="versionControl">TFS source control</param>
		public TfsFile(IVersionedItem fileItem, IVersionControl versionControl)
			: base(fileItem, versionControl)
		{
		}

		/// <summary>
		/// Downloads a file to a given file path.
		/// </summary>
		/// <param name="path">The local path to download to</param>
		public async Task DownloadToAsync(string path)
		{
			var downloadStream = Download();

			var directoryPath = Path.GetDirectoryName(path);
			if (!Directory.Exists(directoryPath))
				Directory.CreateDirectory(directoryPath);

			using (var fileStream = File.OpenWrite(path))
				await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false);
		}
	}
}

using System.IO;
using System.Threading.Tasks;

namespace TestCaseAutomator.TeamFoundation
{
	/// <summary>
	/// Represents a TFS source controlled file.
	/// </summary>
	public class TfsFile : TfsSourceControlledItem
	{
		/// <summary>
		/// Initializes a new <see cref="TfsFile"/>.
		/// </summary>
		/// <param name="fileItem">The source controlled file</param>
		/// <param name="versionControl">TFS source control</param>
		public TfsFile(IVersionedItem fileItem, IVersionControl versionControl)
			: base(fileItem, versionControl)
		{
		}

		/// <summary>
		/// Downloads a file to a given file path.
		/// </summary>
		/// <param name="path">The local path to download to</param>
		public async Task DownloadToAsync(string path)
		{
			var directoryPath = Path.GetDirectoryName(path);
			if (!Directory.Exists(directoryPath))
				Directory.CreateDirectory(directoryPath);

            using (var downloadStream = Download())
			using (var fileStream = File.OpenWrite(path))
				await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false);
		}
	}
}

Put download stream in using statement (doesn't seem to have any effect though).