using System;

namespace StrangerData.Utils
{
    internal static class RandomValues
    {
        public static object ForColumn(TableColumnInfo columnInfo)
        {
            switch (columnInfo.ColumnType)
            {
                case ColumnType.String:
                    // generates a random string
                    return Any.String(columnInfo.MaxLength);
                case ColumnType.Int:
                    // generates a random integer
                    long maxValue = (int)Math.Pow(10, columnInfo.Precision - 1);
                    if (maxValue > int.MaxValue)
                    {
                        return Any.Long(1, maxValue);
                    }
                    return Any.Int(1, (int)maxValue);
                case ColumnType.Decimal:
                    // generates a random decimal
                    return Any.Double(columnInfo.Precision, columnInfo.Scale);
                case ColumnType.Double:
                    // generates a random double
                    return Any.Double(columnInfo.Precision, columnInfo.Scale);
                case ColumnType.Long:
                    // generates a random long
                    return Any.Long(1, (int)Math.Pow(10, columnInfo.Precision - 1));
                case ColumnType.Boolean:
                    // generates a random boolean
                    return Any.Boolean();
                case ColumnType.Guid:
                    // generates a random guid
                    return Guid.NewGuid();
                case ColumnType.Date:
                    // generates a random date
                    return Any.DateTime().Date;
                case ColumnType.Datetime:
                    // generates a random DateTime
                    return Any.DateTime();
                default:
                    return null;
            }
        }
    }
}

using System;

namespace StrangerData.Utils
{
    internal static class RandomValues
    {
        public static object ForColumn(TableColumnInfo columnInfo)
        {
            try
            {
                return GenerateForColumn(columnInfo);
            }
            catch (Exception ex)
            {
                throw new Exception($"Could not generate value for column Name=[{columnInfo.Name}] Type=[{columnInfo.ColumnType}]", ex);
            }
        }

        private static object GenerateForColumn(TableColumnInfo columnInfo)
        {
            switch (columnInfo.ColumnType)
            {
                case ColumnType.String:
                    // generates a random string
                    return Any.String(columnInfo.MaxLength);
                case ColumnType.Int:
                    // generates a random integer
                    long maxValue = (int)Math.Pow(10, columnInfo.Precision - 1);
                    if (maxValue > int.MaxValue)
                    {
                        return Any.Long(1, maxValue);
                    }
                    return Any.Int(1, (int)maxValue);
                case ColumnType.Decimal:
                    // generates a random decimal
                    return Any.Double(columnInfo.Precision, columnInfo.Scale);
                case ColumnType.Double:
                    // generates a random double
                    return Any.Double(columnInfo.Precision, columnInfo.Scale);
                case ColumnType.Long:
                    // generates a random long
                    return Any.Long(1, (int)Math.Pow(10, columnInfo.Precision - 1));
                case ColumnType.Boolean:
                    // generates a random boolean
                    return Any.Boolean();
                case ColumnType.Guid:
                    // generates a random guid
                    return Guid.NewGuid();
                case ColumnType.Date:
                    // generates a random date
                    return Any.DateTime().Date;
                case ColumnType.Datetime:
                    // generates a random DateTime
                    return Any.DateTime();
                default:
                    return null;
            }
        }
    }
}

Add error handling generating random values to inform column name and type


namespace Stranne.VasttrafikNET.Models
{
    /// <summary>
    /// Describes a coordinate in WGS84 decimal
    /// </summary>
    public class Coordinate
    {
        /// <summary>
        /// Latitude in WGS84 decimal form
        /// </summary>
        public double Latitude { get; set; }

        /// <summary>
        /// Longitude in WGS84 decimal form
        /// </summary>
        public double Longitude { get; set; }
    }
}

namespace Stranne.VasttrafikNET.Models
{
    /// <summary>
    /// Describes a coordinate in WGS84 decimal
    /// </summary>
    public class Coordinate
    {
        /// <summary>
        /// Latitude in WGS84 decimal form
        /// </summary>
        public double Latitude { get; set; }

        /// <summary>
        /// Longitude in WGS84 decimal form
        /// </summary>
        public double Longitude { get; set; }

        /// <summary>
        /// Create a new coordinate.
        /// </summary>
        public Coordinate()
        { }

        /// <summary>
        /// Create a coordinate with latitude and longitude pre defined.
        /// </summary>
        /// <param name="latitude">Latitude in WGS84 decimal form</param>
        /// <param name="longitude">Longitude in WGS84 decimal form</param>
        public Coordinate(double latitude, double longitude)
        {
            Latitude = latitude;
            Longitude = longitude;
        }
    }
}

Add constructor with parameters for coordinate

Make it possible to create a defined coordinate with less code.


using System;
using System.Linq;

namespace Rock.Messaging.Routing
{
    public class AppDomainTypeLocator : ITypeLocator
    {
        private readonly IMessageParser _messageParser;
        private readonly AppDomain _appDomain;

        public AppDomainTypeLocator(IMessageParser messageParser, AppDomain appDomain = null)
        {
            _messageParser = messageParser;
            _appDomain = appDomain ?? AppDomain.CurrentDomain;
        }

        public Type GetMessageType(string typeName)
        {
            return
               (from a in _appDomain.GetAssemblies()
                from t in a.GetTypes()
                where !t.IsAbstract && _messageParser.GetTypeName(t) == typeName
                select t).Single();
        }

        public Type GetMessageHandlerType(Type messageType)
        {
            return
               (from a in _appDomain.GetAssemblies()
                from t in a.GetTypes()
                where !t.IsAbstract
                from i in t.GetInterfaces()
                where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMessageHandler<>) && i.GetGenericArguments()[0] == messageType
                select t).Single();
        }
    }
}

using System;
using System.Linq;
using Rock.Reflection;

namespace Rock.Messaging.Routing
{
    public class AppDomainTypeLocator : ITypeLocator
    {
        private readonly IMessageParser _messageParser;
        private readonly AppDomain _appDomain;

        public AppDomainTypeLocator(IMessageParser messageParser, AppDomain appDomain = null)
        {
            _messageParser = messageParser;
            _appDomain = appDomain ?? AppDomain.CurrentDomain;
        }

        public Type GetMessageType(string typeName)
        {
            return
               (from a in _appDomain.GetAssemblies()
                from t in a.GetTypesSafely()
                where !t.IsAbstract && _messageParser.GetTypeName(t) == typeName
                select t).Single();
        }

        public Type GetMessageHandlerType(Type messageType)
        {
            return
               (from a in _appDomain.GetAssemblies()
                from t in a.GetTypesSafely()
                where !t.IsAbstract
                from i in t.GetInterfaces()
                where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMessageHandler<>) && i.GetGenericArguments()[0] == messageType
                select t).Single();
        }
    }
}

Call GetTypesSafely extension method instead of GetTypes method.


using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BTCPayServer.Filters
{
    public class XFrameOptionsAttribute : Attribute, IActionFilter
    {
        public XFrameOptionsAttribute(string value)
        {
            Value = value;
        }
        public string Value
        {
            get; set;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            context.HttpContext.Response.SetHeaderOnStarting("X-Frame-Options", Value);
        }
    }
}

using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BTCPayServer.Filters
{
    public class XFrameOptionsAttribute : Attribute, IActionFilter
    {
        public XFrameOptionsAttribute(string value)
        {
            Value = value;
        }
        public string Value
        {
            get; set;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.IsEffectivePolicy<XFrameOptionsAttribute>(this))
            {
                context.HttpContext.Response.SetHeaderOnStarting("X-Frame-Options", Value);
            }
        }
    }
}

Remove XFrame on the checkout page

Remove XFrame on the checkout page


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Ao3tracksync.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Work
    {
        public long userid { get; set; }
        public long id { get; set; }
        public long chapterid { get; set; }
        public long number { get; set; }
        public long timestamp { get; set; }
        public Nullable<long> location { get; set; }

        public virtual User User { get; set; }
    }
}

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Ao3tracksync.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Work
    {
        public long userid { get; set; }
        public long id { get; set; }
        public long chapterid { get; set; }
        public long number { get; set; }
        public long timestamp { get; set; }
        public long? location { get; set; }

        public virtual User User { get; set; }
    }
}

Use ? instead of Nullable

Use ? instead of Nullable


using System;
using System.Threading;
using NUnit.Framework;

namespace JustSaying.TestingFramework
{
    public static class Patiently
    {
        public static void VerifyExpectation(Action expression)
        {
            VerifyExpectation(expression, 5.Seconds());
        }

        public static void VerifyExpectation(Action expression, TimeSpan timeout)
        {
            bool hasTimedOut;
            var started = DateTime.Now;
            do
            {
                try
                {
                    expression.Invoke();
                    return;
                }
                catch { }
                hasTimedOut = timeout < DateTime.Now - started;
                Thread.Sleep(TimeSpan.FromMilliseconds(50));
                Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds);
            } while (!hasTimedOut);
            expression.Invoke();
        }

        public static void AssertThat(Func<bool> func)
        {
            AssertThat(func, 10.Seconds());
        }

        public static void AssertThat(Func<bool> func, TimeSpan timeout)
        {
            bool result;
            bool hasTimedOut;
            var started = DateTime.Now;
            do
            {
                result = func.Invoke();
                hasTimedOut = timeout < DateTime.Now - started;
                Thread.Sleep(TimeSpan.FromMilliseconds(50));
                Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds);
            } while (!result && !hasTimedOut);

            Assert.True(result);
        }
    }
    public static class Extensions
    {
        public static TimeSpan Seconds(this int seconds)
        {
            return TimeSpan.FromSeconds(seconds);
        }
    }
}

using System;
using System.Threading;
using NUnit.Framework;

namespace JustSaying.TestingFramework
{
    public static class Patiently
    {
        public static void VerifyExpectation(Action expression)
        {
            VerifyExpectation(expression, 5.Seconds());
        }

        public static void VerifyExpectation(Action expression, TimeSpan timeout)
        {
            bool hasTimedOut;
            var started = DateTime.Now;
            do
            {
                try
                {
                    expression.Invoke();
                    return;
                }
                catch { }
                hasTimedOut = timeout < DateTime.Now - started;
                Thread.Sleep(TimeSpan.FromMilliseconds(50));
                Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds);
            } while (!hasTimedOut);
            expression.Invoke();
        }

        public static void AssertThat(Func<bool> func)
        {
            AssertThat(func, 5.Seconds());
        }

        public static void AssertThat(Func<bool> func, TimeSpan timeout)
        {
            bool result;
            bool hasTimedOut;
            var started = DateTime.Now;
            do
            {
                result = func.Invoke();
                hasTimedOut = timeout < DateTime.Now - started;
                Thread.Sleep(TimeSpan.FromMilliseconds(50));
                Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds);
            } while (!result && !hasTimedOut);

            Assert.True(result);
        }
    }
    public static class Extensions
    {
        public static TimeSpan Seconds(this int seconds)
        {
            return TimeSpan.FromSeconds(seconds);
        }
    }
}

Revert "Increase the maximum time we wait for long running tests from 5 to 10."

This reverts commit 65ad52c26cbdee036e616b61263c214abf3b8a27.


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

namespace MediaManager.Media
{
    public abstract class MediaExtractorBase : IMediaExtractor
    {
        public virtual async Task<IMediaItem> CreateMediaItem(string url)
        {
            var mediaItem = new MediaItem(url);
            mediaItem.MediaLocation = GetMediaLocation(mediaItem);
            return await ExtractMetadata(mediaItem);
        }

        public virtual async Task<IMediaItem> CreateMediaItem(FileInfo file)
        {
            var mediaItem = new MediaItem(file.FullName);
            mediaItem.MediaLocation = GetMediaLocation(mediaItem);
            return await ExtractMetadata(mediaItem);
        }

        public virtual async Task<IMediaItem> CreateMediaItem(IMediaItem mediaItem)
        {
            mediaItem.MediaLocation = GetMediaLocation(mediaItem);
            return await ExtractMetadata(mediaItem);
        }

        public virtual Task<object> RetrieveMediaItemArt(IMediaItem mediaItem)
        {
            return null;
        }

        public abstract Task<IMediaItem> ExtractMetadata(IMediaItem mediaItem);

        public virtual MediaLocation GetMediaLocation(IMediaItem mediaItem)
        {
            if (mediaItem.MediaUri.StartsWith("http")) return MediaLocation.Remote;
            if (mediaItem.MediaUri.StartsWith("file")
                || mediaItem.MediaUri.StartsWith("/")
                || mediaItem.MediaUri.Length > 1 && mediaItem.MediaUri[1] == ':') return MediaLocation.FileSystem;

            return MediaLocation.Unknown;
        }
    }
}

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

namespace MediaManager.Media
{
    public abstract class MediaExtractorBase : IMediaExtractor
    {
        public virtual async Task<IMediaItem> CreateMediaItem(string url)
        {
            var mediaItem = new MediaItem(url);
            mediaItem.MediaLocation = GetMediaLocation(mediaItem);
            return await ExtractMetadata(mediaItem);
        }

        public virtual async Task<IMediaItem> CreateMediaItem(FileInfo file)
        {
            var mediaItem = new MediaItem(file.FullName);
            mediaItem.MediaLocation = GetMediaLocation(mediaItem);
            return await ExtractMetadata(mediaItem);
        }

        public virtual async Task<IMediaItem> CreateMediaItem(IMediaItem mediaItem)
        {
            mediaItem.MediaLocation = GetMediaLocation(mediaItem);
            return await ExtractMetadata(mediaItem);
        }

        public virtual Task<object> RetrieveMediaItemArt(IMediaItem mediaItem)
        {
            return null;
        }

        public abstract Task<IMediaItem> ExtractMetadata(IMediaItem mediaItem);

        public virtual MediaLocation GetMediaLocation(IMediaItem mediaItem)
        {
            if (mediaItem.MediaUri.StartsWith("http")) return MediaLocation.Remote;
            if (mediaItem.MediaUri.StartsWith("file")
                || mediaItem.MediaUri.StartsWith("/")
                || (mediaItem.MediaUri.Length > 1 && mediaItem.MediaUri[1] == ':')) return MediaLocation.FileSystem;

            return MediaLocation.Unknown;
        }
    }
}

Add parentheses within the conditional AND and OR expressions to declare the operator precedence


@model IEnumerable<alert_roster.web.Models.Message>

@{
    ViewBag.Title = "Messages";
}

@ViewBag.Title

@foreach (var message in Model)
{

                @message.Content

}

@model IEnumerable<alert_roster.web.Models.Message>

@{
    ViewBag.Title = "Messages";
}

@ViewBag.Title

@foreach (var message in Model)
{

            <fieldset>
                <legend>

                </legend>

                @message.Content
            </fieldset>

}

Use fieldset instead of div

Use fieldset instead of div


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

namespace LodViewProvider {

	public enum AggregationType {
		Min = 0,
		Max = 1,
		Sum = 2,
		Count = 3,
		Average = 4,
		// group by
		// order by
	}

	public class Aggregation : ICondition	{

		public string Variable { get; private set; }
		public AggregationType AggregationType { get; private set; }

		public Aggregation( string variable, AggregationType aggregationType ) {
			Variable = variable;
			AggregationType = aggregationType;
		}

		public override string ToString() {
			var strBuild = new StringBuilder();

			switch ( AggregationType ) {
				case LodViewProvider.AggregationType.Average: {

				} break;
				case LodViewProvider.AggregationType.Count: {

				} break;
				case LodViewProvider.AggregationType.Max: {

				} break;
				case LodViewProvider.AggregationType.Min: {

				} break;
				default: {
					throw new InvalidAggregationTypeException();
				} break;
			}

			return strBuild.ToString();
		}
	}

	public class InvalidAggregationTypeException : Exception {
	}
}

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

namespace LodViewProvider {

	public enum AggregationType {
		Min = 0,
		Max = 1,
		Sum = 2,
		Count = 3,
		Average = 4,
		// group by
		// order by
	}

	public class Aggregation : ICondition	{

		public string Variable { get; private set; }
		public AggregationType AggregationType { get; private set; }

		public Aggregation( string variable, AggregationType aggregationType ) {
			Variable = variable.Trim( '\"' );
			AggregationType = aggregationType;
		}

		public override string ToString() {
			var strBuild = new StringBuilder();

			switch ( AggregationType ) {
				case LodViewProvider.AggregationType.Average: {

				} break;
				case LodViewProvider.AggregationType.Count: {

				} break;
				case LodViewProvider.AggregationType.Max: {

				} break;
				case LodViewProvider.AggregationType.Min: {

				} break;
				default: {
					throw new InvalidAggregationTypeException();
				} break;
			}

			return strBuild.ToString();
		}
	}

	public class InvalidAggregationTypeException : Exception {
	}
}

Trim un-necessarry char from aggregation variable


using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Controllers
{
    [Authorize, ApiExplorerSettings(IgnoreApi = true)]
    public class SSDController : Controller
    {
        private readonly Database db;

        public SSDController(Database db)
        {
            this.db = db;
        }

        public async Task<IActionResult> Index(SoldierSearchService.Query query)
        {
            // Ensure we're only displaying Soldiers we care about here

            query.OnlyEnlisted = true;

            return View("List", await SoldierSearchService.Filter(db, query));
        }

        [HttpPost]
        public async Task<IActionResult> Update(int soldierId, SSD ssd, decimal completion)
        {
            // Take the models and pull the updated data

            var soldier = await SoldiersController.Get(db, soldierId);

            soldier
                .SSDSnapshots
                .Add(new Soldier.SSDSnapshot
                {
                    SSD = ssd,
                    PerecentComplete = completion / 100 // Convert to decimal percentage
                });

            await db.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }
    }
}

using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Controllers
{
    [Authorize, ApiExplorerSettings(IgnoreApi = true)]
    public class SSDController : Controller
    {
        private readonly Database db;

        public SSDController(Database db)
        {
            this.db = db;
        }

        public async Task<IActionResult> Index(SoldierSearchService.Query query)
        {
            // Ensure we're only displaying Soldiers we care about here

            if (!query.Ranks.Any()) query.OnlyEnlisted = true;

            return View("List", await SoldierSearchService.Filter(db, query));
        }

        [HttpPost]
        public async Task<IActionResult> Update(int soldierId, SSD ssd, decimal completion)
        {
            // Take the models and pull the updated data

            var soldier = await SoldiersController.Get(db, soldierId);

            soldier
                .SSDSnapshots
                .Add(new Soldier.SSDSnapshot
                {
                    SSD = ssd,
                    PerecentComplete = completion / 100 // Convert to decimal percentage
                });

            await db.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }
    }
}

Fix for SSD rank filtering

Fix for SSD rank filtering


namespace LiteNetLibManager
{
    public class WebSocketTransportFactory : BaseTransportFactory
    {
        public override bool CanUseWithWebGL { get { return false; } }

        public override ITransport Build()
        {
            return new WebSocketTransport();
        }
    }
}

namespace LiteNetLibManager
{
    public class WebSocketTransportFactory : BaseTransportFactory
    {
        public override bool CanUseWithWebGL { get { return true; } }

        public override ITransport Build()
        {
            return new WebSocketTransport();
        }
    }
}

Add check is transport work with webGL or not at transport factory


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

namespace NuGetGallery
{
    public class WebMatrixPackageCurator : AutomaticPackageCurator
    {
        public override void Curate(
            Package galleryPackage,
            IPackage nugetPackage)
        {
            var curatedFeed = GetService<ICuratedFeedByNameQuery>().Execute("webmatrix");
            if (curatedFeed == null)
            {
                return;
            }

            if (!galleryPackage.IsLatestStable)
            {
                return;
            }

            var shouldBeIncluded = galleryPackage.Tags != null && galleryPackage.Tags.ToLowerInvariant().Contains("aspnetwebpages");

            if (!shouldBeIncluded)
            {
                shouldBeIncluded = true;
                foreach (var file in nugetPackage.GetFiles())
                {
                    var fi = new FileInfo(file.Path);
                    if (fi.Extension == ".ps1" || fi.Extension == ".t4")
                    {
                        shouldBeIncluded = false;
                        break;
                    }
                }
            }

            if (shouldBeIncluded && DependenciesAreCurated(galleryPackage, curatedFeed))
            {
                GetService<ICreateCuratedPackageCommand>().Execute(
                    curatedFeed.Key,
                    galleryPackage.PackageRegistration.Key,
                    automaticallyCurated: true);
            }
        }
    }
}

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

namespace NuGetGallery
{
    public class WebMatrixPackageCurator : AutomaticPackageCurator
    {
        public override void Curate(
            Package galleryPackage,
            IPackage nugetPackage)
        {
            var curatedFeed = GetService<ICuratedFeedByNameQuery>().Execute("webmatrix", includePackages: true);
            if (curatedFeed == null)
            {
                return;
            }

            if (!galleryPackage.IsLatestStable)
            {
                return;
            }

            var shouldBeIncluded = galleryPackage.Tags != null && galleryPackage.Tags.ToLowerInvariant().Contains("aspnetwebpages");

            if (!shouldBeIncluded)
            {
                shouldBeIncluded = true;
                foreach (var file in nugetPackage.GetFiles())
                {
                    var fi = new FileInfo(file.Path);
                    if (fi.Extension == ".ps1" || fi.Extension == ".t4")
                    {
                        shouldBeIncluded = false;
                        break;
                    }
                }
            }

            if (shouldBeIncluded && DependenciesAreCurated(galleryPackage, curatedFeed))
            {
                GetService<ICreateCuratedPackageCommand>().Execute(
                    curatedFeed.Key,
                    galleryPackage.PackageRegistration.Key,
                    automaticallyCurated: true);
            }
        }
    }
}

Fix the null reference exception coming from AutomaticPackageCurator when curatedFeed has been loaded without including Packages.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;

namespace NHibernate.Test.Linq.ByMethod
{
	[TestFixture]
	public class AnyTests : LinqTestCase
	{
        [Test]
        public void AnySublist()
        {
            var orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Quantity == 5)).ToList();
            Assert.AreEqual(61, orders.Count);

            orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Order == null)).ToList();
            Assert.AreEqual(0, orders.Count);
        }

        [Test]
        public void NestedAny()
        {
            var test = (from c in db.Customers
                       where c.ContactName == "Bob" &&
                                 (c.CompanyName == "NormalooCorp" ||
                                  c.Orders.Any(o => o.OrderLines.Any(ol => ol.Discount < 20 && ol.Discount >= 10)))
                       select c).ToList();
            Assert.AreEqual(0, test.Count);
        }
	}
}

using System.Linq;
using NUnit.Framework;

namespace NHibernate.Test.Linq.ByMethod
{
	[TestFixture]
	public class AnyTests : LinqTestCase
	{
		[Test]
		public void AnySublist()
		{
			var orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Quantity == 5)).ToList();
			Assert.AreEqual(61, orders.Count);

			orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Order == null)).ToList();
			Assert.AreEqual(0, orders.Count);
		}

		[Test]
		public void NestedAny()
		{
			var test = (from c in db.Customers
									where c.ContactName == "Bob" &&
														(c.CompanyName == "NormalooCorp" ||
														 c.Orders.Any(o => o.OrderLines.Any(ol => ol.Discount < 20 && ol.Discount >= 10)))
									select c).ToList();
			Assert.AreEqual(0, test.Count);
		}

		[Test]
		public void ManyToManyAny()
		{
			var test = db.Orders.Where(o => o.Employee.FirstName == "test");
			var result = test.Where(o => o.Employee.Territories.Any(t => t.Description == "test")).ToList();

			Assert.AreEqual(0, result.Count);
		}
	}
}

Test for NH-2559 (does not fail)

Test for NH-2559 (does not fail)

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@5835


namespace testproj
{
    using System;

    using JetBrains.dotMemoryUnit;

    using NUnit.Framework;

    [TestFixture]
    public class UnitTest1
    {
        [Test]
        public void TestMethod1()
        {
            dotMemory.Check(
                memory =>
                {
                    var str1 = "1";
                    var str2 = "2";
                    var str3 = "3";
                    Assert.LessOrEqual(2, memory.ObjectsCount);
                    Console.WriteLine(str1 + str2 + str3);
                });
        }
    }
}

namespace testproj
{
    using System;
    using System.Collections.Generic;

    using JetBrains.dotMemoryUnit;

    using NUnit.Framework;

    [TestFixture]
    public class UnitTest1
    {
        [Test]
        public void TestMethod1()
        {
            var strs = new List<string>();
            var memoryCheckPoint = dotMemory.Check();
            strs.Add(GenStr());
            strs.Add(GenStr());
            strs.Add(GenStr());

            dotMemory.Check(
                memory =>
                {
                    var strCount = memory
                        .GetDifference(memoryCheckPoint)
                        .GetNewObjects()
                        .GetObjects(i => i.Type == typeof(string))
                        .ObjectsCount;

                    Assert.LessOrEqual(strCount, 2);
                });

            strs.Clear();
        }

        [Test]
        public void TestMethod2()
        {
            var strs = new List<string>();
            var memoryCheckPoint = dotMemory.Check();
            strs.Add(GenStr());
            strs.Add(GenStr());

            dotMemory.Check(
                memory =>
                {
                    var strCount = memory
                        .GetDifference(memoryCheckPoint)
                        .GetNewObjects()
                        .GetObjects(i => i.Type == typeof(string))
                        .ObjectsCount;

                    Assert.LessOrEqual(strCount, 2);
                });

            strs.Clear();
        }

        private static string GenStr()
        {
            return Guid.NewGuid().ToString();
        }
    }
}

Add broken test to testproj

Add broken test to testproj


using System;
using System.IO;
using System.Security.Cryptography;

namespace Tutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("You must provide the name of a file to read and the name of a file to write.");
                return;
            }

            var sourceFilename = args[0];
            var destinationFilename = args[1];

            using (var sourceStream = File.OpenRead(sourceFilename))
            using (var destinationStream = File.Create(destinationFilename))
            using (var provider = new AesCryptoServiceProvider())
            using (var cryptoTransform = provider.CreateEncryptor())
            using (var cryptoStream = new CryptoStream(destinationStream, cryptoTransform, CryptoStreamMode.Write))
            {
                destinationStream.Write(provider.IV, 0, provider.IV.Length);
                sourceStream.CopyTo(cryptoStream);
                Console.WriteLine(System.Convert.ToBase64String(provider.Key));
            }
        }
    }
}

using System;
using System.IO;
using System.Security.Cryptography;

namespace Tutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("You must provide the name of a file to read and the name of a file to write.");
                return;
            }

            var sourceFilename = args[0];
            var destinationFilename = args[1];

            using (var sourceStream = File.OpenRead(sourceFilename))
            using (var destinationStream = File.Create(destinationFilename))
            using (var provider = new AesCryptoServiceProvider())
            using (var cryptoTransform = provider.CreateEncryptor())
            using (var cryptoStream = new CryptoStream(destinationStream, cryptoTransform, CryptoStreamMode.Write))
            {
                sourceStream.CopyTo(cryptoStream);
            }
        }
    }
}

Remove steps from part 1 that have been moved to part 2.


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

using NUnit.Framework;
using osu.Framework.Graphics.Primitives;
using osuTK;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace osu.Framework.Tests.Primitives
{
    [TestFixture]
    class TriangleTest
    {
        [TestCaseSource(typeof(AreaTestData), nameof(AreaTestData.TestCases))]
        [DefaultFloatingPointTolerance(0.1f)]
        public float TestArea(Triangle testTriangle) => testTriangle.AreaNew;

        private class AreaTestData
        {
            public static IEnumerable TestCases
            {
                get
                {
                    // Point
                    yield return new TestCaseData(new Triangle(Vector2.Zero, Vector2.Zero, Vector2.Zero)).Returns(0);

                    // Angled
                    yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, 0), new Vector2(10))).Returns(50);
                    yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(0, 10), new Vector2(10))).Returns(50);
                    yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, -10), new Vector2(10))).Returns(100);
                    yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, -10), new Vector2(10))).Returns(100);
                }
            }
        }
    }
}

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

using NUnit.Framework;
using osu.Framework.Graphics.Primitives;
using osuTK;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace osu.Framework.Tests.Primitives
{
    [TestFixture]
    class TriangleTest
    {
        [TestCaseSource(typeof(AreaTestData), nameof(AreaTestData.TestCases))]
        [DefaultFloatingPointTolerance(0.1f)]
        public float TestArea(Triangle testTriangle) => testTriangle.Area;

        private class AreaTestData
        {
            public static IEnumerable TestCases
            {
                get
                {
                    // Point
                    yield return new TestCaseData(new Triangle(Vector2.Zero, Vector2.Zero, Vector2.Zero)).Returns(0);

                    // Angled
                    yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, 0), new Vector2(10))).Returns(50);
                    yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(0, 10), new Vector2(10))).Returns(50);
                    yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, -10), new Vector2(10))).Returns(100);
                    yield return new TestCaseData(new Triangle(Vector2.Zero, new Vector2(10, -10), new Vector2(10))).Returns(100);
                }
            }
        }
    }
}

Fix the called parameter being incorrect


using Foundation;
using Internationalization.Core.Helpers;

namespace Internationalization.Touch.Helpers
{
	public class AppInfo : IAppInfo
    {
		public string CurrentLanguage => NSLocale.CurrentLocale.CountryCode.ToLower();
	}
}

using Foundation;
using Internationalization.Core.Helpers;

namespace Internationalization.Touch.Helpers
{
	public class AppInfo : IAppInfo
    {
		public string CurrentLanguage
        {
            get
            {
                return NSLocale.CurrentLocale.LanguageCode.ToLower();
            }
        }
	}
}

Fix code to return LanguageCode not CountryCode


using System.Net;
using System.Net.Sockets;
using System.Text;

namespace NMaier.SimpleDlna.Server.Ssdp
{
  internal sealed class Datagram
  {

    public readonly IPEndPoint EndPoint;
    public readonly string Message;
    public readonly bool Sticky;

    public Datagram(IPEndPoint aEndPoint, string aMessage, bool sticky)
    {
      EndPoint = aEndPoint;
      Message = aMessage;
      Sticky = sticky;
      SendCount = 0;
    }

    public uint SendCount
    {
      get;
      private set;
    }

    public void Send(int port)
    {
      using (var udp = new UdpClient(port, AddressFamily.InterNetwork)) {
        var msg = Encoding.ASCII.GetBytes(Message);
        udp.Send(msg, msg.Length, EndPoint);
      }
      ++SendCount;
    }
  }
}

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using NMaier.SimpleDlna.Utilities;

namespace NMaier.SimpleDlna.Server.Ssdp
{
  internal sealed class Datagram : Logging
  {

    public readonly IPEndPoint EndPoint;
    public readonly string Message;
    public readonly bool Sticky;

    public Datagram(IPEndPoint aEndPoint, string aMessage, bool sticky)
    {
      EndPoint = aEndPoint;
      Message = aMessage;
      Sticky = sticky;
      SendCount = 0;
    }

    public uint SendCount
    {
      get;
      private set;
    }

    public void Send(int port)
    {
      var msg = Encoding.ASCII.GetBytes(Message);
      foreach (var external in IP.ExternalAddresses) {
        try {
          var client = new UdpClient(new IPEndPoint(external, port));
          client.BeginSend(msg, msg.Length, EndPoint, SendCallback, client);
        }
        catch (Exception ex) {
          Error(ex);
        }
      }
      ++SendCount;
    }

    private void SendCallback(IAsyncResult result)
    {
      using (var client = result.AsyncState as UdpClient) {
        try {
          client.EndSend(result);
        }
        catch (Exception ex) {
          Error(ex);
        }
      }
    }
  }
}

Send SSDP UDP Packets out on all external IPs explicitly


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

using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Input.Events;
using osuTK;

namespace osu.Game.Tournament.Screens.Ladder
{
    public class LadderDragContainer : Container
    {
        protected override bool OnDragStart(DragStartEvent e) => true;

        public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;

        private Vector2 target;

        private float scale = 1;

        protected override bool ComputeIsMaskedAway(RectangleF maskingBounds) => false;

        protected override void OnDrag(DragEvent e)
        {
            this.MoveTo(target += e.Delta, 1000, Easing.OutQuint);
        }

        private const float min_scale = 0.6f;
        private const float max_scale = 1.4f;

        protected override bool OnScroll(ScrollEvent e)
        {
            var newScale = Math.Clamp(scale + e.ScrollDelta.Y / 15 * scale, min_scale, max_scale);

            this.MoveTo(target -= e.MousePosition * (newScale - scale), 2000, Easing.OutQuint);
            this.ScaleTo(scale = newScale, 2000, Easing.OutQuint);

            return true;
        }
    }
}

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

using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Input.Events;
using osuTK;

namespace osu.Game.Tournament.Screens.Ladder
{
    public class LadderDragContainer : Container
    {
        protected override bool OnDragStart(DragStartEvent e) => true;

        public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;

        private Vector2 target;

        private float scale = 1;

        protected override bool ComputeIsMaskedAway(RectangleF maskingBounds) => false;

        public override bool UpdateSubTreeMasking(Drawable source, RectangleF maskingBounds) => false;

        protected override void OnDrag(DragEvent e)
        {
            this.MoveTo(target += e.Delta, 1000, Easing.OutQuint);
        }

        private const float min_scale = 0.6f;
        private const float max_scale = 1.4f;

        protected override bool OnScroll(ScrollEvent e)
        {
            var newScale = Math.Clamp(scale + e.ScrollDelta.Y / 15 * scale, min_scale, max_scale);

            this.MoveTo(target -= e.MousePosition * (newScale - scale), 2000, Easing.OutQuint);
            this.ScaleTo(scale = newScale, 2000, Easing.OutQuint);

            return true;
        }
    }
}

Fix dragging tournament ladder too far causing it to disappear


using UnityEngine;
using System.Collections;
using System;

public class LightDiminuer : MonoBehaviour {

	public float intensity = 15;
	public float intensityRate = 0.001F;
	public float ambientIntensity = 3;
	public float torchNoiseRange = 1;

	private GameObject player;
	private Light playerLight;
	private Light ambientPlayerLight;

	// Use this for initialization
	void Awake () {
		player = GameObject.FindGameObjectWithTag ("Player");

		playerLight = GameObject.FindGameObjectWithTag ("PlayerLight").GetComponent<Light>();
		playerLight.intensity = 0;
		playerLight.range = 15;

		ambientPlayerLight = GameObject.FindGameObjectWithTag ("AmbientPlayerLight").GetComponent<Light>();
		ambientPlayerLight.intensity = 0;
	}

	// Update is called once per frame
	void Update () {
		if (playerLight.intensity == 0) {
			ambientPlayerLight.intensity = ambientIntensity;
		} else {
			playerLight.intensity -= intensityRate;
		}
		if (playerLight.intensity < 2F && ambientPlayerLight.intensity < ambientIntensity) {
			ambientPlayerLight.intensity += intensityRate;
		}

		if (Input.GetKey (KeyCode.L)) {
			playerLight.intensity = intensity;
		}
	}
}

using UnityEngine;
using System.Collections;
using System;

public class LightDiminuer : MonoBehaviour {

	public float intensity = 15;
	public float intensityRate = 0.001F;
	public float ambientIntensity = 3;
	public float torchNoiseRange = 1;
	public bool lightOn = false;

	private GameObject player;
	private Light playerLight;
	private Light ambientPlayerLight;

	// Use this for initialization
	void Awake () {
		player = GameObject.FindGameObjectWithTag ("Player");

		playerLight = GameObject.FindGameObjectWithTag ("PlayerLight").GetComponent<Light>();
		playerLight.intensity = 0;
		playerLight.range = 15;

		ambientPlayerLight = GameObject.FindGameObjectWithTag ("AmbientPlayerLight").GetComponent<Light>();
		ambientPlayerLight.intensity = 0;
	}

	// Update is called once per frame
	void Update () {
		if (playerLight.intensity == 0) {
			ambientPlayerLight.intensity = ambientIntensity;
		} else {
			playerLight.intensity -= intensityRate;
		}
		if (playerLight.intensity < 2F && ambientPlayerLight.intensity < ambientIntensity) {
			ambientPlayerLight.intensity += intensityRate;
		}

		if (Input.GetKey (KeyCode.L) && !lightOn) {
			lightOn = true;
			playerLight.intensity = intensity;
		}
	}
}

Set only just one torch

Set only just one torch


using System;
using System.Collections.Generic;

public class MultipleDelegate
{
    private readonly Dictionary<int, Func<int, int>> _delegates = new Dictionary<int, Func<int, int>>();
    private Type _typeOf;
    private int _pos = 0;

    public int Suscribe(Func<int, int> item)
    {
        _delegates.Add(_pos, item);
        return _pos++;
    }

    public void Unsuscribe(int key)
    {
        _delegates.Remove(key);
    }

    public void Empty()
    {
        _delegates.Clear();
    }

    public void Execute(int value)
    {
        foreach (var item in _delegates)
        {
            var func = item.Value;
            func(value);
        }
    }
}

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

public class MultipleDelegate
{
    private readonly List<Func<int, int>> _delegates = new List<Func<int, int>>();
    private Type _typeOf;
    private int _pos = 0;

    public int Suscribe(Func<int, int> item)
    {
        _delegates.Add(item);
        return 0;
    }

    public void Empty()
    {
        _delegates.Clear();
    }

    public void Execute(int value)
    {
        foreach (var func in _delegates)
        {
            func(value);
        }
    }
}

Switch to list instead of Dictionnary

Switch to list instead of Dictionnary


using Oxide.Core.Libraries;
using Oxide.Core.Logging;

namespace Oxide.Ext.Lua.Libraries
{
    /// <summary>
    /// A global library containing game-agnostic Lua utilities
    /// </summary>
    public class LuaGlobal : Library
    {
        /// <summary>
        /// Returns if this library should be loaded into the global namespace
        /// </summary>
        public override bool IsGlobal => true;

        /// <summary>
        /// Gets the logger that this library writes to
        /// </summary>
        public Logger Logger { get; private set; }

        /// <summary>
        /// Initializes a new instance of the LuaGlobal library
        /// </summary>
        /// <param name="logger"></param>
        public LuaGlobal(Logger logger)
        {
            Logger = logger;
        }

        /// <summary>
        /// Prints a message
        /// </summary>
        /// <param name="args"></param>
        [LibraryFunction("print")]
        public void Print(params object[] args)
        {
            if (args.Length == 1)
            {
                Logger.Write(LogType.Info, args[0]?.ToString() ?? "null");
            }
            else
            {
                var message = string.Empty;
                for (var i = 0; i <= args.Length; ++i)
                {
                    if (i > 0) message += "\t";
                    message += args[i]?.ToString() ?? "null";
                }
                Logger.Write(LogType.Info, message);
            }
        }
    }
}

using Oxide.Core.Libraries;
using Oxide.Core.Logging;

namespace Oxide.Ext.Lua.Libraries
{
    /// <summary>
    /// A global library containing game-agnostic Lua utilities
    /// </summary>
    public class LuaGlobal : Library
    {
        /// <summary>
        /// Returns if this library should be loaded into the global namespace
        /// </summary>
        public override bool IsGlobal => true;

        /// <summary>
        /// Gets the logger that this library writes to
        /// </summary>
        public Logger Logger { get; private set; }

        /// <summary>
        /// Initializes a new instance of the LuaGlobal library
        /// </summary>
        /// <param name="logger"></param>
        public LuaGlobal(Logger logger)
        {
            Logger = logger;
        }

        /// <summary>
        /// Prints a message
        /// </summary>
        /// <param name="args"></param>
        [LibraryFunction("print")]
        public void Print(params object[] args)
        {
            if (args.Length == 1)
            {
                Logger.Write(LogType.Info, args[0]?.ToString() ?? "null");
            }
            else
            {
                var message = string.Empty;
                for (var i = 0; i < args.Length; ++i)
                {
                    if (i > 0) message += "\t";
                    message += args[i]?.ToString() ?? "null";
                }
                Logger.Write(LogType.Info, message);
            }
        }
    }
}

Fix array out of index issue @neico

[Lua] Fix array out of index issue @neico


using System.Diagnostics;
using System.Windows.Input;
using DesktopWidgets.Helpers;
using DesktopWidgets.WidgetBase;
using DesktopWidgets.WidgetBase.ViewModel;
using GalaSoft.MvvmLight.Command;

namespace DesktopWidgets.Widgets.Search
{
    public class ViewModel : WidgetViewModelBase
    {
        private string _searchText;

        public ViewModel(WidgetId id) : base(id)
        {
            Settings = id.GetSettings() as Settings;
            if (Settings == null)
                return;
            Go = new RelayCommand(GoExecute);
            OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
        }

        public Settings Settings { get; }

        public ICommand Go { get; set; }
        public ICommand OnKeyUp { get; set; }

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (_searchText != value)
                {
                    _searchText = value;
                    RaisePropertyChanged(nameof(SearchText));
                }
            }
        }

        private void GoExecute()
        {
            var searchText = SearchText;
            SearchText = string.Empty;
            Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}");
        }

        private void OnKeyUpExecute(KeyEventArgs args)
        {
            if (args.Key == Key.Enter)
                GoExecute();
        }
    }
}

using System.Diagnostics;
using System.Windows.Input;
using DesktopWidgets.Helpers;
using DesktopWidgets.WidgetBase;
using DesktopWidgets.WidgetBase.ViewModel;
using GalaSoft.MvvmLight.Command;

namespace DesktopWidgets.Widgets.Search
{
    public class ViewModel : WidgetViewModelBase
    {
        private string _searchText;

        public ViewModel(WidgetId id) : base(id)
        {
            Settings = id.GetSettings() as Settings;
            if (Settings == null)
                return;
            Go = new RelayCommand(GoExecute);
            OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
        }

        public Settings Settings { get; }

        public ICommand Go { get; set; }
        public ICommand OnKeyUp { get; set; }

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (_searchText != value)
                {
                    _searchText = value;
                    RaisePropertyChanged(nameof(SearchText));
                }
            }
        }

        private void GoExecute()
        {
            var searchText = SearchText;
            SearchText = string.Empty;
            Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}");

            OnSpecialEvent();
        }

        private void OnKeyUpExecute(KeyEventArgs args)
        {
            if (args.Key == Key.Enter)
                GoExecute();
        }
    }
}

Call widget "Special Event" on "Search" search


using System.Data.Entity;

namespace RWXViewer.Models
{
    public class ObjectPathContext : DbContext
    {
        public ObjectPathContext() : base("ObjectPathContext")
        {

        }

        public DbSet<World> Worlds { get; set; }
        public DbSet<ObjectPathItem> ObjectPathItem { get; set; }
    }
}

using System.Data.Entity;

namespace RWXViewer.Models
{
    public class ObjectPathContext : DbContext
    {
        public ObjectPathContext() : base("ObjectPathDb")
        {

        }

        public DbSet<World> Worlds { get; set; }
        public DbSet<ObjectPathItem> ObjectPathItem { get; set; }
    }
}

Change the Db name for the object context.


namespace HtmlLogger.Model
{
    public enum LogCategory
    {
        Info,
        Warning,
        Error
    }
}

namespace HtmlLogger.Model
{
    public enum LogCategory
    {
        Info,
        Warning,
        Danger
    }
}

Rename Error category to Danger

Rename Error category to Danger


@inherits UmbracoViewPage<BlockListModel>
@using ContentModels = Umbraco.Web.PublishedModels;
@using Umbraco.Core.Models.Blocks
@{
    if (Model?.Layout == null || !Model.Layout.Any()) { return; }
}
<div class="umb-block-list">
    @foreach (var layout in Model.Layout)
    {
        if (layout?.Udi == null) { continue; }
        var data = layout.Data;
        @Html.Partial("BlockList/" + data.ContentType.Alias, layout)
    }
</div>

@inherits UmbracoViewPage<BlockListModel>
@using Umbraco.Core.Models.Blocks
@{
    if (Model?.Layout == null || !Model.Layout.Any()) { return; }
}
<div class="umb-block-list">
    @foreach (var layout in Model.Layout)
    {
        if (layout?.Udi == null) { continue; }
        var data = layout.Data;
        @Html.Partial("BlockList/Components/" + data.ContentType.Alias, layout)
    }
</div>

Update default rendering partial view

Update default rendering partial view


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

namespace unBand
{
    public static class Telemetry
    {

        public static TelemetryClient Client {get; private set;}

        static Telemetry()
        {
            Client = new TelemetryClient();
            Init();
        }

        private static void Init()
        {
            var props = Properties.Settings.Default;

            if (props.Device == Guid.Empty)
            {
                props.Device = Guid.NewGuid();
                props.Save();

                Client.Context.Session.IsFirst = true;
            }

            Client.Context.Device.Id = props.Device.ToString();
            Client.Context.Session.Id = Guid.NewGuid().ToString();
        }

        /// <summary>
        /// Poor mans enum -> expanded string.
        ///
        /// Once I've been using this for a while I may change this to a pure enum if
        /// spaces in names prove to be annoying for querying / sorting the data
        /// </summary>
        public static class Events
        {
            public const string AppLaunch = "Launch";
            public const string DeclinedFirstRunWarning = "Declined First Run Warning";
            public const string DeclinedTelemetry = "Declined Telemetry";

            public const string ChangeBackground = "Change Background";
            public const string ChangeThemeColor = "Change Theme Color";
        }

    }
}

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

namespace unBand
{
    public static class Telemetry
    {

        public static TelemetryClient Client {get; private set;}

        static Telemetry()
        {
            Client = new TelemetryClient();
            Init();
        }

        private static void Init()
        {
            var props = Properties.Settings.Default;

            if (props.Device == Guid.Empty)
            {
                props.Device = Guid.NewGuid();
                props.Save();

                Client.Context.Session.IsFirst = true;
            }

            Client.Context.Device.Id              = props.Device.ToString();
            Client.Context.Session.Id             = Guid.NewGuid().ToString();
            Client.Context.Device.OperatingSystem = GetOS();
            Client.Context.Device.Language        = System.Globalization.CultureInfo.InstalledUICulture.TwoLetterISOLanguageName;
            Client.Context.Component.Version      = About.Current.Version;
        }

        private static string GetOS()
        {
            return Environment.OSVersion.VersionString + "(" +
                (Environment.Is64BitOperatingSystem ? "x64" : "x86") + ")";
        }

        /// <summary>
        /// Poor mans enum -> expanded string.
        ///
        /// Once I've been using this for a while I may change this to a pure enum if
        /// spaces in names prove to be annoying for querying / sorting the data
        /// </summary>
        public static class Events
        {
            public const string AppLaunch = "Launch";
            public const string DeclinedFirstRunWarning = "Declined First Run Warning";
            public const string DeclinedTelemetry = "Declined Telemetry";

            public const string ChangeBackground = "Change Background";
            public const string ChangeThemeColor = "Change Theme Color";
        }

    }
}

Add OS and Version information to telemetry


using System.Collections.Generic;
using System.Threading.Tasks;
using Flurl.Http;
using ProGet.Net.Common;
using ProGet.Net.PackagePromotion.Models;

// ReSharper disable CheckNamespace

namespace ProGet.Net
{
    public partial class ProGetClient
    {
        private IFlurlClient GetPackagePromotionApiClient(string path, object queryParamValues = null) => GetApiClient("/api/promotions")
            .AppendPathSegment(path)
            .SetQueryParams(queryParamValues, Flurl.NullValueHandling.NameOnly)
            .ConfigureClient(settings => settings.OnError = ErrorHandler);

        public async Task<IEnumerable<Promotion>> PackagePromotion_ListPromotionsAsync(string fromFeed, string toFeed, string groupName, string packageName, string version)
        {
            var queryParamValues = QueryParamValues.From(
                new NamedValue(nameof(fromFeed), fromFeed),
                new NamedValue(nameof(toFeed), toFeed),
                new NamedValue(nameof(groupName), groupName),
                new NamedValue(nameof(packageName), packageName),
                new NamedValue(nameof(version), version)
            );

            return await GetPackagePromotionApiClient("list", queryParamValues)
                .GetJsonAsync<IEnumerable<Promotion>>();
        }

        public async Task<bool> PackagePromotion_PromotePackageAsync(PackagePromotionContents packagePromotion)
        {
            var response = await GetPackagePromotionApiClient("promote")
                .PostJsonAsync(packagePromotion);

            return response.IsSuccessStatusCode;
        }
    }
}

using System.Collections.Generic;
using System.Threading.Tasks;
using Flurl.Http;
using ProGet.Net.Common;
using ProGet.Net.PackagePromotion.Models;

// ReSharper disable CheckNamespace

namespace ProGet.Net
{
    public partial class ProGetClient
    {
        private IFlurlClient GetPackagePromotionApiClient(string path, object queryParamValues = null) => GetApiClient("/api/promotions")
            .AppendPathSegment(path)
            .SetQueryParams(queryParamValues, Flurl.NullValueHandling.NameOnly)
            .ConfigureClient(settings => settings.OnError = ErrorHandler);

        public async Task<IEnumerable<Promotion>> PackagePromotion_ListPromotionsAsync(string fromFeed, string toFeed, string groupName, string packageName, string version)
        {
            var queryParamValues = QueryParamValues.From(
                new NamedValue(nameof(fromFeed), fromFeed),
                new NamedValue(nameof(toFeed), toFeed),
                new NamedValue(nameof(groupName), groupName),
                new NamedValue(nameof(packageName), packageName),
                new NamedValue(nameof(version), version)
            );

            return await GetPackagePromotionApiClient("list", queryParamValues)
                .GetJsonAsync<IEnumerable<Promotion>>();
        }

        public async Task<bool> PackagePromotion_PromotePackageAsync(PackagePromotionContents packagePromotion)
        {
            var response = await GetPackagePromotionApiClient("promote")
                .WithHeader("X-ApiKey", _apiKey)
                .PostJsonAsync(packagePromotion);

            return response.IsSuccessStatusCode;
        }
    }
}

Add X-ApiKey header to promote API.

Add X-ApiKey header to promote API.


using System;
using System.Linq;
using System.Reflection;

namespace Scrutor
{
    public class MissingTypeRegistrationException : InvalidOperationException
    {
        public MissingTypeRegistrationException(Type serviceType)
            : base($"Could not find any registered services for type '{GetFriendlyName(serviceType)}'.")
        {
            ServiceType = serviceType;
        }

        public Type ServiceType { get; }

        private static string GetFriendlyName(Type type)
        {
            if (type == typeof(int)) return "int";
            if (type == typeof(short)) return "short";
            if (type == typeof(byte)) return "byte";
            if (type == typeof(bool)) return "bool";
            if (type == typeof(char)) return "char";
            if (type == typeof(long)) return "long";
            if (type == typeof(float)) return "float";
            if (type == typeof(double)) return "double";
            if (type == typeof(decimal)) return "decimal";
            if (type == typeof(string)) return "string";
            if (type == typeof(object)) return "object";

            var typeInfo = type.GetTypeInfo();
            if (typeInfo.IsGenericType) return GetGenericFriendlyName(typeInfo);

            return type.Name;
        }

        private static string GetGenericFriendlyName(TypeInfo typeInfo)
        {
            var argumentNames = typeInfo.GenericTypeArguments.Select(GetFriendlyName).ToArray();

            var baseName = typeInfo.Name.Split('`').First();

            return $"{baseName}<{string.Join(", ", argumentNames)}>";
        }
    }
}

using System;
using Microsoft.Extensions.Internal;

namespace Scrutor
{
    public class MissingTypeRegistrationException : InvalidOperationException
    {
        public MissingTypeRegistrationException(Type serviceType)
            : base($"Could not find any registered services for type '{TypeNameHelper.GetTypeDisplayName(serviceType)}'.")
        {
            ServiceType = serviceType;
        }

        public Type ServiceType { get; }
    }
}

Use TypeNameHelper instead of private method


using NUnit.Framework;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web.Routing;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.template;

namespace Umbraco.Tests.Routing
{
	[TestFixture]
	public class LookupByAliasTests : BaseRoutingTest
	{
		public override void Initialize()
		{
			base.Initialize();
			Umbraco.Core.Configuration.UmbracoSettings.UseLegacyXmlSchema = false;
		}

		/// <summary>
		/// We don't need a db for this test, will run faster without one
		/// </summary>
		protected override bool RequiresDbSetup
		{
			get { return false; }
		}

		[TestCase("/this/is/my/alias", 1046)]
		[TestCase("/anotheralias", 1046)]
		[TestCase("/page2/alias", 1173)]
		[TestCase("/2ndpagealias", 1173)]
		[TestCase("/only/one/alias", 1174)]
		[TestCase("/ONLY/one/Alias", 1174)]
		public void Lookup_By_Url_Alias(string urlAsString, int nodeMatch)
		{
			var routingContext = GetRoutingContext(urlAsString);
			var url = routingContext.UmbracoContext.CleanedUmbracoUrl; //very important to use the cleaned up umbraco url
			var docRequest = new PublishedContentRequest(url, routingContext);
			var lookup = new LookupByAlias();

			var result = lookup.TrySetDocument(docRequest);

			Assert.IsTrue(result);
			Assert.AreEqual(docRequest.DocumentId, nodeMatch);
		}
	}
}

using NUnit.Framework;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web.Routing;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.template;

namespace Umbraco.Tests.Routing
{
	[TestFixture]
	public class LookupByAliasTests : BaseRoutingTest
	{
		public override void Initialize()
		{
			base.Initialize();
			Umbraco.Core.Configuration.UmbracoSettings.UseLegacyXmlSchema = false;
		}

		[TestCase("/this/is/my/alias", 1046)]
		[TestCase("/anotheralias", 1046)]
		[TestCase("/page2/alias", 1173)]
		[TestCase("/2ndpagealias", 1173)]
		[TestCase("/only/one/alias", 1174)]
		[TestCase("/ONLY/one/Alias", 1174)]
		public void Lookup_By_Url_Alias(string urlAsString, int nodeMatch)
		{
			var routingContext = GetRoutingContext(urlAsString);
			var url = routingContext.UmbracoContext.CleanedUmbracoUrl; //very important to use the cleaned up umbraco url
			var docRequest = new PublishedContentRequest(url, routingContext);
			var lookup = new LookupByAlias();

			var result = lookup.TrySetDocument(docRequest);

			Assert.IsTrue(result);
			Assert.AreEqual(docRequest.DocumentId, nodeMatch);
		}
	}
}

Fix routing tests, we DO need a database for these


namespace SupermarketChain.Client.Console
{
    using System;
    using System.Linq;

    using SupermarketChain.Data.SqlServer;
    using SupermarketChain.Model;
    using SupermarketChain.Data.SqlServer.Repositories;

    class Program
    {
        static void Main(string[] args)
        {
            // Testing SupermarketChainDbContext
            var dbContext = new SupermarketChainDbContext();
            Console.WriteLine(dbContext.Vendors.FirstOrDefault(v => v.Name == "Kamenitza").Name);

            Console.WriteLine(dbContext.Vendors.FirstOrDefault(v => v.Name == "Amstel").Name);
            Console.WriteLine(dbContext.Vendors.Find(2).Name);            // Testing repository
            var dbVendors = new Repository<Vendor>();
            dbVendors.Add(new Vendor { Name = "Zagorka" });
            dbVendors.SaveChanges();
        }
    }
}

namespace SupermarketChain.Client.Console
{
    using System;
    using System.Linq;

    using SupermarketChain.Data.SqlServer;
    using SupermarketChain.Model;
    using SupermarketChain.Data.SqlServer.Repositories;

    class Program
    {
        static void Main(string[] args)
        {
            // Testing SupermarketChainDbContext
            var dbContext = new SupermarketChainDbContext();
            Console.WriteLine(dbContext.Vendors.FirstOrDefault(v => v.Name == "Kamenitza").Name);
            Console.WriteLine(dbContext.Vendors.FirstOrDefault(v => v.Name == "Kamenitza").Name);
            Console.WriteLine(dbContext.Vendors.Find(2).Name);

            // Testing repository
            var dbVendors = new Repository<Vendor>();
            dbVendors.Add(new Vendor { Name = "Zagorka" });
            dbVendors.SaveChanges();
        }
    }
}

Fix an error with console client test

Fix an error with console client test


using System;
using System.Threading;

namespace Depends
{
    public delegate void ProgressBarIncrementer();

    public class Progress
    {
        private long _total = 0;
        private ProgressBarIncrementer _progBarIncr;
        private long _workMultiplier = 1;

        public static Progress NOPProgress()
        {
            ProgressBarIncrementer pbi = () => { return; };
            return new Progress(pbi, 1L);
        }

        public Progress(ProgressBarIncrementer progBarIncrement, long workMultiplier)
        {
            _progBarIncr = progBarIncrement;
            _workMultiplier = workMultiplier;
        }

        public long TotalWorkUnits
        {
            get { return _total; }
            set { _total = value; }
        }

        public long UpdateEvery
        {
            get { return Math.Max(1L, _total / 100L / _workMultiplier); }
        }

        public void IncrementCounter()
        {
            _progBarIncr();
        }
    }
}

using System;
using System.Threading;

namespace Depends
{
    public delegate void ProgressBarIncrementer();

    public class Progress
    {
        private bool _cancelled = false;
        private long _total = 0;
        private ProgressBarIncrementer _progBarIncr;
        private long _workMultiplier = 1;

        public static Progress NOPProgress()
        {
            ProgressBarIncrementer pbi = () => { return; };
            return new Progress(pbi, 1L);
        }

        public Progress(ProgressBarIncrementer progBarIncrement, long workMultiplier)
        {
            _progBarIncr = progBarIncrement;
            _workMultiplier = workMultiplier;
        }

        public long TotalWorkUnits
        {
            get { return _total; }
            set { _total = value; }
        }

        public long UpdateEvery
        {
            get { return Math.Max(1L, _total / 100L / _workMultiplier); }
        }

        public void IncrementCounter()
        {
            _progBarIncr();
        }

        public void Cancel()
        {
            _cancelled = true;
        }

        public bool IsCancelled()
        {
            return _cancelled;
        }
    }
}

Add cancellation field to progress object.


using System;
using System.Globalization;

namespace MultiMiner.Win.Extensions
{
    static class DateTimeExtensions
    {
        public static string ToReallyShortDateString(this DateTime dateTime)
        {
            //short date no year
            string shortDateValue = dateTime.ToShortDateString();
            int lastIndex = shortDateValue.LastIndexOf(CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator);
            return shortDateValue.Remove(lastIndex);
        }
    }
}

using System;
using System.Globalization;

namespace MultiMiner.Win.Extensions
{
    public static class DateTimeExtensions
    {
        public static string ToReallyShortDateString(this DateTime dateTime)
        {
            //short date no year
            string shortDateString = dateTime.ToShortDateString();

            //year could be at beginning (JP) or end (EN)
            string dateSeparator = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator;
            string value1 = dateTime.Year + dateSeparator;
            string value2 = dateSeparator + dateTime.Year;

            return shortDateString.Replace(value1, String.Empty).Replace(value2, String.Empty);
        }
    }
}

Fix formatting of dates when the year comes first (JP)


using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Talagozis.Website.Controllers
{
    public abstract class BaseController : Controller
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            this.ViewBag.startTime = DateTime.Now;
            this.ViewBag.AssemblyVersion = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Version.ToString() ?? string.Empty;

            base.OnActionExecuting(context);
        }
    }
}

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Talagozis.Website.Controllers
{
    public abstract class BaseController : Controller
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            this.ViewBag.startTime = DateTime.Now;
            this.ViewBag.AssemblyVersion = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Version?.ToString() ?? string.Empty;

            base.OnActionExecuting(context);
        }
    }
}

Fix issue on possible null reference.

Fix issue on possible null reference.


namespace Parsley
{
    public sealed class CharLexer : Lexer
    {
        public CharLexer(string source)
            : this(new Text(source)) { }

        public CharLexer(Text text)
            : base(text, new TokenMatcher(typeof(char), @".")) { }
    }
}

namespace Parsley
{
    public sealed class CharLexer : Lexer
    {
        public CharLexer(string source)
            : base(new Text(source), new TokenMatcher(typeof(char), @".")) { }
    }
}

Simplify AbstractGrammarSpec by replacing deprecated helper methods with a sample Lexer implementation


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

using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.ProjectModel.Graph;

namespace Microsoft.DotNet.Watcher.Core.Internal
{
    internal class Project : IProject
    {
        public Project(ProjectModel.Project runtimeProject)
        {
            ProjectFile = runtimeProject.ProjectFilePath;
            ProjectDirectory = runtimeProject.ProjectDirectory;

            Files = runtimeProject.Files.SourceFiles.Concat(
                    runtimeProject.Files.ResourceFiles.Values.Concat(
                    runtimeProject.Files.PreprocessSourceFiles.Concat(
                    runtimeProject.Files.SharedFiles))).Concat(
                    new string[] { runtimeProject.ProjectFilePath })
                .ToList();

            var projectLockJsonPath = Path.Combine(runtimeProject.ProjectDirectory, "project.lock.json");

            if (File.Exists(projectLockJsonPath))
            {
                var lockFile = LockFileReader.Read(projectLockJsonPath, designTime: false);
                ProjectDependencies = lockFile.ProjectLibraries.Select(dep => GetProjectRelativeFullPath(dep.Path)).ToList();
            }
            else
            {
                ProjectDependencies = new string[0];
            }
        }

        public IEnumerable<string> ProjectDependencies { get; private set; }

        public IEnumerable<string> Files { get; private set; }

        public string ProjectFile { get; private set; }

        public string ProjectDirectory { get; private set; }

        private string GetProjectRelativeFullPath(string path)
        {
            return Path.GetFullPath(Path.Combine(ProjectDirectory, path));
        }
    }
}

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

using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.ProjectModel.Graph;

namespace Microsoft.DotNet.Watcher.Core.Internal
{
    internal class Project : IProject
    {
        public Project(ProjectModel.Project runtimeProject)
        {
            ProjectFile = runtimeProject.ProjectFilePath;
            ProjectDirectory = runtimeProject.ProjectDirectory;

            Files = runtimeProject.Files.SourceFiles.Concat(
                    runtimeProject.Files.ResourceFiles.Values.Concat(
                    runtimeProject.Files.PreprocessSourceFiles.Concat(
                    runtimeProject.Files.SharedFiles))).Concat(
                    new string[] { runtimeProject.ProjectFilePath })
                .ToList();

            var projectLockJsonPath = Path.Combine(runtimeProject.ProjectDirectory, "project.lock.json");

            if (File.Exists(projectLockJsonPath))
            {
                var lockFile = LockFileReader.Read(projectLockJsonPath);
                ProjectDependencies = lockFile.ProjectLibraries.Select(dep => GetProjectRelativeFullPath(dep.Path)).ToList();
            }
            else
            {
                ProjectDependencies = new string[0];
            }
        }

        public IEnumerable<string> ProjectDependencies { get; private set; }

        public IEnumerable<string> Files { get; private set; }

        public string ProjectFile { get; private set; }

        public string ProjectDirectory { get; private set; }

        private string GetProjectRelativeFullPath(string path)
        {
            return Path.GetFullPath(Path.Combine(ProjectDirectory, path));
        }
    }
}

Revert "Reacting to CLI breaking change"

This reverts commit 4788506b57c736c7d54f4c05fd2c3b1cbe620a10.


using System;
using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Formatting.Json;

namespace Experimentation.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var env = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}";

            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

            Log.Logger = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .MinimumLevel.Debug()
                .WriteTo.RollingFile(new JsonFormatter(), "Logs/log-{Date}.json")
                .CreateLogger();

            try
            {
                Log.Information("Firing up the experimentation api...");
                BuildWebHost(args, builder).Run();
            }
            catch (Exception e)
            {
                Log.Fatal(e, "Api  terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        private static IWebHost BuildWebHost(string[] args, IConfiguration builder) =>
            WebHost.CreateDefaultBuilder(args)
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseApplicationInsights()
                .UseConfiguration(builder)
                .Build();
    }
}

using System;
using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Formatting.Json;

namespace Experimentation.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                var env = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}";

                var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env}.json", optional: true)
                    .AddEnvironmentVariables()
                    .Build();

                Log.Logger = new LoggerConfiguration()
                    .Enrich.FromLogContext()
                    .MinimumLevel.Debug()
                    .WriteTo.RollingFile(new JsonFormatter(), "Logs/log-{Date}.json")
                    .CreateLogger();

                Log.Information("Firing up the experimentation api...");
                BuildWebHost(args, builder).Run();
            }
            catch (Exception e)
            {
                Log.Fatal(e, "Api  terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        private static IWebHost BuildWebHost(string[] args, IConfiguration builder) =>
            WebHost.CreateDefaultBuilder(args)
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseApplicationInsights()
                .UseConfiguration(builder)
                .Build();
    }
}

Move set-up and config code into t/c/f block - this will handle 'unhandled exeptions' that hapen outside of the OWIN pipeline.


using Autofac;
using System.Management.Automation;

namespace PoshGit2.Cmdlets
{
    public class DICmdlet : Cmdlet
    {
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            PoshGit2Container.Instance.InjectUnsetProperties(this);
        }
    }
}

using Autofac;
using System;
using System.Management.Automation;

namespace PoshGit2.Cmdlets
{
    public class DICmdlet : PSCmdlet, IDisposable
    {
        private readonly ILifetimeScope _lifetimeScope;

        public DICmdlet()
        {
            _lifetimeScope = PoshGit2Container.Instance.BeginLifetimeScope(builder =>
           {
               builder.Register<SessionState>(_ => SessionState).AsSelf();
           });
        }

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

            // TODO: This needs to be here for now, otherwise SessionState is not defined yet.
            // TODO: Is this called on each time something is piped through?
            _lifetimeScope.InjectUnsetProperties(this);
        }

        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _lifetimeScope.Dispose();
                }

                disposedValue = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }
    }
}

Use a lifetime scope for resolution

Use a lifetime scope for resolution

This allows us to use SessionState objects


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

namespace PixelPet.Commands {
	internal class DeserializeTilemapCmd : CliCommand {
		public DeserializeTilemapCmd()
			: base("Deserialize-Tilemap") { }

		public override void Run(Workbench workbench, Cli cli) {
			cli.Log("Deserializing tilemap...");

			workbench.Stream.Position = 0;
			workbench.Tilemap = new Tilemap();

			int bpe = 2;		// bytes per tile entry

			byte[] buffer = new byte[bpe];
			while (workbench.Stream.Read(buffer, 0, 2) != bpe) {
				int scrn = buffer[0] | (buffer[1] << 8);

				TileEntry te = new TileEntry() {
					TileNumber = scrn & 0x3FF,
					HFlip = (scrn & (1 << 10)) != 0,
					VFlip = (scrn & (1 << 11)) != 0,
					PaletteNumber = (scrn >> 12) & 0xF
				};

				workbench.Tilemap.TileEntries.Add(te);
			}
		}
	}
}

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

namespace PixelPet.Commands {
	internal class DeserializeTilemapCmd : CliCommand {
		public DeserializeTilemapCmd()
			: base("Deserialize-Tilemap") { }

		public override void Run(Workbench workbench, Cli cli) {
			cli.Log("Deserializing tilemap...");

			workbench.Stream.Position = 0;
			workbench.Tilemap = new Tilemap();

			int bpe = 2;		// bytes per tile entry

			byte[] buffer = new byte[bpe];
			while (workbench.Stream.Read(buffer, 0, 2) == bpe) {
				int scrn = buffer[0] | (buffer[1] << 8);

				TileEntry te = new TileEntry() {
					TileNumber = scrn & 0x3FF,
					HFlip = (scrn & (1 << 10)) != 0,
					VFlip = (scrn & (1 << 11)) != 0,
					PaletteNumber = (scrn >> 12) & 0xF
				};

				workbench.Tilemap.TileEntries.Add(te);
			}
		}
	}
}

Fix loop condition on Deserialize-Tilemap.


using System;
using System.IO;
using Newtonsoft.Json;
using SmartMeter.Business.Extractor;
using SmartMeter.Business.Interface;
using SmartMeter.Business.Interface.Extractor;
using SmartMeter.Business.Interface.Translator;

namespace SmartMeter.Business.Translator {
  public class TranslatorService {
    public void Execute() {
      FileInfo[] extractedFiles = _ListExtractedFiles();

      foreach (FileInfo extractedFile in extractedFiles) {
        try {
          ITranslateFile fileTranslator = new FileTranslator();
          ITelegram telegram = fileTranslator.Translate(extractedFile);
          string serializedTelegram = JsonConvert.SerializeObject(telegram);

          IWriteFile fileWriter = new FileWriter();

          fileWriter
            .WithPath(Path.Combine(Directory.GetDirectoryRoot(AppContext.BaseDirectory), "applicationdata", "smartmeter", "translated"))
            .WithFilename(_CreateFilename(extractedFile))
            .WithContents(serializedTelegram)
            .Write();
        }
        catch (Exception ex) {
          Console.WriteLine($"An error occured while translating file '{extractedFile.FullName}': {ex}");
        }
      }
    }

    private FileInfo[] _ListExtractedFiles() {
      DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(Directory.GetDirectoryRoot(AppContext.BaseDirectory), "applicationdata", "smartmeter", "extracted"));

      //TODO: Filter for specific file extensions to prevent reading uncompleted files
      return directoryInfo.GetFiles();
    }

    private string _CreateFilename(FileInfo extractedFile) {
      return $"{Path.GetFileNameWithoutExtension(extractedFile.Name)}.telegram";
    }
  }
}

using System;
using System.IO;
using Newtonsoft.Json;
using SmartMeter.Business.Extractor;
using SmartMeter.Business.Interface;
using SmartMeter.Business.Interface.Extractor;
using SmartMeter.Business.Interface.Translator;

namespace SmartMeter.Business.Translator {
  public class TranslatorService {
    public void Execute() {
      FileInfo[] extractedFiles = _ListExtractedFiles();

      foreach (FileInfo extractedFile in extractedFiles) {
        try {
          ITranslateFile fileTranslator = new FileTranslator();
          ITelegram telegram = fileTranslator.Translate(extractedFile);
          string serializedTelegram = JsonConvert.SerializeObject(telegram);

          IWriteFile fileWriter = new FileWriter();

          fileWriter
            .WithPath(Path.Combine(Directory.GetDirectoryRoot(AppContext.BaseDirectory), "applicationdata", "smartmeter", "translated"))
            .WithFilename(_CreateFilename(extractedFile))
            .WithContents(serializedTelegram)
            .Write();

          //TODO: Remove extracted file after created translated file
        }
        catch (Exception ex) {
          Console.WriteLine($"An error occured while translating file '{extractedFile.FullName}': {ex}");
        }
      }
    }

    private FileInfo[] _ListExtractedFiles() {
      DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(Directory.GetDirectoryRoot(AppContext.BaseDirectory), "applicationdata", "smartmeter", "extracted"));

      //TODO: Filter for specific file extensions to prevent reading uncompleted files
      return directoryInfo.GetFiles();
    }

    private string _CreateFilename(FileInfo extractedFile) {
      return $"{Path.GetFileNameWithoutExtension(extractedFile.Name)}.telegram";
    }
  }
}

Add TODO to remove extracted file after translating it


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

using Microsoft.MixedReality.Toolkit.Utilities;

namespace Microsoft.MixedReality.Toolkit.Input
{
    public static class HandJointUtils
    {
        /// <summary>
        /// Try to find the first matching hand controller and return the pose of the requested joint for that hand.
        /// </summary>
        public static bool TryGetJointPose(TrackedHandJoint joint, Handedness handedness, out MixedRealityPose pose)
        {
            IMixedRealityHand hand = FindHand(handedness);
            if (hand != null)
            {
                return hand.TryGetJoint(joint, out pose);
            }

            pose = MixedRealityPose.ZeroIdentity;
            return false;
        }

        /// <summary>
        /// Find the first detected hand controller with matching handedness.
        /// </summary>
        public static IMixedRealityHand FindHand(Handedness handedness)
        {
            foreach (var detectedController in MixedRealityToolkit.InputSystem.DetectedControllers)
            {
                var hand = detectedController as IMixedRealityHand;
                if (hand != null)
                {
                    if (detectedController.ControllerHandedness == handedness)
                    {
                        return hand;
                    }
                }
            }
            return null;
        }
    }
}

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

using Microsoft.MixedReality.Toolkit.Utilities;

namespace Microsoft.MixedReality.Toolkit.Input
{
    public static class HandJointUtils
    {
        /// <summary>
        /// Tries to get the the pose of the requested joint for the first controller with the specified handedness.
        /// </summary>
        /// <param name="joint">The requested joint</param>
        /// <param name="handedness">The specific hand of interest. This should be either Handedness.Left or Handedness.Right</param>
        /// <param name="pose">The output pose data</param>
        public static bool TryGetJointPose(TrackedHandJoint joint, Handedness handedness, out MixedRealityPose pose)
        {
            IMixedRealityHand hand = FindHand(handedness);
            if (hand != null)
            {
                return hand.TryGetJoint(joint, out pose);
            }

            pose = MixedRealityPose.ZeroIdentity;
            return false;
        }

        /// <summary>
        /// Find the first detected hand controller with matching handedness.
        /// </summary>
        /// <remarks>
        /// The given handeness should be either Handedness.Left or Handedness.Right.
        /// </remarks>
        public static IMixedRealityHand FindHand(Handedness handedness)
        {
            foreach (var detectedController in MixedRealityToolkit.InputSystem.DetectedControllers)
            {
                var hand = detectedController as IMixedRealityHand;
                if (hand != null)
                {
                    if (detectedController.ControllerHandedness == handedness)
                    {
                        return hand;
                    }
                }
            }
            return null;
        }
    }
}

Update the TryGetJointPose docs to accurately describe the set of inputs it can take.

These functions only work if you pass in the specific Handedness.Left or Handedness.Right. They should be documented as such.


#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using Kooboo.CMS.Sites.Extension.ModuleArea;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kooboo.CMS.Sites.Extension;
using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models;
namespace Kooboo.CMS.ModuleArea.Areas.Empty
{
    [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = SampleAreaRegistration.ModuleName)]
    public class ModuleAction : IModuleAction
    {
        public void OnExcluded(Sites.Models.Site site)
        {
            // Add code here that will be executed when the module was excluded to the site.
        }

        public void OnIncluded(Sites.Models.Site site)
        {
            // Add code here that will be executed when the module was included to the site.
        }

        public void OnInstalling(ControllerContext controllerContext)
        {
            var moduleInfo = ModuleInfo.Get(SampleAreaRegistration.ModuleName);
            var installModel = new InstallModel();
            Kooboo.CMS.Sites.Extension.PagePluginHelper.BindModel<InstallModel>(installModel, controllerContext);

            moduleInfo.DefaultSettings.CustomSettings["DatabaseServer"] = installModel.DatabaseServer;
            moduleInfo.DefaultSettings.CustomSettings["UserName"] = installModel.UserName;
            moduleInfo.DefaultSettings.CustomSettings["Password"] = installModel.Password;
            ModuleInfo.Save(moduleInfo);

            // Add code here that will be executed when the module installing.
        }

        public void OnUninstalling(ControllerContext controllerContext)
        {
            // Add code here that will be executed when the module uninstalling.
        }
    }
}

#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using Kooboo.CMS.Sites.Extension.ModuleArea;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kooboo.CMS.Sites.Extension;
using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models;
namespace Kooboo.CMS.ModuleArea.Areas.Empty
{
    [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = ModuleAreaRegistration.ModuleName)]
    public class ModuleAction : IModuleAction
    {
        public void OnExcluded(Sites.Models.Site site)
        {
            // Add code here that will be executed when the module was excluded to the site.
        }

        public void OnIncluded(Sites.Models.Site site)
        {
            // Add code here that will be executed when the module was included to the site.
        }

        public void OnInstalling(ControllerContext controllerContext)
        {
            // Add code here that will be executed when the module installing.
        }

        public void OnUninstalling(ControllerContext controllerContext)
        {
            // Add code here that will be executed when the module uninstalling.
        }
    }
}

Update the Empty module template.

Update the Empty module template.


using ExoWeb;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using ExoWeb.Templates;
using System.IO;
using System.Linq;

namespace ExoWeb.UnitTests.Server
{
	/// <summary>
	///This is a test class for ExoWebTest and is intended
	///to contain all ExoWebTest Unit Tests
	///</summary>
	[TestClass()]
	public class ExoWebTest
	{
		[TestMethod]
		public void ParseTemplate()
		{
			var templates =
				Directory.GetFiles(@"C:\Users\thomasja\Projects\VC3.TestView\Mainline\VC3.TestView.WebUI\Common\templates", "*.htm").Union(
				Directory.GetFiles(@"C:\Users\thomasja\Projects\VC3.TestView\Mainline\VC3.TestView.WebUI\Common\templates\sections", "*.htm"))
				.Where(p => !p.Contains("Reports.htm"))
				.SelectMany(p => Template.Load(p));

			foreach (var template in templates)
				Console.WriteLine(template);
		}
	}
}

using System;
using System.IO;
using System.Linq;
using ExoWeb.Templates.MicrosoftAjax;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ExoWeb.UnitTests.Server
{
	/// <summary>
	///This is a test class for ExoWebTest and is intended
	///to contain all ExoWebTest Unit Tests
	///</summary>
	[TestClass()]
	public class ExoWebTest
	{
		[TestMethod]
		public void ParseTemplate()
		{
			var templates =
				Directory.GetFiles(@"C:\Users\thomasja\Projects\VC3.TestView\Mainline\VC3.TestView.WebUI\Common\templates", "*.htm").Union(
				Directory.GetFiles(@"C:\Users\thomasja\Projects\VC3.TestView\Mainline\VC3.TestView.WebUI\Common\templates\sections", "*.htm"))
				.Where(p => !p.Contains("Reports.htm"))
				.SelectMany(p => Template.Load(p));

			foreach (var template in templates)
				Console.WriteLine(template);
		}
	}
}

Add using for Template class.

Add using for Template class.


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens.Menu;
using OpenTK;

namespace osu.Game.Screens
{
    public class Loader : OsuScreen
    {
        public override bool ShowOverlays => false;

        public Loader()
        {
            ValidForResume = false;
        }

        protected override void LogoArriving(OsuLogo logo, bool resuming)
        {
            base.LogoArriving(logo, resuming);

            logo.RelativePositionAxes = Axes.Both;
            logo.Triangles = false;
            logo.Position = new Vector2(0.9f);
            logo.Scale = new Vector2(0.2f);

            logo.FadeInFromZero(5000, Easing.OutQuint);
        }

        [BackgroundDependencyLoader]
        private void load(OsuGameBase game)
        {
            if (game.IsDeployedBuild)
                LoadComponentAsync(new Disclaimer(), d => Push(d));
            else
                LoadComponentAsync(new Intro(), d => Push(d));
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens.Menu;
using OpenTK;
using osu.Framework.Screens;

namespace osu.Game.Screens
{
    public class Loader : OsuScreen
    {
        private bool showDisclaimer;

        public override bool ShowOverlays => false;

        public Loader()
        {
            ValidForResume = false;
        }

        protected override void LogoArriving(OsuLogo logo, bool resuming)
        {
            base.LogoArriving(logo, resuming);

            logo.RelativePositionAxes = Axes.None;
            logo.Triangles = false;
            logo.Origin = Anchor.BottomRight;
            logo.Anchor = Anchor.BottomRight;
            logo.Position = new Vector2(-40);
            logo.Scale = new Vector2(0.2f);

            logo.FadeInFromZero(5000, Easing.OutQuint);
        }

        protected override void OnEntering(Screen last)
        {
            base.OnEntering(last);

            if (showDisclaimer)
                LoadComponentAsync(new Disclaimer(), d => Push(d));
            else
                LoadComponentAsync(new Intro(), d => Push(d));
        }

        protected override void LogoSuspending(OsuLogo logo)
        {
            base.LogoSuspending(logo);
            logo.FadeOut(100).OnComplete(l =>
            {
                l.Anchor = Anchor.TopLeft;
                l.Origin = Anchor.Centre;
            });
        }

        [BackgroundDependencyLoader]
        private void load(OsuGameBase game)
        {
            showDisclaimer = game.IsDeployedBuild;
        }
    }
}

Fix loader pushing children screens before it is displayed itself