using System;

namespace LiveSplit.TimeFormatters
{
    public class PossibleTimeSaveFormatter : ITimeFormatter
    {
        public TimeAccuracy Accuracy { get; set; }

        public string Format(TimeSpan? time)
        {
            var formatter = new ShortTimeFormatter();
            if (time == null)
                return "−";
            else
            {
                var timeString = formatter.Format(time);
                if (Accuracy == TimeAccuracy.Hundredths)
                    return timeString;
                else if (Accuracy == TimeAccuracy.Tenths)
                    return timeString.Substring(0, timeString.Length - 1);
                else
                    return timeString.Substring(0, timeString.Length - 3);

            }

        }
    }
}

using System;

namespace LiveSplit.TimeFormatters
{
    public class PossibleTimeSaveFormatter : ITimeFormatter
    {
        public TimeAccuracy Accuracy { get; set; }

        public string Format(TimeSpan? time)
        {
            var formatter = new ShortTimeFormatter();
            if (time == null)
                return "-";
            else
            {
                var timeString = formatter.Format(time);
                if (Accuracy == TimeAccuracy.Hundredths)
                    return timeString;
                else if (Accuracy == TimeAccuracy.Tenths)
                    return timeString.Substring(0, timeString.Length - 1);
                else
                    return timeString.Substring(0, timeString.Length - 3);

            }

        }
    }
}

Fix dash being minus sign in PTS Formatter


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

using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;

namespace GoogleCloudSamples.Controllers
{
    // [START login]
    public class SessionController : Controller
    {
        public void Login()
        {
            // Redirect to the Google OAuth 2.0 user consent screen
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                "Google"
            );
        }

        // ...
        // [END login]

        // [START logout]
        public ActionResult Logout()
        {
            Request.GetOwinContext().Authentication.SignOut();
            return Redirect("/");
        }
        // [END logout]
    }
}

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

using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;

namespace GoogleCloudSamples.Controllers
{
    public class SessionController : Controller
    {
        // [START login]
        public void Login()
        {
            // Redirect to the Google OAuth 2.0 user consent screen
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                "Google"
            );
        }
        // [END login]

        // [START logout]
        public ActionResult Logout()
        {
            Request.GetOwinContext().Authentication.SignOut();
            return Redirect("/");
        }
        // [END logout]
    }
}

Simplify login docs region & only show action


using MyDocs.Common.Contract.Service;
using MyDocs.Common.Contract.Storage;
using MyDocs.Common.Model;
using MyDocs.WindowsStore.Storage;
using System;
using System.Threading.Tasks;
using Windows.Media.Capture;

namespace MyDocs.WindowsStore.Service
{
    public class CameraService : ICameraService
    {
        public async Task<Photo> CapturePhotoAsync()
        {
            CameraCaptureUI camera = new CameraCaptureUI();
            var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
            if (file == null) {
                return null;
            }
            return new Photo(DateTime.Now.ToString("G"), new WindowsStoreFile(file));
        }
    }
}

using MyDocs.Common.Contract.Service;
using MyDocs.Common.Contract.Storage;
using MyDocs.Common.Model;
using MyDocs.WindowsStore.Storage;
using System;
using System.Threading.Tasks;
using Windows.Media.Capture;

namespace MyDocs.WindowsStore.Service
{
    public class CameraService : ICameraService
    {
        public async Task<Photo> CapturePhotoAsync()
        {
            var camera = new CameraCaptureUI();
            var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
            if (file == null) {
                return null;
            }
            return new Photo(DateTime.Now.ToString("G"), new WindowsStoreFile(file));
        }
    }
}

Use type inference in type definition

Use type inference in type definition


using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Xunit;

namespace AppHarbor.Tests.Commands
{
	public class CreateCommandTest
	{
		private readonly IFixture _fixture;

		public CreateCommandTest()
		{
			_fixture = new Fixture().Customize(new AutoMoqCustomization());
		}

		[Fact]
		public void ShouldCreateApplication()
		{
			var client = _fixture.Freeze<Mock<IAppHarborClient>>();
			var command = _fixture.CreateAnonymous<CreateCommand>();

			command.Execute(new string[] { "foo", "var" });

			client.Verify(x => x.CreateApplication("bar", "baz"), Times.Once());
		}
	}
}

using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;

namespace AppHarbor.Tests.Commands
{
	public class CreateCommandTest
	{
		private readonly IFixture _fixture;

		public CreateCommandTest()
		{
			_fixture = new Fixture().Customize(new AutoMoqCustomization());
		}

		[Theory, AutoCommandData]
		public void ShouldCreateApplication([Frozen]Mock<IAppHarborClient> client, CreateCommand command)
		{
			command.Execute(new string[] { "foo", "bar" });

			client.Verify(x => x.CreateApplication("foo", "bar"), Times.Once());
		}
	}
}

Refactor test to use AutoCommandData

Refactor test to use AutoCommandData


using System.ComponentModel.DataAnnotations;
using API.WindowsService.Validators;
using Contract;
using FluentValidation.Attributes;

namespace API.WindowsService.Models
{
    [Validator(typeof(AudioRequestValidator))]
    public class AudioJobRequestModel : JobRequestModel
    {
        [Required]
        public AudioDestinationFormat[] Targets { get; set; }

        public string DestinationFilenamePrefix { get; set; }

        [Required]
        public string SourceFilename { get; set; }
    }
}

using System.ComponentModel.DataAnnotations;
using API.WindowsService.Validators;
using Contract;
using FluentValidation.Attributes;

namespace API.WindowsService.Models
{
    [Validator(typeof(AudioRequestValidator))]
    public class AudioJobRequestModel : JobRequestModel
    {
        [Required]
        public AudioDestinationFormat[] Targets { get; set; }

        [Required]
        public string DestinationFilenamePrefix { get; set; }

        [Required]
        public string SourceFilename { get; set; }
    }
}

Change DestinationFilenamePrefix to be a required field


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

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

namespace osu.Game.Overlays.Settings.Sections.UserInterface
{
    public class GeneralSettings : SettingsSubsection
    {
        protected override LocalisableString Header => UserInterfaceStrings.GeneralHeader;

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsCheckbox
                {
                    LabelText = UserInterfaceStrings.CursorRotation,
                    Current = config.GetBindable<bool>(OsuSetting.CursorRotation)
                },
                new SettingsSlider<float, SizeSlider>
                {
                    LabelText = UserInterfaceStrings.MenuCursorSize,
                    Current = config.GetBindable<float>(OsuSetting.MenuCursorSize),
                    KeyboardStep = 0.01f
                },
                new SettingsCheckbox
                {
                    LabelText = UserInterfaceStrings.Parallax,
                    Current = config.GetBindable<bool>(OsuSetting.MenuParallax)
                },
                new SettingsSlider<double, TimeSlider>
                {
                    LabelText = UserInterfaceStrings.HoldToConfirmActivationTime,
                    Current = config.GetBindable<double>(OsuSetting.UIHoldActivationDelay),
                    KeyboardStep = 50
                },
            };
        }
    }
}

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

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

namespace osu.Game.Overlays.Settings.Sections.UserInterface
{
    public class GeneralSettings : SettingsSubsection
    {
        protected override LocalisableString Header => UserInterfaceStrings.GeneralHeader;

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsCheckbox
                {
                    LabelText = UserInterfaceStrings.CursorRotation,
                    Current = config.GetBindable<bool>(OsuSetting.CursorRotation)
                },
                new SettingsSlider<float, SizeSlider>
                {
                    LabelText = UserInterfaceStrings.MenuCursorSize,
                    Current = config.GetBindable<float>(OsuSetting.MenuCursorSize),
                    KeyboardStep = 0.01f
                },
                new SettingsCheckbox
                {
                    LabelText = UserInterfaceStrings.Parallax,
                    Current = config.GetBindable<bool>(OsuSetting.MenuParallax)
                },
                new SettingsSlider<double, TimeSlider>
                {
                    LabelText = UserInterfaceStrings.HoldToConfirmActivationTime,
                    Current = config.GetBindable<double>(OsuSetting.UIHoldActivationDelay),
                    Keywords = new[] { @"delay" },
                    KeyboardStep = 50
                },
            };
        }
    }
}

Add keyword "delay" to hold-to-confirm activation time setting


using System;
using System.Windows.Input;

namespace OutlookMatters.Settings
{
    public class SaveCommand : ICommand
    {
        private readonly ISettingsSaveService _saveService;
        private readonly IClosableWindow _window;

        public SaveCommand(ISettingsSaveService saveService, IClosableWindow window)
        {
            _saveService = saveService;
            _window = window;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            var viewModel = parameter as SettingsViewModel;
            if (viewModel == null)
            {
                throw new ArgumentException(@"Invalid ViewModel", nameof(parameter));
            }
            var settings = new Settings(
                viewModel.MattermostUrl,
                viewModel.TeamId,
                viewModel.ChannelId,
                viewModel.Username,
                Properties.Settings.Default.ChannelsMap
                );
            _saveService.Save(settings);
            _window.Close();
        }

        public event EventHandler CanExecuteChanged;
    }
}

using System;
using System.Windows.Input;

namespace OutlookMatters.Settings
{
    public class SaveCommand : ICommand
    {
        private readonly ISettingsSaveService _saveService;
        private readonly IClosableWindow _window;

        public SaveCommand(ISettingsSaveService saveService, IClosableWindow window)
        {
            _saveService = saveService;
            _window = window;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            var viewModel = parameter as SettingsViewModel;
            if (viewModel == null)
            {
                throw new ArgumentException(@"Invalid ViewModel ", "parameter");
            }
            var settings = new Settings(
                viewModel.MattermostUrl,
                viewModel.TeamId,
                viewModel.ChannelId,
                viewModel.Username,
                Properties.Settings.Default.ChannelsMap
                );
            _saveService.Save(settings);
            _window.Close();
        }

        public event EventHandler CanExecuteChanged;
    }
}

Refactor to build on Visual Studio 2013

Refactor to build on Visual Studio 2013


using UnityEngine;
using System.Collections;

public abstract class ConsoleAction : ActionBase {
  public abstract void Activate();
}

using UnityEngine;
using System.Collections;

public abstract class ConsoleAction : MonoBehaviour {
  public abstract void Activate();
}

Fix exception when including this in a project without TriggerAction


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

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

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

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

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

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

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

[assembly: InternalsVisibleTo ("NDesk.DBus.GLib")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]

Use the correct strong name for dbus-sharp-glib friend assembly


using System;
using System.Collections.Generic;

namespace NValidate
{
    public class BaseEnviron : Environ
    {
        readonly Dictionary<Type, Func<Environ, object>> _modelExtractors;
        readonly Dictionary<Type, object> _models;

        public BaseEnviron(Dictionary<Type, Func<Environ, object>> modelExtractors, Dictionary<Type, object> models)
        {
            _modelExtractors = modelExtractors;
            _models = models;
        }

        public override Environ Add(object model)
        {
            return new LinkedEnviron(model, this);
        }

        public override object GetByType(Type type, Environ topEnviron = null)
        {
            object result = null;
            _models.TryGetValue(type, out result);

            if (result != null)
            {
                return result;
            }
            else if (_modelExtractors != null)
            {
                Func<Environ, object> extractor = null;
                if (!_modelExtractors.TryGetValue(type, out extractor))
                    return null;

                return extractor(topEnviron ?? this);
            }
            else
            {
                return null;
            }
        }
    }
}

using System;
using System.Collections.Generic;

namespace NValidate
{
    public class BaseEnviron : Environ
    {
        readonly Dictionary<Type, Func<Environ, object>> _modelExtractors;
        readonly Dictionary<Type, object> _models;

        public BaseEnviron(Dictionary<Type, Func<Environ, object>> modelExtractors, Dictionary<Type, object> models)
        {
            _modelExtractors = modelExtractors;
            _models = models;
        }

        public override Environ Add(object model)
        {
            return new LinkedEnviron(model, this);
        }

        public override object GetByType(Type type, Environ topEnviron = null)
        {
            object result = null;
            _models.TryGetValue(type, out result);

            if (result != null)
            {
                return result;
            }
            else if (_modelExtractors != null)
            {
                Func<Environ, object> extractor = null;
                if (!_modelExtractors.TryGetValue(type, out extractor))
                    return null;

                return extractor(topEnviron ?? this);
            }
            else
            {
                return null;
            }
        }
    }

    public class BaseEnvironBuilder
    {
        readonly Dictionary<Type, Func<Environ, object>> _modelExtractors;
        readonly Dictionary<Type, object> _models;

        public BaseEnvironBuilder()
        {
            _modelExtractors = new Dictionary<Type, Func<Environ, object>>();
            _models = new Dictionary<Type, object>();
        }

        public BaseEnvironBuilder AddModel(object model)
        {
            _models[model.GetType()] = model;
            return this;
        }

        public BaseEnvironBuilder AddModelExtractor<T>(Func<Environ, object> modelExtractor)
        {
            _models[typeof(T)] = modelExtractor;
            return this;
        }

        public BaseEnviron Build()
        {
            return new BaseEnviron(_modelExtractors, _models);
        }
    }
}

Add a builder for the base environ, so it's easier to work with


// Copyright 2015 Apcera Inc. All rights reserved.

using System;

namespace NATS.Client
{
    // Tracks individual backend servers.
    internal class Srv
    {
        internal Uri url = null;
        internal bool didConnect = false;
        internal int reconnects = 0;
        internal DateTime lastAttempt = DateTime.Now;
        internal bool isImplicit = false;

        // never create a srv object without a url.
        private Srv() { }

        internal Srv(string urlString)
        {
            // allow for host:port, without the prefix.
            if (urlString.ToLower().StartsWith("nats") == false)
                urlString = "nats://" + urlString;

            url = new Uri(urlString);
        }

        internal Srv(string urlString, bool isUrlImplicit) : this(urlString)
        {
            isImplicit = isUrlImplicit;
        }

        internal void updateLastAttempt()
        {
            lastAttempt = DateTime.Now;
        }

        internal TimeSpan TimeSinceLastAttempt
        {
            get
            {
                return (DateTime.Now - lastAttempt);
            }
        }
    }
}

// Copyright 2015 Apcera Inc. All rights reserved.

using System;

namespace NATS.Client
{
    // Tracks individual backend servers.
    internal class Srv
    {
        internal Uri url = null;
        internal bool didConnect = false;
        internal int reconnects = 0;
        internal DateTime lastAttempt = DateTime.Now;
        internal bool isImplicit = false;

        // never create a srv object without a url.
        private Srv() { }

        internal Srv(string urlString)
        {
            // allow for host:port, without the prefix.
            if (urlString.ToLower().StartsWith("nats://") == false)
                urlString = "nats://" + urlString;

            url = new Uri(urlString);
        }

        internal Srv(string urlString, bool isUrlImplicit) : this(urlString)
        {
            isImplicit = isUrlImplicit;
        }

        internal void updateLastAttempt()
        {
            lastAttempt = DateTime.Now;
        }

        internal TimeSpan TimeSinceLastAttempt
        {
            get
            {
                return (DateTime.Now - lastAttempt);
            }
        }
    }
}

Fix problem with parsing server url.

Fix problem with parsing server url.

When passed urlString starts with ‘nats’ (like ‘nats.domain.com’) the protocol supplement will be skipped and connection will fail.


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

namespace EddiDataDefinitions
{
    ///
    /// A star or planet
    ///
    public class Body
    {
        /// The ID of this body in EDDB
        public long EDDBID { get; set; }

        /// The name of the body
        public string name { get; set;  }

        ///
        /// Convert gravity in m/s to g
        ///
        public static decimal ms2g(decimal gravity)
        {
            return gravity / (decimal)9.8;
        }
    }
}

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

namespace EddiDataDefinitions
{
    ///
    /// A star or planet
    ///
    public class Body
    {
        /// The ID of this body in EDDB
        public long EDDBID { get; set; }

        /// The name of the body
        public string name { get; set;  }

        ///
        /// Convert gravity in m/s to g
        ///
        public static decimal ms2g(decimal gravity)
        {
            return gravity / (decimal)9.80665;
        }
    }
}

Increase precision of 'g', as requested.


using NSubstitute;
using NUnit.Framework;

namespace DependencyKata.Tests
{
    [TestFixture]
    public class DoItAllTests
    {
        [Test, Category("Integration")]
        public void DoItAll_Does_ItAll()
        {
            var expected = "The passwords don't match";
            var io = Substitute.For<IOutputInputAdapter>();
            var logging = Substitute.For<ILogging>();
            var doItAll = new DoItAll(io, logging);
            var result = doItAll.Do();
            Assert.AreEqual(expected, result);
        }
        [Test, Category("Integration")]
        public void DoItAll_Does_ItAll_MatchingPasswords()
        {
            var expected = "Database.SaveToLog Exception:";
            var io = Substitute.For<IOutputInputAdapter>();
            io.GetInput().Returns("something");
            var logging = new DatabaseLogging();
            var doItAll = new DoItAll(io, logging);
            var result = doItAll.Do();
            StringAssert.Contains(expected, result);
        }
        [Test, Category("Integration")]
        public void DoItAll_Does_ItAll_MockLogging()
        {
            var expected = string.Empty;
            var io = Substitute.For<IOutputInputAdapter>();
            io.GetInput().Returns("something");
            var logging = Substitute.For<ILogging>();
            var doItAll = new DoItAll(io, logging);
            var result = doItAll.Do();
            StringAssert.Contains(expected, result);
        }
    }
}

using NSubstitute;
using NUnit.Framework;

namespace DependencyKata.Tests
{
    [TestFixture]
    public class DoItAllTests
    {
        [Test, Category("Integration")]
        public void DoItAll_Does_ItAll()
        {
            var expected = "The passwords don't match";
            var io = Substitute.For<IOutputInputAdapter>();
            var logging = Substitute.For<ILogging>();
            var doItAll = new DoItAll(io, logging);
            var result = doItAll.Do();
            Assert.AreEqual(expected, result);
        }
        [Test, Category("Integration")]
        public void DoItAll_Does_ItAll_MatchingPasswords()
        {
            var expected = "Database.SaveToLog Exception:";
            var io = Substitute.For<IOutputInputAdapter>();
            io.GetInput().Returns("something");
            var logging = new DatabaseLogging();
            var doItAll = new DoItAll(io, logging);
            var result = doItAll.Do();
            StringAssert.Contains(expected, result);
        }
        [Test]
        public void DoItAll_Does_ItAll_MockLogging()
        {
            var expected = string.Empty;
            var io = Substitute.For<IOutputInputAdapter>();
            io.GetInput().Returns("something");
            var logging = Substitute.For<ILogging>();
            var doItAll = new DoItAll(io, logging);
            var result = doItAll.Do();
            StringAssert.Contains(expected, result);
        }
    }
}

Update Step 3 - Remove integration test category.


using System.Collections.Generic;
using MeidoCommon;

namespace MeidoBot
{
    public static class PluginExtensions
    {
        public static string Name(this IMeidoHook plugin)
        {
            string name = plugin.Name.Trim();
            switch (name)
            {
                case "":
                case null:
                name = "Unknown";
                break;
                // Reserved names.
                case "Main":
                case "Meido":
                case "Triggers":
                case "Auth":
                name = "_" + name;
                break;
            }

            return name;
        }

        public static Dictionary<string, string> Help(this IMeidoHook plugin)
        {
            if (plugin.Help != null)
                return plugin.Help;

            return new Dictionary<string, string>();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using MeidoCommon;

namespace MeidoBot
{
    public static class PluginExtensions
    {
        public static string Name(this IMeidoHook plugin)
        {
            string name = plugin.Name.Trim();
            switch (name)
            {
                case "":
                case null:
                name = "Unknown";
                break;
                // Reserved names.
                case "Main":
                case "Meido":
                case "Triggers":
                case "Auth":
                name = "_" + name;
                break;
            }

            return name;
        }

        public static Dictionary<string, string> Help(this IMeidoHook plugin)
        {
            if (plugin.Help != null)
                return plugin.Help;

            return new Dictionary<string, string>();
        }

        public static bool Query(this TriggerHelp root, string[] fullCommand, out CommandHelp help)
        {
            help = null;
            var cmdHelpNodes = root.Commands;
            foreach (string cmdPart in fullCommand)
            {
                if (TryGetHelp(cmdPart, cmdHelpNodes, out help))
                    cmdHelpNodes = help.Subcommands;
                else
                {
                    help = null;
                    break;
                }
            }

            return help != null;
        }

        static bool TryGetHelp(
            string command,
            ReadOnlyCollection<CommandHelp> searchSpace,
            out CommandHelp help)
        {
            foreach (var cmdHelp in searchSpace)
            {
                if (cmdHelp.Command.Equals(command, StringComparison.Ordinal))
                {
                    help = cmdHelp;
                    return true;
                }
            }

            help = null;
            return false;
        }
    }
}

Extend TriggerHelp for querying help

MeidoBot: Extend TriggerHelp for querying help


using Sloth.Interfaces.Core;
using System;

namespace Sloth.Core
{
    public class WinUtilities : IWinUtilities
    {
        public IntPtr FindControlHandle(IntPtr windowsHandle, string controlName)
        {
            throw new NotImplementedException();
        }

        public IntPtr FindWindowsHandle(string className,string windowsName)
        {
            throw new NotImplementedException();
        }

        public string GetClassName(IntPtr windowsHandle)
        {
            throw new NotImplementedException();
        }

        public string GetWindowText(IntPtr windowsHandle)
        {
            throw new NotImplementedException();
        }

        public void SendMessage(IntPtr windowsHandle, IntPtr controlHandle, ISlothEvent slothEvent)
        {
            throw new NotImplementedException();
        }
    }

}

using Sloth.Interfaces.Core;
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Sloth.Core
{
    public class WinUtilities : IWinUtilities
    {
        public IntPtr FindControlHandle(IntPtr windowsHandle, string controlName)
        {
            throw new NotImplementedException();
        }

        public IntPtr FindWindowsHandle(string className,string windowsName)
        {
            throw new NotImplementedException();
        }

        public string GetClassName(IntPtr windowsHandle)
        {
            throw new NotImplementedException();
        }

        public string GetWindowText(IntPtr windowsHandle)
        {
            throw new NotImplementedException();
        }

        public void SendMessage(IntPtr windowsHandle, IntPtr controlHandle, ISlothEvent slothEvent)
        {
            throw new NotImplementedException();
        }

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        [DllImport("user32.dll")]
        static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    }

}

Add user32 function in winutilities

Add user32 function in winutilities


namespace Framework.Cli.Command
{
    /// <summary>
    /// Cli start command.
    /// </summary>
    public class CommandStart : CommandBase
    {
        public CommandStart(AppCli appCli)
            : base(appCli, "start", "Start server and open browser")
        {

        }

        protected internal override void Execute()
        {
            CommandBuild.InitConfigWebServer(AppCli); // Copy ConnectionString from ConfigCli.json to ConfigWebServer.json.

            string folderName = UtilFramework.FolderName + @"Application.Server/";
            UtilCli.DotNet(folderName, "build");
            UtilCli.DotNet(folderName, "run --no-build", false);
            UtilCli.OpenWebBrowser("http://localhost:50919/"); // For port setting see also: Application.Server\Properties\launchSettings.json (applicationUrl, sslPort)
        }
    }
}

namespace Framework.Cli.Command
{
    using System.Runtime.InteropServices;

    /// <summary>
    /// Cli start command.
    /// </summary>
    public class CommandStart : CommandBase
    {
        public CommandStart(AppCli appCli)
            : base(appCli, "start", "Start server and open browser")
        {

        }

        protected internal override void Execute()
        {
            CommandBuild.InitConfigWebServer(AppCli); // Copy ConnectionString from ConfigCli.json to ConfigWebServer.json.

            string folderName = UtilFramework.FolderName + @"Application.Server/";
            UtilCli.DotNet(folderName, "build");
            UtilCli.DotNet(folderName, "run --no-build", false);
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                UtilCli.OpenWebBrowser("http://localhost:50919/"); // For port setting see also: Application.Server\Properties\launchSettings.json (applicationUrl, sslPort)
            }
        }
    }
}

Update for cli start command on Ubuntu

Update for cli start command on Ubuntu


// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dependencies;

namespace Core2D.Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateSampleProject();
        }

        static EditorContext CreateContext()
        {
            var context = new EditorContext()
            {
                View = null,
                Renderers = null,
                ProjectFactory = new ProjectFactory(),
                TextClipboard = null,
                Serializer = new NewtonsoftSerializer(),
                PdfWriter = null,
                DxfWriter = null,
                CsvReader = null,
                CsvWriter = null
            };

            context.InitializeEditor();
            context.InitializeCommands();
            context.New();

            return context;
        }

        static void CreateSampleProject()
        {
            try
            {
                var context = CreateContext();

                var factory = new ShapeFactory(context);

                factory.Line(30, 30, 60, 30);
                factory.Text(30, 30, 60, 60, "Sample");

                context.Save("sample.project");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.ReadKey(true);
            }
        }
    }
}

// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dependencies;

namespace Core2D.Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateSampleProject();
        }

        static EditorContext CreateContext()
        {
            var context = new EditorContext()
            {
                View = null,
                Renderers = null,
                ProjectFactory = new ProjectFactory(),
                TextClipboard = null,
                Serializer = new NewtonsoftSerializer(),
                PdfWriter = null,
                DxfWriter = null,
                CsvReader = null,
                CsvWriter = null
            };

            var project = context.ProjectFactory.GetProject();

            context.Editor = Editor.Create(project);

            context.New();

            return context;
        }

        static void CreateSampleProject()
        {
            try
            {
                var context = CreateContext();

                var factory = new ShapeFactory(context);

                factory.Line(30, 30, 60, 30);
                factory.Text(30, 30, 60, 60, "Sample");

                context.Save("sample.project");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.ReadKey(true);
            }
        }
    }
}

Create project and editor explicitly

Create project and editor explicitly


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

namespace Shippo
{
    [JsonObject (MemberSerialization.OptIn)]
    public class BatchShipment : ShippoId
    {
        [JsonProperty (PropertyName = "object_status")]
        public string ObjectStatus;

        [JsonProperty (PropertyName = "carrier_account")]
        public string CarrierAccount;

        [JsonProperty (PropertyName = "servicelevel_token")]
        public string ServicelevelToken;

        [JsonProperty (PropertyName = "shipment")]
        public Object Shipment;

        [JsonProperty (PropertyName = "transaction")]
        public string Transaction;

        [JsonProperty (PropertyName = "messages")]
        public List<String> Messages;

        [JsonProperty (PropertyName = "metadata")]
        public string Metadata;

        public override string ToString ()
        {
            return string.Format ("[BatchShipment: ObjectStatus={0}, CarrierAccount={1}, ServicelevelToken={2}, " +
                                  "Shipment={3}, Transaction={4}, Messages={5}, Metadata={6}]", ObjectStatus,
                                  CarrierAccount, ServicelevelToken, Shipment, Transaction, Messages, Metadata);
        }
    }
}

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

namespace Shippo
{
    [JsonObject (MemberSerialization.OptIn)]
    public class BatchShipment : ShippoId
    {
        [JsonProperty (PropertyName = "object_status")]
        public string ObjectStatus;

        [JsonProperty (PropertyName = "carrier_account")]
        public string CarrierAccount;

        [JsonProperty (PropertyName = "servicelevel_token")]
        public string ServicelevelToken;

        [JsonProperty (PropertyName = "shipment")]
        public Object Shipment;

        [JsonProperty (PropertyName = "transaction")]
        public string Transaction;

        [JsonProperty (PropertyName = "messages")]
        public object Messages;

        [JsonProperty (PropertyName = "metadata")]
        public string Metadata;

        public override string ToString ()
        {
            return string.Format ("[BatchShipment: ObjectStatus={0}, CarrierAccount={1}, ServicelevelToken={2}, " +
                                  "Shipment={3}, Transaction={4}, Messages={5}, Metadata={6}]", ObjectStatus,
                                  CarrierAccount, ServicelevelToken, Shipment, Transaction, Messages, Metadata);
        }
    }
}

Change messages attribute to type "object"


using System;
using System.Threading;
using System.Windows.Threading;
using Throttle;
using Xunit;
using TomsToolbox.Desktop;

public class ThrottleSample
{
    int throttledCalls;

    [Fact]
    public void Run()
    {
        var dispatcher = Dispatcher.CurrentDispatcher;

        dispatcher.BeginInvoke(() =>
        {
            ThrottledMethod();
            Delay(5);
            ThrottledMethod();
            Delay(5);
            ThrottledMethod();
            Delay(5);
            ThrottledMethod();
            Delay(5);
            ThrottledMethod();
            Delay(5);
            Assert.Equal(0, throttledCalls);
            Delay(20);
            Assert.Equal(1, throttledCalls);

            dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle);
        });

        Dispatcher.Run();
    }

    static void Delay(int timeSpan)
    {
        var frame = new DispatcherFrame();
        var timer = new DispatcherTimer(TimeSpan.FromMilliseconds(timeSpan), DispatcherPriority.Normal, (sender, args) => frame.Continue = false, Dispatcher.CurrentDispatcher);
        timer.Start();
        Dispatcher.PushFrame(frame);
    }

    [Throttled(typeof(TomsToolbox.Desktop.Throttle), 10)]
    void ThrottledMethod()
    {
        Interlocked.Increment(ref throttledCalls);
    }
}

using System;
using System.Threading;
using System.Windows.Threading;
using Throttle;
using Xunit;
using TomsToolbox.Desktop;

public class ThrottleSample
{
    int throttledCalls;

    [Fact]
    public void Run()
    {
        var dispatcher = Dispatcher.CurrentDispatcher;

        dispatcher.BeginInvoke(() =>
        {
            ThrottledMethod();
            Delay(5);
            ThrottledMethod();
            Delay(5);
            ThrottledMethod();
            Delay(5);
            ThrottledMethod();
            Delay(5);
            ThrottledMethod();
            Delay(5);
            Assert.Equal(0, throttledCalls);
            Delay(200);
            Assert.Equal(1, throttledCalls);

            dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle);
        });

        Dispatcher.Run();
    }

    static void Delay(int timeSpan)
    {
        var frame = new DispatcherFrame();
        var timer = new DispatcherTimer(TimeSpan.FromMilliseconds(timeSpan), DispatcherPriority.Normal, (sender, args) => frame.Continue = false, Dispatcher.CurrentDispatcher);
        timer.Start();
        Dispatcher.PushFrame(frame);
    }

    [Throttled(typeof(TomsToolbox.Desktop.Throttle), 100)]
    void ThrottledMethod()
    {
        Interlocked.Increment(ref throttledCalls);
    }
}

Adjust timing ratio to prevent occasional failing


using System;
using Treehopper;
using System.Threading.Tasks;

using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;

namespace Blink
{
    /// <summary>
    /// This demo blinks the built-in LED using async programming.
    /// </summary>
    class Program
    {
        static TreehopperUsb Board;
        static void Main(string[] args)
        {
            // We can't do async calls from the Console's Main() function, so we run all our code in a separate async method.
            RunBlink().Wait();
        }
        static async Task RunBlink()
        {
            while (true)
            {
                Console.Write("Waiting for board...");
                // Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected.
                Board = await ConnectionService.Instance.GetFirstDeviceAsync();

                Console.WriteLine("Found board: " + Board);
                Console.WriteLine("Version: " + Board.Version);

                // You must explicitly connect to a board before communicating with it
                await Board.ConnectAsync();
                Board.Pins[0].SoftPwm.Enabled = true;
                Board.Pins[0].SoftPwm.DutyCycle = 0.5;
                Console.WriteLine("Start blinking. Press any key to stop.");
                while (Board.IsConnected && !Console.KeyAvailable)
                {
                    // toggle the LED.
                    Board.Led = !Board.Led;
                    await Task.Delay(100);
                }
            }

        }
    }
}

using System;
using Treehopper;
using System.Threading.Tasks;

using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;

namespace Blink
{
    /// <summary>
    /// This demo blinks the built-in LED using async programming.
    /// </summary>
    class Program
    {
        static TreehopperUsb Board;
        static void Main(string[] args)
        {
            // We can't do async calls from the Console's Main() function, so we run all our code in a separate async method.
            RunBlink().Wait();
        }
        static async Task RunBlink()
        {
            while (true)
            {
                Console.Write("Waiting for board...");
                // Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected.
                Board = await ConnectionService.Instance.GetFirstDeviceAsync();

                Console.WriteLine("Found board: " + Board);
                Console.WriteLine("Version: " + Board.Version);

                // You must explicitly connect to a board before communicating with it
                await Board.ConnectAsync();

                Console.WriteLine("Start blinking. Press any key to stop.");
                while (Board.IsConnected && !Console.KeyAvailable)
                {
                    // toggle the LED.
                    Board.Led = !Board.Led;
                    await Task.Delay(100);
                }
            }

        }
    }
}

Remove random SoftPwm test code

Remove random SoftPwm test code


@model biz.dfch.CS.Appclusive.UI.Models.Core.Acl
@using biz.dfch.CS.Appclusive.UI.App_LocalResources

@if (Model != null && !string.IsNullOrEmpty(Model.Name))
{
    if (biz.dfch.CS.Appclusive.UI.Navigation.PermissionDecisions.Current.HasPermission(Model.GetType(), "CanRead"))
    {
        string id = (string)ViewContext.Controller.ControllerContext.RouteData.Values["id"];
        string action = (string)ViewContext.Controller.ControllerContext.RouteData.Values["action"];
        string controller = (string)ViewContext.Controller.ControllerContext.RouteData.Values["controller"];
        @Html.ActionLink(Model.Name, "ItemDetails", "Acls", new { id = Model.Id, rId = id, rAction = action, rController = controller }, null)
    }
    else
    {
        @Html.DisplayFor(model => model.Name)
    }
}

@model biz.dfch.CS.Appclusive.UI.Models.Core.Acl
@using biz.dfch.CS.Appclusive.UI.App_LocalResources

@if (Model != null && !string.IsNullOrEmpty(Model.Name))
{
    if (biz.dfch.CS.Appclusive.UI.Navigation.PermissionDecisions.Current.HasPermission(Model.GetType(), "CanRead"))
    {
        string id = (string)ViewContext.Controller.ControllerContext.RouteData.Values["id"];
        string action = (string)ViewContext.Controller.ControllerContext.RouteData.Values["action"];
        string controller = (string)ViewContext.Controller.ControllerContext.RouteData.Values["controller"];
        @Html.ActionLink(Model.Name, "Details", "Acls", new { id = Model.Id, rId = id, rAction = action, rController = controller }, null)
    }
    else
    {
        @Html.DisplayFor(model => model.Name)
    }
}

Fix Navigation link on acl

Fix Navigation link on acl


@Html.ActionLink("Michael's Music", "Index", "Home")

                    Guitars

All Guitars

Guitars by Brand

                    Amps

All Amps

Amps by Brand

                    Pedals

All Pedals

Pedals by Brand

                    @Html.ActionLink("About", "About", "Home")

@Html.ActionLink("Michael's Music", "Index", "Home")

                    Guitars

                    Amps

                    Pedals

                    @Html.ActionLink("About", "About", "Home")

Remove drop menus from main menu

Remove drop menus from main menu


using System.Collections.Generic;
using Hacknet;
using HarmonyLib;
using Pathfinder.Event;
using Pathfinder.Event.Loading;
using Pathfinder.Util;

namespace Pathfinder.BaseGameFixes.Performance
{
    [HarmonyPatch]
    internal static class NodeLookup
    {
        [HarmonyPostfix]
        [HarmonyPatch(typeof(List<Computer>), nameof(List<Computer>.Add))]
        internal static void AddComputerReference(List<Computer> __instance, Computer item)
        {
            if (object.ReferenceEquals(__instance, OS.currentInstance?.netMap?.nodes))
            {
                ComputerLookup.PopulateLookups(item);
            }
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
        internal static bool ModifyComputerLoaderLookup(out Computer __result, string target)
        {
            __result = ComputerLookup.FindById(target);
            return false;
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
        internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name)
        {
            __result = ComputerLookup.Find(ip_Or_ID_or_Name);
            return false;
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
        internal static void ClearOnQuitGame()
        {
            ComputerLookup.ClearLookups();
        }
    }
}

using System.Collections.Generic;
using Hacknet;
using HarmonyLib;
using Pathfinder.Event;
using Pathfinder.Event.Loading;
using Pathfinder.Util;

namespace Pathfinder.BaseGameFixes.Performance
{
    [HarmonyPatch]
    internal static class NodeLookup
    {
        [HarmonyPostfix]
        [HarmonyPatch(typeof(List<Computer>), nameof(List<Computer>.Add))]
        [HarmonyPatch(typeof(List<Computer>), nameof(List<Computer>.Insert))]
        internal static void AddComputerReference(List<Computer> __instance, Computer item)
        {
            if (object.ReferenceEquals(__instance, OS.currentInstance?.netMap?.nodes))
            {
                ComputerLookup.PopulateLookups(item);
            }
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
        internal static bool ModifyComputerLoaderLookup(out Computer __result, string target)
        {
            __result = ComputerLookup.FindById(target);
            return false;
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
        internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name)
        {
            __result = ComputerLookup.Find(ip_Or_ID_or_Name);
            return false;
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
        internal static void ClearOnQuitGame()
        {
            ComputerLookup.ClearLookups();
        }
    }
}

Make sure playerComp is in the node lookup list


using System;
using System.Linq;

namespace SSLLWrapper.ConsoleAppTester
{
	class Program
	{
		private const string apiUrl = "https://api.dev.ssllabs.com/api/fa78d5a4";

		static void Main(string[] args)
		{
			AnalyzeTester();
		}

		static void AnalyzeTester()
		{
			var apiService = new ApiService(apiUrl);
			var analyze = apiService.Analyze("http://www.ashleypoole.co.uk");

			Console.WriteLine("Has Error Occoured: {0}", analyze.HasErrorOccurred);
			Console.WriteLine("Status Code: {0}", analyze.Headers.statusCode);
			Console.WriteLine("Status: {0}", analyze.status);

			Console.ReadLine();
		}
	}
}

using System;
using System.Linq;

namespace SSLLWrapper.ConsoleAppTester
{
	class Program
	{
		private const string ApiUrl = "https://api.dev.ssllabs.com/api/fa78d5a4";
		static readonly ApiService ApiService = new ApiService(ApiUrl);

		static void Main(string[] args)
		{
			//AnalyzeTester();
			//InfoTester();
			GetEndpointData();
		}

		static void InfoTester()
		{
			var info = ApiService.Info();

			Console.WriteLine("Has Error Occoured: {0}", info.HasErrorOccurred);
			Console.WriteLine("Status Code: {0}", info.Headers.statusCode);
			Console.WriteLine("Engine Version: {0}", info.engineVersion);
			Console.WriteLine("Online: {0}", info.Online);

			Console.ReadLine();
		}

		static void AnalyzeTester()
		{
			var analyze = ApiService.Analyze("http://www.ashleypoole.co.uk");

			Console.WriteLine("Has Error Occoured: {0}", analyze.HasErrorOccurred);
			Console.WriteLine("Status Code: {0}", analyze.Headers.statusCode);
			Console.WriteLine("Status: {0}", analyze.status);

			Console.ReadLine();
		}

		static void GetEndpointData()
		{
			var endpointDataModel = ApiService.GetEndpointData("http://www.ashleypoole.co.uk", "104.28.6.2");

			Console.WriteLine("Has Error Occoured: {0}", endpointDataModel.HasErrorOccurred);
			Console.WriteLine("Status Code: {0}", endpointDataModel.Headers.statusCode);
			Console.WriteLine("IP Adress: {0}", endpointDataModel.ipAddress);
			Console.WriteLine("Grade: {0}", endpointDataModel.grade);
			Console.WriteLine("Status Message: {0}", endpointDataModel.statusMessage);

			Console.ReadLine();
		}
	}
}

Add GetEndpointData manual test to ConsoleAppTester


using Mono.Cecil;
using Mono.Cecil.Cil;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MonoMod.DebugIL {
    public static class DebugILGeneratorExt {

        public readonly static Type t_MetadataType = typeof(MetadataType);

        public static ScopeDebugInformation GetOrAddScope(this MethodDebugInformation mdi) {
            if (mdi.Scope != null)
                return mdi.Scope;
            return mdi.Scope = new ScopeDebugInformation(
                mdi.Method.Body.Instructions[0],
                mdi.Method.Body.Instructions[mdi.Method.Body.Instructions.Count - 1]
            );
        }

        public static string GenerateVariableName(this VariableDefinition @var, MethodDefinition method = null, int i = -1) {
            TypeReference type = @var.VariableType;
            string name = type.Name;

            if (type.MetadataType == MetadataType.Boolean)
                name = "flag";
            else if (type.IsPrimitive)
                name = Enum.GetName(t_MetadataType, type.MetadataType);

            name = name.Substring(0, 1).ToLowerInvariant() + name.Substring(1);

            if (method == null)
                return i < 0 ? name : (name + i);

            // Check for usage as loop counter or similar?

            return i < 0 ? name : (name + i);
        }

    }
}

using Mono.Cecil;
using Mono.Cecil.Cil;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MonoMod.DebugIL {
    public static class DebugILGeneratorExt {

        public readonly static Type t_MetadataType = typeof(MetadataType);

        public static ScopeDebugInformation GetOrAddScope(this MethodDebugInformation mdi) {
            if (mdi.Scope != null)
                return mdi.Scope;
            return mdi.Scope = new ScopeDebugInformation(
                mdi.Method.Body.Instructions[0],
                mdi.Method.Body.Instructions[mdi.Method.Body.Instructions.Count - 1]
            );
        }

        public static string GenerateVariableName(this VariableDefinition @var, MethodDefinition method = null, int i = -1) {
            TypeReference type = @var.VariableType;
            while (type is TypeSpecification)
                type = ((TypeSpecification) type).ElementType;

            string name = type.Name;

            if (type.MetadataType == MetadataType.Boolean)
                name = "flag";
            else if (type.IsPrimitive)
                name = Enum.GetName(t_MetadataType, type.MetadataType);

            name = name.Substring(0, 1).ToLowerInvariant() + name.Substring(1);

            if (method == null)
                return i < 0 ? name : (name + i);

            // Check for usage as loop counter or similar?

            return i < 0 ? name : (name + i);
        }

    }
}

DbgILGen: Use element type name for variable names


using System.Threading.Tasks;
using Stockfighter.Helpers;

namespace Stockfighter
{
    public class Venue
    {
        public string Symbol { get; private set; }

        public Venue(string symbol)
        {
            Symbol = symbol;
        }

        public async Task<bool> IsUp()
        {
            using (var client = new Client())
            {
                try
                {
                    var response = await client.Get<Heartbeat>($"venues/{Symbol}/heartbeat");
                    return response.ok;
                }
                catch
                {
                    return false;
                }
            }
        }

        public async Task<Stock[]> GetStocks()
        {
            using (var client = new Client())
            {
                var stocks = await client.Get<Stock[]>($"venues/{Symbol}/stocks");

                foreach (var stock in stocks)
                    stock.Venue = Symbol;

                return stocks;
            }
        }

        private class Heartbeat
        {
            public bool ok { get; set; }
            public string venue { get; set; }
        }
    }
}

using System.Threading.Tasks;
using Stockfighter.Helpers;

namespace Stockfighter
{
    public class Venue
    {
        public string Symbol { get; private set; }

        public Venue(string symbol)
        {
            Symbol = symbol;
        }

        public async Task<bool> IsUp()
        {
            using (var client = new Client())
            {
                try
                {
                    var response = await client.Get<Heartbeat>($"venues/{Symbol}/heartbeat");
                    return response.ok;
                }
                catch
                {
                    return false;
                }
            }
        }

        public async Task<Stock[]> GetStocks()
        {
            using (var client = new Client())
            {
                var response = await client.Get<StocksResponse>($"venues/{Symbol}/stocks");

                foreach (var stock in response.symbols)
                    stock.Venue = Symbol;

                return response.symbols;
            }
        }

        private class Heartbeat
        {
            public bool ok { get; set; }
            public string venue { get; set; }
        }

        private class StocksResponse
        {
            public bool ok { get; set; }
            public Stock[] symbols { get; set; }
        }
    }
}

Fix GetStocks by reading the response in the proper format.


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

using System;
using System.Collections.Generic;
using System.IO;

namespace RepoTasks.ProjectModel
{
    internal class ProjectInfo
    {
        public ProjectInfo(string fullPath,
            IReadOnlyList<ProjectFrameworkInfo> frameworks,
            IReadOnlyList<DotNetCliReferenceInfo> tools,
            bool isPackable,
            string packageId,
            string packageVersion)
        {
            if (!Path.IsPathRooted(fullPath))
            {
                throw new ArgumentException("Path must be absolute", nameof(fullPath));
            }

            Frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks));
            Tools = tools ?? throw new ArgumentNullException(nameof(tools));

            FullPath = fullPath;
            FileName = Path.GetFileName(fullPath);
            Directory = Path.GetDirectoryName(FullPath);
            IsPackable = isPackable;
            PackageId = packageId;
            PackageVersion = packageVersion;
        }

        public string FullPath { get; }
        public string FileName { get; }
        public string Directory { get; }
        public string PackageId { get; }
        public string PackageVersion { get; }
        public bool IsPackable { get; }

        public SolutionInfo SolutionInfo { get; set; }

        public IReadOnlyList<ProjectFrameworkInfo> Frameworks { get; }
        public IReadOnlyList<DotNetCliReferenceInfo> Tools { get; }
        public SolutionInfo SolutionInfo { get; internal set; }
    }
}

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

using System;
using System.Collections.Generic;
using System.IO;

namespace RepoTasks.ProjectModel
{
    internal class ProjectInfo
    {
        public ProjectInfo(string fullPath,
            IReadOnlyList<ProjectFrameworkInfo> frameworks,
            IReadOnlyList<DotNetCliReferenceInfo> tools,
            bool isPackable,
            string packageId,
            string packageVersion)
        {
            if (!Path.IsPathRooted(fullPath))
            {
                throw new ArgumentException("Path must be absolute", nameof(fullPath));
            }

            Frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks));
            Tools = tools ?? throw new ArgumentNullException(nameof(tools));

            FullPath = fullPath;
            FileName = Path.GetFileName(fullPath);
            Directory = Path.GetDirectoryName(FullPath);
            IsPackable = isPackable;
            PackageId = packageId;
            PackageVersion = packageVersion;
        }

        public string FullPath { get; }
        public string FileName { get; }
        public string Directory { get; }
        public string PackageId { get; }
        public string PackageVersion { get; }
        public bool IsPackable { get; }

        public SolutionInfo SolutionInfo { get; set; }

        public IReadOnlyList<ProjectFrameworkInfo> Frameworks { get; }
        public IReadOnlyList<DotNetCliReferenceInfo> Tools { get; }
    }
}

Fix compiler error introduced by merge conflict


using System;
using System.Linq;
using System.Threading.Tasks;
using Geocoding.Google;
using Xunit;

namespace Geocoding.Tests
{
	[Collection("Settings")]
	public class GoogleAsyncGeocoderTest : AsyncGeocoderTest
	{
		readonly SettingsFixture settings;
		GoogleGeocoder geoCoder;

		public GoogleAsyncGeocoderTest(SettingsFixture settings)
		{
			this.settings = settings;
		}

		protected override IGeocoder CreateAsyncGeocoder()
		{
			string apiKey = settings.GoogleApiKey;

			if (String.IsNullOrEmpty(apiKey))
			{
				geoCoder = new GoogleGeocoder();
			}
			else
			{
				geoCoder = new GoogleGeocoder(apiKey);
			}

			return geoCoder;
		}

		[Theory]
		[InlineData("United States", GoogleAddressType.Country)]
		[InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)]
		[InlineData("New York, New York", GoogleAddressType.Locality)]
		[InlineData("90210, US", GoogleAddressType.PostalCode)]
		[InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.StreetAddress)]
		public async Task CanParseAddressTypes(string address, GoogleAddressType type)
		{
		    var result = await geoCoder.GeocodeAsync(address);
			GoogleAddress[] addresses = result.ToArray();
			Assert.Equal(type, addresses[0].Type);
		}
	}
}

using System;
using System.Linq;
using System.Threading.Tasks;
using Geocoding.Google;
using Xunit;

namespace Geocoding.Tests
{
	[Collection("Settings")]
	public class GoogleAsyncGeocoderTest : AsyncGeocoderTest
	{
		GoogleGeocoder geoCoder;

		protected override IGeocoder CreateAsyncGeocoder()
		{
			string apiKey = settings.GoogleApiKey;

			if (String.IsNullOrEmpty(apiKey))
			{
				geoCoder = new GoogleGeocoder();
			}
			else
			{
				geoCoder = new GoogleGeocoder(apiKey);
			}

			return geoCoder;
		}

		[Theory]
		[InlineData("United States", GoogleAddressType.Country)]
		[InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)]
		[InlineData("New York, New York", GoogleAddressType.Locality)]
		[InlineData("90210, US", GoogleAddressType.PostalCode)]
		[InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.Establishment)]
		public async Task CanParseAddressTypes(string address, GoogleAddressType type)
		{
		    var result = await geoCoder.GeocodeAsync(address);
			GoogleAddress[] addresses = result.ToArray();
			Assert.Equal(type, addresses[0].Type);
		}
	}
}

Fix issue with tests where settings were not being injected into test class and causing a null error at runtime. Now uses parent settings class. Also changed one expected test return type to reflect change in Google data.


using System;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using Common.Logging;

namespace NuGet.Lucene.Web
{
    public static class UnhandledExceptionLogger
    {
        internal static readonly ILog Log = LogManager.GetLogger(typeof(UnhandledExceptionLogger));

        public static void LogException(Exception exception)
        {
            LogException(exception, string.Format("Unhandled exception: {0}: {1}", exception.GetType(), exception.Message));
        }

        public static void LogException(Exception exception, string message)
        {
            var log = GetLogSeverityDelegate(exception);

            log(m => m(message), exception.StackTrace != null ? exception : null);
        }

        private static Action<Action<FormatMessageHandler>, Exception> GetLogSeverityDelegate(Exception exception)
        {
            if (exception is HttpRequestValidationException || exception is ViewStateException)
            {
                return Log.Warn;
            }

            if (exception is TaskCanceledException || exception is OperationCanceledException)
            {
                return Log.Info;
            }

            var httpError = exception as HttpException;
            if (httpError != null && (httpError.ErrorCode == unchecked((int)0x80070057) || httpError.ErrorCode == unchecked((int)0x800704CD)))
            {
                // "The remote host closed the connection."
                return Log.Debug;
            }

            if (httpError != null && (httpError.GetHttpCode() < 500))
            {
                return Log.Info;
            }

            return Log.Error;
        }
    }
}

using System;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using Common.Logging;

namespace NuGet.Lucene.Web
{
    public static class UnhandledExceptionLogger
    {
        internal static readonly ILog Log = LogManager.GetLogger(typeof(UnhandledExceptionLogger));

        public static void LogException(Exception exception)
        {
            LogException(exception, m => m("Unhandled exception: {0}: {1}", exception.GetType(), exception.Message));
        }

        public static void LogException(Exception exception, Action<FormatMessageHandler> formatMessageCallback)
        {
            var log = GetLogSeverityDelegate(exception);

            log(formatMessageCallback, exception.StackTrace != null ? exception : null);
        }

        private static Action<Action<FormatMessageHandler>, Exception> GetLogSeverityDelegate(Exception exception)
        {
            if (exception is HttpRequestValidationException || exception is ViewStateException)
            {
                return Log.Warn;
            }

            if (exception is TaskCanceledException || exception is OperationCanceledException)
            {
                return Log.Info;
            }

            var httpError = exception as HttpException;
            if (httpError != null && (httpError.ErrorCode == unchecked((int)0x80070057) || httpError.ErrorCode == unchecked((int)0x800704CD)))
            {
                // "The remote host closed the connection."
                return Log.Debug;
            }

            if (httpError != null && (httpError.GetHttpCode() < 500))
            {
                return Log.Info;
            }

            return Log.Error;
        }
    }
}

Use FormatMessageHandler instead of eagerly formatting.


using Newtonsoft.Json;
using System;
using System.Globalization;
using System.IO;
using System.Text;

namespace Glimpse
{
    public class DefaultMessageConverter : IMessageConverter
    {
        private readonly JsonSerializer _jsonSerializer;

        public DefaultMessageConverter(JsonSerializer jsonSerializer)
        {
            _jsonSerializer = jsonSerializer;
        }

        public IMessageEnvelope ConvertMessage(IMessage message)
        {
            var newMessage = new MessageEnvelope();
            newMessage.Type = message.GetType().FullName;
            newMessage.Payload = Serialize(message);

            return newMessage;
        }

        protected string Serialize(object data)
        {
            // Brought across from - https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConvert.cs#L635
            var stringBuilder = new StringBuilder(256);
            using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
            using (var jsonWriter = new JsonTextWriter(stringWriter))
            {
                _jsonSerializer.Serialize(jsonWriter, data, data.GetType());

                return stringWriter.ToString();
            }
        }
    }
}

using Newtonsoft.Json;
using System;
using System.Globalization;
using System.IO;
using System.Text;

namespace Glimpse
{
    public class DefaultMessageConverter : IMessageConverter
    {
        private readonly JsonSerializer _jsonSerializer;
        private readonly IServiceProvider _serviceProvider;

        public DefaultMessageConverter(JsonSerializer jsonSerializer, IServiceProvider serviceProvider)
        {
            _jsonSerializer = jsonSerializer;
            _serviceProvider = serviceProvider;
        }

        public IMessageEnvelope ConvertMessage(IMessage message)
        {
            //var context = (MessageContext)_serviceProvider.GetService(typeof(MessageContext));

            var newMessage = new MessageEnvelope();
            newMessage.Type = message.GetType().FullName;
            newMessage.Payload = Serialize(message);
            //newMessage.Context = context;

            return newMessage;
        }

        protected string Serialize(object data)
        {
            // Brought across from - https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConvert.cs#L635
            var stringBuilder = new StringBuilder(256);
            using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
            using (var jsonWriter = new JsonTextWriter(stringWriter))
            {
                _jsonSerializer.Serialize(jsonWriter, data, data.GetType());

                return stringWriter.ToString();
            }
        }
    }
}

Update message converter to access context


using System.ComponentModel;
using System.Diagnostics;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace DesktopWidgets.Classes
{
    [ExpandableObject]
    [DisplayName("Process File")]
    public class ProcessFile : FilePath
    {
        public ProcessFile(string path) : base(path)
        {
            Path = path;
        }

        public ProcessFile()
        {
        }

        [PropertyOrder(2)]
        [DisplayName("Arguments")]
        public string Arguments { get; set; } = "";

        [PropertyOrder(1)]
        [DisplayName("Start in Folder")]
        public string StartInFolder { get; set; } = "";

        [PropertyOrder(3)]
        [DisplayName("Window Style")]
        public ProcessWindowStyle WindowStyle { get; set; } = ProcessWindowStyle.Normal;
    }
}

using System.ComponentModel;
using System.Diagnostics;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace DesktopWidgets.Classes
{
    [ExpandableObject]
    [DisplayName("Process File")]
    public class ProcessFile : FilePath
    {
        public ProcessFile(string path) : base(path)
        {
            Path = path;
        }

        public ProcessFile()
        {
        }

        [PropertyOrder(2)]
        [DisplayName("Arguments")]
        public string Arguments { get; set; } = "";

        [PropertyOrder(1)]
        [DisplayName("Start in Folder")]
        public string StartInFolder { get; set; } = "";

        [PropertyOrder(3)]
        [DisplayName("Window Style")]
        public ProcessWindowStyle WindowStyle { get; set; } = ProcessWindowStyle.Normal;

        public override string ToString()
        {
            return string.Join(" ", Path, Arguments);
        }
    }
}

Add ToString override to Process File

Add ToString override to Process File

Returns path and argument


using System;
using UnityEngine;

namespace com.adjust.sdk.imei
{
    public class AdjustImei : MonoBehaviour
    {
        private const string errorMsgEditor = "[AdjustImei]: Adjust IMEI plugin can not be used in Editor.";
        private const string errorMsgPlatform = "[AdjustImei]: Adjust IMEI plugin can only be used in Android apps.";

        public bool readImei = false;

        void Awake()
        {
            if (IsEditor()) { return; }

            DontDestroyOnLoad(transform.gameObject);

            if (this.readImei)
            {
                AdjustImei.ReadImei();
            }
            else
            {
                AdjustImei.DoNotReadImei();
            }
        }

        public static void ReadImei()
        {
            if (IsEditor()) { return; }

            #if UNITY_ANDROID
                AdjustImeiAndroid.ReadImei();
            #else
                Debug.Log(errorMsgPlatform);
            #endif
        }

        public static void DoNotReadImei()
        {
            if (IsEditor()) { return; }

            #if UNITY_ANDROID
                AdjustImeiAndroid.DoNotReadImei();
            #else
                Debug.Log(errorMsgPlatform);
            #endif
        }

        private static bool IsEditor()
        {
            #if UNITY_EDITOR
                Debug.Log(errorMsgEditor);
                return true;
            #else
                return false;
            #endif
        }
    }
}

using System;
using UnityEngine;

namespace com.adjust.sdk.imei
{
    public class AdjustImei : MonoBehaviour
    {
        private const string errorMsgEditor = "[AdjustImei]: Adjust IMEI plugin can not be used in Editor.";
        private const string errorMsgPlatform = "[AdjustImei]: Adjust IMEI plugin can only be used in Android apps.";

        public bool startManually = true;
        public bool readImei = false;

        void Awake()
        {
            if (IsEditor()) { return; }

            DontDestroyOnLoad(transform.gameObject);

            if (!this.startManually)
            {
                if (this.readImei)
                {
                    AdjustImei.ReadImei();
                }
                else
                {
                    AdjustImei.DoNotReadImei();
                }
            }
        }

        public static void ReadImei()
        {
            if (IsEditor()) { return; }

            #if UNITY_ANDROID
                AdjustImeiAndroid.ReadImei();
            #else
                Debug.Log(errorMsgPlatform);
            #endif
        }

        public static void DoNotReadImei()
        {
            if (IsEditor()) { return; }

            #if UNITY_ANDROID
                AdjustImeiAndroid.DoNotReadImei();
            #else
                Debug.Log(errorMsgPlatform);
            #endif
        }

        private static bool IsEditor()
        {
            #if UNITY_EDITOR
                Debug.Log(errorMsgEditor);
                return true;
            #else
                return false;
            #endif
        }
    }
}

Add Start Manually option to IMEI prefab


using UnityEngine;

namespace Devdayo
{
    [DisallowMultipleComponent]
    public class TriggerEnter2D : FsmEvent<Collider2D>
    {
        void OnTrigger2DEnter(Collider2D other)
        {
            Notify(other);
        }
    }

    [DisallowMultipleComponent]
    public class TriggerStay2D : FsmEvent<Collider2D>
    {
        void OnTrigger2DStay(Collider2D other)
        {
            Notify(other);
        }
    }

    [DisallowMultipleComponent]
    public class TriggerExit2D : FsmEvent<Collider2D>
    {
        void OnTrigger2DExit(Collider2D other)
        {
            Notify(other);
        }
    }
}

using UnityEngine;

namespace Devdayo
{
    [DisallowMultipleComponent]
    public class TriggerEnter2D : FsmEvent<Collider2D>
    {
        void OnTriggerEnter2D(Collider2D other)
        {
            Notify(other);
        }
    }

    [DisallowMultipleComponent]
    public class TriggerStay2D : FsmEvent<Collider2D>
    {
        void OnTriggerStay2D(Collider2D other)
        {
            Notify(other);
        }
    }

    [DisallowMultipleComponent]
    public class TriggerExit2D : FsmEvent<Collider2D>
    {
        void OnTriggerExit2D(Collider2D other)
        {
            Notify(other);
        }
    }
}

Fix Trigger2D wrong method names

Fix Trigger2D wrong method names


namespace XSharp.Tokens
{
    public class Variable : Identifier
    {
        public Variable() {
            mFirstChars = ".";
        }

        protected override bool CheckChar(int aLocalPos, char aChar)
        {
            // The name of the variable must start with a alphabet
            if (aLocalPos == 1)
            {
                return Chars.Alpha.IndexOf(aChar) > -1;
            }
            return base.CheckChar(aLocalPos, aChar);
        }

        public override object Check(string aText)
        {
            return aText.Substring(1);
        }
    }

    public class VariableAddress : Spruce.Tokens.AlphaNum
    {
        public VariableAddress() : base(Chars.AlphaNum, "@")
        {
        }

        protected override bool CheckChar(int aLocalPos, char aChar)
        {
            switch (aLocalPos)
            {
                case 0:
                    return aChar == '@';

                case 1:
                    return aChar == '.';

                case 2:
                    return Chars.Alpha.IndexOf(aChar) > -1;
            }
            return base.CheckChar(aLocalPos, aChar);
        }

        public override object Check(string aText)
        {
            return aText.Substring(2);
        }
    }
}

namespace XSharp.Tokens
{
    public class Variable : Identifier
    {
        public Variable() {
            mFirstChars = ".";
        }

        protected override bool CheckChar(int aLocalPos, char aChar)
        {
            // The name of the variable must start with a alphabet
            if (aLocalPos == 1)
            {
                return Chars.Alpha.IndexOf(aChar) > -1;
            }
            return base.CheckChar(aLocalPos, aChar);
        }

        public override object Check(string aText)
        {
            return aText.Substring(1);
        }
    }

    public class VariableAddress : Identifier
    {
        public VariableAddress()
        {
            mFirstChars = "@";
        }

        protected override bool CheckChar(int aLocalPos, char aChar)
        {
            switch (aLocalPos)
            {
                case 1:
                    return aChar == '.';

                case 2:
                    return Chars.Alpha.IndexOf(aChar) > -1;
            }
            return base.CheckChar(aLocalPos, aChar);
        }

        public override object Check(string aText)
        {
            return aText.Substring(2);
        }
    }
}

Change VarAddr to use identifier

Change VarAddr to use identifier


// Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System.Collections.Specialized;

namespace CefSharp
{
    public interface IRequest
    {
        string Url { get; set; }
        string Method { get; }
        string Body { get; }
        NameValueCollection Headers { get; set; }

        /// <summary>
        /// Get the transition type for this request.
        /// Applies to requests that represent a main frame or sub-frame navigation.
        /// </summary>
        TransitionType TransitionType { get; }
    }
}

// Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;
using System.Collections.Specialized;

namespace CefSharp
{
    public interface IRequest : IDisposable
    {
        string Url { get; set; }
        string Method { get; }
        string Body { get; }
        NameValueCollection Headers { get; set; }

        /// <summary>
        /// Get the transition type for this request.
        /// Applies to requests that represent a main frame or sub-frame navigation.
        /// </summary>
        TransitionType TransitionType { get; }
    }
}

Make this interface disposable so taht code analysis should hopefully remind users to call .Dispose on it.


using System;
using System.Net;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.CommitmentsV2.Application.Queries.GetAllLearners;

namespace SFA.DAS.CommitmentsV2.Api.Controllers
{
    [ApiController]
    [Route("api/learners")]
    public class LearnerController : ControllerBase
    {
        private readonly IMediator _mediator;

        public LearnerController(IMediator mediator)
        {
            _mediator = mediator;
        }

        [HttpGet]
        public async Task<IActionResult> GetAllLearners(DateTime? sinceTime = null, int batch_number = 1, int batch_size = 1000)
        {
            var result = await _mediator.Send(new GetAllLearnersQuery(sinceTime, batch_number, batch_size));

            var settings = new JsonSerializerSettings
            {
                 DateFormatString = "yyyy-MM-dd'T'HH:mm:ss"
            };

            var jsonResult = new JsonResult(new GetAllLearnersResponse()
            {
                Learners = result.Learners,
                BatchNumber = result.BatchNumber,
                BatchSize = result.BatchSize,
                TotalNumberOfBatches = result.TotalNumberOfBatches
            }, settings);
            jsonResult.StatusCode = (int)HttpStatusCode.OK;
            jsonResult.ContentType = "application/json";

            return jsonResult;
        }
    }
}

using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.CommitmentsV2.Application.Queries.GetAllLearners;
using System;
using System.Net;
using System.Threading.Tasks;

namespace SFA.DAS.CommitmentsV2.Api.Controllers
{
    [ApiController]
    [Authorize]
    [Route("api/learners")]
    public class LearnerController : ControllerBase
    {
        private readonly IMediator _mediator;

        public LearnerController(IMediator mediator)
        {
            _mediator = mediator;
        }

        [HttpGet]
        public async Task<IActionResult> GetAllLearners(DateTime? sinceTime = null, int batch_number = 1, int batch_size = 1000)
        {
            var result = await _mediator.Send(new GetAllLearnersQuery(sinceTime, batch_number, batch_size));

            var settings = new JsonSerializerSettings
            {
                 DateFormatString = "yyyy-MM-dd'T'HH:mm:ss"
            };

            var jsonResult = new JsonResult(new GetAllLearnersResponse()
            {
                Learners = result.Learners,
                BatchNumber = result.BatchNumber,
                BatchSize = result.BatchSize,
                TotalNumberOfBatches = result.TotalNumberOfBatches
            }, settings);
            jsonResult.StatusCode = (int)HttpStatusCode.OK;
            jsonResult.ContentType = "application/json";

            return jsonResult;
        }
    }
}

Add auth to Learners endpoint

Add auth to Learners endpoint


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

namespace Andromeda
{
    public static class CredentialManager
    {

        public static string GetUser()
        {
            return "null";
        }

        public static string GetPass()
        {
            return "null";
        }
    }
}

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

namespace Andromeda
{
    public static class CredentialManager
    {

        public static string UserName { get; set; }

        public static string GetDomain()
        {
            return Environment.UserDomainName;
        }

        public static string GetUser()
        {
            return "null";
        }

        public static string GetPass()
        {
            return "null";
        }

        public static bool DoesUserExistInActiveDirectory(string userName)
        {
            try
            {
                using (var domainContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName))
                {
                    using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
                    {
                        return foundUser != null;
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }

        }

        public static bool IsUserLocal(string userName)
        {
            bool exists = false;

            using (var domainContext = new PrincipalContext(ContextType.Machine))
            {
                using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
                {
                    return true;
                }
            }

            return false;
        }
    }
}

Check for AD credentials, check if local account


namespace ForwarderConsole
{
    using System;
    using System.Text;

    public static class Print
    {
        public static void Error(string error)
        {
            InternalPrint("--- ERROR --", error, ConsoleColor.Red);
        }

        public static void Request(byte[] bytes)
        {
            string request = Encoding.ASCII.GetString(bytes);

            InternalPrint("--- REQUEST ---", request, ConsoleColor.White);
        }

        public static void Response(byte[] bytes)
        {
            string response = Encoding.ASCII.GetString(bytes);

            InternalPrint("--- RESPONSE ---", response, ConsoleColor.Yellow);
        }

        public static void Color(string message, ConsoleColor color)
        {
            Console.ForegroundColor = color;

            Console.WriteLine(message);
        }

        private static void InternalPrint(string header, string message, ConsoleColor color)
        {
            string txt =
                Line(header) +
                Line() +
                Line(message) +
                Line("==================================================");

            Print.Color(txt, color);
        }

        private static string Line(string txt = "")
        {
            return txt + Environment.NewLine;
        }
    }
}

namespace ForwarderConsole
{
    using System;
    using System.Text;

    public static class Print
    {
        public static void Error(string error)
        {
            InternalPrint("--- ERROR --", error, ConsoleColor.Red);
        }

        public static void Request(byte[] bytes)
        {
            string request = Encoding.ASCII.GetString(bytes);

            InternalPrint("--- REQUEST ---", request, ConsoleColor.White);
        }

        public static void Response(byte[] bytes)
        {
            string response = Encoding.ASCII.GetString(bytes);

            InternalPrint("--- RESPONSE ---", response, ConsoleColor.Yellow);
        }

        public static void Color(string message, ConsoleColor color)
        {
            Console.ForegroundColor = color;

            // Replace the BELL character.
            message = message.Replace('\a', 'B');

            Console.WriteLine(message);
        }

        private static void InternalPrint(string header, string message, ConsoleColor color)
        {
            string txt =
                Line(header) +
                Line() +
                Line(message) +
                Line("==================================================");

            Print.Color(txt, color);
        }

        private static string Line(string txt = "")
        {
            return txt + Environment.NewLine;
        }
    }
}

Replace the BELL character before writing to the console.


using System;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!");
            Console.WriteLine("Bigsby Gates was here!");
        }
    }
}

using System;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!");
            Console.WriteLine("Bigsby Gates was here!");
            Console.WriteLine("Bigsby Trovalds was here!");
        }
    }
}

Add Bigsby Trovalds was here

Add Bigsby Trovalds was here


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CloudNotes.DesktopClient
{
    public static class Directories
    {
        private const string CloudNotesDataFolder = "CloudNotes";
        public static string GetFullName(string fileOrDir)
        {
#if DEBUG
            return Path.Combine(Application.StartupPath, fileOrDir);
#else
            var path = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                CloudNotesDataFolder);
            return Path.Combine(path, fileOrDir);
#endif
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CloudNotes.DesktopClient
{
    public static class Directories
    {
        private const string CloudNotesDataFolder = "CloudNotes";
        public static string GetFullName(string fileOrDir)
        {
#if DEBUG
            return Path.Combine(Application.StartupPath, fileOrDir);
#else
            var path = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                CloudNotesDataFolder);
            return Path.Combine(path, fileOrDir);
#endif
        }
    }
}

Use the AppData instead of the CommonAppData folder to save the profile and settings, to avoid the UAC.


using CefSharp.Wpf;
using System.Windows.Controls;

namespace Cactbot
{
    public partial class BrowserControl : UserControl
    {
        public BrowserControl()
        {
            DataContext = this;
            InitializeComponent();
            CreationHandlers = delegate {};
        }

        public delegate void OnBrowserCreation(object sender, IWpfWebBrowser browser);
        public OnBrowserCreation CreationHandlers { get; set; }

        public class BoundObject
        {
            public string MyProperty { get; set; }
        }

        private IWpfWebBrowser webBrowser;
        public IWpfWebBrowser WebBrowser
        {
            get
            {
                return webBrowser;
            }
            set
            {
                if (value != null)
                    value.RegisterJsObject("bound", new BoundObject());

                if (webBrowser == value)
                    return;

                webBrowser = value;

                if (webBrowser != null)
                    CreationHandlers(this, webBrowser);
            }
        }
    }
}

using CefSharp.Wpf;
using System.Windows.Controls;

namespace Cactbot
{
    public partial class BrowserControl : UserControl
    {
        public BrowserControl()
        {
            DataContext = this;
            InitializeComponent();
            CreationHandlers = delegate {};
        }

        public delegate void OnBrowserCreation(object sender, IWpfWebBrowser browser);
        public OnBrowserCreation CreationHandlers { get; set; }

        private IWpfWebBrowser webBrowser;
        public IWpfWebBrowser WebBrowser
        {
            get
            {
                return webBrowser;
            }
            set
            {
                if (webBrowser == value)
                    return;

                webBrowser = value;

                if (webBrowser != null)
                    CreationHandlers(this, webBrowser);
            }
        }
    }
}

Clean up old BoundObject code

Clean up old BoundObject code


using System;
namespace Business.Core
{
	public partial class Individual
	{
		public IDatabase Database { get; private set; }

		public Individual(IDatabase database, UInt64? id = null) {
			Database = database;
			if(id != null)
				Load((UInt64)id);
		}

		private void Load(UInt64 id) {
			// Overwrite this object with Individual id
			Empty();
			Id = id;
			// Default to person for now
			Person = true;

			if (Database != null) {
				Database.Connect();
				Database.Connection.Open();

				Database.Command.CommandText = GetIndividualSQL;
				Database.Command.Parameters.Add(new Parameter() { Name= "@id", Value = 3 });
				var reader = Database.Command.ExecuteReader();
				if (reader.HasRows) {
					if (reader.Read()) {
						try {
							FullName = reader.GetString(0);
							GoesBy = reader.GetString(1);
						} catch (Exception ex) {
							// Some sort of type or data issue
							Database.Profile.Log?.Error($"reading Individual: {ex.Message}");
						}
					}
				}
			}
		}

		private const string GetIndividualSQL = @"
SELECT fullname, goesBy
FROM People
WHERE individual = @id
";
	}
}

using System;
namespace Business.Core
{
	public partial class Individual
	{
		public IDatabase Database { get; private set; }

		public Individual(IDatabase database, UInt64? id = null) {
			Database = database;
			if(id != null)
				Load((UInt64)id);
		}

		private void Load(UInt64 id) {
			// Overwrite this object with Individual id
			Empty();
			Id = id;
			// Default to person for now
			Person = true;

			if (Database != null) {
				Database.Connect();
				Database.Connection.Open();

				Database.Command.CommandText = GetIndividualSQL;
				Database.Command.Parameters.Add(new Parameter() { Name= "@id", Value = id });
				var reader = Database.Command.ExecuteReader();
				if (reader.HasRows) {
					if (reader.Read()) {
						try {
							FullName = reader.GetString(0);
							GoesBy = reader.GetString(1);
						} catch (Exception ex) {
							// Some sort of type or data issue
							Database.Profile.Log?.Error($"reading Individual: {ex.Message}");
						}
					}
				}
			}
		}

		private const string GetIndividualSQL = @"
SELECT fullname, goesBY
FROM (
 SELECT fullname, goesBy
 FROM People
 WHERE individual = @id
 UNION
 SELECT name AS fullname, goesBy
 FROM Entities
 WHERE individual = @id
) AS Individual
LIMIT 1
";
	}
}

Use Id instead of fixed value

Use Id instead of fixed value


// ViewUserControl.cs
// Copyright (c) Nikhil Kothari, 2008. All Rights Reserved.
// http://www.nikhilk.net
//
// Silverlight.FX is an application framework for building RIAs with Silverlight.
// This project is licensed under the BSD license. See the accompanying License.txt
// file for more information.
// For updated project information please visit http://projects.nikhilk.net/SilverlightFX.
//

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace SilverlightFX.UserInterface {

    /// <summary>
    /// Represents a user control within the application's user interface.
    /// </summary>
    public class ViewUserControl : View {

        /// <summary>
        /// Initializes an instance of a ViewUserControl.
        /// </summary>
        public ViewUserControl() {
        }

        /// <summary>
        /// Initializes an instance of a ViewUserControl with an associated view model.
        /// The view model is set as the DataContext of the Form.
        /// </summary>
        /// <param name="viewModel">The associated view model object.</param>
        public ViewUserControl(Model viewModel)
            : base(viewModel) {
        }
    }
}

// ViewUserControl.cs
// Copyright (c) Nikhil Kothari, 2008. All Rights Reserved.
// http://www.nikhilk.net
//
// Silverlight.FX is an application framework for building RIAs with Silverlight.
// This project is licensed under the BSD license. See the accompanying License.txt
// file for more information.
// For updated project information please visit http://projects.nikhilk.net/SilverlightFX.
//

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace SilverlightFX.UserInterface {

    /// <summary>
    /// Represents a user control within the application's user interface.
    /// </summary>
    public class ViewUserControl : View {

        /// <summary>
        /// Initializes an instance of a ViewUserControl.
        /// </summary>
        public ViewUserControl() {
        }

        /// <summary>
        /// Initializes an instance of a ViewUserControl with an associated view model.
        /// The view model is set as the DataContext of the Form.
        /// </summary>
        /// <param name="viewModel">The associated view model object.</param>
        public ViewUserControl(object viewModel)
            : base(viewModel) {
        }
    }
}

Fix ctor to take arbitrary object type as model.


using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;

namespace Nowin
{
    public class IpIsLocalChecker : IIpIsLocalChecker
    {
        readonly Dictionary<IPAddress, bool> _dict;

        public IpIsLocalChecker()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            _dict = host.AddressList.Where(
                a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6).
                ToDictionary(p => p, p => true);
            _dict[IPAddress.Loopback] = true;
            _dict[IPAddress.IPv6Loopback] = true;
        }

        public bool IsLocal(IPAddress address)
        {
            return _dict.ContainsKey(address);
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;

namespace Nowin
{
    public class IpIsLocalChecker : IIpIsLocalChecker
    {
        readonly Dictionary<IPAddress, bool> _dict;

        public IpIsLocalChecker()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            _dict = host.AddressList.Where(
                a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6)
                .Distinct()
                .ToDictionary(p => p, p => true);
            _dict[IPAddress.Loopback] = true;
            _dict[IPAddress.IPv6Loopback] = true;
        }

        public bool IsLocal(IPAddress address)
        {
            return _dict.ContainsKey(address);
        }
    }
}

Remove duplicate addresses before converting to dictionary