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

namespace Booma.Proxy
{
	/// <summary>
	/// An unimplemented or unknown subcommand for the 0x6D packets.
	/// </summary>
	[WireDataContract]
	public sealed class UnknownSubCommand6DCommand : BaseSubCommand6D, IUnknownPayloadType
	{
		/// <inheritdoc />
		public short OperationCode => (short)base.CommandOperationCode;

		/// <inheritdoc />
		[ReadToEnd]
		[WireMember(1)]
		public byte[] UnknownBytes { get; } = new byte[0]; //readtoend requires at least an empty array init

		private UnknownSubCommand6DCommand()
		{

		}

		/// <inheritdoc />
		public override string ToString()
		{
			if(Enum.IsDefined(typeof(SubCommand6DOperationCode), (byte)OperationCode))
				return $"Unknown Subcommand6D OpCode: {OperationCode:X} Name: {((SubCommand6DOperationCode)OperationCode).ToString()} Type: {GetType().Name} CommandSize: {CommandSize * 4 - 2} (bytes size)";
			else
				return $"Unknown Subcommand6D OpCode: {OperationCode:X} Type: {GetType().Name} CommandSize: {CommandSize * 4 - 2} (bytes size)";
		}
	}
}

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

namespace Booma.Proxy
{
	/// <summary>
	/// An unimplemented or unknown subcommand for the 0x6D packets.
	/// </summary>
	[WireDataContract]
	public sealed class UnknownSubCommand6DCommand : BaseSubCommand6D, IUnknownPayloadType
	{
		/// <inheritdoc />
		public short OperationCode => (short)base.CommandOperationCode;

		/// <inheritdoc />
		[ReadToEnd]
		[WireMember(1)]
		public byte[] UnknownBytes { get; } = new byte[0]; //readtoend requires at least an empty array init

		private UnknownSubCommand6DCommand()
		{

		}

		/// <inheritdoc />
		public override string ToString()
		{
			if(Enum.IsDefined(typeof(SubCommand6DOperationCode), (byte)OperationCode))
				return $"Unknown Subcommand6D OpCode: {OperationCode:X} Name: {((SubCommand6DOperationCode)OperationCode).ToString()} Type: {GetType().Name} CommandSize: {CommandSize} (bytes size)";
			else
				return $"Unknown Subcommand6D OpCode: {OperationCode:X} Type: {GetType().Name} CommandSize: {CommandSize} (bytes size)";
		}
	}
}

Fix unknown 0x6D size logging

Fix unknown 0x6D size logging


using Microsoft.AspNet.Identity;
using SendGrid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web;

namespace VotingApplication.Web.Api.Services
{
    public class SendMailEmailSender : IMailSender
    {
        private NetworkCredential credentials;
        private string hostEmail;

        public SendMailEmailSender(NetworkCredential credentials, string hostEmail)
        {
            this.credentials = credentials;
            this.hostEmail = hostEmail;
        }

        public Task SendMail(string to, string subject, string message)
        {
            SendGridMessage mail = new SendGridMessage();

            mail.From = new MailAddress(this.hostEmail, "Voting App");
            mail.AddTo(to);
            mail.Subject = subject;
            mail.Html = message;

            var transportWeb = new SendGrid.Web(this.credentials);

            return transportWeb.DeliverAsync(mail);
        }
    }
}

using SendGrid;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;

namespace VotingApplication.Web.Api.Services
{
    public class SendMailEmailSender : IMailSender
    {
        private NetworkCredential credentials;
        private string hostEmail;

        public SendMailEmailSender(NetworkCredential credentials, string hostEmail)
        {
            this.credentials = credentials;
            this.hostEmail = hostEmail;
        }

        public Task SendMail(string to, string subject, string message)
        {
            SendGridMessage mail = new SendGridMessage();

            mail.From = new MailAddress(this.hostEmail, "Vote On");
            mail.AddTo(to);
            mail.Subject = subject;
            mail.Html = message;

            var transportWeb = new SendGrid.Web(this.credentials);

            return transportWeb.DeliverAsync(mail);
        }
    }
}

Fix email sender to 'vote on'

Fix email sender to 'vote on'


// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.NavigateTo;

namespace Microsoft.CodeAnalysis.Remote
{
    internal partial class CodeAnalysisService : IRemoteNavigateToSearchService
    {
        public async Task<SerializableNavigateToSearchResult[]> SearchDocumentAsync(
            DocumentId documentId, string searchPattern)
        {
            var solution = await GetSolutionAsync().ConfigureAwait(false);

            var project = solution.GetDocument(documentId);
            var result = await AbstractNavigateToSearchService.SearchDocumentInCurrentProcessAsync(
                project, searchPattern, CancellationToken).ConfigureAwait(false);

            return Convert(result);
        }

        public async Task<SerializableNavigateToSearchResult[]> SearchProjectAsync(
            ProjectId projectId, string searchPattern)
        {
            var solution = await GetSolutionAsync().ConfigureAwait(false);

            var project = solution.GetProject(projectId);
            var result = await AbstractNavigateToSearchService.SearchProjectInCurrentProcessAsync(
                project, searchPattern, CancellationToken).ConfigureAwait(false);

            return Convert(result);
        }

        private SerializableNavigateToSearchResult[] Convert(
            ImmutableArray<INavigateToSearchResult> result)
        {
            return result.Select(SerializableNavigateToSearchResult.Dehydrate).ToArray();
        }
    }
}

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.NavigateTo;

namespace Microsoft.CodeAnalysis.Remote
{
    internal partial class CodeAnalysisService : IRemoteNavigateToSearchService
    {
        public async Task<SerializableNavigateToSearchResult[]> SearchDocumentAsync(
            DocumentId documentId, string searchPattern)
        {
            using (UserOperationBooster.Boost())
            {
                var solution = await GetSolutionAsync().ConfigureAwait(false);

                var project = solution.GetDocument(documentId);
                var result = await AbstractNavigateToSearchService.SearchDocumentInCurrentProcessAsync(
                    project, searchPattern, CancellationToken).ConfigureAwait(false);

                return Convert(result);
            }
        }

        public async Task<SerializableNavigateToSearchResult[]> SearchProjectAsync(
            ProjectId projectId, string searchPattern)
        {
            using (UserOperationBooster.Boost())
            {
                var solution = await GetSolutionAsync().ConfigureAwait(false);

                var project = solution.GetProject(projectId);
                var result = await AbstractNavigateToSearchService.SearchProjectInCurrentProcessAsync(
                    project, searchPattern, CancellationToken).ConfigureAwait(false);

                return Convert(result);
            }
        }

        private SerializableNavigateToSearchResult[] Convert(
            ImmutableArray<INavigateToSearchResult> result)
        {
            return result.Select(SerializableNavigateToSearchResult.Dehydrate).ToArray();
        }
    }
}

Boost priority of NavigateTo when running in OOP server.


@model IEnumerable<Tag>

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

Tag Index

@if (User.Identity.IsAuthenticated)
{

        Create new Tag

}

@Model.Count() tags

    @Html.Partial("_TagButtons", Model)

Update tag button container markup

Update tag button container markup


using System;

namespace Terrajobst.Pns.Scanner
{
    public struct PnsResult
    {
        public static readonly PnsResult DoesNotThrow = new PnsResult(-1);

        private PnsResult(int level)
        {
            Level = level;
        }

        public static PnsResult ThrowsAt(int level)
        {
            return new PnsResult(level);
        }

        public PnsResult Combine(PnsResult other)
        {
            if (!Throws)
                return other;

            return ThrowsAt(Math.Min(Level, other.Level));
        }

        public bool Throws => Level >= 0;

        public int Level { get; }

        public override string ToString()
        {
            return Level.ToString();
        }
    }
}

using System;

namespace Terrajobst.Pns.Scanner
{
    public struct PnsResult
    {
        public static readonly PnsResult DoesNotThrow = new PnsResult(-1);

        private PnsResult(int level)
        {
            Level = level;
        }

        public static PnsResult ThrowsAt(int level)
        {
            return new PnsResult(level);
        }

        public PnsResult Combine(PnsResult other)
        {
            if (!Throws)
                return other;

            if (!other.Throws)
                return this;

            return ThrowsAt(Math.Min(Level, other.Level));
        }

        public bool Throws => Level >= 0;

        public int Level { get; }

        public override string ToString()
        {
            return Level.ToString();
        }
    }
}

Fix bug in properties and event detection


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lokad.Cqrs.Properties;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using NUnit.Framework;

namespace Lokad.Cqrs.Feature.TapeStorage
{
    [TestFixture]
    public class BlobTapeStorageTests : TapeStorageTests
    {
        const string ContainerName = "blob-tape-test";
        CloudBlobClient _cloudBlobClient;
        ISingleThreadTapeWriterFactory _writerFactory;
        ITapeReaderFactory _readerFactory;

        protected override void SetUp()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher(
                (configName, configSetter) => configSetter((string) Settings.Default[configName]));

            var cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
            _cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

            _writerFactory = new BlobTapeWriterFactory(_cloudBlobClient, ContainerName);
            _writerFactory.Init();

            _readerFactory = new BlobTapeReaderFactory(_cloudBlobClient, ContainerName);
        }

        protected override void TearDown()
        {
            _cloudBlobClient.GetContainerReference(ContainerName).Delete();
        }

        protected override TestConfiguration GetConfiguration()
        {
            return new TestConfiguration
            {
                Name = "test",
                WriterFactory = _writerFactory,
                ReaderFactory = _readerFactory
            };
        }
    }
}

using System;
using Lokad.Cqrs.Properties;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using NUnit.Framework;

namespace Lokad.Cqrs.Feature.TapeStorage
{
    [TestFixture]
    public class BlobTapeStorageTests : TapeStorageTests
    {
        const string ContainerName = "blob-tape-test";
        CloudBlobClient _cloudBlobClient;
        ISingleThreadTapeWriterFactory _writerFactory;
        ITapeReaderFactory _readerFactory;

        protected override void SetUp()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher(
                (configName, configSetter) => configSetter((string) Settings.Default[configName]));

            var cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
            _cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

            try
            {
                _cloudBlobClient.GetContainerReference(ContainerName).FetchAttributes();
                throw new InvalidOperationException("Container '" + ContainerName + "' already exists!");
            }
            catch (StorageClientException e)
            {
                if (e.ErrorCode != StorageErrorCode.ResourceNotFound)
                    throw new InvalidOperationException("Container '" + ContainerName + "' already exists!");
            }

            _writerFactory = new BlobTapeWriterFactory(_cloudBlobClient, ContainerName);
            _writerFactory.Init();

            _readerFactory = new BlobTapeReaderFactory(_cloudBlobClient, ContainerName);
        }

        protected override void TearDown()
        {
            _cloudBlobClient.GetContainerReference(ContainerName).Delete();
        }

        protected override TestConfiguration GetConfiguration()
        {
            return new TestConfiguration
            {
                Name = "test",
                WriterFactory = _writerFactory,
                ReaderFactory = _readerFactory
            };
        }
    }
}

Abort test if test container exists.

Abort test if test container exists.

--HG--
branch : 2011-05-28-es


using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

using Steeltoe.Extensions.Configuration.CloudFoundry;

namespace CloudFoundry
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                // Lab01 - Lab04 Start
                .AddCloudFoundry()
                // Lab01 - Lab04 End
                .Build();
    }
}

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Steeltoe.Extensions.Configuration.CloudFoundry;

namespace CloudFoundry
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args)
        {
            // Lab01 - Lab04 Start
            var configuration = new ConfigurationBuilder().AddCommandLine(args).Build();
            // Lab01 - Lab04 End

            return WebHost.CreateDefaultBuilder(args)

                // Lab01 - Lab04 Start
                .UseConfiguration(configuration)
                // Lab01 - Lab04 End

                .UseStartup<Startup>()
                // Lab01 - Lab04 Start
                .AddCloudFoundry()
                // Lab01 - Lab04 End
                .Build();
        }
    }
}

Fix startup problem on windows

Fix startup problem on windows


using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;

namespace NuGet.Dialog.Providers {

    internal class PackagesSearchNode : PackagesTreeNodeBase {

        private string _searchText;
        private readonly PackagesTreeNodeBase _baseNode;

        public PackagesTreeNodeBase BaseNode {
            get {
                return _baseNode;
            }
        }

        public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
            base(parent, provider) {

            if (baseNode == null) {
                throw new ArgumentNullException("baseNode");
            }

            _searchText = searchText;
            _baseNode = baseNode;

            // Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
            IsSearchResultsNode = true;
        }

        public override string Name {
            get {
                return Resources.Dialog_RootNodeSearch;
            }
        }

        public void SetSearchText(string newSearchText) {
            if (newSearchText == null) {
                throw new ArgumentNullException("newSearchText");
            }

            if (_searchText != newSearchText) {
                _searchText = newSearchText;

                if (IsSelected) {
                    ResetQuery();
                    Refresh();
                }
            }
        }

        public override IQueryable<IPackage> GetPackages() {
            return _baseNode.GetPackages().Find(_searchText);
        }
    }
}

using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;

namespace NuGet.Dialog.Providers {

    internal class PackagesSearchNode : PackagesTreeNodeBase {

        private string _searchText;
        private readonly PackagesTreeNodeBase _baseNode;

        public PackagesTreeNodeBase BaseNode {
            get {
                return _baseNode;
            }
        }

        public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
            base(parent, provider) {

            if (baseNode == null) {
                throw new ArgumentNullException("baseNode");
            }

            _searchText = searchText;
            _baseNode = baseNode;

            // Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
            IsSearchResultsNode = true;
        }

        public override string Name {
            get {
                return Resources.Dialog_RootNodeSearch;
            }
        }

        public void SetSearchText(string newSearchText) {
            if (newSearchText == null) {
                throw new ArgumentNullException("newSearchText");
            }

            if (_searchText != newSearchText) {
                _searchText = newSearchText;

                if (IsSelected) {
                    ResetQuery();
                    LoadPage(1);
                }
            }
        }

        public override IQueryable<IPackage> GetPackages() {
            return _baseNode.GetPackages().Find(_searchText);
        }
    }
}

Reset page number to 1 when perform a new search.
Work items: 569

--HG--
branch : 1.1


using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SharpDox.Build.Roslyn.MethodVisitors;

namespace SharpDox.Build.Roslyn.Parser.ProjectParser
{
    internal class MethodCallParser : BaseParser
    {
        internal MethodCallParser(ParserOptions parserOptions) : base(parserOptions) { }

        internal void ParseMethodCalls()
        {
            var namespaces = ParserOptions.SDRepository.GetAllNamespaces();
            foreach (var sdNamespace in namespaces)
            {
                foreach (var sdType in sdNamespace.Types)
                {
                    foreach (var sdMethod in sdType.Methods)
                    {
                        HandleOnItemParseStart(sdMethod.Name);
                        var fileId = ParserOptions.CodeSolution.GetDocumentIdsWithFilePath(sdMethod.Region.FilePath).Single();
                        var file = ParserOptions.CodeSolution.GetDocument(fileId);
                        var syntaxTree = file.GetSyntaxTreeAsync().Result;

                        if (file.Project.Language == "C#")
                        {
                            var methodVisitor = new CSharpMethodVisitor(ParserOptions.SDRepository, sdMethod, sdType, file);
                            var methodSyntaxNode = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>()
                                                    .Single(m => m.Span.Start == sdMethod.Region.Start &&
                                                    m.Span.End == sdMethod.Region.End);
                            methodVisitor.Visit(methodSyntaxNode);
                        }
                        else if (file.Project.Language == "VBNET")
                        {

                        }
                    }
                }
            }
        }
    }
}

using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SharpDox.Build.Roslyn.MethodVisitors;

namespace SharpDox.Build.Roslyn.Parser.ProjectParser
{
    internal class MethodCallParser : BaseParser
    {
        internal MethodCallParser(ParserOptions parserOptions) : base(parserOptions) { }

        internal void ParseMethodCalls()
        {
            var namespaces = ParserOptions.SDRepository.GetAllNamespaces();
            foreach (var sdNamespace in namespaces)
            {
                foreach (var sdType in sdNamespace.Types)
                {
                    foreach (var sdMethod in sdType.Methods)
                    {
                        HandleOnItemParseStart(sdMethod.Name);
                        var fileId = ParserOptions.CodeSolution.GetDocumentIdsWithFilePath(sdMethod.Region.FilePath).FirstOrDefault();
                        var file = ParserOptions.CodeSolution.GetDocument(fileId);
                        var syntaxTree = file.GetSyntaxTreeAsync().Result;

                        if (file.Project.Language == "C#")
                        {
                            var methodVisitor = new CSharpMethodVisitor(ParserOptions.SDRepository, sdMethod, sdType, file);
                            var methodSyntaxNode = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>()
                                                    .FirstOrDefault(m => m.Span.Start == sdMethod.Region.Start &&
                                                    m.Span.End == sdMethod.Region.End);
                            if (methodSyntaxNode != null)
                            {
                                methodVisitor.Visit(methodSyntaxNode);
                            }
                        }
                        else if (file.Project.Language == "VBNET")
                        {

                        }
                    }
                }
            }
        }
    }
}

Fix Roslyn compiler issues when the same file is being used for multiple target platforms (and might result in a class without methods)


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

using Microsoft.Azure.Management.Sql.Models;
using Microsoft.Azure.Management.Sql;
using Xunit;

namespace Sql.Tests
{
    public class ServiceObjectiveScenarioTests
    {
        [Fact]
        public void TestGetListServiceObjectives()
        {
            string testPrefix = "sqlcrudtest-";
            string suiteName = this.GetType().FullName;
            string serverName = SqlManagementTestUtilities.GenerateName(testPrefix);

            SqlManagementTestUtilities.RunTestInNewV12Server(suiteName, "TestGetListServiceObjectives", testPrefix, (resClient, sqlClient, resourceGroup, server) =>
            {
                var serviceObjectives = sqlClient.Servers.ListServiceObjectives(resourceGroup.Name, server.Name);

                foreach(ServiceObjective objective in serviceObjectives)
                {
                    Assert.NotNull(objective.ServiceObjectiveName);
                    Assert.NotNull(objective.IsDefault);
                    Assert.NotNull(objective.IsSystem);
                    Assert.NotNull(objective.Enabled);

                    // Assert Get finds the service objective from List
                    Assert.NotNull(sqlClient.Servers.GetServiceObjective(resourceGroup.Name, server.Name, objective.Name));
                }
            });
        }
    }
}

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

using Microsoft.Azure.Management.Sql.Models;
using Microsoft.Azure.Management.Sql;
using Xunit;

namespace Sql.Tests
{
    public class ServiceObjectiveScenarioTests
    {
        [Fact]
        public void TestGetListServiceObjectives()
        {
            string testPrefix = "sqlcrudtest-";
            string suiteName = this.GetType().FullName;

            SqlManagementTestUtilities.RunTestInNewV12Server(suiteName, "TestGetListServiceObjectives", testPrefix, (resClient, sqlClient, resourceGroup, server) =>
            {
                var serviceObjectives = sqlClient.Servers.ListServiceObjectives(resourceGroup.Name, server.Name);

                foreach(ServiceObjective objective in serviceObjectives)
                {
                    Assert.NotNull(objective.ServiceObjectiveName);
                    Assert.NotNull(objective.IsDefault);
                    Assert.NotNull(objective.IsSystem);
                    Assert.NotNull(objective.Enabled);

                    // Assert Get finds the service objective from List
                    Assert.NotNull(sqlClient.Servers.GetServiceObjective(resourceGroup.Name, server.Name, objective.Name));
                }
            });
        }
    }
}

Fix test failing in playback

Fix test failing in playback


using System.Collections.Generic;
using Mono.Debugger.Cli.Debugging;
using Mono.Debugger.Cli.Logging;

namespace Mono.Debugger.Cli.Commands
{
    public sealed class LocalsCommand : ICommand
    {
        public string Name
        {
            get { return "Locals"; }
        }

        public string Description
        {
            get { return "Prints local variables."; }
        }

        public IEnumerable<string> Arguments
        {
            get { return Argument.None(); }
        }

        public void Execute(CommandArguments args)
        {
            var backtrace = SoftDebugger.Backtrace;

            if (backtrace == null)
            {
                Logger.WriteErrorLine("No backtrace available.");
                return;
            }

            var frame = backtrace.CurrentStackFrame;

            if (frame == null)
            {
                Logger.WriteErrorLine("No stack frame available.");
                return;
            }

            foreach (var local in frame.GetLocalVariables())
                Logger.WriteInfoLine("[{0}] {1}: {2}", local.TypeName, local.Name, local.DisplayValue);
        }
    }
}

using System.Collections.Generic;
using Mono.Debugger.Cli.Debugging;
using Mono.Debugger.Cli.Logging;

namespace Mono.Debugger.Cli.Commands
{
    public sealed class LocalsCommand : ICommand
    {
        public string Name
        {
            get { return "Locals"; }
        }

        public string Description
        {
            get { return "Prints local variables."; }
        }

        public IEnumerable<string> Arguments
        {
            get { return Argument.None(); }
        }

        public void Execute(CommandArguments args)
        {
            var backtrace = SoftDebugger.Backtrace;

            if (backtrace == null)
            {
                Logger.WriteErrorLine("No backtrace available.");
                return;
            }

            var frame = backtrace.CurrentStackFrame;

            if (frame == null)
            {
                Logger.WriteErrorLine("No stack frame available.");
                return;
            }

            foreach (var local in frame.GetLocalVariables())
                if (!local.IsUnknown && !local.IsError && !local.IsNotSupported)
                    Logger.WriteInfoLine("[{0}] {1}: {2}", local.TypeName, local.Name, local.DisplayValue);
        }
    }
}

Make local evaluation a little safer.

Make local evaluation a little safer.


using OrienteeringToolWPF.Model;
using OrienteeringToolWPF.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OrienteeringToolWPF.DAO
{
    public static class CompetitorHelper
    {
        public static List<Competitor> CompetitorsJoinedWhereRelayId(long RelayId)
        {
            var db = DatabaseUtils.GetDatabase();
            dynamic resultsAlias, punchAlias;
            var CompetitorList = (List<Competitor>)db.Competitors.FindAllByRelayId(RelayId)
                        .LeftJoin(db.Results, out resultsAlias)
                        .On(db.Results.Chip == db.Competitors.Chip)
                        .LeftJoin(db.Punches, out punchAlias)
                        .On(db.Punches.Chip == db.Competitors.Chip)
                        .With(resultsAlias)
                        .With(punchAlias);

            foreach (var competitor in CompetitorList)
            {
                var punches = (List<Punch>)competitor.Punches;
                try
                {
                    punches?.Sort();
                    Punch.CalculateDeltaStart(ref punches, competitor.Result.StartTime);
                    Punch.CalculateDeltaPrevious(ref punches);
                }
                catch (ArgumentNullException) { }
                competitor.Punches = punches;
            }

            return CompetitorList;
        }
    }
}

using OrienteeringToolWPF.Model;
using OrienteeringToolWPF.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OrienteeringToolWPF.DAO
{
    public static class CompetitorHelper
    {
        public static List<Competitor> CompetitorsJoinedWhereRelayId(long RelayId)
        {
            var db = DatabaseUtils.GetDatabase();
            dynamic resultsAlias, punchAlias;
            var CompetitorList = (List<Competitor>)db.Competitors.FindAllByRelayId(RelayId)
                        .LeftJoin(db.Results, out resultsAlias)
                        .On(db.Results.Chip == db.Competitors.Chip)
                        .LeftJoin(db.Punches, out punchAlias)
                        .On(db.Punches.Chip == db.Competitors.Chip)
                        .With(resultsAlias)
                        .With(punchAlias);

            foreach (var competitor in CompetitorList)
            {
                var punches = (List<Punch>)competitor.Punches;
                try
                {
                    punches?.Sort();
                    Punch.CalculateDeltaStart(ref punches, competitor.Result.StartTime);
                    Punch.CalculateDeltaPrevious(ref punches);
                }
                catch (NullReferenceException) { }
                competitor.Punches = punches;
            }

            return CompetitorList;
        }
    }
}

Change exception to proper class

Change exception to proper class


using LiveScoreUpdateSystem.Data.Models.Contracts;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Security.Claims;
using System.Threading.Tasks;

namespace LiveScoreUpdateSystem.Data.Models
{
    public class User : IdentityUser, IDeletable, IAuditable, IDataModel
    {
        public DateTime? CreatedOn { get; set; }

        public DateTime? ModifiedOn { get; set; }

        public bool IsDeleted { get; set; }

        public DateTime? DeletedOn { get; set; }

        Guid IDataModel.Id => throw new NotImplementedException();

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }
}

using LiveScoreUpdateSystem.Data.Models.Contracts;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Security.Claims;
using System.Threading.Tasks;

namespace LiveScoreUpdateSystem.Data.Models
{
    public class User : IdentityUser, IDeletable, IAuditable, IDataModel
    {
        public DateTime? CreatedOn { get; set; }

        public DateTime? ModifiedOn { get; set; }

        public bool IsDeleted { get; set; }

        public DateTime? DeletedOn { get; set; }

        Guid IDataModel.Id { get;  }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }
}

Remove fat arrow getter because of appveyor .net version support


@model Vehicle

@switch(Model.Status)
{
    case Vehicle.VehicleStatus.FMC:
        FMC
        return;

    case Vehicle.VehicleStatus.NMC:
        NMC
        return;

    default:
        @Model
        return;
}

@model Vehicle

@switch(Model.Status)
{
    case Vehicle.VehicleStatus.FMC:
        FMC
        return;

    case Vehicle.VehicleStatus.NMC:
        NMC
                return;

    case Vehicle.VehicleStatus.Unknown:
        Unknown
        return;
}

Fix for Unknown status display

Fix for Unknown status display


using System.Windows.Controls.Primitives;

namespace SharpGraphEditor.Controls.GraphElements
{
    /// <summary>
    /// Логика взаимодействия для VertexControl.xaml
    /// </summary>
    public partial class VertexControl : Thumb
    {
        public VertexControl()
        {
            InitializeComponent();
        }
    }
}

using System.Windows.Controls.Primitives;

namespace SharpGraphEditor.Controls.GraphElements
{
    /// <summary>
    /// Логика взаимодействия для VertexControl.xaml
    /// </summary>
    public partial class VertexControl : Thumb
    {
        public VertexControl()
        {
            InitializeComponent();
            SizeChanged += (_, __) =>
            {
                var centerX = ActualWidth / 2;
                var centerY = ActualHeight / 2;
                Margin = new System.Windows.Thickness(-centerX, -centerY, centerX, centerY);
            };
        }
    }
}

Fix bug: incorrectly determines the center of the top


// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.

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

namespace Responsive
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

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

            // Add framework services.
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseDetection();

            app.UseRouting();

            app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
        }
    }
}

// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.

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

namespace Responsive
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

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

            // Add framework services.
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseDetection();

            app.UseRouting();

            app.UseEndpoints(
                endpoints =>
                {
                    endpoints.MapControllerRoute(
                        "default",
                        "{controller=Home}/{action=Index}/{id?}");
                    endpoints.MapControllerRoute(
                        "areas",
                        "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                    );
                });
        }
    }
}

Set endpoint routing in responsive sample web app


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;

namespace CodeComb.AspNet.Upload.Models
{
    public static class ModelBuilderExtensions
    {
        public static ModelBuilder SetupBlob(this ModelBuilder self)
        {
            return self.Entity<File>(e =>
            {
                e.HasIndex(x => x.Time);
                e.HasIndex(x => x.FileName);
            });
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;

namespace CodeComb.AspNet.Upload.Models
{
    public static class ModelBuilderExtensions
    {
        public static ModelBuilder SetupFiles(this ModelBuilder self)
        {
            return self.Entity<File>(e =>
            {
                e.HasIndex(x => x.Time);
                e.HasIndex(x => x.FileName);
            });
        }
    }
}

Rename setup blob => setup files

Rename setup blob => setup files


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

namespace Xamarin.Forms.GoogleMaps
{
    public static class GeoConstants
    {
        public const double EarthRadiusKm = 6371;
        public const double EarthCircumferenceKm = EarthRadiusKm * 2 * Math.PI;
        public const double MetersPerMile = 1609.344;
        public const double MetersPerKilometer = 1000.0;
    }
}

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

namespace Xamarin.Forms.GoogleMaps
{
    internal static class GeoConstants
    {
        public const double EarthRadiusKm = 6371;
        public const double EarthCircumferenceKm = EarthRadiusKm * 2 * Math.PI;
        public const double MetersPerMile = 1609.344;
        public const double MetersPerKilometer = 1000.0;
    }
}

Change classe accessibility to internal

Change classe accessibility to internal


using CodeHub.Services;
using GalaSoft.MvvmLight;

namespace CodeHub.ViewModels.Settings
{
	public class NofiticationSettingsViewModel : ObservableObject
	{
		private bool _isToastEnabled = SettingsService.Get<bool>(SettingsKeys.IsToastEnabled);

		public bool IsToastEnabled
		{
			get => _isToastEnabled;
			set
			{
				if (_isToastEnabled != value)
				{
					_isToastEnabled = value;
					SettingsService.Save(SettingsKeys.IsToastEnabled, value);
					RaisePropertyChanged();
				}
			}
		}

		public NofiticationSettingsViewModel()
		{

		}
	}
}

using CodeHub.Services;
using GalaSoft.MvvmLight;

namespace CodeHub.ViewModels.Settings
{
    public class NofiticationSettingsViewModel : ObservableObject
    {
        private bool _isToastEnabled = SettingsService.Get<bool>(SettingsKeys.IsToastEnabled);
        private bool _isLiveTilesEnabled = SettingsService.Get<bool>(SettingsKeys.IsLiveTilesEnabled);
        private bool _isLiveTilesBadgeEnabled = SettingsService.Get<bool>(SettingsKeys.IsLiveTilesBadgeEnabled);
        private bool _isLiveTileUpdateAllBadgesEnabled = SettingsService.Get<bool>(SettingsKeys.IsLiveTileUpdateAllBadgesEnabled);

        public bool IsToastEnabled
        {
            get => _isToastEnabled;
            set
            {
                if (_isToastEnabled != value)
                {
                    _isToastEnabled = value;
                    SettingsService.Save(SettingsKeys.IsToastEnabled, value);
                    RaisePropertyChanged(() => IsToastEnabled);
                }
            }
        }

        public bool IsLiveTilesEnabled
        {
            get => _isLiveTilesEnabled;
            set
            {
                if (_isLiveTilesEnabled != value)
                {
                    _isLiveTilesEnabled = value;
                    SettingsService.Save(SettingsKeys.IsLiveTilesEnabled, value);
                    RaisePropertyChanged(() => IsLiveTilesEnabled);
                }
                if (!value && IsLiveTilesBadgeEnabled)
                {
                    IsLiveTilesBadgeEnabled = false;
                }
            }
        }

        public bool IsLiveTilesBadgeEnabled
        {
            get => _isLiveTilesBadgeEnabled;
            set
            {
                if (_isLiveTilesBadgeEnabled != value)
                {
                    _isLiveTilesBadgeEnabled = value;
                    SettingsService.Save(SettingsKeys.IsLiveTilesBadgeEnabled, value);
                    RaisePropertyChanged(() => IsLiveTilesBadgeEnabled);
                }
                if (!value && IsAllBadgesUpdateEnabled)
                {
                    IsAllBadgesUpdateEnabled = false;
                }
            }
        }

        public bool IsAllBadgesUpdateEnabled
        {
            get => _isLiveTilesEnabled;
            set
            {
                if (_isLiveTileUpdateAllBadgesEnabled != value)
                {
                    _isLiveTileUpdateAllBadgesEnabled = value;
                    SettingsService.Save(SettingsKeys.IsLiveTileUpdateAllBadgesEnabled, value);
                    RaisePropertyChanged(() => IsAllBadgesUpdateEnabled);
                }
            }
        }

        public NofiticationSettingsViewModel()
        {

        }
    }
}

Update NotificationSettingsVM for LiveTiles settings


// Helpers/Settings.cs
using Refractored.Xam.Settings;
using Refractored.Xam.Settings.Abstractions;

namespace CodeCamp.Helpers
{
  /// <summary>
  /// This is the Settings static class that can be used in your Core solution or in any
  /// of your client applications. All settings are laid out the same exact way with getters
  /// and setters.
  /// </summary>
  public static class Settings
  {
    private static ISettings AppSettings
    {
      get
      {
        return CrossSettings.Current;
      }
    }

    #region Setting Constants

    private const string SettingsKey = "settings_key";
    private static readonly string SettingsDefault = string.Empty;

    #endregion

    public static string GeneralSettings
    {
      get
      {
        return AppSettings.GetValueOrDefault(SettingsKey, SettingsDefault);
      }
      set
      {
        //if value has changed then save it!
        if (AppSettings.AddOrUpdateValue(SettingsKey, value))
          AppSettings.Save();
      }
    }

  }
}

// Helpers/Settings.cs
using Refractored.Xam.Settings;
using Refractored.Xam.Settings.Abstractions;

namespace CodeCamp.Helpers
{
  /// <summary>
  /// This is the Settings static class that can be used in your Core solution or in any
  /// of your client applications. All settings are laid out the same exact way with getters
  /// and setters.
  /// </summary>
  public static class Settings
  {
    private static ISettings AppSettings
    {
      get
      {
        return CrossSettings.Current;
      }
    }

    #region Setting Constants

    private const string UsernameKey = "username_key";
    private static readonly string UsernameDefault = string.Empty;

    private const string MasterConferenceKey = "masterconference_key";
    private static readonly int MasterConferenceDefault = -1;

    private const string ConferenceKey = "conference_key";
    private static readonly int ConferenceDefault = -1;
    #endregion

    public static string UsernameSettings
    {
      get
      {
        return AppSettings.GetValueOrDefault(UsernameKey, UsernameDefault);
      }
      set
      {
        if (AppSettings.AddOrUpdateValue(UsernameKey, value))
          AppSettings.Save();
      }
    }

    public static int MasterConference
    {
      get
      {
        return AppSettings.GetValueOrDefault(MasterConferenceKey, MasterConferenceDefault);
      }
      set
      {
        if (AppSettings.AddOrUpdateValue(MasterConferenceKey, value))
          AppSettings.Save();
      }
    }

    public static int Conference
    {
      get
      {
        return AppSettings.GetValueOrDefault(ConferenceKey, ConferenceDefault);
      }
      set
      {
        if (AppSettings.AddOrUpdateValue(ConferenceKey, value))
          AppSettings.Save();
      }
    }

  }
}

Update settings with username and conference ids


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

namespace CyLR
{
    internal static class CollectionPaths
    {
        public static List<string> GetPaths(Arguments arguments)
        {
            var paths = new List<string>
            {
                        @"C:\Windows\System32\config",
                        @"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup",
                        @"C:\Windows\Prefetch",
                        @"C:\Windows\Tasks",
                        @"C:\Windows\SchedLgU.Txt",
                        @"C:\Windows\System32\winevt\logs",
                        @"C:\Windows\System32\drivers\etc\hosts",
                        @"C:\$MFT"
            };
            if (Platform.IsUnixLike())
            {
                paths = new List<string>
                {
                    "/root/.bash_history",
                    "/var/logs"
                };
            }

            if (arguments.CollectionFilePath != ".")
            {
                if (File.Exists(arguments.CollectionFilePath))
                {
                    paths.Clear();
                    paths.AddRange(File.ReadAllLines(arguments.CollectionFilePath));
                }
                else
                {
                    Console.WriteLine("Error: Could not find file: {0}", arguments.CollectionFilePath);
                    Console.WriteLine("Exiting");
                    throw new ArgumentException();
                }

            }

            return paths;
        }
    }
}

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

namespace CyLR
{
    internal static class CollectionPaths
    {
        public static List<string> GetPaths(Arguments arguments)
        {
            var paths = new List<string>
            {
                        @"C:\Windows\System32\config",
                        @"C:\Windows\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup",
                        @"C:\Windows\Prefetch",
                        @"C:\Windows\Tasks",
                        @"C:\Windows\SchedLgU.Txt",
                        @"C:\Windows\System32\winevt\logs",
                        @"C:\Windows\System32\drivers\etc\hosts",
                        @"C:\$MFT"
            };
            if (Platform.IsUnixLike())
            {
                paths = new List<string>
                {
                    "/root/.bash_history",
                    "/var/logs"
                };
            }

            if (arguments.CollectionFilePath != ".")
            {
                if (File.Exists(arguments.CollectionFilePath))
                {
                    paths.Clear();
                    paths.AddRange(File.ReadAllLines(arguments.CollectionFilePath));
                }
                else
                {
                    Console.WriteLine("Error: Could not find file: {0}", arguments.CollectionFilePath);
                    Console.WriteLine("Exiting");
                    throw new ArgumentException();
                }

            }

            return paths;
        }
    }
}

Revert "Fixing bad default path."

Revert "Fixing bad default path."

This reverts commit 28f7d396adb79d66431aa7fad1c4c6b52f7bc125.


@{
    var parsedModel = TempData.GetStatusMessageModel();
}

@if (parsedModel != null)
{

        @if (parsedModel.AllowDismiss)
        {
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                ×
            </button>
        }
        @if (!string.IsNullOrEmpty(parsedModel.Message))
        {
            @parsedModel.Message
        }
        @if (!string.IsNullOrEmpty(parsedModel.Html))
        {
            @Safe.Raw(parsedModel.Html)
        }

}

Improve spacing for status messages

Improve spacing for status messages


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

using System;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Edit.Timing;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Screens.Edit.Compose.Components.Timeline
{
    public class TimelineButton : CompositeDrawable
    {
        public Action Action;
        public readonly BindableBool Enabled = new BindableBool(true);

        public IconUsage Icon
        {
            get => button.Icon;
            set => button.Icon = value;
        }

        private readonly TimelineIconButton button;

        public TimelineButton()
        {
            InternalChild = button = new TimelineIconButton { Action = () => Action?.Invoke() };

            button.Enabled.BindTo(Enabled);
            Width = button.Width;
        }

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

            button.Size = new Vector2(button.Width, DrawHeight);
        }

        private class TimelineIconButton : IconButton
        {
            public TimelineIconButton()
            {
                Anchor = Anchor.Centre;
                Origin = Anchor.Centre;
                IconColour = OsuColour.Gray(0.35f);
                IconHoverColour = Color4.White;
                HoverColour = OsuColour.Gray(0.25f);
                FlashColour = OsuColour.Gray(0.5f);

                Add(new RepeatingButtonBehaviour(this));
            }

            protected override HoverSounds CreateHoverSounds(HoverSampleSet sampleSet) => new HoverSounds(sampleSet);
        }
    }
}

// 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.Game.Graphics.UserInterface;
using osu.Game.Overlays;
using osu.Game.Screens.Edit.Timing;

namespace osu.Game.Screens.Edit.Compose.Components.Timeline
{
    public class TimelineButton : IconButton
    {
        [BackgroundDependencyLoader]
        private void load(OverlayColourProvider colourProvider)
        {
            // These are using colourProvider but don't match the design.
            // Just something to fit until someone implements the updated design.
            IconColour = colourProvider.Background1;
            IconHoverColour = colourProvider.Content2;

            HoverColour = colourProvider.Background1;
            FlashColour = colourProvider.Content2;

            Add(new RepeatingButtonBehaviour(this));
        }

        protected override HoverSounds CreateHoverSounds(HoverSampleSet sampleSet) => new HoverSounds(sampleSet);
    }
}

Remove unnecessary nesting of `IconButton` and update design a touch


<script type="text/javascript">
angular.module("myapp")
    .constant("WAIT", @ViewBag.WAIT)
    .constant("NAME", @ViewBag.NAME)
;
</script>

<script type="text/javascript">
angular.module("myapp")
    .constant("WAIT", @ViewBag.WAIT)
    .constant("NAME", '@ViewBag.NAME')
;
</script>

Fix string injection of NAME from ViewBag to ng.constant


using Glimpse.Web;
using Microsoft.AspNet.Http;
using Newtonsoft.Json;
using System.IO;
using System.Text;
using Microsoft.AspNet.Builder;

namespace Glimpse.Server.Web
{
    public class HttpChannelReceiver : IMiddlewareResourceComposer
    {
        private readonly IServerBroker _messageServerBus;

        public HttpChannelReceiver(IServerBroker messageServerBus)
        {
            _messageServerBus = messageServerBus;
        }

        public void Register(IApplicationBuilder appBuilder)
        {
            appBuilder.Map("/agent", chuldApp => chuldApp.Run(async context =>
            {
                var envelope = ReadMessage(context.Request);

                _messageServerBus.SendMessage(envelope);

                // TEST CODE ONLY!!!!
                var response = context.Response;

                response.Headers.Set("Content-Type", "text/plain");

                var data = Encoding.UTF8.GetBytes(envelope.Payload);
                await response.Body.WriteAsync(data, 0, data.Length);
                // TEST CODE ONLY!!!!
            }));
        }

        private Message ReadMessage(HttpRequest request)
        {
            var reader = new StreamReader(request.Body);
            var text = reader.ReadToEnd();

            var message = JsonConvert.DeserializeObject<Message>(text);

            return message;
        }
    }
}

using Glimpse.Web;
using Microsoft.AspNet.Http;
using Newtonsoft.Json;
using System.IO;
using System.Text;
using Microsoft.AspNet.Builder;

namespace Glimpse.Server.Web
{
    public class HttpChannelReceiver : IMiddlewareResourceComposer
    {
        private readonly IServerBroker _messageServerBus;

        public HttpChannelReceiver(IServerBroker messageServerBus)
        {
            _messageServerBus = messageServerBus;
        }

        public void Register(IApplicationBuilder appBuilder)
        {
            appBuilder.Map("/agent", childApp => childApp.Run(async context =>
            {
                var envelope = ReadMessage(context.Request);

                _messageServerBus.SendMessage(envelope);

                // TODO: Really should do something better
                var response = context.Response;
                response.Headers.Set("Content-Type", "text/plain");

                var data = Encoding.UTF8.GetBytes("OK");
                await response.Body.WriteAsync(data, 0, data.Length);
            }));
        }

        private Message ReadMessage(HttpRequest request)
        {
            var reader = new StreamReader(request.Body);
            var text = reader.ReadToEnd();

            var message = JsonConvert.DeserializeObject<Message>(text);

            return message;
        }
    }
}

Simplify the response from the server on the agent-server http channel


using System.Collections.Generic;
using JoinRpg.DataModel;
using JoinRpg.Domain;
using Claim = System.Security.Claims.Claim;
using ClaimTypes = System.Security.Claims.ClaimTypes;

namespace Joinrpg.Web.Identity
{
    internal static class ClaimInfoBuilder
    {
        public static IList<Claim> ToClaimsList(this User dbUser)
        {
            return new List<Claim>
            {
                new Claim(ClaimTypes.Email, dbUser.Email),
                new Claim(JoinClaimTypes.DisplayName, dbUser.GetDisplayName()),
                new Claim(JoinClaimTypes.AvatarId, dbUser.SelectedAvatarId?.ToString())
            };
        }
    }
}

using System.Collections.Generic;
using JoinRpg.DataModel;
using JoinRpg.Domain;
using Claim = System.Security.Claims.Claim;
using ClaimTypes = System.Security.Claims.ClaimTypes;

namespace Joinrpg.Web.Identity
{
    internal static class ClaimInfoBuilder
    {
        public static IList<Claim> ToClaimsList(this User dbUser)
        {
            var claimList = new List<Claim>
            {
                new Claim(ClaimTypes.Email, dbUser.Email),
                new Claim(JoinClaimTypes.DisplayName, dbUser.GetDisplayName()),
            };
            if (dbUser.SelectedAvatarId is not null)
            {
                //TODO: When we fix all avatars, it will be not required check
                claimList.Add(new Claim(JoinClaimTypes.AvatarId, dbUser.SelectedAvatarId?.ToString()));
            }
            return claimList;
        }
    }
}

Fix problem with missing avatars

Fix problem with missing avatars


namespace Nubot.Abstractions
{
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;

    public abstract class RobotPluginBase : IRobotPlugin
    {
        protected readonly IRobot Robot;

        protected RobotPluginBase(string pluginName, IRobot robot)
        {
            Name = pluginName;

            Robot = robot;

            HelpMessages = new List<string>();
        }

        static RobotPluginBase()
        {
            ExecutingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            BasePluginsDirectory = Path.Combine(ExecutingDirectory, "plugins");
        }

        public string Name { get; protected set; }

        public static string ExecutingDirectory { get; private set; }

        public static string BasePluginsDirectory { get; private set; }

        public IEnumerable<string> HelpMessages { get; protected set; }

        public virtual IEnumerable<IPluginSetting> Settings { get { return Enumerable.Empty<IPluginSetting>();} }

        public virtual string MakeConfigFileName()
        {
            var pluginName = Name.Replace(" ", string.Empty);

            //Bug it is not defined that the plugin is from the root folder
            var file = string.Format("{0}.config", pluginName);
            var configFileName = Path.Combine(BasePluginsDirectory, file);

            return configFileName;
        }
    }
}

namespace Nubot.Abstractions
{
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;

    public abstract class RobotPluginBase : IRobotPlugin
    {
        protected readonly IRobot Robot;

        protected RobotPluginBase(string pluginName, IRobot robot)
        {
            Name = pluginName;

            Robot = robot;

            HelpMessages = new List<string>();
        }

        static RobotPluginBase()
        {
            ExecutingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            BasePluginsDirectory = Path.Combine(ExecutingDirectory, "plugins");
        }

        public string Name { get; private set; }

        public static string ExecutingDirectory { get; private set; }

        public static string BasePluginsDirectory { get; private set; }

        public IEnumerable<string> HelpMessages { get; protected set; }

        public virtual IEnumerable<IPluginSetting> Settings { get { return Enumerable.Empty<IPluginSetting>();} }

        public virtual string MakeConfigFileName()
        {
            var pluginName = Name.Replace(" ", string.Empty);

            var file = string.Format("{0}.config", pluginName);

            return Directory.GetFiles(BasePluginsDirectory, file, SearchOption.AllDirectories).FirstOrDefault();
        }
    }
}

Read plugin settings from BasePluginsDirectory and all sub-directories


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

using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components
{
    public class SliderBodyPiece : BlueprintPiece<Slider>
    {
        private readonly ManualSliderBody body;

        public SliderBodyPiece()
        {
            InternalChild = body = new ManualSliderBody
            {
                AccentColour = Color4.Transparent
            };
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            body.BorderColour = colours.Yellow;
        }

        public override void UpdateFrom(Slider hitObject)
        {
            base.UpdateFrom(hitObject);

            body.PathRadius = hitObject.Scale * OsuHitObject.OBJECT_RADIUS;

            var vertices = new List<Vector2>();
            hitObject.Path.GetPathToProgress(vertices, 0, 1);

            body.SetVertices(vertices);

            Size = body.Size;
            OriginPosition = body.PathOffset;
        }
    }
}

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

using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components
{
    public class SliderBodyPiece : BlueprintPiece<Slider>
    {
        private readonly ManualSliderBody body;

        public SliderBodyPiece()
        {
            InternalChild = body = new ManualSliderBody
            {
                AccentColour = Color4.Transparent
            };
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            body.BorderColour = colours.Yellow;
        }

        public override void UpdateFrom(Slider hitObject)
        {
            base.UpdateFrom(hitObject);

            body.PathRadius = hitObject.Scale * OsuHitObject.OBJECT_RADIUS;

            var vertices = new List<Vector2>();
            hitObject.Path.GetPathToProgress(vertices, 0, 1);

            body.SetVertices(vertices);

            Size = body.Size;
            OriginPosition = body.PathOffset;
        }

        public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => body.ReceivePositionalInputAt(screenSpacePos);
    }
}

Fix slider selection input handled outside path


using Autofac;
using Autofac.Integration.Owin;
using Bit.Owin.Contracts;
using Bit.Owin.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Owin;
using Owin;
using System;
using System.Reflection;
using System.Threading.Tasks;

namespace Bit.OwinCore.Middlewares
{
    public class AspNetCoreAutofacDependencyInjectionMiddlewareConfiguration : IOwinMiddlewareConfiguration
    {
        public virtual void Configure(IAppBuilder owinApp)
        {
            owinApp.Use<AspNetCoreAutofacDependencyInjectionMiddleware>();

            owinApp.Use<AutofacScopeBasedDependencyResolverMiddleware>();
        }
    }

    public class AspNetCoreAutofacDependencyInjectionMiddleware : OwinMiddleware
    {
        public AspNetCoreAutofacDependencyInjectionMiddleware(OwinMiddleware next)
            : base(next)
        {

        }

        static AspNetCoreAutofacDependencyInjectionMiddleware()
        {
            TypeInfo autofacConstantsType = typeof(OwinContextExtensions).GetTypeInfo().Assembly.GetType("Autofac.Integration.Owin.Constants").GetTypeInfo();

            FieldInfo owinLifetimeScopeKeyField = autofacConstantsType.GetField("OwinLifetimeScopeKey", BindingFlags.Static | BindingFlags.NonPublic);

            if (owinLifetimeScopeKeyField == null)
                throw new InvalidOperationException($"OwinLifetimeScopeKey field could not be found in {nameof(OwinContextExtensions)} ");

            OwinLifetimeScopeKey = (string)owinLifetimeScopeKeyField.GetValue(null);
        }

        private static readonly string OwinLifetimeScopeKey;

        public override async Task Invoke(IOwinContext context)
        {
            HttpContext aspNetCoreContext = (HttpContext)context.Environment["Microsoft.AspNetCore.Http.HttpContext"];

            aspNetCoreContext.Items["OwinContext"] = context;

            ILifetimeScope autofacScope = aspNetCoreContext.RequestServices.GetService<ILifetimeScope>();

            context.Set(OwinLifetimeScopeKey, autofacScope);

            await Next.Invoke(context);
        }
    }
}

using Autofac;
using Autofac.Integration.Owin;
using Bit.Owin.Contracts;
using Bit.Owin.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Owin;
using Owin;
using System.Threading.Tasks;

namespace Bit.OwinCore.Middlewares
{
    public class AspNetCoreAutofacDependencyInjectionMiddlewareConfiguration : IOwinMiddlewareConfiguration
    {
        public virtual void Configure(IAppBuilder owinApp)
        {
            owinApp.Use<AspNetCoreAutofacDependencyInjectionMiddleware>();

            owinApp.Use<AutofacScopeBasedDependencyResolverMiddleware>();
        }
    }

    public class AspNetCoreAutofacDependencyInjectionMiddleware : OwinMiddleware
    {
        public AspNetCoreAutofacDependencyInjectionMiddleware(OwinMiddleware next)
            : base(next)
        {

        }

        public override async Task Invoke(IOwinContext context)
        {
            HttpContext aspNetCoreContext = (HttpContext)context.Environment["Microsoft.AspNetCore.Http.HttpContext"];

            aspNetCoreContext.Items["OwinContext"] = context;

            ILifetimeScope autofacScope = aspNetCoreContext.RequestServices.GetService<ILifetimeScope>();

            context.SetAutofacLifetimeScope(autofacScope);

            await Next.Invoke(context);
        }
    }
}

Use newly introduced autofac's SetAutofacLifetimeScope method to pass autofac scope from asp.net core pipeline to owin pipeline


namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Seasons
{
    using Enums;
    using Objects.Basic;
    using Objects.Get.Shows.Seasons;
    using System.Collections.Generic;

    internal class TraktSeasonCommentsRequest : TraktGetByIdSeasonRequest<TraktPaginationListResult<TraktSeasonComment>, TraktSeasonComment>
    {
        internal TraktSeasonCommentsRequest(TraktClient client) : base(client) { }

        internal TraktCommentSortOrder? Sorting { get; set; }

        protected override IDictionary<string, object> GetUriPathParameters()
        {
            var uriParams = base.GetUriPathParameters();

            if (Sorting.HasValue && Sorting.Value != TraktCommentSortOrder.Unspecified)
                uriParams.Add("sorting", Sorting.Value.AsString());

            return uriParams;
        }

        protected override string UriTemplate => "shows/{id}/seasons/{season}/comments/{sorting}";

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Seasons
{
    using Enums;
    using Objects.Basic;
    using Objects.Get.Shows.Seasons;
    using System.Collections.Generic;

    internal class TraktSeasonCommentsRequest : TraktGetByIdSeasonRequest<TraktPaginationListResult<TraktSeasonComment>, TraktSeasonComment>
    {
        internal TraktSeasonCommentsRequest(TraktClient client) : base(client) { }

        internal TraktCommentSortOrder? Sorting { get; set; }

        protected override IDictionary<string, object> GetUriPathParameters()
        {
            var uriParams = base.GetUriPathParameters();

            if (Sorting.HasValue && Sorting.Value != TraktCommentSortOrder.Unspecified)
                uriParams.Add("sorting", Sorting.Value.AsString());

            return uriParams;
        }

        protected override string UriTemplate => "shows/{id}/seasons/{season}/comments{/sorting}";

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

Fix uri templates in season requests.

Fix uri templates in season requests.


using System;
using System.Collections;
using System.Collections.Immutable;
using System.Linq;

using NQuery.Binding;

namespace NQuery.Optimization
{
    internal sealed class AggregationPhysicalOperatorChooser : BoundTreeRewriter
    {
        protected override BoundRelation RewriteGroupByAndAggregationRelation(BoundGroupByAndAggregationRelation node)
        {
            var input = RewriteRelation(node.Input);
            var sortedValues = node.Groups.Select(g => new BoundSortedValue(g, Comparer.Default)).ToImmutableArray();
            var sortedInput = new BoundSortRelation(input, sortedValues);
            return new BoundStreamAggregatesRelation(sortedInput, node.Groups, node.Aggregates);
        }
    }
}

using System;
using System.Collections;
using System.Collections.Immutable;
using System.Linq;

using NQuery.Binding;

namespace NQuery.Optimization
{
    internal sealed class AggregationPhysicalOperatorChooser : BoundTreeRewriter
    {
        protected override BoundRelation RewriteGroupByAndAggregationRelation(BoundGroupByAndAggregationRelation node)
        {
            var input = RewriteRelation(node.Input);
            var sortedValues = node.Groups.Select(g => new BoundSortedValue(g, Comparer.Default)).ToImmutableArray();
            var sortedInput = sortedValues.Any()
                ? new BoundSortRelation(input, sortedValues)
                : input;
            return new BoundStreamAggregatesRelation(sortedInput, node.Groups, node.Aggregates);
        }
    }
}

Fix bug which causes unnecessary sorts

Fix bug which causes unnecessary sorts

We currently insert a sort node independent of whether the aggregation
has any groups. Omit the sorting if we only need to aggregate.


namespace Stripe.Terminal
{
    using System;
    using Newtonsoft.Json;

    public class ReaderListOptions : ListOptions
    {
        [JsonProperty("location")]
        public string Location { get; set; }

        [Obsolete("This feature has been deprecated and should not be used moving forward.")]
        [JsonProperty("operator_account")]
        public string OperatorAccount { get; set; }
    }
}

namespace Stripe.Terminal
{
    using System;
    using Newtonsoft.Json;

    public class ReaderListOptions : ListOptions
    {
        /// <summary>
        /// A location ID to filter the response list to only readers at the specific location.
        /// </summary>
        [JsonProperty("location")]
        public string Location { get; set; }

        /// <summary>
        /// A status filter to filter readers to only offline or online readers. Possible values
        /// are <c>offline</c> and <c>online</c>.
        /// </summary>
        [JsonProperty("status")]
        public string Status { get; set; }

        [Obsolete("This feature has been deprecated and should not be used moving forward.")]
        [JsonProperty("operator_account")]
        public string OperatorAccount { get; set; }
    }
}

Support `Status` filter when listing Terminal `Reader`s


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

using System;
using Microsoft.Azure.WebJobs.Description;

namespace Microsoft.Azure.WebJobs.ServiceBus
{
    /// <summary>
    /// Setup an 'trigger' on a parameter to listen on events from an event hub.
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter)]
    [Binding]
    public sealed class EventHubTriggerAttribute : Attribute
    {
        /// <summary>
        /// Create an instance of this attribute.
        /// </summary>
        /// <param name="eventHubName">Event hub to listen on for messages. </param>
        public EventHubTriggerAttribute(string eventHubName)
        {
            this.EventHubName = eventHubName;
        }

        /// <summary>
        /// Name of the event hub.
        /// </summary>
        public string EventHubName { get; private set; }

        /// <summary>
        /// Optional Name of the consumer group. If missing, then use the default name, "$Default"
        /// </summary>
        public string ConsumerGroup { get; set; }
    }
}

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

using System;
using Microsoft.Azure.WebJobs.Description;

namespace Microsoft.Azure.WebJobs.ServiceBus
{
    /// <summary>
    /// Setup an 'trigger' on a parameter to listen on events from an event hub.
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter)]
    [Binding]
    public sealed class EventHubTriggerAttribute : Attribute
    {
        /// <summary>
        /// Create an instance of this attribute.
        /// </summary>
        /// <param name="eventHubName">Event hub to listen on for messages. </param>
        public EventHubTriggerAttribute(string eventHubName)
        {
            this.EventHubName = eventHubName;
        }

        /// <summary>
        /// Name of the event hub.
        /// </summary>
        public string EventHubName { get; private set; }

        /// <summary>
        /// Optional Name of the consumer group. If missing, then use the default name, "$Default"
        /// </summary>
        public string ConsumerGroup { get; set; }

        /// <summary>
        /// Optional connection name. If missing, tries to use a registered event hub receiver.
        /// </summary>
        public string Connection { get; set; }
    }
}

Add event hub connection property

Add event hub connection property


using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using BookSleeve;
using SignalR;

namespace Compilify.Web.EndPoints
{
    public class ExecuteEndPoint : PersistentConnection
    {
        /// <summary>
        /// Handle messages sent by the client.</summary>
        protected override Task OnReceivedAsync(string connectionId, string data)
        {
            var redis = DependencyResolver.Current.GetService<RedisConnection>();

            var command = new ExecuteCommand
                            {
                                ClientId = connectionId,
                                Code = data
                            };

            var message = Convert.ToBase64String(command.GetBytes());

            redis.Lists.AddLast(0, "queue:execute", message);

            return Send(new { status = "ok" });
        }
    }
}

using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using BookSleeve;
using SignalR;

namespace Compilify.Web.EndPoints
{
    public class ExecuteEndPoint : PersistentConnection
    {
        /// <summary>
        /// Handle messages sent by the client.</summary>
        protected override Task OnReceivedAsync(string connectionId, string data)
        {
            var redis = DependencyResolver.Current.GetService<RedisConnection>();

            if (redis.State != RedisConnectionBase.ConnectionState.Open)
            {
                throw new InvalidOperationException("RedisConnection state is " + redis.State);
            }

            var command = new ExecuteCommand
                            {
                                ClientId = connectionId,
                                Code = data
                            };

            var message = Convert.ToBase64String(command.GetBytes());

            redis.Lists.AddLast(0, "queue:execute", message);

            return Send(new { status = "ok" });
        }
    }
}

Throw an exception if the Redis connection is not open


using System.Diagnostics;
using System.Windows.Input;

using Norma.Models;
using Norma.ViewModels.Internal;

using Prism.Commands;

namespace Norma.ViewModels
{
    internal class LibraryViewModel : ViewModel
    {
        private readonly Library _library;

        public string Name => _library.Name;

        public string Url => _library.Url;

        public string License => _library.License;

        public LibraryViewModel(Library library)
        {
            _library = library;
        }

        #region OpenHyperlinkCommand

        private ICommand _openHyperlinkCommand;

        public ICommand OpenHyperlinkCommand =>
            _openHyperlinkCommand ?? (_openHyperlinkCommand = new DelegateCommand(OpenHyperlink));

        private void OpenHyperlink() => Process.Start(Url);

        #endregion
    }
}

using System.Diagnostics;
using System.Windows.Input;

using Norma.Models;
using Norma.ViewModels.Internal;

using Prism.Commands;

namespace Norma.ViewModels
{
    internal class LibraryViewModel : ViewModel
    {
        private readonly Library _library;

        public string Name => _library.Name;

        public string Url => _library.Url.Replace("https://", "").Replace("http://", "");

        public string License => _library.License;

        public LibraryViewModel(Library library)
        {
            _library = library;
        }

        #region OpenHyperlinkCommand

        private ICommand _openHyperlinkCommand;

        public ICommand OpenHyperlinkCommand =>
            _openHyperlinkCommand ?? (_openHyperlinkCommand = new DelegateCommand(OpenHyperlink));

        private void OpenHyperlink() => Process.Start(_library.Url);

        #endregion
    }
}

Remove protocol from licenses view.

Remove protocol from licenses view.


using System;
using System.ComponentModel;

namespace CoffeeFilter.UITests.Shared
{
	public static class UITestsHelpers
	{
		public static string XTCApiKey {
			get;
		} = "024b0d715a7e9c22388450cf0069cb19";

		public static TestType SelectedTest { get; set; }
		public enum TestType
		{
			NoConnection,
			ParseError,
			OpenCoffee,
			ClosedCoffee,
			NoLocations,
			UserMoved
		}
	}

	public static class TestTypeExtensions
	{
		public static string ToFriendlyString(this UITestsHelpers.TestType me)
		{
			switch(me)
			{
			case UITestsHelpers.TestType.NoConnection:
				return "No Internet Connection";
			case UITestsHelpers.TestType.ParseError:
				return "Parse Error";
			case UITestsHelpers.TestType.OpenCoffee:
				return "Open Coffee Locations";
			case UITestsHelpers.TestType.ClosedCoffee:
				return "Closed Coffee Locations";
			case UITestsHelpers.TestType.NoLocations:
				return "No Locations Around";
			case UITestsHelpers.TestType.UserMoved:
				return "User Moved and Refreshed";
			}
			return string.Empty;
		}
	}

}

using System;
using System.ComponentModel;

namespace CoffeeFilter.UITests.Shared
{
	public static class UITestsHelpers
	{
		public static string XTCApiKey {
			get;
		} = "024b0d715a7e9c22388450cf0069cb19";

		public static TestType SelectedTest { get; set; }
		public enum TestType
		{
			OpenCoffee = 0,
			NoConnection,
			ParseError,
			ClosedCoffee,
			NoLocations,
			UserMoved
		}
	}

	public static class TestTypeExtensions
	{
		public static string ToFriendlyString(this UITestsHelpers.TestType me)
		{
			switch(me)
			{
			case UITestsHelpers.TestType.NoConnection:
				return "No Internet Connection";
			case UITestsHelpers.TestType.ParseError:
				return "Parse Error";
			case UITestsHelpers.TestType.OpenCoffee:
				return "Open Coffee Locations";
			case UITestsHelpers.TestType.ClosedCoffee:
				return "Closed Coffee Locations";
			case UITestsHelpers.TestType.NoLocations:
				return "No Locations Around";
			case UITestsHelpers.TestType.UserMoved:
				return "User Moved and Refreshed";
			}
			return string.Empty;
		}
	}

}

Set OpenCoffee as default test type

[CoffeeFilter.UITests] Set OpenCoffee as default test type


using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using CompaniesHouse.Response.Document;
using CompaniesHouse.UriBuilders;
using FluentAssertions;
using Moq;
using NUnit.Framework;

namespace CompaniesHouse.Tests.CompaniesHouseDocumentClientTests
{
    [TestFixture]
    public class CompaniesHouseDocumentClientTests
    {
        private CompaniesHouseClientResponse<DocumentDownload> _result;
        private const string ExpectedMediaType = "application/pdf";
        private const string ExpectedContent = "test pdf";
        private const string DocumentId = "wibble";

        [SetUp]
        public async Task GivenAClient_WhenDownloadingDocument()
        {
            var requestUri = new Uri($"https://document-api.companieshouse.gov.uk/document/{DocumentId}/content");
            var stubHttpMessageHandler = new StubHttpMessageHandler(requestUri, ExpectedContent, ExpectedMediaType);
            var mockUriBuilder = new Mock<IDocumentUriBuilder>();
            mockUriBuilder.Setup(x => x.WithContent()).Returns(mockUriBuilder.Object);
            mockUriBuilder.Setup(x => x.Build(DocumentId)).Returns(requestUri.ToString());

            _result = await new CompaniesHouseDocumentClient(new HttpClient(stubHttpMessageHandler), mockUriBuilder.Object).DownloadDocumentAsync(DocumentId);
        }

        [Test]
        public void ThenDocumentContentIsCorrect()
        {
            var memoryStream = new MemoryStream();
            _result.Data.Content.CopyToAsync(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);

            new StreamReader(memoryStream).ReadToEnd().Should().Be(ExpectedContent);
        }
    }
}

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using CompaniesHouse.Response.Document;
using CompaniesHouse.UriBuilders;
using FluentAssertions;
using Moq;
using NUnit.Framework;

namespace CompaniesHouse.Tests.CompaniesHouseDocumentClientTests
{
    [TestFixture]
    public class CompaniesHouseDocumentClientTests
    {
        private CompaniesHouseClientResponse<DocumentDownload> _result;
        private const string ExpectedMediaType = "application/pdf";
        private const string ExpectedContent = "test pdf";
        private const string DocumentId = "wibble";

        [SetUp]
        public async Task GivenAClient_WhenDownloadingDocument()
        {
            var requestUri = new Uri($"https://document-api.companieshouse.gov.uk/document/{DocumentId}/content");
            var stubHttpMessageHandler = new StubHttpMessageHandler(requestUri, ExpectedContent, ExpectedMediaType);
            var mockUriBuilder = new Mock<IDocumentUriBuilder>();
            mockUriBuilder.Setup(x => x.WithContent()).Returns(mockUriBuilder.Object);
            mockUriBuilder.Setup(x => x.Build(DocumentId)).Returns(requestUri.ToString());

            _result = await new CompaniesHouseDocumentClient(new HttpClient(stubHttpMessageHandler), mockUriBuilder.Object).DownloadDocumentAsync(DocumentId);
        }

        [Test]
        public void ThenDocumentContentIsCorrect()
        {
            using var memoryStream = new MemoryStream();
            _result.Data.Content.CopyToAsync(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);

            new StreamReader(memoryStream).ReadToEnd().Should().Be(ExpectedContent);
        }
    }
}

Add using when creating a memorystream

Add using when creating a memorystream


using System;
using System.Runtime.InteropServices;
using Klawr.ClrHost.Managed;
using Klawr.ClrHost.Interfaces;
using Klawr.ClrHost.Managed.SafeHandles;

namespace Klawr.UnrealEngine
{
    public class TestActor : AActorScriptObject
    {
        public TestActor(long instanceID, UObjectHandle nativeObject) : base(instanceID, nativeObject)
        {
            Console.WriteLine("TestActor()");
        }

        public override void BeginPlay()
        {
            Console.WriteLine("BeginPlay()");
			var world = K2_GetWorld();
			var worldClass = UWorld.StaticClass();
            bool isWorldClass = world.IsA(worldClass);
            var anotherWorldClass = (UClass)typeof(UWorld);
            bool isSameClass = worldClass == anotherWorldClass;
            bool isWorldClassDerivedFromObjectClass = worldClass.IsChildOf(UObject.StaticClass());
            world.Dispose();
        }

        public override void Tick(float deltaTime)
        {
            Console.WriteLine("Tick()");
        }

        public override void Destroy()
        {
            Console.WriteLine("Destroy()");
        }
    }
}

using System;
using System.Runtime.InteropServices;
using Klawr.ClrHost.Managed;
using Klawr.ClrHost.Interfaces;
using Klawr.ClrHost.Managed.SafeHandles;

namespace Klawr.UnrealEngine
{
    // NOTE: IScriptObject should probably be considered deprecated in favor of UKlawrScriptComponent
    public class TestActor : AActorScriptObject
    {
        public TestActor(long instanceID, UObjectHandle nativeObject) : base(instanceID, nativeObject)
        {
            Console.WriteLine("TestActor()");
        }

        public override void BeginPlay()
        {
            Console.WriteLine("BeginPlay()");
            // FIXME: AActor::K2_GetWorld() is no more, and AActor::GetWorld() is not exposed to
            //        Blueprints at all... may need to expose UObject::GetWorld() manually.
            /*
			var world = K2_GetWorld();
			var worldClass = UWorld.StaticClass();
            bool isWorldClass = world.IsA(worldClass);
            var anotherWorldClass = (UClass)typeof(UWorld);
            bool isSameClass = worldClass == anotherWorldClass;
            bool isWorldClassDerivedFromObjectClass = worldClass.IsChildOf(UObject.StaticClass());
            world.Dispose();
            */
        }

        public override void Tick(float deltaTime)
        {
            Console.WriteLine("Tick()");
        }

        public override void Destroy()
        {
            Console.WriteLine("Destroy()");
        }
    }
}

Comment out some test code that no longer works due to API changes in UE

AActor::K2_GetWorld() was removed in UE 4.7, and there doesn't seem to
be any direct Blueprint equivalent for AActor::GetWorld().


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

namespace FluentSample.Test.Unit
{
    using System;
    using System.Threading.Tasks;
    using FluentAssertions;
    using FluentSample;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class BeCompletedTest
    {
        [TestMethod]
        public void CompletedTaskShouldPassBeCompleted()
        {
            Task task = Task.FromResult(false);

            Action act = () => task.Should().BeCompleted();

            act.ShouldNotThrow();
        }

        [TestMethod]
        public void PendingTaskShouldFailBeCompleted()
        {
            Task task = new TaskCompletionSource<bool>().Task;

            Action act = () => task.Should().BeCompleted();

            act.ShouldThrow<AssertFailedException>().WithMessage("Expected task to be completed but was WaitingForActivation.");
        }

        [TestMethod]
        public void NullTaskShouldFailBeCompleted()
        {
            Task task = null;

            Action act = () => task.Should().BeCompleted();

            act.ShouldThrow<AssertFailedException>().WithMessage("Expected task to be completed but was <null>.");
        }

        [TestMethod]
        public void FaultedTaskShouldPassBeCompleted()
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
            tcs.SetException(new InvalidCastException("Expected failure."));
            Task task = tcs.Task;

            Action act = () => task.Should().BeCompleted();

            act.ShouldNotThrow();
        }
    }
}

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

namespace FluentSample.Test.Unit
{
    using System;
    using System.Threading.Tasks;
    using FluentAssertions;
    using FluentSample;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class BeCompletedTest
    {
        [TestMethod]
        public void CompletedTaskShouldPass()
        {
            Task task = Task.FromResult(false);

            Action act = () => task.Should().BeCompleted();

            act.ShouldNotThrow();
        }

        [TestMethod]
        public void PendingTaskShouldFail()
        {
            Task task = new TaskCompletionSource<bool>().Task;

            Action act = () => task.Should().BeCompleted();

            act.ShouldThrow<AssertFailedException>().WithMessage("Expected task to be completed but was WaitingForActivation.");
        }

        [TestMethod]
        public void NullTaskShouldFail()
        {
            Task task = null;

            Action act = () => task.Should().BeCompleted();

            act.ShouldThrow<AssertFailedException>().WithMessage("Expected task to be completed but was <null>.");
        }

        [TestMethod]
        public void FaultedTaskShouldPass()
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
            tcs.SetException(new InvalidCastException("Expected failure."));
            Task task = tcs.Task;

            Action act = () => task.Should().BeCompleted();

            act.ShouldNotThrow();
        }
    }
}

Rename tests after file rename

Rename tests after file rename


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

namespace Microsoft.DocAsCode.MarkdigEngine.Extensions
{
    using Markdig;
    using Markdig.Renderers;
    using Markdig.Syntax;
    using Markdig.Syntax.Inlines;

    public class ResolveLinkExtension : IMarkdownExtension
    {
        private readonly MarkdownContext _context;

        public ResolveLinkExtension(MarkdownContext context)
        {
            _context = context;
        }

        public void Setup(MarkdownPipelineBuilder pipeline)
        {
            pipeline.DocumentProcessed += UpdateLinks;
        }

        public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
        {
        }

        private void UpdateLinks(MarkdownObject markdownObject)
        {
            switch (markdownObject)
            {
                case TabTitleBlock _:
                    break;

                case LinkInline linkInline:
                    linkInline.Url = _context.GetLink(linkInline.Url, linkInline);
                    break;

                case ContainerBlock containerBlock:
                    foreach (var subBlock in containerBlock)
                    {
                        UpdateLinks(subBlock);
                    }
                    break;

                case LeafBlock leafBlock when leafBlock.Inline != null:
                    foreach (var subInline in leafBlock.Inline)
                    {
                        UpdateLinks(subInline);
                    }
                    break;

                case ContainerInline containerInline:
                    foreach (var subInline in containerInline)
                    {
                        UpdateLinks(subInline);
                    }
                    break;

                default:
                    break;
            }
        }
    }
}

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

namespace Microsoft.DocAsCode.MarkdigEngine.Extensions
{
    using Markdig;
    using Markdig.Renderers;
    using Markdig.Syntax;
    using Markdig.Syntax.Inlines;

    public class ResolveLinkExtension : IMarkdownExtension
    {
        private readonly MarkdownContext _context;

        public ResolveLinkExtension(MarkdownContext context)
        {
            _context = context;
        }

        public void Setup(MarkdownPipelineBuilder pipeline)
        {
            pipeline.DocumentProcessed += UpdateLinks;
        }

        public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
        {
        }

        private void UpdateLinks(MarkdownObject markdownObject)
        {
            switch (markdownObject)
            {
                case TabTitleBlock _:
                    break;

                case LinkInline linkInline:
                    linkInline.Url = _context.GetLink(linkInline.Url, linkInline);
                    foreach (var subBlock in linkInline)
                    {
                        UpdateLinks(subBlock);
                    }
                    break;

                case ContainerBlock containerBlock:
                    foreach (var subBlock in containerBlock)
                    {
                        UpdateLinks(subBlock);
                    }
                    break;

                case LeafBlock leafBlock when leafBlock.Inline != null:
                    foreach (var subInline in leafBlock.Inline)
                    {
                        UpdateLinks(subInline);
                    }
                    break;

                case ContainerInline containerInline:
                    foreach (var subInline in containerInline)
                    {
                        UpdateLinks(subInline);
                    }
                    break;

                default:
                    break;
            }
        }
    }
}

Fix link resolve not resolving child token


using System;
using Orchard.Environment;
using Orchard.Environment.Extensions;
using Orchard.Environment.Extensions.Models;
using Orchard.Localization;
using Orchard.Packaging.Services;
using Orchard.UI.Notify;

namespace Orchard.Packaging {
    [OrchardFeature("Gallery")]
    public class DefaultPackagingUpdater : IFeatureEventHandler {
        private readonly IPackagingSourceManager _packagingSourceManager;
        private readonly INotifier _notifier;

        public DefaultPackagingUpdater(IPackagingSourceManager packagingSourceManager, INotifier notifier) {
            _packagingSourceManager = packagingSourceManager;
            _notifier = notifier;
        }

        public Localizer T { get; set; }

        public void Install(Feature feature) {
            _packagingSourceManager.AddSource(new PackagingSource { Id = Guid.NewGuid(), FeedTitle = "Orchard Module Gallery", FeedUrl = "http://orchardproject.net/gallery/feed" });
        }

        public void Enable(Feature feature) {
        }

        public void Disable(Feature feature) {
        }

        public void Uninstall(Feature feature) {
        }
    }
}

using System;
using Orchard.Environment;
using Orchard.Environment.Extensions;
using Orchard.Environment.Extensions.Models;
using Orchard.Localization;
using Orchard.Packaging.Services;
using Orchard.UI.Notify;

namespace Orchard.Packaging {
    [OrchardFeature("Gallery")]
    public class DefaultPackagingUpdater : IFeatureEventHandler {
        private readonly IPackagingSourceManager _packagingSourceManager;
        private readonly INotifier _notifier;

        public DefaultPackagingUpdater(IPackagingSourceManager packagingSourceManager, INotifier notifier) {
            _packagingSourceManager = packagingSourceManager;
            _notifier = notifier;
        }

        public Localizer T { get; set; }

        public void Install(Feature feature) {
            _packagingSourceManager.AddSource(new PackagingSource { Id = Guid.NewGuid(), FeedTitle = "Orchard Module Gallery", FeedUrl = "http://orchardproject.net/gallery08/feed" });
        }

        public void Enable(Feature feature) {
        }

        public void Disable(Feature feature) {
        }

        public void Uninstall(Feature feature) {
        }
    }
}

Change the feed url to the new url for 0.8

--HG--
branch : dev