using ClosedXML.Excel;
using NUnit.Framework;
using System.IO;
using System.Threading;

namespace ClosedXML_Tests.Excel.Globalization
{
    [TestFixture]
    public class GlobalizationTests
    {
        [Test]
        [TestCase("A1*10", "1230")]
        [TestCase("A1/10", "12.3")]
        [TestCase("A1&\" cells\"", "123 cells")]
        [TestCase("A1&\"000\"", "123000")]
        [TestCase("ISNUMBER(A1)", "True")]
        [TestCase("ISBLANK(A1)", "False")]
        [TestCase("DATE(2018,1,28)", "43128")]
        public void LoadFormulaCachedValue(string formula, object expectedValue)
        {
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("ru-RU");

            using (var ms = new MemoryStream())
            {
                using (XLWorkbook book1 = new XLWorkbook())
                {
                    var sheet = book1.AddWorksheet("sheet1");
                    sheet.Cell("A1").Value = 123;
                    sheet.Cell("A2").FormulaA1 = formula;
                    var options = new SaveOptions { EvaluateFormulasBeforeSaving = true };

                    book1.SaveAs(ms, options);
                }
                ms.Position = 0;

                using (XLWorkbook book2 = new XLWorkbook(ms))
                {
                    var ws = book2.Worksheet(1);
                    var storedValueA2 = ws.Cell("A2").ValueCached;
                    Assert.IsTrue(ws.Cell("A2").NeedsRecalculation);
                    Assert.AreEqual(expectedValue, storedValueA2);
                }
            }
        }
    }
}

Add test for persisting cached value under different culture.


// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.LondonTravel.Site.Integration
{
    using System;
    using System.Globalization;
    using System.Net;
    using System.Threading.Tasks;
    using System.Xml;
    using Shouldly;
    using Xunit;

    /// <summary>
    /// A class containing tests for the site map.
    /// </summary>
    public class SiteMapTests : IntegrationTest
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SiteMapTests"/> class.
        /// </summary>
        /// <param name="fixture">The fixture to use.</param>
        public SiteMapTests(HttpServerFixture fixture)
            : base(fixture)
        {
        }

        [Fact]
        public async Task Site_Map_Locations_Are_Valid()
        {
            XmlNodeList locations;

            // Act
            using (var response = await Fixture.Client.GetAsync("sitemap.xml"))
            {
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                string xml = await response.Content.ReadAsStringAsync();
                locations = GetSitemapLocations(xml);
            }

            // Assert
            locations.ShouldNotBeNull();
            locations.Count.ShouldBeGreaterThan(0);

            foreach (XmlNode location in locations)
            {
                string url = location.InnerText;
                Assert.True(Uri.TryCreate(url, UriKind.Absolute, out Uri uri));

                uri.Scheme.ShouldBe("https");
                uri.Port.ShouldBe(443);
                uri.Host.ShouldBe("londontravel.martincostello.com");
                uri.AbsolutePath.ShouldEndWith("/");

                using (var response = await Fixture.Client.GetAsync(uri.PathAndQuery))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }
            }
        }

        private static XmlNodeList GetSitemapLocations(string xml)
        {
            string prefix = "ns";
            string uri = "http://www.sitemaps.org/schemas/sitemap/0.9";

            var sitemap = new XmlDocument();
            sitemap.LoadXml(xml);

            var nsmgr = new XmlNamespaceManager(sitemap.NameTable);
            nsmgr.AddNamespace(prefix, uri);

            string xpath = string.Format(CultureInfo.InvariantCulture, "/{0}:urlset/{0}:url/{0}:loc", prefix);
            return sitemap.SelectNodes(xpath, nsmgr);
        }
    }
}

Add integration test for sitemap.xml

Add integration test for sitemap.xml

Add an integration test for sitemap.xml to test that it contains valid
URLs.
Resolves #124.


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

namespace Meowtrix.osuAMT.Training.DataGenerator
{
    class OszArchive : Archive, IDisposable
    {
        public ZipArchive archive;

        public OszArchive(Stream stream)
        {
            archive = new ZipArchive(stream, ZipArchiveMode.Read, false);
        }

        public void Dispose() => archive.Dispose();

        public override Stream OpenFile(string filename) => archive.GetEntry(filename).Open();

        public override IEnumerable<Stream> OpenOsuFiles() => archive.Entries.Where(x => x.Name.EndsWith(".osz")).Select(e => e.Open());
    }
}

Read file from osz archive.

Read file from osz archive.


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

namespace SimplifiedProtocolTestWpfCore
{
    internal static class IntegrationTest
    {
        public static Task<IntegrationTestResult[]> RunAsync(CancellationToken ct)
        {
            return Task<IntegrationTestResult[]>.Run(() => RunTestCases(testCases, ct));
        }

        private static IntegrationTestResult[] RunTestCases(
            IEnumerable<IntegrationTestCase> localTestCases,
            CancellationToken ct)
        {
            return RunTestCases().ToArray();

            IEnumerable<IntegrationTestResult> RunTestCases()
            {
                foreach (var testCase in localTestCases)
                {
                    if (ct.IsCancellationRequested)
                    {
                        // Return a failed "cancelled" result only if
                        // there were more test cases to work on.
                        yield return new IntegrationTestResult
                        {
                            Success = false,
                            Messages = new List<string> { "Test run cancelled" },
                        };

                        break;
                    }

                    yield return RunTestSafe(testCase);
                }
            }
        }

        private static IntegrationTestResult RunTestSafe(IntegrationTestCase testCase)
        {
            return new IntegrationTestResult
            {
                Success = false,
                TestName = testCase.Name,
                Messages = new List<string> { "No code to run tests yet" },
            };
        }

        private delegate IntegrationTestResult IntegrationTestRunner(string name);

        private struct IntegrationTestCase
        {
            public string Name;
            public IntegrationTestRunner IntegrationTestRunner;
        }

        private static readonly IntegrationTestCase[] testCases =
        {
            new IntegrationTestCase
            {
                Name = "Dummy test",
                IntegrationTestRunner = name => { return new IntegrationTestResult(); },
            },
        };
    }
}

Add foundation of integration test runner


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

namespace Csla.Test.EditableRootList
{
  public class ERitem : BusinessBase<ERitem>
  {
    string _data = string.Empty;
    public string Data
    {
      [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
      get
      {
        CanReadProperty(true);
        return _data;
      }
      [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
      set
      {
        CanWriteProperty(true);
        if (!_data.Equals(value))
        {
          _data = value;
          PropertyHasChanged();
        }
      }
    }

    protected override object GetIdValue()
    {
      return _data;
    }

    private ERitem()
    { /* require use of factory methods */ }

    private ERitem(string data)
    {
      _data = data;
      MarkOld();
    }

    public static ERitem NewItem()
    {
      return new ERitem();
    }

    public static ERitem GetItem(string data)
    {
      return new ERitem(data);
    }

    protected override void DataPortal_Insert()
    {
      ApplicationContext.GlobalContext["DP"] = "Insert";
    }

    protected override void DataPortal_Update()
    {
      ApplicationContext.GlobalContext["DP"] = "Update";
    }

    protected override void DataPortal_DeleteSelf()
    {
      ApplicationContext.GlobalContext["DP"] = "DeleteSelf";
    }

    protected override void DataPortal_Delete(object criteria)
    {
      ApplicationContext.GlobalContext["DP"] = "Delete";
    }
  }
}

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

namespace Csla.Test.EditableRootList
{
  [Serializable]
  public class ERitem : BusinessBase<ERitem>
  {
    string _data = string.Empty;
    public string Data
    {
      [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
      get
      {
        CanReadProperty(true);
        return _data;
      }
      [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
      set
      {
        CanWriteProperty(true);
        if (!_data.Equals(value))
        {
          _data = value;
          PropertyHasChanged();
        }
      }
    }

    protected override object GetIdValue()
    {
      return _data;
    }

    private ERitem()
    { /* require use of factory methods */ }

    private ERitem(string data)
    {
      _data = data;
      MarkOld();
    }

    public static ERitem NewItem()
    {
      return new ERitem();
    }

    public static ERitem GetItem(string data)
    {
      return new ERitem(data);
    }

    protected override void DataPortal_Insert()
    {
      ApplicationContext.GlobalContext["DP"] = "Insert";
    }

    protected override void DataPortal_Update()
    {
      ApplicationContext.GlobalContext["DP"] = "Update";
    }

    protected override void DataPortal_DeleteSelf()
    {
      ApplicationContext.GlobalContext["DP"] = "DeleteSelf";
    }

    protected override void DataPortal_Delete(object criteria)
    {
      ApplicationContext.GlobalContext["DP"] = "Delete";
    }
  }
}

Fix test to use serializable classes now that ERLB clones objects on save.


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Diagnostics.Tracing;
using System.Diagnostics;
using Xunit;
using System;

namespace BasicEventSourceTests
{
    internal class TestUtilities
    {
        /// <summary>
        /// Confirms that there are no EventSources running.
        /// </summary>
        /// <param name="message">Will be printed as part of the Assert</param>
        public static void CheckNoEventSourcesRunning(string message = "")
        {
            var eventSources = EventSource.GetSources();

            string eventSourceNames = "";
            foreach (var eventSource in EventSource.GetSources())
            {
                if (eventSource.Name != "System.Threading.Tasks.TplEventSource"
                   && eventSource.Name != "System.Diagnostics.Eventing.FrameworkEventSource")
                {
                    eventSourceNames += eventSource.Name + " ";
                }
            }

            Debug.WriteLine(message);
            Assert.Equal("", eventSourceNames);
        }
    }
}

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Diagnostics.Tracing;
using System.Diagnostics;
using Xunit;
using System;

namespace BasicEventSourceTests
{
    internal class TestUtilities
    {
        /// <summary>
        /// Confirms that there are no EventSources running.
        /// </summary>
        /// <param name="message">Will be printed as part of the Assert</param>
        public static void CheckNoEventSourcesRunning(string message = "")
        {
            var eventSources = EventSource.GetSources();

            string eventSourceNames = "";
            foreach (var eventSource in EventSource.GetSources())
            {
                if (eventSource.Name != "System.Threading.Tasks.TplEventSource"
                   && eventSource.Name != "System.Diagnostics.Eventing.FrameworkEventSource"
                   && eventSource.Name != "System.Buffers.ArrayPoolEventSource")
                {
                    eventSourceNames += eventSource.Name + " ";
                }
            }

            Debug.WriteLine(message);
            Assert.Equal("", eventSourceNames);
        }
    }
}

Fix EventSource test to be aware of ArrayPoolEventSource


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

using System;
using osu.Framework.Desktop;
using osu.Framework.OS;

namespace SampleGame
{
    public static class Program
    {
        [STAThread]
        public static void Main()
        {
            BasicGameHost host = Host.GetSuitableHost();
            host.Load(new osu.Desktop.SampleGame());
            host.Run();
        }
    }
}

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

using System;
using osu.Framework.Desktop;
using osu.Framework.OS;
using osu.Framework;

namespace SampleGame
{
    public static class Program
    {
        [STAThread]
        public static void Main()
        {
            using (Game game = new osu.Desktop.SampleGame())
            using (BasicGameHost host = Host.GetSuitableHost())
            {
                host.Load(game);
                host.Run();
            }
        }
    }
}

Use using when creating game/host.

Use using when creating game/host.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using MonoGame.Extended.BitmapFonts;

namespace Citysim.Views
{
    public class DebugView : IView
    {
        public void LoadContent(ContentManager content)
        {
        }

        public void Render(SpriteBatch spriteBatch, Citysim game, GameTime gameTime)
        {
            if (!game.debug)
                return; // Debug mode disabled

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Citysim " + Citysim.VERSION);
            sb.AppendLine("Map size " + game.city.world.height + "x" + game.city.world.width);

            spriteBatch.DrawString(game.font, sb, new Vector2(10, 10), Color.Black, 0F, new Vector2(0,0), 0.5F, SpriteEffects.None, 1.0F);
        }

        public void Update(Citysim game, GameTime gameTime)
        {
            // F3 toggles debug mode
            if (KeyboardHelper.IsKeyPressed(Keys.F3))
                game.debug = !game.debug;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using MonoGame.Extended.BitmapFonts;

namespace Citysim.Views
{
    public class DebugView : IView
    {
        public void LoadContent(ContentManager content)
        {
        }

        public void Render(SpriteBatch spriteBatch, Citysim game, GameTime gameTime)
        {
            if (!game.debug)
                return; // Debug mode disabled

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Citysim " + Citysim.VERSION);
            sb.AppendLine("Map size " + game.city.world.height + "x" + game.city.world.width);
            sb.AppendLine("Camera: " + game.camera.position.X + "," + game.camera.position.Y + " [" + game.camera.speed + "]");

            spriteBatch.DrawString(game.font, sb, new Vector2(10, 10), Color.Black, 0F, new Vector2(0,0), 0.5F, SpriteEffects.None, 1.0F);
        }

        public void Update(Citysim game, GameTime gameTime)
        {
            // F3 toggles debug mode
            if (KeyboardHelper.IsKeyPressed(Keys.F3))
                game.debug = !game.debug;
        }
    }
}

Debug view now displays the camera position and speed.


using System.Web;
using MvcMusicStore.Data.Context.Interfaces;

namespace MvcMusicStore.Data.Context
{
    public class ContextManager<TContext> : IContextManager<TContext>
        where TContext : IDbContext, new()
    {
        private string ContextKey = "ContextManager.Context";

        public ContextManager()
        {
            ContextKey = "ContextKey." + typeof(TContext).Name;
        }

        public IDbContext GetContext()
        {
            if (HttpContext.Current.Items[ContextKey] == null)
                HttpContext.Current.Items[ContextKey] = new TContext();
            return HttpContext.Current.Items[ContextKey] as IDbContext;
        }

        public void Finish()
        {
            if (HttpContext.Current.Items[ContextKey] != null)
                (HttpContext.Current.Items[ContextKey] as IDbContext).Dispose();
        }
    }
}

using System.Web;
using MvcMusicStore.Data.Context.Interfaces;

namespace MvcMusicStore.Data.Context
{
    public class ContextManager<TContext> : IContextManager<TContext>
        where TContext : IDbContext, new()
    {
        private readonly string ContextKey;

        public ContextManager()
        {
            ContextKey = "ContextKey." + typeof(TContext).Name;
        }

        public IDbContext GetContext()
        {
            if (HttpContext.Current.Items[ContextKey] == null)
                HttpContext.Current.Items[ContextKey] = new TContext();
            return HttpContext.Current.Items[ContextKey] as IDbContext;
        }

        public void Finish()
        {
            if (HttpContext.Current.Items[ContextKey] != null)
                (HttpContext.Current.Items[ContextKey] as IDbContext).Dispose();
        }
    }
}

Add readonly in ContextKey property

Add readonly in ContextKey property


using EarTrumpet.UI.ViewModels;
using System.Windows;
using System.Windows.Controls;

namespace EarTrumpet.UI.Views
{
    public partial class AppItemView : UserControl
    {
        private AppItemViewModel App => (AppItemViewModel)DataContext;

        public AppItemView()
        {
            InitializeComponent();

            PreviewMouseRightButtonUp += AppVolumeControl_PreviewMouseRightButtonUp;
        }

        private void AppVolumeControl_PreviewMouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ExpandApp();
        }

        private void MuteButton_Click(object sender, RoutedEventArgs e)
        {
            App.IsMuted = !App.IsMuted;
            e.Handled = true;
        }

        public void ExpandApp()
        {
            App.OpenPopup(this);
        }

        private void UserControl_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            App.RefreshDisplayName();
        }
    }
}

using EarTrumpet.UI.ViewModels;
using System.Windows;
using System.Windows.Controls;

namespace EarTrumpet.UI.Views
{
    public partial class AppItemView : UserControl
    {
        private IAppItemViewModel App => (IAppItemViewModel)DataContext;

        public AppItemView()
        {
            InitializeComponent();

            PreviewMouseRightButtonUp += AppVolumeControl_PreviewMouseRightButtonUp;
        }

        private void AppVolumeControl_PreviewMouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ExpandApp();
        }

        private void MuteButton_Click(object sender, RoutedEventArgs e)
        {
            App.IsMuted = !App.IsMuted;
            e.Handled = true;
        }

        public void ExpandApp()
        {
            App.OpenPopup(this);
        }

        private void UserControl_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            App.RefreshDisplayName();
        }
    }
}

Fix cast crash in AppItemView

Fix cast crash in AppItemView


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Anabi.DataAccess.Ef.DbModels
{
    public class AssetDb : BaseEntity
    {
        public string Name { get; set; }

        public int? AddressId { get; set; }

        public virtual AddressDb Address { get; set; }

        public int CategoryId { get; set; }

        public virtual CategoryDb Category { get; set; }

        public string Description { get; set; }

        public int? DecisionId { get; set; }

        public virtual DecisionDb CurrentDecision { get; set; }

        public string Identifier { get; set; }

        public decimal? NecessaryVolume { get; set; }

        public  List<HistoricalStageDb> HistoricalStages { get; set; } =
            new List<HistoricalStageDb>();

        public bool IsDeleted { get; set; }

        public int? NrOfObjects     { get; set; }

        public string MeasureUnit   { get; set; }

        public string Remarks       { get; set; }

        public virtual ICollection<AssetsFileDb> FilesForAsset { get; set; }

        public virtual ICollection<AssetStorageSpaceDb> AssetsStorageSpaces { get; set; }

        public virtual ICollection<AssetDefendantDb> Defendants { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Anabi.DataAccess.Ef.DbModels
{
    public class AssetDb : BaseEntity
    {
        public string Name { get; set; }

        public int? AddressId { get; set; }

        public virtual AddressDb Address { get; set; }

        public int CategoryId { get; set; }

        public virtual CategoryDb Category { get; set; }

        public string Description { get; set; }

        public int? DecisionId { get; set; }

        public virtual DecisionDb CurrentDecision { get; set; }

        public string Identifier { get; set; }

        public decimal? NecessaryVolume { get; set; }

        public  virtual ICollection<HistoricalStageDb> HistoricalStages { get; set; } =
            new Collection<HistoricalStageDb>();

        public bool IsDeleted { get; set; }

        public int? NrOfObjects     { get; set; }

        public string MeasureUnit   { get; set; }

        public string Remarks       { get; set; }

        public virtual ICollection<AssetsFileDb> FilesForAsset { get; set; }

        public virtual ICollection<AssetStorageSpaceDb> AssetsStorageSpaces { get; set; }

        public virtual ICollection<AssetDefendantDb> Defendants { get; set; }
    }
}

Use Collection instead of List for consistency


namespace Winium.Mobile.Connectivity
{
    #region

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

    using Microsoft.Phone.Tools.Deploy.Patched;

    #endregion

    public class Devices
    {
        #region Static Fields

        private static readonly Lazy<Devices> LazyInstance = new Lazy<Devices>(() => new Devices());

        #endregion

        #region Constructors and Destructors

        private Devices()
        {
            this.AvailableDevices = Utils.GetDevices().Where(x => !x.ToString().Equals("Device")).ToList();
        }

        #endregion

        #region Public Properties

        public static Devices Instance
        {
            get
            {
                return LazyInstance.Value;
            }
        }

        #endregion

        #region Properties

        private IEnumerable<DeviceInfo> AvailableDevices { get; set; }

        #endregion

        #region Public Methods and Operators

        public DeviceInfo GetMatchingDevice(string desiredName, bool strict)
        {
            DeviceInfo deviceInfo;
            if (strict)
            {
                deviceInfo =
                    this.AvailableDevices.FirstOrDefault(
                        x => x.ToString().Equals(desiredName, StringComparison.OrdinalIgnoreCase));
            }
            else
            {
                deviceInfo =
                    this.AvailableDevices.FirstOrDefault(
                        x => x.ToString().StartsWith(desiredName, StringComparison.OrdinalIgnoreCase));
            }

            return deviceInfo;
        }

        public bool IsValidDeviceName(string desiredName)
        {
            var deviceInfo = this.GetMatchingDevice(desiredName, true);
            return deviceInfo != null;
        }

        public override string ToString()
        {
            return string.Join("\n", this.AvailableDevices.Select(x => x.ToString()));
        }

        #endregion
    }
}

namespace Winium.Mobile.Connectivity
{
    #region

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

    using Microsoft.Phone.Tools.Deploy.Patched;

    #endregion

    public class Devices
    {
        #region Static Fields

        private static readonly Lazy<Devices> LazyInstance = new Lazy<Devices>(() => new Devices());

        #endregion

        #region Constructors and Destructors

        private Devices()
        {
            this.AvailableDevices = Utils.GetDevices().Where(x => !x.ToString().Equals("Device")).ToList();
        }

        #endregion

        #region Public Properties

        public static Devices Instance
        {
            get
            {
                return LazyInstance.Value;
            }
        }

        #endregion

        #region Properties

        private IEnumerable<DeviceInfo> AvailableDevices { get; set; }

        #endregion

        #region Public Methods and Operators

        public DeviceInfo GetMatchingDevice(string desiredName, bool strict)
        {
            DeviceInfo deviceInfo;

            deviceInfo =
                this.AvailableDevices.FirstOrDefault(
                    x => x.ToString().Equals(desiredName, StringComparison.OrdinalIgnoreCase));

            if (!strict && deviceInfo == null)
            {
                deviceInfo =
                    this.AvailableDevices.FirstOrDefault(
                        x => x.ToString().StartsWith(desiredName, StringComparison.OrdinalIgnoreCase));
            }

            return deviceInfo;
        }

        public bool IsValidDeviceName(string desiredName)
        {
            var deviceInfo = this.GetMatchingDevice(desiredName, true);
            return deviceInfo != null;
        }

        public override string ToString()
        {
            return string.Join("\n", this.AvailableDevices.Select(x => x.ToString()));
        }

        #endregion
    }
}

Change logic for deviceName matching

Change logic for deviceName matching

https://github.com/2gis/winphonedriver/pull/82


using System;

namespace IntegrationEngine.Model
{
    public class CronTrigger : IHasStringId, IIntegrationJobTrigger
    {
        public string Id { get; set; }
        public string JobType { get; set; }
        public string CronExpressionString { get; set; }
        public TimeZoneInfo TimeZone { get; set; }
    }
}

using System;

namespace IntegrationEngine.Model
{
    public class CronTrigger : IHasStringId, IIntegrationJobTrigger
    {
        public string Id { get; set; }
        public string JobType { get; set; }
        public string CronExpressionString { get; set; }
        TimeZoneInfo _timeZone { get; set; }
        public TimeZoneInfo TimeZone { get { return _timeZone ?? TimeZoneInfo.Utc; } set { _timeZone = value; } }
    }
}

Set default time zone to UTC

Set default time zone to UTC


#if !CORE
namespace Nancy.Helpers
{
    using System;
    using System.Reflection;
    using Nancy.Extensions;

    internal class ProxyNancyReferenceProber : MarshalByRefObject
    {
        public bool HasReference(AssemblyName assemblyNameForProbing, AssemblyName referenceAssemblyName)
        {
            var assemblyForInspection = Assembly.Load(assemblyNameForProbing);

            return assemblyForInspection.IsReferencing(referenceAssemblyName);
        }
    }
}
#endif

#if !CORE
namespace Nancy.Helpers
{
    using System;
    using System.Reflection;
    using Nancy.Extensions;

    internal class ProxyNancyReferenceProber : MarshalByRefObject
    {
        public bool HasReference(AssemblyName assemblyNameForProbing, AssemblyName referenceAssemblyName)
        {
            var assemblyForInspection = Assembly.ReflectionOnlyLoad(assemblyNameForProbing.Name);

            return assemblyForInspection.IsReferencing(referenceAssemblyName);
        }
    }
}
#endif

Use ReflectionOnlyLoad() in the remote proxy reference prober


using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BulkWriter.Pipeline.Internal;
using BulkWriter.Pipeline.Steps;

namespace BulkWriter.Pipeline
{
    public class EtlPipeline : IEtlPipeline
    {
        private readonly Stack<IEtlPipelineStep> _pipelineSteps = new Stack<IEtlPipelineStep>();

        public Task ExecuteAsync()
        {
            return ExecuteAsync(CancellationToken.None);
        }

        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var finalStep = _pipelineSteps.Pop();
            var finalTask = Task.Run(() => finalStep.Run(cancellationToken), cancellationToken);

            while (_pipelineSteps.Count != 0)
            {
                var taskAction = _pipelineSteps.Pop();
                Task.Run(() => taskAction.Run(cancellationToken), cancellationToken);
            }

            return finalTask;
        }

        public IEtlPipelineStep<T, T> StartWith<T>(IEnumerable<T> input)
        {
            var etlPipelineSetupContext = new EtlPipelineContext(this, (p, s) => _pipelineSteps.Push(s));
            var step = new StartEtlPipelineStep<T>(etlPipelineSetupContext, input);

            _pipelineSteps.Push(step);

            return step;
        }
    }
}

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BulkWriter.Pipeline.Internal;
using BulkWriter.Pipeline.Steps;

namespace BulkWriter.Pipeline
{
    public sealed class EtlPipeline : IEtlPipeline
    {
        private readonly Stack<IEtlPipelineStep> _pipelineSteps = new Stack<IEtlPipelineStep>();

        private EtlPipeline()
        {
        }

        public Task ExecuteAsync()
        {
            return ExecuteAsync(CancellationToken.None);
        }

        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var finalStep = _pipelineSteps.Pop();
            var finalTask = Task.Run(() => finalStep.Run(cancellationToken), cancellationToken);

            while (_pipelineSteps.Count != 0)
            {
                var taskAction = _pipelineSteps.Pop();
                Task.Run(() => taskAction.Run(cancellationToken), cancellationToken);
            }

            return finalTask;
        }

        public static IEtlPipelineStep<T, T> StartWith<T>(IEnumerable<T> input)
        {
            var pipeline = new EtlPipeline();
            var etlPipelineSetupContext = new EtlPipelineContext(pipeline, (p, s) => pipeline._pipelineSteps.Push(s));
            var step = new StartEtlPipelineStep<T>(etlPipelineSetupContext, input);

            pipeline._pipelineSteps.Push(step);

            return step;
        }
    }
}

Improve pipeline interface so that StartWith is now static and actually creates the pipeline for us


using Moegirlpedia.MediaWikiInterop.Primitives.Action.Models;
using Moegirlpedia.MediaWikiInterop.Primitives.Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Moegirlpedia.MediaWikiInterop.Primitives.Transform
{
    public class QueryRequestSerializer : IRequestSerializer<QueryInputModel>
    {
        public Task<HttpContent> SerializeRequestAsync(QueryInputModel content,
            CancellationToken ctkn = default(CancellationToken))
        {
            if (content == null) throw new ArgumentNullException(nameof(content));

            return Task.Factory.StartNew<HttpContent>(() =>
            {
                // Intermediate Key-Value pair
                var kvPairs = new List<KeyValuePair<string, string>>();
                // Query providers
                kvPairs.AddRange(content.m_queryProviders.SelectMany(k => k.ToKeyValuePairCollection()));
                // Base parameters
                kvPairs.AddRange(content.ToKeyValuePairCollection());

                // Set Raw continuation to true
                kvPairs.Add(new KeyValuePair<string, string>("rawcontinue", "1"));

                // Add format config
                kvPairs.AddRange(JsonFormatConfig.FormatConfig);

                return new FormUrlEncodedContent(kvPairs);
            }, ctkn);
        }
    }
}

using Moegirlpedia.MediaWikiInterop.Primitives.Action.Models;
using Moegirlpedia.MediaWikiInterop.Primitives.Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using Moegirlpedia.MediaWikiInterop.Primitives.Foundation.Query;

namespace Moegirlpedia.MediaWikiInterop.Primitives.Transform
{
    public class QueryRequestSerializer : IRequestSerializer<QueryInputModel>
    {
        public Task<HttpContent> SerializeRequestAsync(QueryInputModel content,
            CancellationToken ctkn = default(CancellationToken))
        {
            if (content == null) throw new ArgumentNullException(nameof(content));

            return Task.Factory.StartNew<HttpContent>(() =>
            {
                return new FormUrlEncodedContent(GetKeyPairs(content));
            }, ctkn);
        }

        internal List<KeyValuePair<string, string>> GetKeyPairs(QueryInputModel content)
        {
            // Intermediate Key-Value pair
            var kvPairs = new List<KeyValuePair<string, string>>();

            // Query providers
            kvPairs.AddRange(content.m_queryProviders.SelectMany(k => k.GetParameters()));

            // Query providers meta
            kvPairs.AddRange(content.m_queryProviders.Select(i => i.GetType().GetTypeInfo().GetCustomAttribute<QueryProviderAttribute>())
                .GroupBy(i => i.Category)
                .Select(i => new KeyValuePair<string, string>(i.Key, string.Join("|", i.Select(a => a.Name)))));

            // Base parameters
            kvPairs.AddRange(content.ToKeyValuePairCollection());

            // Set Raw continuation to true
            kvPairs.Add(new KeyValuePair<string, string>("rawcontinue", "1"));

            // Add format config
            kvPairs.AddRange(JsonFormatConfig.FormatConfig);

            return kvPairs;
        }
    }
}

Address an issue blocks query provider parameters being sent.


using System.Configuration;

namespace Cassette
{
    public sealed class CassetteConfigurationSection : ConfigurationSection
    {
        [ConfigurationProperty("debug", DefaultValue = null)]
        public bool? Debug
        {
            get { return (bool?)this["debug"]; }
            set { this["debug"] = value; }
        }

        [ConfigurationProperty("rewriteHtml", DefaultValue = true)]
        public bool RewriteHtml
        {
            get { return (bool)this["rewriteHtml"]; }
            set { this["rewriteHtml"] = value; }
        }

        [ConfigurationProperty("allowRemoteDiagnostics", DefaultValue = false)]
        public bool AllowRemoteDiagnostics
        {
            get { return (bool)this["allowRemoteDiagnostics"]; }
            set { this["allowRemoteDiagnostics"] = value; }
        }

        // TODO: Use it or lose it!
        [ConfigurationProperty("watchFileSystem", DefaultValue = null)]
        public bool? WatchFileSystem
        {
            get { return (bool?)this["watchFileSystem"]; }
            set { this["watchFileSystem"] = value; }
        }

        [ConfigurationProperty("cacheDirectory", DefaultValue = null)]
        public string CacheDirectory
        {
            get { return (string)this["cacheDirectory"]; }
            set { this["cacheDirectory"] = value; }
        }
    }
}

using System.Configuration;

namespace Cassette
{
    public sealed class CassetteConfigurationSection : ConfigurationSection
    {
        [ConfigurationProperty("debug", DefaultValue = null)]
        public bool? Debug
        {
            get { return (bool?)this["debug"]; }
            set { this["debug"] = value; }
        }

        [ConfigurationProperty("rewriteHtml", DefaultValue = true)]
        public bool RewriteHtml
        {
            get { return (bool)this["rewriteHtml"]; }
            set { this["rewriteHtml"] = value; }
        }

        [ConfigurationProperty("allowRemoteDiagnostics", DefaultValue = false)]
        public bool AllowRemoteDiagnostics
        {
            get { return (bool)this["allowRemoteDiagnostics"]; }
            set { this["allowRemoteDiagnostics"] = value; }
        }

        [ConfigurationProperty("cacheDirectory", DefaultValue = null)]
        public string CacheDirectory
        {
            get { return (string)this["cacheDirectory"]; }
            set { this["cacheDirectory"] = value; }
        }
    }
}

Remove watchFileSystem config section property - no longer needed


using Microsoft.AspNetCore.Mvc.Formatters;

namespace FubarDev.WebDavServer.AspNetCore.Formatters
{
    public class WebDavXmlSerializerInputFormatter : XmlSerializerInputFormatter
    {
        public override bool CanRead(InputFormatterContext context)
        {
            var request = context.HttpContext.Request;
            if (request.ContentType == null)
            {
                var contentLength = request.ContentLength;
                if (request.Method == "PROPFIND" && contentLength.HasValue && contentLength.Value == 0)
                {
                    return true;
                }
            }

            return base.CanRead(context);
        }
    }
}

using Microsoft.AspNetCore.Mvc.Formatters;

namespace FubarDev.WebDavServer.AspNetCore.Formatters
{
    public class WebDavXmlSerializerInputFormatter : XmlSerializerInputFormatter
    {
        public override bool CanRead(InputFormatterContext context)
        {
            var request = context.HttpContext.Request;
            if (request.ContentType == null)
            {
                var contentLength = request.ContentLength;
                if (contentLength.HasValue && contentLength.Value == 0)
                {
                    switch (request.Method)
                    {
                        case "PROPFIND":
                            return true;
                    }
                }
            }

            return base.CanRead(context);
        }
    }
}

Make the intent clearer to accept bodyless PROPFIND


@using ASPWiki.Model
@model WikiPage

@Model.Title

    @Html.Raw(@Model.GetContentSummary())

    @Html.Partial("~/Views/Wiki/Label.cshtml", Model.label)
    Written by: Unknown - Size: @Model.GetSizeKiloBytes() - @Html.DisplayFor(model => model.LastModified)
    5

Fix ui when contentSummary has unclosed dom tags.


using ApiApp.Models;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;

namespace ApiApp.MongoAccess
{
    static class MongoUtil
    {
        #region Fields

        private static IMongoClient _client;
        private static IMongoDatabase _database;

        #endregion Fields

        #region Constructors

        static MongoUtil()
        {
            // Production config
            //var connectionString = WebConfigurationManager.AppSettings["primaryConnectionString"];
            //_client = new MongoClient(connectionString);
            //var dbName = WebConfigurationManager.AppSettings["primaryDatabaseName"];

            // Test config
            var connectionString = WebConfigurationManager.AppSettings["testConnectionString"];
            _client = new MongoClient(connectionString);
            var dbName = WebConfigurationManager.AppSettings["testDatabaseName"];
            _database = _client.GetDatabase(dbName);
        }

        #endregion Constructors

        #region Methods

        /// <summary>
        /// ดึงข้อมูลจากตาราง
        /// </summary>
        /// <typeparam name="T">ข้อมูลที่ทำงานด้วย</typeparam>
        /// <param name="tableName">ชื่อตาราง</param>
        public static IMongoCollection<T> GetCollection<T>(string tableName)
        {
            return _database.GetCollection<T>(tableName);
        }

        #endregion Methods
    }
}

using ApiApp.Models;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;

namespace ApiApp.MongoAccess
{
    static class MongoUtil
    {
        #region Fields

        private static IMongoClient _client;
        private static IMongoDatabase _database;

        #endregion Fields

        #region Constructors

        static MongoUtil()
        {
            // Production config
            var connectionString = WebConfigurationManager.AppSettings["primaryConnectionString"];
            _client = new MongoClient(connectionString);
            var dbName = WebConfigurationManager.AppSettings["primaryDatabaseName"];

            // Test config
            //var connectionString = WebConfigurationManager.AppSettings["testConnectionString"];
            //_client = new MongoClient(connectionString);
            //var dbName = WebConfigurationManager.AppSettings["testDatabaseName"];
            _database = _client.GetDatabase(dbName);
        }

        #endregion Constructors

        #region Methods

        /// <summary>
        /// ดึงข้อมูลจากตาราง
        /// </summary>
        /// <typeparam name="T">ข้อมูลที่ทำงานด้วย</typeparam>
        /// <param name="tableName">ชื่อตาราง</param>
        public static IMongoCollection<T> GetCollection<T>(string tableName)
        {
            return _database.GetCollection<T>(tableName);
        }

        #endregion Methods
    }
}

CHANGE CONFIG TO PRODUCTION !!!

CHANGE CONFIG TO PRODUCTION !!!

Signed-off-by: Sakul Jaruthanaset <17b4bfe9c570ddd7d4345ec4b3617835712513c0@perfenterprise.com>


Regular Poller?

        Register for more config choices. It's free!

    <form name="quickPollForm" ng-submit="createPoll(pollQuestion)">

            Your Question

            <input id="question" placeholder="E.g. Where should we go for lunch?" ng-model="pollQuestion" required />

            <button type="submit" class="active-btn btn-medium shadowed" ng-disabled="quickPollForm.$invalid">Quick Poll</button>

    </form>

or

        <button class="active-btn btn-medium shadowed pull-left" ng-click="openLoginDialog()">Sign In</button>
        <button class="active-btn btn-medium shadowed pull-right" ng-click="openRegisterDialog()">Register</button>

Remove "register for more config choices"


using System;
using System.Reflection;
using System.Text.RegularExpressions;
using InfluxData.Net.Common;
using System.Linq;

namespace InfluxData.Net.InfluxDb.Helpers
{
    public static class QueryHelpers
    {
        public static string BuildParameterizedQuery(string query, object param)
        {
            var paramRegex = "@([A-Za-z0-9åäöÅÄÖ'_-]+)";

            var matches = Regex.Matches(query, paramRegex);

            Type t = param.GetType();
            PropertyInfo[] pi = t.GetProperties();

            foreach(Match match in matches)
            {
                if (!pi.Any(x => match.Groups[0].Value.Contains(x.Name)))
                    throw new ArgumentException($"Missing parameter value for {match.Groups[0].Value}");
            }

            foreach (var propertyInfo in pi)
            {
                var paramValue = propertyInfo.GetValue(param);
                var paramType = paramValue.GetType();

                if(!paramType.IsPrimitive && paramType != typeof(String))
                    throw new NotSupportedException($"The type {paramType.Name} is not a supported query parameter type.");

                var sanitizedParamValue = paramValue;

                if(paramType == typeof(String)) {
                    sanitizedParamValue = ((string)sanitizedParamValue).Sanitize();
                }

                while (Regex.IsMatch(query, $"@{propertyInfo.Name}"))
                {
                    var match = Regex.Match(query, $"@{propertyInfo.Name}");

                    query = query.Remove(match.Index, match.Length);
                    query = query.Insert(match.Index, $"{sanitizedParamValue}");
                }
            }

            return query;
        }
    }
}

using System;
using System.Reflection;
using System.Text.RegularExpressions;
using InfluxData.Net.Common;
using System.Linq;

namespace InfluxData.Net.InfluxDb.Helpers
{
    public static class QueryHelpers
    {
        public static string BuildParameterizedQuery(string query, object param)
        {
            Type t = param.GetType();
            PropertyInfo[] pi = t.GetProperties();

            foreach (var propertyInfo in pi)
            {
                var regex = $@"@{propertyInfo.Name}(?!\w)";

                if(!Regex.IsMatch(query, regex) && Nullable.GetUnderlyingType(propertyInfo.GetType()) != null)
                    throw new ArgumentException($"Missing parameter identifier for @{propertyInfo.Name}");

                var paramValue = propertyInfo.GetValue(param);
                if (paramValue == null)
                    continue;

                var paramType = paramValue.GetType();

                if (!paramType.IsPrimitive && paramType != typeof(String) && paramType != typeof(DateTime))
                    throw new NotSupportedException($"The type {paramType.Name} is not a supported query parameter type.");

                var sanitizedParamValue = paramValue;

                if (paramType == typeof(String))
                {
                    sanitizedParamValue = ((string)sanitizedParamValue).Sanitize();
                }

                while (Regex.IsMatch(query, regex))
                {
                    var match = Regex.Match(query, regex);

                    query = query.Remove(match.Index, match.Length);
                    query = query.Insert(match.Index, $"{sanitizedParamValue}");
                }
            }

            return query;
        }
    }
}

Correct regex to match only full words

Correct regex to match only full words


namespace FunWithNinject.Initialization
{
    using Ninject;
    using NUnit.Framework;

    [TestFixture]
    public class Tests
    {
        [Test]
        public void OnActivation_CanCallMethodOnImplementation()
        {
            // Assemble
            var k = new StandardKernel();
            k.Bind<IInitializable>()
                .To<Initializable>()
                .OnActivation(i => i.CallMe());

            // Act
            var initted = k.Get<IInitializable>();

            // Assert
            Assert.IsTrue(((Initializable)initted).CalledMe);
        }

        [Test]
        public void OnActivation_CanCallMethodOnInterface()
        {
            // Assemble
            var k = new StandardKernel();
            k.Bind<IInitializable>()
                .To<Initializable>()
                .OnActivation(i => i.Init());

            // Act
            var initted = k.Get<IInitializable>();

            // Assert
            Assert.IsTrue(initted.IsInit);
        }
    }
}

namespace FunWithNinject.Initialization
{
    using Ninject;
    using NUnit.Framework;
    using System.Threading;

    [TestFixture]
    public class Tests
    {
        [Test]
        public void OnActivation_CanCallMethodOnImplementation()
        {
            // Assemble
            var k = new StandardKernel();
            k.Bind<IInitializable>()
                .To<Initializable>()
                .OnActivation(i => i.CallMe());

            // Act
            var initted = k.Get<IInitializable>();

            // Assert
            Assert.IsTrue(((Initializable)initted).CalledMe);
        }

        [Test]
        public void OnActivation_CanCallMethodOnInterface()
        {
            // Assemble
            var k = new StandardKernel();
            k.Bind<IInitializable>()
                .To<Initializable>()
                .OnActivation(i => i.Init());

            // Act
            var initted = k.Get<IInitializable>();

            // Assert
            Assert.IsTrue(initted.IsInit);
        }

        [Test]
        public void OnActivation_RunsSyncrhonously()
        {
            var currentId = Thread.CurrentThread.ManagedThreadId;
            var k = new StandardKernel();
            k.Bind<IFoo>()
                .To<Foo>()
                .OnActivation(i =>
                {
                    Assert.AreEqual(currentId, Thread.CurrentThread.ManagedThreadId);
                });
        }
    }
}

Add test to prove that OnActivation is syncronous


//-----------------------------------------------------------------------
// <copyright file="EventWindowTest.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace TraceAnalysisSample.Test.Unit
{
    using System;
    using System.Threading.Tasks;
    using Xunit;

    public class EventWindowTest
    {
        public EventWindowTest()
        {
        }

        [Fact]
        public void Add_adds_operation_to_pending()
        {
            EventWindow window = new EventWindow();
            int eventId = 1;
            Guid instanceId = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);

            window.Add(eventId, instanceId);

            Assert.Equal(1, window.GetPendingCount(eventId));
        }
    }
}

//-----------------------------------------------------------------------
// <copyright file="EventWindowTest.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace TraceAnalysisSample.Test.Unit
{
    using System;
    using System.Threading.Tasks;
    using Xunit;

    public class EventWindowTest
    {
        public EventWindowTest()
        {
        }

        [Fact]
        public void Add_adds_operation_to_pending()
        {
            EventWindow window = new EventWindow();
            int eventId = 1;
            Guid instanceId = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);

            window.Add(eventId, instanceId);

            Assert.Equal(1, window.GetPendingCount(eventId));
        }

        [Fact]
        public void Add_same_type_twices_adds_2_operations_to_pending()
        {
            EventWindow window = new EventWindow();
            int eventId = 1;
            Guid instanceId1 = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
            Guid instanceId2 = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2);

            window.Add(eventId, instanceId1);
            window.Add(eventId, instanceId2);

            Assert.Equal(2, window.GetPendingCount(eventId));
        }
    }
}

Add same type twices adds 2 operations to pending


@{ViewBag.Title = "Search for your organisation"; }

Search for your organisation

Use the companies house number for an organisation that your apprentices will be employed through.

            <form method="POST" action="@Url.Action("SelectEmployer")">

                    @Html.AntiForgeryToken()

                    Companies House number

                    @if (TempData["companyNumberError"] != null)
                    {
                        <legend>
                            @TempData["companyNumberError"]
                        </legend>
                    }
                    <input class="form-control form-control-3-4" id="EmployerRef" name="EmployerRef" type="text"
                           aria-required="true"/>

                <button type="submit" class="button" id="submit">Continue</button>
            </form>

@section breadcrumb {

Back to Your User Profile

}

@{ViewBag.Title = "Search for your organisation"; }

Enter Companies House number

Use the Companies House number for an organisation that your apprentices will be employed through.

Find my Companies House number

            <form method="POST" action="@Url.Action("SelectEmployer")">

                    @Html.AntiForgeryToken()

                    Companies House number

                    @if (TempData["companyNumberError"] != null)
                    {
                        <legend>
                            @TempData["companyNumberError"]
                        </legend>
                    }
                    <input class="form-control form-control-3-4" id="EmployerRef" name="EmployerRef" type="text"
                           aria-required="true"/>

                <button type="submit" class="button" id="submit">Continue</button>
            </form>

@section breadcrumb {

Back to Your User Profile

}

Copy changes and companies house link on the company search page


using ChartJS.NET.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChartJS.NET.Charts.Bar
{
    public class BarChart : BaseChart<BarDataSet, BarChartOptions>
    {
        private readonly BarChartOptions _barChartOptions = new BarChartOptions();

        public override Enums.ChartTypes ChartType { get { return Enums.ChartTypes.Pie; } }

        public override BarChartOptions ChartConfig
        {
            get { return _barChartOptions; }
        }
    }
}

using ChartJS.NET.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChartJS.NET.Charts.Bar
{
    public class BarChart : BaseChart<BarDataSet, BarChartOptions>
    {
        private readonly BarChartOptions _barChartOptions = new BarChartOptions();

        public override Enums.ChartTypes ChartType { get { return Enums.ChartTypes.Bar; } }

        public override BarChartOptions ChartConfig
        {
            get { return _barChartOptions; }
        }
    }
}

Change bar chart type to bar instead of pie


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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("763b7fef-ff24-407d-8dce-5313e6129941")]

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

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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("763b7fef-ff24-407d-8dce-5313e6129941")]

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

Revert "new capabilites, minor version"

Revert "new capabilites, minor version"

This reverts commit 425fb58a0c23d6321581ebb16167cfda224fd70f.


using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Curse.NET
{
	internal class MillisecondEpochConverter : DateTimeConverterBase
	{
		private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			writer.WriteRawValue(((int)(((DateTime)value - epoch).TotalMilliseconds)).ToString());
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			if (reader.Value == null)
			{
				return DateTime.MinValue;
			}
			return epoch.AddMilliseconds((long)reader.Value);
		}
	}

	internal class NullableIntConverter : DateTimeConverterBase
	{
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			writer.WriteRawValue(((int)value).ToString());
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			if (reader.Value == null)
			{
				return 0;
			}
			// Double cast is necessary to convert a boxed long first to a long, then to an int.
			return (int)(long)reader.Value;
		}
	}
}

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Curse.NET
{
	internal class MillisecondEpochConverter : DateTimeConverterBase
	{
		private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			writer.WriteRawValue(((int)(((DateTime)value - epoch).TotalMilliseconds)).ToString());
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			if (reader.Value == null || (long) reader.Value == 0)
			{
				return DateTime.MinValue;
			}
			return epoch.AddMilliseconds((long)reader.Value);
		}
	}

	/// <summary>
	/// Converter for JSON integer properties that are set to null when they should've been set to zero.
	/// </summary>
	internal class NullableIntConverter : DateTimeConverterBase
	{
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			writer.WriteRawValue(((int)value).ToString());
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			if (reader.Value == null)
			{
				return 0;
			}
			// Double cast is necessary to convert a boxed long first to a long, then to an int.
			return (int)(long)reader.Value;
		}
	}
}

Fix zero being interpreted as 1/1/1970 instead of DateTime.MinValue


using System;
using Pixie.Terminal;
using Pixie.Loyc;
using Pixie;
using Pixie.Transforms;
using Loyc.Syntax;
using Loyc;
using Loyc.Ecs;
using Loyc.Collections;
using Pixie.Markup;

namespace LoycInterop
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            // This example demonstrates how to translate an error
            // generated by Loyc into a Pixie diagnostic.

            // First, acquire a terminal log. We'll configure it to
            // turn everything it sees into a diagnostic.
            var log = new TransformLog(
                TerminalLog.Acquire(),
                new Func<LogEntry, LogEntry>[]
                {
                    MakeDiagnostic
                });

            // Create a message sink that redirects messages to the log.
            var messageSink = new PixieMessageSink(log);

            // Next, we'll create a C# source file with a syntax error
            // in it.
            var file = new SourceFile<ICharSource>(new UString("int int x = 10;"), "input.cs");

            // Now, parse the document and watch the syntax error emerge
            // as a Pixie diagnostic.
            EcsLanguageService.Value.Parse(
                file.Text,
                file.FileName,
                messageSink,
                null,
                true).ToArray<LNode>();
        }

        private static LogEntry MakeDiagnostic(LogEntry entry)
        {
            var newEntry = DiagnosticExtractor.Transform(entry, "program");
            return new LogEntry(newEntry.Severity, WrapBox.WordWrap(newEntry.Contents));
        }
    }
}

using System;
using Pixie.Terminal;
using Pixie.Loyc;
using Pixie;
using Pixie.Transforms;
using Loyc.Syntax;
using Loyc;
using Loyc.Ecs;
using Loyc.Collections;
using Pixie.Markup;

namespace LoycInterop
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            // This example demonstrates how to translate an error
            // generated by Loyc into a Pixie diagnostic.

            // First, acquire a terminal log. We'll configure it to
            // turn everything it sees into a diagnostic.
            var log = new TransformLog(
                TerminalLog.Acquire(),
                new Func<LogEntry, LogEntry>[]
                {
                    MakeDiagnostic
                });

            // Create a message sink that redirects messages to the log.
            var messageSink = new PixieMessageSink(log);

            // Next, we'll create a C# source file with some syntax errors
            // in it.
            var file = new SourceFile<ICharSource>(new UString("int int x = 10; class A"), "input.cs");

            // Now, parse the document and watch the syntax error emerge
            // as a Pixie diagnostic.
            EcsLanguageService.Value.Parse(
                file.Text,
                file.FileName,
                messageSink,
                null,
                true).ToArray<LNode>();
        }

        private static LogEntry MakeDiagnostic(LogEntry entry)
        {
            var newEntry = DiagnosticExtractor.Transform(entry, "program");
            return new LogEntry(newEntry.Severity, WrapBox.WordWrap(newEntry.Contents));
        }
    }
}

Add another error message to LoycInterop example


/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/

using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;

namespace ShiftDrive {

    /// <summary>
    /// A simple static container, for holding game assets like textures and meshes.
    /// </summary>
    internal static class Assets {

        public static SpriteFont
            fontDefault,
            fontBold;

        public static readonly Dictionary<string, Texture2D>
            textures = new Dictionary<string, Texture2D>();

        public static Model
            mdlSkybox;

        public static Effect
            fxUnlit;

        public static SoundEffect
            sndUIConfirm,
            sndUICancel,
            sndUIAppear1,
            sndUIAppear2,
            sndUIAppear3,
            sndUIAppear4;

        public static Texture2D GetTexture(string name) {
            return textures[name.ToLowerInvariant()];
        }

    }

}

/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/

using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;

namespace ShiftDrive {

    /// <summary>
    /// A simple static container, for holding game assets like textures and meshes.
    /// </summary>
    internal static class Assets {

        public static SpriteFont
            fontDefault,
            fontBold;

        public static readonly Dictionary<string, Texture2D>
            textures = new Dictionary<string, Texture2D>();

        public static Model
            mdlSkybox;

        public static Effect
            fxUnlit;

        public static SoundEffect
            sndUIConfirm,
            sndUICancel,
            sndUIAppear1,
            sndUIAppear2,
            sndUIAppear3,
            sndUIAppear4;

        public static Texture2D GetTexture(string name) {
            if (!textures.ContainsKey(name.ToLowerInvariant()))
                throw new KeyNotFoundException("Texture '" + name + "' was not found.");
            return textures[name.ToLowerInvariant()];
        }

    }

}

Add better exceptions for invalid keys

Add better exceptions for invalid keys


namespace Game
{
    using UnityEngine;

    [RequireComponent(typeof(Collider))]
    public class Tank : MonoBehaviour
    {
        public PlayerController player;

        [Range(10f, 1000f)]
        public float max = 100f;

        [Range(0.1f, 20f)]
        public float leakRatePerSecond = 2f;

        [ReadOnly]
        private float current = 0f;

        public bool isLeaking
        {
            get;
            set;
        }

        private void OnEnable()
        {
            this.name = string.Concat("Player ", this.player.playerIndex, " Tank");
            this.current = this.max;
        }

        private void Update()
        {
            if (!this.isLeaking)
            {
                return;
            }

            this.current -= 1f / this.leakRatePerSecond;
            if (this.current <= 0f)
            {
                this.player.Die();
                this.enabled = false;
            }
        }

        private void OnCollisionEnter(Collision collision)
        {
            if (this.isLeaking)
            {
                return;
            }

            var other = collision.gameObject;
            if (((1 << other.layer) & Layers.instance.playerLayer) == 0)
            {
                // not a player
                return;
            }

            Debug.Log(this.ToString() + " start leaking");
            this.isLeaking = true;
        }
    }
}

namespace Game
{
    using UnityEngine;

    [RequireComponent(typeof(Collider))]
    public class Tank : MonoBehaviour
    {
        public PlayerController player;

        [Range(10f, 1000f)]
        public float max = 100f;

        [Range(0.1f, 20f)]
        public float leakRatePerSecond = 2f;

        [ReadOnly]
        private float current = 0f;

        public bool isLeaking
        {
            get;
            set;
        }

        private void OnEnable()
        {
            this.name = string.Concat("Player ", this.player.playerIndex, " Tank");
            this.current = this.max;
        }

        private void Update()
        {
            if (!this.isLeaking)
            {
                return;
            }

            this.current -= 1f / this.leakRatePerSecond;
            if (this.current <= 0f)
            {
                this.player.Die();
                this.enabled = false;
            }

            // TODO: Debug ONLY
            var frac = this.current / this.max;
            this.GetComponent<Renderer>().material.color = new Color(frac, frac, frac);
        }

        private void OnCollisionEnter(Collision collision)
        {
            if (this.isLeaking)
            {
                return;
            }

            var other = collision.gameObject;
            if (((1 << other.layer) & Layers.instance.playerLayer) == 0)
            {
                // not a player
                return;
            }

            Debug.Log(this.ToString() + " start leaking");
            this.isLeaking = true;
        }
    }
}

Change color of tank for debug purposes

Change color of tank for debug purposes


using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using YnabApi.Files;
using YnabApi.Helpers;

namespace YnabApi
{
    public class YnabApi
    {
        private readonly IFileSystem _fileSystem;

        public YnabApi(IFileSystem fileSystem)
        {
            this._fileSystem = fileSystem;
        }

        public async Task<IList<Budget>> GetBudgetsAsync()
        {
            string ynabSettingsFilePath = YnabPaths.YnabSettingsFile();

            var ynabSettingsJson = await this._fileSystem.ReadFileAsync(ynabSettingsFilePath);
            var ynabSettings = JObject.Parse(ynabSettingsJson);

            string relativeBudgetsFolder = ynabSettings.Value<string>("relativeDefaultBudgetsFolder");

            return ynabSettings
                .Value<JArray>("relativeKnownBudgets")
                .Values()
                .Select(f => f.Value<string>())
                .Select(f => new Budget(this._fileSystem, this.ExtractBudgetName(f, relativeBudgetsFolder), f))
                .ToArray();
        }

        private string ExtractBudgetName(string budgetPath, string budgetsFolderPath)
        {
            var regex = new Regex(budgetsFolderPath + "/(.*)~.*");

            if (regex.IsMatch(budgetPath))
                return regex.Match(budgetPath).Groups[1].Value;

            return budgetPath;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using YnabApi.Files;
using YnabApi.Helpers;

namespace YnabApi
{
    public class YnabApi
    {
        private readonly IFileSystem _fileSystem;

        private Lazy<Task<IList<Budget>>> _cachedBudgets;

        public YnabApi(IFileSystem fileSystem)
        {
            this._fileSystem = fileSystem;
        }

        public Task<IList<Budget>> GetBudgetsAsync()
        {
            if (this._cachedBudgets == null)
            {
                this._cachedBudgets = new Lazy<Task<IList<Budget>>>(async () =>
                {
                    string ynabSettingsFilePath = YnabPaths.YnabSettingsFile();

                    var ynabSettingsJson = await this._fileSystem.ReadFileAsync(ynabSettingsFilePath);
                    var ynabSettings = JObject.Parse(ynabSettingsJson);

                    string relativeBudgetsFolder = ynabSettings.Value<string>("relativeDefaultBudgetsFolder");

                    return ynabSettings
                        .Value<JArray>("relativeKnownBudgets")
                        .Values()
                        .Select(f => f.Value<string>())
                        .Select(f => new Budget(this._fileSystem, this.ExtractBudgetName(f, relativeBudgetsFolder), f))
                        .ToArray();
                });
            }

            return this._cachedBudgets.Value;
        }

        private string ExtractBudgetName(string budgetPath, string budgetsFolderPath)
        {
            var regex = new Regex(budgetsFolderPath + "/(.*)~.*");

            if (regex.IsMatch(budgetPath))
                return regex.Match(budgetPath).Groups[1].Value;

            return budgetPath;
        }
    }
}

Add caching to the GetBudgetsAsync method


using GeoIP.Models;
using MaxMind.GeoIP2;
using MaxMind.GeoIP2.Exceptions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GeoIP.Executers
{
    public class MaxMindQuery : IQuery
    {
        public async Task<object> Query(string ipAddress, string dataSource)
        {
            object result;

            try
            {
                using (var reader = new DatabaseReader(dataSource))
                {
                    var city = await Task.Run(() =>
                    {
                        return reader.City(ipAddress);
                    });

                    result = new Geolocation()
                    {
                        IPAddress = ipAddress,
                        City = city.City.Name,
                        Country = city.Country.Name,
                        Latitude = city.Location.Latitude,
                        Longitude = city.Location.Longitude
                    };

                }
            }
            catch (AddressNotFoundException ex)
            {
                result = new Error()
                {
                    ErrorMessage = ex.Message
                };
            }

            return result;
        }
    }
}

Put Task.Run in a single line

Put Task.Run in a single line


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

    internal class TraktShowsPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktShow>, TraktShow>
    {
        internal TraktShowsPopularRequest(TraktClient client) : base(client) { }

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

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

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

    internal class TraktShowsPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktShow>, TraktShow>
    {
        internal TraktShowsPopularRequest(TraktClient client) : base(client) { }

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

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        internal TraktShowFilter Filter { get; set; }

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

Add filter property to popular shows request.


using Waf.NewsReader.Applications.Services;
using Xamarin.Essentials;

namespace Waf.NewsReader.Presentation.Services
{
    public class AppInfoService : IAppInfoService
    {
        public AppInfoService()
        {
            AppName = AppInfo.Name;
            VersionString = AppInfo.VersionString + "." + AppInfo.BuildString;
        }

        public string AppName { get; }

        public string VersionString { get; }
    }
}

using Waf.NewsReader.Applications.Services;
using Xamarin.Essentials;

namespace Waf.NewsReader.Presentation.Services
{
    public class AppInfoService : IAppInfoService
    {
        public AppInfoService()
        {
            AppName = AppInfo.Name;
            VersionString = AppInfo.VersionString;
        }

        public string AppName { get; }

        public string VersionString { get; }
    }
}

Revert "NR Improve display of version number"

This reverts commit c5568ddb6ff60c9e55b862e49ff1c8c3aa2d5fbb.


using NUnit.Framework;

using Rant.Resources;

namespace Rant.Tests
{
	[TestFixture]
	public class PackageVersions
	{
		[TestCase("1.2.5", "1.2.4", true)]
		[TestCase("0.2.5", "0.2.4", true)]
		[TestCase("0.0.3", "0.0.4", false)]
		[TestCase("0.3.1", "0.4.0", false)]
		public void VersionGreaterThan(string v1, string v2, bool expactedResult)
		{
			Assert.IsTrue(RantPackageVersion.Parse(v1) > RantPackageVersion.Parse(v2) == expactedResult, $"Expected {expactedResult}");
		}

		[TestCase("2.2.1", "2.2.4", true)]
		[TestCase("0.2.3", "0.2.4", true)]
		[TestCase("1.3.0", "0.5.4", false)]
		public void VersionLessThan(string v1, string v2, bool expectedResult)
		{
			Assert.IsTrue(RantPackageVersion.Parse(v1) < RantPackageVersion.Parse(v2) == expectedResult, $"Expected {expectedResult}");
		}
	}
}

using NUnit.Framework;

using Rant.Resources;

namespace Rant.Tests
{
	[TestFixture]
	public class PackageVersions
	{
		[TestCase("1.2.5", "1.2.4", true)]
		[TestCase("0.2.5", "0.2.4", true)]
		[TestCase("0.0.3", "0.0.4", false)]
		[TestCase("0.3.1", "0.4.0", false)]
		public void VersionGreaterThan(string v1, string v2, bool expactedResult)
		{
			Assert.IsTrue(RantPackageVersion.Parse(v1) > RantPackageVersion.Parse(v2) == expactedResult, $"Expected {expactedResult}");
		}

		[TestCase("2.2.1", "2.2.4", true)]
		[TestCase("3.2.1", "2.1.4", false)]
		[TestCase("0.2.3", "0.2.4", true)]
		[TestCase("1.3.0", "0.5.4", false)]
		public void VersionLessThan(string v1, string v2, bool expectedResult)
		{
			Assert.IsTrue(RantPackageVersion.Parse(v1) < RantPackageVersion.Parse(v2) == expectedResult, $"Expected {expectedResult}");
		}
	}
}

Add additional test case for package versions


using System.Collections.Generic;
using System.Management.Automation.Runspaces;

using Aggregator.Core.Interfaces;
using Aggregator.Core.Monitoring;

namespace Aggregator.Core
{
    /// <summary>
    /// Invokes Powershell scripting engine
    /// </summary>
    public class PsScriptEngine : ScriptEngine
    {
        private readonly Dictionary<string, string> scripts = new Dictionary<string, string>();

        public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug)
            : base(store, logger, debug)
        {
        }

        public override bool Load(string scriptName, string script)
        {
            this.scripts.Add(scriptName, script);
            return true;
        }

        public override bool LoadCompleted()
        {
            return true;
        }

        public override void Run(string scriptName, IWorkItem workItem)
        {
            string script = this.scripts[scriptName];

            var config = RunspaceConfiguration.Create();
            using (var runspace = RunspaceFactory.CreateRunspace(config))
            {
                runspace.Open();

                runspace.SessionStateProxy.SetVariable("self", workItem);
                runspace.SessionStateProxy.SetVariable("store", this.Store);

                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);

                // execute
                var results = pipeline.Invoke();

                this.Logger.ResultsFromScriptRun(scriptName, results);
            }
        }
    }
}

using System.Collections.Generic;
using System.Management.Automation.Runspaces;

using Aggregator.Core.Interfaces;
using Aggregator.Core.Monitoring;

namespace Aggregator.Core
{
    /// <summary>
    /// Invokes Powershell scripting engine
    /// </summary>
    public class PsScriptEngine : ScriptEngine
    {
        private readonly Dictionary<string, string> scripts = new Dictionary<string, string>();

        public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug)
            : base(store, logger, debug)
        {
        }

        public override bool Load(string scriptName, string script)
        {
            this.scripts.Add(scriptName, script);
            return true;
        }

        public override bool LoadCompleted()
        {
            return true;
        }

        public override void Run(string scriptName, IWorkItem workItem)
        {
            string script = this.scripts[scriptName];

            var config = RunspaceConfiguration.Create();
            using (var runspace = RunspaceFactory.CreateRunspace(config))
            {
                runspace.Open();

                runspace.SessionStateProxy.SetVariable("self", workItem);
                runspace.SessionStateProxy.SetVariable("store", this.Store);
                runspace.SessionStateProxy.SetVariable("logger", this.Logger);

                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);

                // execute
                var results = pipeline.Invoke();

                this.Logger.ResultsFromScriptRun(scriptName, results);
            }
        }
    }
}

FIX logger variable in PS scripts

FIX logger variable in PS scripts


using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace FreecraftCore.Serializer
{
	public class RootSerializationMethodBlockEmitter<TSerializableType> : IMethodBlockEmittable, INestedClassesEmittable
		where TSerializableType : new()
	{
		public BlockSyntax CreateBlock()
		{
			//TODO: Figure out how we should decide which strategy to use, right now only simple and flat are supported.
			//TSerializableType
			return new FlatComplexTypeSerializationMethodBlockEmitter<TSerializableType>()
				.CreateBlock();
		}

		public IEnumerable<ClassDeclarationSyntax> CreateClasses()
		{
			//Find all KnownSize types and emit classes for each one
			foreach (var mi in typeof(TSerializableType)
				.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
			{
				KnownSizeAttribute sizeAttribute = mi.GetCustomAttribute<KnownSizeAttribute>();
				if (sizeAttribute == null)
					continue;

				//This creates a class declaration for the int static type.
				yield return new StaticlyTypedIntegerGenericTypeClassEmitter<int>(sizeAttribute.KnownSize)
					.Create();
			}
		}
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace FreecraftCore.Serializer
{
	public class RootSerializationMethodBlockEmitter<TSerializableType> : IMethodBlockEmittable, INestedClassesEmittable
		where TSerializableType : new()
	{
		public BlockSyntax CreateBlock()
		{
			//TODO: Figure out how we should decide which strategy to use, right now only simple and flat are supported.
			//TSerializableType
			return new FlatComplexTypeSerializationMethodBlockEmitter<TSerializableType>()
				.CreateBlock();
		}

		public IEnumerable<ClassDeclarationSyntax> CreateClasses()
		{
			SortedSet<int> alreadyCreatedSizeClasses = new SortedSet<int>();

			//Find all KnownSize types and emit classes for each one
			foreach (var mi in typeof(TSerializableType)
				.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
			{
				KnownSizeAttribute sizeAttribute = mi.GetCustomAttribute<KnownSizeAttribute>();
				if (sizeAttribute == null)
					continue;

				if (alreadyCreatedSizeClasses.Contains(sizeAttribute.KnownSize))
					continue;

				alreadyCreatedSizeClasses.Add(sizeAttribute.KnownSize);

				//This creates a class declaration for the int static type.
				yield return new StaticlyTypedIntegerGenericTypeClassEmitter<int>(sizeAttribute.KnownSize)
					.Create();
			}
		}
	}
}

Make statically typed numeric generation distinct


using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;

namespace KryBot
{
    internal static class Program
    {
        /// <summary>
        ///     Главная точка входа для приложения.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION");
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);
            string programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
            key?.SetValue(programName, 10001, RegistryValueKind.DWord);

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

using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;

namespace KryBot
{
    internal static class Program
    {
        /// <summary>
        ///     Главная точка входа для приложения.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION");
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);
            string programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
            key?.SetValue(programName, (decimal)11000, RegistryValueKind.DWord);

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

CHANGE: Change force emulation IE10 to IE11
Изменена принудительная эмуляция IE10 на IE11


@model AnlabMvc.Models.Analysis.AnalysisMethodViewModel

@{
    ViewBag.Title = @Model.AnalysisMethod.Title;
}

@Model.AnalysisMethod.Id

@Model.AnalysisMethod.Title

    @Html.Raw(Model.HtmlContent)

        @foreach (var method in Model.AnalysesInCategory)
        {

@method.Title

        }

@model AnlabMvc.Models.Analysis.AnalysisMethodViewModel

@{
    ViewBag.Title = @Model.AnalysisMethod.Title;
}

@Model.AnalysisMethod.Id

@Model.AnalysisMethod.Title

    @Html.Raw(Model.HtmlContent)

        @foreach (var method in Model.AnalysesInCategory)
        {

@method.Id - @method.Title

        }

Add to the details page too

Add to the details page too


using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;

namespace XtabFileOpener.TableContainer.SpreadsheetTableContainer.ExcelTableContainer
{
    /// <summary>
    /// Implementation of Table, that manages an Excel table
    /// </summary>
    internal class ExcelTable : Table
    {
        internal ExcelTable(string name, Range cells) : base(name)
        {
            tableArray = cells.Value2;
            firstRowContainsColumnNames = true;
        }
    }
}

using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;

namespace XtabFileOpener.TableContainer.SpreadsheetTableContainer.ExcelTableContainer
{
    /// <summary>
    /// Implementation of Table, that manages an Excel table
    /// </summary>
    internal class ExcelTable : Table
    {
        internal ExcelTable(string name, Range cells) : base(name)
        {
            /*
             * "The only difference between this property and the Value property is that the Value2 property
             *  doesn’t use the Currency and Date data types. You can return values formatted with these
             *  data types as floating-point numbers by using the Double data type."
             * */
            tableArray = cells.Value;
            firstRowContainsColumnNames = true;
        }
    }
}

Use cell.Value instead of cell.Value2 to allow for Date formatting


using UnityEngine;
using System.Collections;

public class PlanetSpawner : MonoBehaviour {

	public GameObject camera;
	public GameObject planetPrefab;
	public GravityAttractor blackHole;
//	public GravityAttractor blackHole1;
//	public GravityAttractor blackHole2;
	public float force = 100f;

	void Start()
	{

	}

	void Update()
	{
		if (GvrViewer.Instance.Triggered)
		{
			GetComponent<AudioSource>().Play();
			GameObject planet = (GameObject) Instantiate(planetPrefab, transform.position, new Quaternion());
			planet.GetComponent<GravityBody>().attractor = blackHole;
//			GravityAttractor[] attractors = new GravityAttractor[2];
//			attractors[0] = blackHole1;
//			attractors[1] = blackHole2;
//			planet.GetComponent<GravityBody>().attractors = attractors;
			planet.GetComponent<Rigidbody>().AddForce(camera.transform.forward * force, ForceMode.VelocityChange);
		}
	}
}

using UnityEngine;
using System.Collections;

public class PlanetSpawner : MonoBehaviour {

	public GameObject camera;
	public GameObject planetPrefab;
	public GravityAttractor blackHole;
//	public GravityAttractor blackHole1;
//	public GravityAttractor blackHole2;
	public float thrust = 100f;
	public float torque = 25000f;

	void Start()
	{

	}

	void Update()
	{
		if (GvrViewer.Instance.Triggered)
		{
			GetComponent<AudioSource>().Play();
			GameObject planet = (GameObject) Instantiate(planetPrefab, transform.position, new Quaternion());
			planet.GetComponent<GravityBody>().attractor = blackHole;
//			GravityAttractor[] attractors = new GravityAttractor[2];
//			attractors[0] = blackHole1;
//			attractors[1] = blackHole2;
//			planet.GetComponent<GravityBody>().attractors = attractors;
			planet.GetComponent<Rigidbody>().AddForce(camera.transform.forward * thrust, ForceMode.VelocityChange);
			planet.GetComponent<Rigidbody>().AddTorque(transform.up * torque);
		}
	}
}

Add torque to launched planets

Add torque to launched planets


using System;
using System.Runtime.InteropServices;

namespace Mamesaver.Windows
{
    // This class contains the GDI32 APIs used...
    public class PlatformInvokeGdi32
    {
        public const int SRCOPY = 13369376;

        [DllImport("gdi32.dll", EntryPoint = "DeleteDC")]
        public static extern IntPtr DeleteDC(IntPtr hDc);

        [DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
        public static extern IntPtr DeleteObject(IntPtr hDc);

        [DllImport("gdi32.dll", EntryPoint = "BitBlt")]
        public static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, int RasterOp);

        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleDC(IntPtr hdc);

        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);

        [DllImport("gdi32.dll", EntryPoint = "SelectObject")]
        public static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp);
    }
}

using System;
using System.Runtime.InteropServices;

namespace Mamesaver.Windows
{
    // This class contains the GDI32 APIs used...
    public class PlatformInvokeGdi32
    {
        public const int SRCOPY = 13369376;

        [DllImport("gdi32.dll", EntryPoint = "DeleteDC")]
        public static extern IntPtr DeleteDC(IntPtr hDc);

        [DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
        public static extern IntPtr DeleteObject(IntPtr hDc);

        [DllImport("gdi32.dll", EntryPoint = "BitBlt")]
        public static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, int RasterOp);

        [DllImport("gdi32.dll", EntryPoint = "StretchBlt")]
        public static extern bool StretchBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, int wSrc, int hSrc, int RasterOp);

        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleDC(IntPtr hdc);

        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);

        [DllImport("gdi32.dll", EntryPoint = "SelectObject")]
        public static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp);
    }
}

Add stretchblt for copy and resize

Add stretchblt for copy and resize


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

namespace AppHarbor
{
	public class CommandDispatcher
	{
		private readonly IEnumerable<ICommand> _commands;

		public CommandDispatcher(IEnumerable<ICommand> commands)
		{
			_commands = commands;
		}

		public void Dispatch(string[] args)
		{
			var commandName = args[0];
			var command = _commands.FirstOrDefault(x => x.GetType().Name.ToLower().StartsWith(commandName.ToLower()));

			if (command == null)
			{
				throw new ArgumentException(string.Format("The command \"{0}\" does not exist", commandName));
			}
			command.Execute(args.Skip(1).ToArray());
		}
	}
}

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

namespace AppHarbor
{
	public class CommandDispatcher
	{
		private readonly IEnumerable<ICommand> _commands;

		public CommandDispatcher(IEnumerable<ICommand> commands)
		{
			_commands = commands;
		}

		public void Dispatch(string[] args)
		{
			var commandName = args[0];
			var command = _commands.FirstOrDefault(x => x.GetType().Name.ToLower().StartsWith(commandName.ToLower()));

			if (command == null)
			{
				throw new ArgumentException(string.Format("The command \"{0}\" does not exist", commandName));
			}

			try
			{
				command.Execute(args.Skip(1).ToArray());
			}
			catch (CommandException exception)
			{
				Console.WriteLine(string.Format("Error: {0}", exception.Message));
			}
		}
	}
}

Write command exception message to the console


using System;
using System.Runtime.WootzJs;
using WootzJs.Web;

namespace WootzJs.Mvc.Views
{
    public class TextBox : Control
    {
        public event Action Changed;

        public new InputElement Node
        {
            get { return base.Node.As<InputElement>(); }
        }

        public TextBoxType Type
        {
            get { return TextBoxTypes.Parse(Node.GetAttribute("type")); }
            set { Node.SetAttribute("type", value.GetInputType()); }
        }

        public string Name
        {
            get { return Node.GetAttribute("name"); }
            set { Node.SetAttribute("name", value); }
        }

        public string Placeholder
        {
            get { return Node.GetAttribute("placeholder"); }
            set { Node.SetAttribute("placeholder", value); }
        }

        protected override Element CreateNode()
        {
            var textBox = Browser.Document.CreateElement("input");
            textBox.SetAttribute("type", "text");
            textBox.AddEventListener("change", OnJsChanged);

            return textBox;
        }

        private void OnJsChanged(Event evt)
        {
            var changed = Changed;
            if (changed != null)
                changed();
        }

        public string Text
        {
            get
            {
                EnsureNodeExists();
                return Node.Value;
            }
            set
            {
                EnsureNodeExists();
                Node.Value = value;
            }
        }
    }
}

using System;
using System.Runtime.WootzJs;
using WootzJs.Web;

namespace WootzJs.Mvc.Views
{
    public class TextBox : Control
    {
        public event Action Changed;

        public new InputElement Node
        {
            get { return base.Node.As<InputElement>(); }
        }

        public TextBoxType Type
        {
            get { return TextBoxTypes.Parse(Node.GetAttribute("type")); }
            set { Node.SetAttribute("type", value.GetInputType()); }
        }

        public string Name
        {
            get { return Node.GetAttribute("name"); }
            set { Node.SetAttribute("name", value); }
        }

        public string Placeholder
        {
            get { return Node.GetAttribute("placeholder"); }
            set { Node.SetAttribute("placeholder", value); }
        }

        public int? MaxLength
        {
            get
            {
                var maxLength = Node.GetAttribute("maxlength");
                return maxLength != null ? (int?)int.Parse(maxLength) : null;
            }
            set
            {
                if (value != null)
                    Node.SetAttribute("maxlength", value.Value.ToString());
                else
                    Node.RemoveAttribute("maxlength");
            }
        }

        protected override Element CreateNode()
        {
            var textBox = Browser.Document.CreateElement("input");
            textBox.SetAttribute("type", "text");
            textBox.AddEventListener("change", OnJsChanged);

            return textBox;
        }

        private void OnJsChanged(Event evt)
        {
            var changed = Changed;
            if (changed != null)
                changed();
        }

        public string Text
        {
            get
            {
                EnsureNodeExists();
                return Node.Value;
            }
            set
            {
                EnsureNodeExists();
                Node.Value = value;
            }
        }
    }
}

Add MaxLength property to text boxes

Add MaxLength property to text boxes