//*********************************************************//
//    Copyright (c) Microsoft. All rights reserved.
//
//    Apache 2.0 License
//
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
//    implied. See the License for the specific language governing
//    permissions and limitations under the License.
//
//*********************************************************//

using System.Threading.Tasks;
using Microsoft.NodejsTools.Npm;
using Microsoft.NodejsTools.Npm.SPI;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace NpmTests {
    [TestClass]
    public class NpmExecuteCommandTests {
        // https://nodejstools.codeplex.com/workitem/1575
        [TestMethod, Priority(0), Timeout(180000)]
        public async Task TestNpmCommandProcessExitSucceeds() {
            var npmPath = NpmHelpers.GetPathToNpm();
            var redirector = new NpmCommand.NpmCommandRedirector(new NpmBinCommand(null, false));

            for (int j = 0; j < 200; j++) {
                await NpmHelpers.ExecuteNpmCommandAsync(
                    redirector,
                    npmPath,
                    null,
                    new[] {"config", "get", "registry"},
                    null);
            }
        }
    }
}

//*********************************************************//
//    Copyright (c) Microsoft. All rights reserved.
//
//    Apache 2.0 License
//
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
//    implied. See the License for the specific language governing
//    permissions and limitations under the License.
//
//*********************************************************//

using System.Threading.Tasks;
using Microsoft.NodejsTools.Npm;
using Microsoft.NodejsTools.Npm.SPI;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace NpmTests {
    [TestClass]
    public class NpmExecuteCommandTests {
        // https://nodejstools.codeplex.com/workitem/1575
        [Ignore]
        [TestMethod, Priority(0), Timeout(180000)]
        public async Task TestNpmCommandProcessExitSucceeds() {
            var npmPath = NpmHelpers.GetPathToNpm();
            var redirector = new NpmCommand.NpmCommandRedirector(new NpmBinCommand(null, false));

            for (int j = 0; j < 200; j++) {
                await NpmHelpers.ExecuteNpmCommandAsync(
                    redirector,
                    npmPath,
                    null,
                    new[] {"config", "get", "registry"},
                    null);
            }
        }
    }
}

Disable locally failiny npm command test


using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
// ReSharper disable UnusedType.Global

namespace Content.Server.Database;

public sealed class DesignTimeContextFactoryPostgres : IDesignTimeDbContextFactory<PostgresServerDbContext>
{
    public PostgresServerDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<PostgresServerDbContext>();
        optionsBuilder.UseNpgsql(args[0]);
        return new PostgresServerDbContext(optionsBuilder.Options);
    }
}

public sealed class DesignTimeContextFactorySqlite : IDesignTimeDbContextFactory<SqliteServerDbContext>
{
    public SqliteServerDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<SqliteServerDbContext>();
        optionsBuilder.UseSqlite(args[0]);
        return new SqliteServerDbContext(optionsBuilder.Options);
    }
}

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
// ReSharper disable UnusedType.Global

namespace Content.Server.Database;

public sealed class DesignTimeContextFactoryPostgres : IDesignTimeDbContextFactory<PostgresServerDbContext>
{
    public PostgresServerDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<PostgresServerDbContext>();
        optionsBuilder.UseNpgsql("Server=localhost");
        return new PostgresServerDbContext(optionsBuilder.Options);
    }
}

public sealed class DesignTimeContextFactorySqlite : IDesignTimeDbContextFactory<SqliteServerDbContext>
{
    public SqliteServerDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<SqliteServerDbContext>();
        optionsBuilder.UseSqlite("Data Source=:memory:");
        return new SqliteServerDbContext(optionsBuilder.Options);
    }
}

Fix arg parsing for design time db contexts.

Don't need to pull this from command line, you can specify --context.


using System;
using System.Data.Entity;
using System.Linq;
using System.Web;
using MusicPickerService.Models;
using StackExchange.Redis;

namespace MusicPickerService.Hubs
{
    public class MusicHub
    {
        private static ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
        private ApplicationDbContext dbContext = new ApplicationDbContext();

        private IDatabase Store
        {
            get
            {
                return redis.GetDatabase();
            }
        }

        public void Queue(int deviceId, int[] trackIds)
        {
            string queue = String.Format("musichub.device.{0}.queue", deviceId);
            string deviceQueue = String.Format("musichub.device.{0}.queue.device", deviceId);
            Store.KeyDelete(queue);
            Store.KeyDelete(deviceQueue);

            foreach (int trackId in trackIds)
            {
                Store.ListRightPush(queue, trackId);
                string trackDeviceId = (from dt in this.dbContext.DeviceTracks
                    where dt.DeviceId == deviceId && dt.TrackId == trackId
                    select dt.DeviceTrackId).First();
                Store.ListRightPush(deviceQueue, trackDeviceId);
            }
        }

        public void Play(int deviceId)
        {

        }

        public void Pause(int deviceId)
        {

        }

        public void Stop(int deviceId)
        {

        }
    }
}

using System;
using System.Data.Entity;
using System.Linq;
using System.Web;
using MusicPickerService.Models;
using StackExchange.Redis;
using Microsoft.AspNet.SignalR;

namespace MusicPickerService.Hubs
{
    public class MusicHub: Hub
    {
        private static ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
        private ApplicationDbContext dbContext = new ApplicationDbContext();

        private IDatabase Store
        {
            get
            {
                return redis.GetDatabase();
            }
        }

        public void Queue(int deviceId, int[] trackIds)
        {
            string queue = String.Format("musichub.device.{0}.queue", deviceId);
            string deviceQueue = String.Format("musichub.device.{0}.queue.device", deviceId);
            Store.KeyDelete(queue);
            Store.KeyDelete(deviceQueue);

            foreach (int trackId in trackIds)
            {
                Store.ListRightPush(queue, trackId);
                string trackDeviceId = (from dt in this.dbContext.DeviceTracks
                    where dt.DeviceId == deviceId && dt.TrackId == trackId
                    select dt.DeviceTrackId).First();
                Store.ListRightPush(deviceQueue, trackDeviceId);
            }
        }

        public void Play(int deviceId)
        {

        }

        public void Pause(int deviceId)
        {

        }

        public void Next(int deviceId)
        {

        }
    }
}

Add inherit from Hub and Next

Add inherit from Hub and Next


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
using System.Web.Compilation;
using System.Web.Http;
using Newtonsoft.Json;
using RestSharp;
using WizardCentralServer.Model.Dtos;
using WizardWebApi.Models.Objects;

namespace WizardWebApi.Controllers
{
    public class TweetsController : ApiController
    {
        //

        // GET: api/Tweets
        public IHttpActionResult Get()
        {
            //
            var tokenRequest = new RestRequest("https://api.twitter.com/oauth2/token")
            {
                Method = Method.POST
            };
            tokenRequest.AddHeader("Authorization",
                ConfigurationManager.AppSettings["TwitterAuthKey"]);
            tokenRequest.AddParameter("grant_type", "client_credentials");

            var tokenResult = new RestClient().Execute(tokenRequest);
            var accessToken = JsonConvert.DeserializeObject<AccessToken>(tokenResult.Content);

            var request = new RestRequest(@"https://api.twitter.com/1.1/search/tweets.json?q=%23shrek&lang=en&result_type=recent&count=20")
            {
                Method = Method.GET
            };
            request.AddHeader("Authorization", "Bearer " + accessToken.token);

            var result = new RestClient().Execute(request);

            var tweets = JsonConvert.DeserializeObject<TwitterStatusResults>(result.Content);
            return Ok(tweets.Statuses);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
using System.Web.Compilation;
using System.Web.Http;
using Newtonsoft.Json;
using RestSharp;
using WizardCentralServer.Model.Dtos;
using WizardWebApi.Models.Objects;

namespace WizardWebApi.Controllers
{
    public class TweetsController : ApiController
    {
        //

        // GET: api/Tweets
        public IHttpActionResult Get()
        {
            //
            var tokenRequest = new RestRequest("https://api.twitter.com/oauth2/token")
            {
                Method = Method.POST
            };
            tokenRequest.AddHeader("Authorization",
                ConfigurationManager.AppSettings["TwitterAuthKey"]);
            tokenRequest.AddParameter("grant_type", "client_credentials");

            var tokenResult = new RestClient().Execute(tokenRequest);
            var accessToken = JsonConvert.DeserializeObject<AccessToken>(tokenResult.Content);

            var request = new RestRequest(@"https://api.twitter.com/1.1/search/tweets.json?q=%23shrek%20OR%20%23dumbledore%20OR%20%23gandalf%20OR%20%23snape&lang=en&result_type=recent&count=20")
            {
                Method = Method.GET
            };
            request.AddHeader("Authorization", "Bearer " + accessToken.token);

            var result = new RestClient().Execute(request);

            var tweets = JsonConvert.DeserializeObject<TwitterStatusResults>(result.Content);
            return Ok(tweets.Statuses);
        }
    }
}

Change tweet query to include fictional wizards


using System;
using NUnit.Framework;

namespace Atata.Tests
{
    [TestFixture]
    public class AtataContextBuilderTests
    {
        [Test]
        public void AtataContextBuilder_Build_WithoutDriver()
        {
            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>
               AtataContext.Configure().Build());

            Assert.That(exception.Message, Does.Contain("no driver is specified"));
        }
    }
}

using System;
using NUnit.Framework;

namespace Atata.Tests
{
    public class AtataContextBuilderTests : UITestFixtureBase
    {
        [Test]
        public void AtataContextBuilder_Build_WithoutDriver()
        {
            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>
               AtataContext.Configure().Build());

            Assert.That(exception.Message, Does.Contain("no driver is specified"));
        }

        [Test]
        public void AtataContextBuilder_OnDriverCreated()
        {
            int executionsCount = 0;

            AtataContext.Configure().
                UseChrome().
                OnDriverCreated(driver =>
                {
                    executionsCount++;
                }).
                Build();

            Assert.That(executionsCount, Is.EqualTo(1));
        }

        [Test]
        public void AtataContextBuilder_OnDriverCreated_RestartDriver()
        {
            int executionsCount = 0;

            AtataContext.Configure().
                UseChrome().
                OnDriverCreated(() =>
                {
                    executionsCount++;
                }).
                Build();

            AtataContext.Current.RestartDriver();

            Assert.That(executionsCount, Is.EqualTo(2));
        }
    }
}

Add AtataContextBuilder_OnDriverCreated and AtataContextBuilder_OnDriverCreated_RestartDriver tests


using System.Collections.Generic;

namespace Treenumerable
{
    internal static class EnumerableExtensions
    {
        internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
            this IEnumerable<T> source,
            VirtualTree<T> virtualTree)
        {
            foreach (T node in source)
            {
                yield return virtualTree.ShallowCopy(node);
            }
        }

        internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
            this IEnumerable<T> source,
            ITreeWalker<T> walker)
        {

            foreach (T root in source)
            {
                yield return new VirtualTree<T>(walker, root);
            }
        }

        internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
            this IEnumerable<T> source,
            ITreeWalker<T> walker,
            IEqualityComparer<T> comparer)
        {
            foreach (T root in source)
            {
                yield return new VirtualTree<T>(walker, root, comparer);
            }
        }
    }
}

using System.Collections.Generic;

namespace Treenumerable
{
    internal static partial class EnumerableExtensions
    {
        internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
            this IEnumerable<T> source,
            VirtualTree<T> virtualTree)
        {
            foreach (T node in source)
            {
                yield return virtualTree.ShallowCopy(node);
            }
        }

        internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
            this IEnumerable<T> source,
            ITreeWalker<T> walker)
        {

            foreach (T root in source)
            {
                yield return new VirtualTree<T>(walker, root);
            }
        }

        internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
            this IEnumerable<T> source,
            ITreeWalker<T> walker,
            IEqualityComparer<T> comparer)
        {
            foreach (T root in source)
            {
                yield return new VirtualTree<T>(walker, root, comparer);
            }
        }
    }
}

Change EnumerableExtensions to partial class


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

using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;

namespace ActivatorWebSite
{
    public class RegularController : Controller
    {
        public void Index()
        {
            // This verifies that ModelState and Context are activated.
            if (ModelState.IsValid)
            {
                Context.Response.WriteAsync("Hello world").Wait();
            }
        }
    }
}

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

using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;

namespace ActivatorWebSite
{
    public class RegularController : Controller
    {
        public async Task<EmptyResult> Index()
        {
            // This verifies that ModelState and Context are activated.
            if (ModelState.IsValid)
            {
                await Context.Response.WriteAsync("Hello world");
            }

            return new EmptyResult();
        }
    }
}

Fix an inadvertent 204 in activator tests

On a web server, this test ends up giving back a 204 because of the MVC
behavior when an action is declared to return void. The fix is to use
EmptyResult.


using System.Web.Mvc;
using StackExchange.DataExplorer.Helpers;

namespace StackExchange.DataExplorer.Controllers
{
    public class TutorialController : StackOverflowController
    {
        [StackRoute("tutorial")]
        public ActionResult Index()
        {
            SetHeader("Tutorial");
            return View();
        }

        [StackRoute("tutorial/intro-to-databases")]
        public ActionResult DatabasePrimer()
        {
            SetHeader("Tutorial");
            return View();
        }

        [StackRoute("tutorial/intro-to-queries")]
        public ActionResult Queries()
        {
            SetHeader("Tutorial");
            return View();
        }

        [StackRoute("tutorial/query-basics")]
        public ActionResult QueryBasics()
        {
            SetHeader("Tutorial");
            return View();
        }

        [StackRoute("tutorial/query-joins")]
        public ActionResult QueryJoins()
        {
            SetHeader("Tutorial");
            return View();
        }

        [StackRoute("tutorial/query-parameters")]
        public ActionResult QueryParameters()
        {
            SetHeader("Tutorial");
            return View();
        }

        [StackRoute("tutorial/query-computations")]
        public ActionResult QueryComputations()
        {
            SetHeader("Tutorial");
            return View();
        }

        [StackRoute("tutorial/next-steps")]
        public ActionResult NextSteps()
        {
            SetHeader("Tutorial");
            return View();
        }
    }
}

using System.Web.Mvc;
using StackExchange.DataExplorer.Helpers;

namespace StackExchange.DataExplorer.Controllers
{
    public class TutorialController : StackOverflowController
    {
        [StackRoute("tutorial")]
        public ActionResult Index()
        {
            SetHeader("Tutorial");
            ViewData["PageTitle"] = "Tutorial - Stack Exchange Data Explorer";
            return View();
        }

        [StackRoute("tutorial/intro-to-databases")]
        public ActionResult DatabasePrimer()
        {
            SetHeader("Tutorial");
            ViewData["PageTitle"] = "Introduction to Databases - Stack Exchange Data Explorer";
            return View();
        }

        [StackRoute("tutorial/intro-to-queries")]
        public ActionResult Queries()
        {
            SetHeader("Tutorial");
            ViewData["PageTitle"] = "Introduction to Queries - Stack Exchange Data Explorer";
            return View();
        }

        [StackRoute("tutorial/query-basics")]
        public ActionResult QueryBasics()
        {
            SetHeader("Tutorial");
            ViewData["PageTitle"] = "Query Basics - Stack Exchange Data Explorer";
            return View();
        }

        [StackRoute("tutorial/query-joins")]
        public ActionResult QueryJoins()
        {
            SetHeader("Tutorial");
            ViewData["PageTitle"] = "Query Joins - Stack Exchange Data Explorer";
            return View();
        }

        [StackRoute("tutorial/query-parameters")]
        public ActionResult QueryParameters()
        {
            SetHeader("Tutorial");
            ViewData["PageTitle"] = "Query Parameters - Stack Exchange Data Explorer";
            return View();
        }

        [StackRoute("tutorial/query-computations")]
        public ActionResult QueryComputations()
        {
            SetHeader("Tutorial");
            ViewData["PageTitle"] = "Query Computations - Stack Exchange Data Explorer";
            return View();
        }

        [StackRoute("tutorial/next-steps")]
        public ActionResult NextSteps()
        {
            SetHeader("Tutorial");
            ViewData["PageTitle"] = "Next Steps - Stack Exchange Data Explorer";
            return View();
        }
    }
}

Add titles to tutorial pages

Add titles to tutorial pages


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

namespace KafkaNet
{
    public interface IKafkaTcpSocket : IDisposable
    {
        Uri ClientUri { get; }
        Task<byte[]> ReadAsync(int readSize);
        Task<byte[]> ReadAsync(int readSize, CancellationToken cancellationToken);

        Task WriteAsync(byte[] buffer, int offset, int count);
        Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);
    }
}

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

namespace KafkaNet
{
    public interface IKafkaTcpSocket : IDisposable
    {
        /// <summary>
        /// The Uri to the connected server.
        /// </summary>
        Uri ClientUri { get; }

        /// <summary>
        /// Read a certain byte array size return only when all bytes received.
        /// </summary>
        /// <param name="readSize">The size in bytes to receive from server.</param>
        /// <returns>Returns a byte[] array with the size of readSize.</returns>
        Task<byte[]> ReadAsync(int readSize);

        /// <summary>
        /// Read a certain byte array size return only when all bytes received.
        /// </summary>
        /// <param name="readSize">The size in bytes to receive from server.</param>
        /// <param name="cancellationToken">A cancellation token which will cancel the request.</param>
        /// <returns>Returns a byte[] array with the size of readSize.</returns>
        Task<byte[]> ReadAsync(int readSize, CancellationToken cancellationToken);

        /// <summary>
        /// Convenience function to write full buffer data to the server.
        /// </summary>
        /// <param name="buffer">The buffer data to send.</param>
        /// <returns>Returns Task handle to the write operation.</returns>
        Task WriteAsync(byte[] buffer);

        /// <summary>
        /// Write the buffer data to the server.
        /// </summary>
        /// <param name="buffer">The buffer data to send.</param>
        /// <param name="offset">The offset to start the read from the buffer.</param>
        /// <param name="count">The length of data to read off the buffer.</param>
        /// <returns>Returns Task handle to the write operation.</returns>
        Task WriteAsync(byte[] buffer, int offset, int count);

        /// <summary>
        /// Write the buffer data to the server.
        /// </summary>
        /// <param name="buffer">The buffer data to send.</param>
        /// <param name="offset">The offset to start the read from the buffer.</param>
        /// <param name="count">The length of data to read off the buffer.</param>
        /// <param name="cancellationToken">A cancellation token which will cancel the request.</param>
        /// <returns>Returns Task handle to the write operation.</returns>
        Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);
    }
}

Add documentation and convenience func to interface


using BenchmarkDotNet.Running;

namespace Benchmark.NetCore
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //BenchmarkRunner.Run<MetricCreationBenchmarks>();
            //BenchmarkRunner.Run<SerializationBenchmarks>();
            //BenchmarkRunner.Run<LabelBenchmarks>();
            //BenchmarkRunner.Run<HttpExporterBenchmarks>();
            //BenchmarkRunner.Run<SummaryBenchmarks>();
            BenchmarkRunner.Run<MetricPusherBenchmarks>();
        }
    }
}

using BenchmarkDotNet.Running;

namespace Benchmark.NetCore
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // Give user possibility to choose which benchmark to run.
            // Can be overridden from the command line with the --filter option.
            new BenchmarkSwitcher(typeof(Program).Assembly).Run(args);
        }
    }
}

Add commandline switch to benchmark to avoid need for rebuilds


namespace Rackspace.VisualStudio.CloudExplorer.Files
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.VSDesigner.ServerExplorer;
    using net.openstack.Core.Domain;
    using net.openstack.Providers.Rackspace;

    public class CloudFilesEndpointNode : EndpointNode
    {
        public CloudFilesEndpointNode(CloudIdentity identity, ServiceCatalog serviceCatalog, Endpoint endpoint)
            : base(identity, serviceCatalog, endpoint)
        {
        }

        protected override async Task<Node[]> CreateChildrenAsync(CancellationToken cancellationToken)
        {
            Tuple<CloudFilesProvider, Container[]> containers = await ListContainersAsync(cancellationToken);
            return Array.ConvertAll(containers.Item2, i => CreateContainerNode(containers.Item1, i, null));
        }

        private CloudFilesContainerNode CreateContainerNode(CloudFilesProvider provider, Container container, ContainerCDN containerCdn)
        {
            return new CloudFilesContainerNode(provider, container, containerCdn);
        }

        private async Task<Tuple<CloudFilesProvider, Container[]>> ListContainersAsync(CancellationToken cancellationToken)
        {
            CloudFilesProvider provider = CreateProvider();
            List<Container> containers = new List<Container>();
            containers.AddRange(await Task.Run(() => provider.ListContainers()));
            return Tuple.Create(provider, containers.ToArray());
        }

        private CloudFilesProvider CreateProvider()
        {
            return new CloudFilesProvider(Identity, Endpoint.Region, null, null);
        }
    }
}

namespace Rackspace.VisualStudio.CloudExplorer.Files
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.VSDesigner.ServerExplorer;
    using net.openstack.Core.Domain;
    using net.openstack.Providers.Rackspace;

    public class CloudFilesEndpointNode : EndpointNode
    {
        public CloudFilesEndpointNode(CloudIdentity identity, ServiceCatalog serviceCatalog, Endpoint endpoint)
            : base(identity, serviceCatalog, endpoint)
        {
        }

        protected override async Task<Node[]> CreateChildrenAsync(CancellationToken cancellationToken)
        {
            Tuple<CloudFilesProvider, Container[]> containers = await ListContainersAsync(cancellationToken);
            return Array.ConvertAll(containers.Item2, i => CreateContainerNode(containers.Item1, i, null));
        }

        private CloudFilesContainerNode CreateContainerNode(CloudFilesProvider provider, Container container, ContainerCDN containerCdn)
        {
            return new CloudFilesContainerNode(provider, container, containerCdn);
        }

        private async Task<Tuple<CloudFilesProvider, Container[]>> ListContainersAsync(CancellationToken cancellationToken)
        {
            CloudFilesProvider provider = CreateProvider();
            List<Container> containers = new List<Container>();
            containers.AddRange(await Task.Run(() => provider.ListContainers()));
            return Tuple.Create(provider, containers.ToArray());
        }

        private CloudFilesProvider CreateProvider()
        {
            CloudFilesProvider provider = new CloudFilesProvider(Identity, Endpoint.Region, null, null);
            provider.ConnectionLimit = 50;
            return provider;
        }
    }
}

Increase the default Cloud Files connection limit


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

namespace Geode.Geometry
{
    public class Polygon<T> : IGeoType
    {
        public string Type => "Polygon";
        public IEnumerable<IEnumerable<T>> Coordinates { get; set; }
        public Polygon(IEnumerable<IEnumerable<T>> coordinates)
        {
            Coordinates = coordinates;
        }
    }
}

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

namespace Geode.Geometry
{
    public class Polygon: IGeoType
    {
        public string Type => "Polygon";
        public IEnumerable<IEnumerable<double>> Coordinates { get; set; }
        public Polygon(IEnumerable<IEnumerable<double>> coordinates)
        {
            Coordinates = coordinates;
        }
    }

    public class Polygon<T> : IGeoType
    {
        public string Type => "Polygon";
        public IEnumerable<IEnumerable<T>> Coordinates { get; set; }
        public Polygon(IEnumerable<IEnumerable<T>> coordinates)
        {
            Coordinates = coordinates;
        }
    }
}

Add non-generic polygon type that uses double type by default.


using System;
using System.Security.Cryptography.Pkcs;

namespace AuthenticodeLint.Rules
{
    public class PublisherInformationPresentRule : IAuthenticodeRule
    {
        public int RuleId { get; } = 10004;

        public string RuleName { get; } = "Publisher Information Rule";

        public string ShortDescription { get; } = "Checks that the signature provided publisher information.";

        public RuleResult Validate(Graph<SignerInfo> graph, SignatureLoggerBase verboseWriter)
        {
            var signatures = graph.VisitAll();
            var result = RuleResult.Pass;
            foreach(var signature in signatures)
            {
                PublisherInformation info = null;
                foreach(var attribute in signature.SignedAttributes)
                {
                    if (attribute.Oid.Value == KnownOids.OpusInfo)
                    {
                        info = new PublisherInformation(attribute.Values[0]);
                        break;
                    }
                }
                if (info == null)
                {
                    result = RuleResult.Fail;
                    verboseWriter.LogMessage(signature, "Signature does not have any publisher information.");
                }
                if (string.IsNullOrWhiteSpace(info.Description))
                {
                    result = RuleResult.Fail;
                    verboseWriter.LogMessage(signature, "Signature does not have an accompanying description.");
                }

                if (string.IsNullOrWhiteSpace(info.UrlLink))
                {
                    result = RuleResult.Fail;
                    verboseWriter.LogMessage(signature, "Signature does not have an accompanying URL.");
                }
            }
            return result;
        }
    }
}

using System;
using System.Security.Cryptography.Pkcs;

namespace AuthenticodeLint.Rules
{
    public class PublisherInformationPresentRule : IAuthenticodeRule
    {
        public int RuleId { get; } = 10004;

        public string RuleName { get; } = "Publisher Information Rule";

        public string ShortDescription { get; } = "Checks that the signature provided publisher information.";

        public RuleResult Validate(Graph<SignerInfo> graph, SignatureLoggerBase verboseWriter)
        {
            var signatures = graph.VisitAll();
            var result = RuleResult.Pass;
            foreach(var signature in signatures)
            {
                PublisherInformation info = null;
                foreach(var attribute in signature.SignedAttributes)
                {
                    if (attribute.Oid.Value == KnownOids.OpusInfo)
                    {
                        info = new PublisherInformation(attribute.Values[0]);
                        break;
                    }
                }
                if (info == null)
                {
                    result = RuleResult.Fail;
                    verboseWriter.LogMessage(signature, "Signature does not have any publisher information.");
                }
                if (string.IsNullOrWhiteSpace(info.Description))
                {
                    result = RuleResult.Fail;
                    verboseWriter.LogMessage(signature, "Signature does not have an accompanying description.");
                }

                if (string.IsNullOrWhiteSpace(info.UrlLink))
                {
                    result = RuleResult.Fail;
                    verboseWriter.LogMessage(signature, "Signature does not have an accompanying URL.");
                }
                Uri uri;
                if (!Uri.TryCreate(info.UrlLink, UriKind.Absolute, out uri))
                {
                    result = RuleResult.Fail;
                    verboseWriter.LogMessage(signature, "Signature's accompanying URL is not a valid URI.");
                }
            }
            return result;
        }
    }
}

Check for valid URI in publisher information.

In addition to being present, the URL must be a valid URI.


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

namespace ServiceProvider
{
    public static class SettingsManager
    {
        internal static void CheckForXmlFileDirectory(Func<string> getXmlFilePath, Action<string, string> messageForUser)
        {
            if (string.IsNullOrEmpty(DataStorage.Default.xmlFileDirectory))
            {
                messageForUser.Invoke("Please press OK and choose a folder to store your expenditure in", "Setup");
                DataStorage.Default.xmlFileDirectory = getXmlFilePath.Invoke();
                DataStorage.Default.Save();
            }
        }
    }
}

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

namespace ServiceProvider
{
    public static class SettingsManager
    {
        internal static void CheckForXmlFileDirectory(Func<string> getXmlFilePath, Action<string, string> messageForUser)
        {
            if (string.IsNullOrEmpty(DataStorage.Default.xmlFileDirectory))
            {
                DataStorage.Default.xmlFileDirectory = getXmlFilePath.Invoke();
                DataStorage.Default.Save();
            }
        }
    }
}

Remove code involving MessageBox that did not belong in this class


using System;

namespace NQuery.Language
{
    public sealed class SyntaxTree
    {
        private readonly CompilationUnitSyntax _root;
        private readonly TextBuffer _textBuffer;

        private SyntaxTree(CompilationUnitSyntax root, TextBuffer textBuffer)
        {
            _root = root;
            _textBuffer = textBuffer;
        }

        public static SyntaxTree ParseQuery(string source)
        {
            var parser = new Parser(source);
            var query = parser.ParseRootQuery();
            var textBuffer = new TextBuffer(source);
            return new SyntaxTree(query, textBuffer);
        }

        public static SyntaxTree ParseExpression(string source)
        {
            var parser = new Parser(source);
            var expression = parser.ParseRootQuery();
            var textBuffer = new TextBuffer(source);
            return new SyntaxTree(expression, textBuffer);
        }

        public CompilationUnitSyntax Root
        {
            get { return _root; }
        }

        public TextBuffer TextBuffer
        {
            get { return _textBuffer; }
        }
    }
}

using System;

namespace NQuery.Language
{
    public sealed class SyntaxTree
    {
        private readonly CompilationUnitSyntax _root;
        private readonly TextBuffer _textBuffer;

        private SyntaxTree(CompilationUnitSyntax root, TextBuffer textBuffer)
        {
            _root = root;
            _textBuffer = textBuffer;
        }

        public static SyntaxTree ParseQuery(string source)
        {
            var parser = new Parser(source);
            var query = parser.ParseRootQuery();
            var textBuffer = new TextBuffer(source);
            return new SyntaxTree(query, textBuffer);
        }

        public static SyntaxTree ParseExpression(string source)
        {
            var parser = new Parser(source);
            var expression = parser.ParseRootExpression();
            var textBuffer = new TextBuffer(source);
            return new SyntaxTree(expression, textBuffer);
        }

        public CompilationUnitSyntax Root
        {
            get { return _root; }
        }

        public TextBuffer TextBuffer
        {
            get { return _textBuffer; }
        }
    }
}

Fix bug where ParseExpression doesn't parse an expression but a query


using System.Collections.Generic;
using UniProgramGen;

namespace UniProgramGen.Data
{
    public class Requirements
    {
        public readonly double weight;
        public readonly List<Helpers.TimeSlot> availableTimeSlots;
        public readonly List<Room> requiredRooms;

        public Requirements(double weight, List<Helpers.TimeSlot> availableTimeSlots, List<Room> requiredRooms)
        {
            this.weight = weight;
            this.availableTimeSlots = availableTimeSlots;
            this.requiredRooms = requiredRooms;
        }
    }
}

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

namespace UniProgramGen.Data
{
    public class Requirements
    {
        public const uint TOTAL_HOURS = 15;
        public const uint TOTAL_WEEK_HOURS = 5 * TOTAL_HOURS;

        public readonly double weight;
        public readonly List<Helpers.TimeSlot> availableTimeSlots;
        public readonly List<Room> requiredRooms;

        private double internalWeight;

        public Requirements(double weight, List<Helpers.TimeSlot> availableTimeSlots, List<Room> requiredRooms)
        {
            this.weight = weight;
            this.availableTimeSlots = availableTimeSlots;
            this.requiredRooms = requiredRooms;
        }

        internal void CalculateInternalWeight(int roomsLength)
        {
            var availableTime = availableTimeSlots.Aggregate((uint) 0, (total, timeSlot) => total + timeSlot.EndHour - timeSlot.StartHour);
            internalWeight = ((availableTime / TOTAL_WEEK_HOURS) + (requiredRooms.Count / roomsLength)) / 2;
        }
    }
}

Add internal weight calculation for requirements


using System.IO;
using Stranne.VasttrafikNET.Tests.Json;

namespace Stranne.VasttrafikNET.Tests.Helpers
{
    public static class JsonHelper
    {
        public static string GetJson(JsonFile jsonFile)
        {
            var fileName = $"{jsonFile}.json";
            var json = File.ReadAllText($@"Json\{fileName}");
            return json;
        }
    }
}

using System.IO;
using Stranne.VasttrafikNET.Tests.Json;

namespace Stranne.VasttrafikNET.Tests.Helpers
{
    public static class JsonHelper
    {
        public static string GetJson(JsonFile jsonFile)
        {
            var fileName = $"{jsonFile}.json";
            var json = File.ReadAllText($@"Json/{fileName}");
            return json;
        }
    }
}

Fix test json file path on unix systems

Fix test json file path on unix systems


using AutoMapper;

namespace Caelan.Frameworks.Common.Classes
{
	public static class GenericBuilder
	{
		public static BaseBuilder<TSource, TDestination> Create<TSource, TDestination>()
			where TDestination : class, new()
			where TSource : class, new()
		{
			var builder = new BaseBuilder<TSource, TDestination>();

			if (Mapper.FindTypeMapFor<TSource, TDestination>() == null) Mapper.AddProfile(builder);

			return builder;
		}
	}
}

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

namespace Caelan.Frameworks.Common.Classes
{
	public static class GenericBuilder
	{
		public static BaseBuilder<TSource, TDestination> Create<TSource, TDestination>()
			where TDestination : class, new()
			where TSource : class, new()
		{
			var builder = new BaseBuilder<TSource, TDestination>();

			var customBuilder = Assembly.GetExecutingAssembly().GetReferencedAssemblies().OrderBy(t => t.Name).Select(Assembly.Load).SelectMany(assembly => assembly.GetTypes().Where(t => t.BaseType == builder.GetType())).SingleOrDefault();

			if (customBuilder != null) builder = Activator.CreateInstance(customBuilder) as BaseBuilder<TSource, TDestination>;

			if (Mapper.FindTypeMapFor<TSource, TDestination>() == null) Mapper.AddProfile(builder);

			return builder;
		}
	}
}

Fix for searching for basebuilder already defined on all assemblies


/*
* Programmed by Umut Celenli umut@celenli.com
*/

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

namespace MimeBank
{
    /// <summary>
    /// This is the main class to check the file mime type
    /// Header list is loaded once
    /// </summary>
    public class MimeChecker
    {
        private const int maxBufferSize = 256;

        private static List<FileHeader> list { get; set; }
        private List<FileHeader> List
        {
            get
            {
                if (list == null)
                {
                    list = HeaderData.GetList();
                }
                return list;
            }
        }
        private byte[] Buffer;

        public MimeChecker()
        {
            Buffer = new byte[maxBufferSize];
        }

        public FileHeader GetFileHeader(string file)
        {
            using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                fs.Read(Buffer, 0, maxBufferSize);
            }
            return this.List.FirstOrDefault(mime => mime.Check(Buffer));
        }
    }
}

/*
* Programmed by Umut Celenli umut@celenli.com
*/

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

namespace MimeBank
{
    /// <summary>
    /// This is the main class to check the file mime type
    /// Header list is loaded once
    /// </summary>
    public class MimeChecker
    {
        private const int maxBufferSize = 256;

        private static List<FileHeader> list { get; set; }
        private List<FileHeader> List
        {
            get
            {
                if (list == null)
                {
                    list = HeaderData.GetList();
                }
                return list;
            }
        }
        private byte[] Buffer;

        public MimeChecker()
        {
            Buffer = new byte[maxBufferSize];
        }

        public FileHeader GetFileHeader(Stream stream)
        {
            stream.Read(Buffer, 0, maxBufferSize);
            return this.List.FirstOrDefault(mime => mime.Check(Buffer));
        }

        public FileHeader GetFileHeader(string file)
        {
            using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                return GetFileHeader(stream);
            }
        }
    }
}

Add stream variant of GetFileHeader()

Add stream variant of GetFileHeader()


using Ensconce.Database;
using Ensconce.Helpers;
using System.Data.SqlClient;

namespace Ensconce.Cli
{
    internal static class DatabaseInteraction
    {
        internal static void DoDeployment()
        {
            SqlConnectionStringBuilder connStr = null;

            if (!string.IsNullOrEmpty(Arguments.ConnectionString))
            {
                connStr = new SqlConnectionStringBuilder(Arguments.ConnectionString.Render());
            }
            else if (!string.IsNullOrEmpty(Arguments.DatabaseName))
            {
                connStr = Database.Database.GetLocalConnectionStringFromDatabaseName(Arguments.DatabaseName.Render());
            }

            Logging.Log("Deploying scripts from {0} using connection string {1}", Arguments.DeployFrom, connStr.ConnectionString);

            var database = new Database.Database(connStr, Arguments.WarnOnOneTimeScriptChanges)
            {
                WithTransaction = Arguments.WithTransaction,
                OutputPath = Arguments.RoundhouseOutputPath
            };

            database.Deploy(Arguments.DeployFrom, Arguments.DatabaseRepository.Render(), Arguments.DropDatabase, Arguments.DatabaseCommandTimeout);
        }
    }
}

using Ensconce.Database;
using Ensconce.Helpers;
using System.Data.SqlClient;

namespace Ensconce.Cli
{
    internal static class DatabaseInteraction
    {
        internal static void DoDeployment()
        {
            SqlConnectionStringBuilder connStr = null;

            if (!string.IsNullOrEmpty(Arguments.ConnectionString))
            {
                connStr = new SqlConnectionStringBuilder(Arguments.ConnectionString.Render());
            }
            else if (!string.IsNullOrEmpty(Arguments.DatabaseName))
            {
                connStr = Database.Database.GetLocalConnectionStringFromDatabaseName(Arguments.DatabaseName.Render());
            }

            Logging.Log("Deploying scripts from {0} using connection string {1}", Arguments.DeployFrom, RedactPassword(connStr));

            var database = new Database.Database(connStr, Arguments.WarnOnOneTimeScriptChanges)
            {
                WithTransaction = Arguments.WithTransaction,
                OutputPath = Arguments.RoundhouseOutputPath
            };

            database.Deploy(Arguments.DeployFrom, Arguments.DatabaseRepository.Render(), Arguments.DropDatabase, Arguments.DatabaseCommandTimeout);
        }

        private static SqlConnectionStringBuilder RedactPassword(SqlConnectionStringBuilder connStr)
        {
            return string.IsNullOrEmpty(connStr.Password) ?
                   connStr :
                   new SqlConnectionStringBuilder(connStr.ConnectionString)
                   {
                       Password = new string('*', connStr.Password.Length)
                   };
        }
    }
}

Redact DB password in logging

Redact DB password in logging


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace TechProFantasySoccer
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace TechProFantasySoccer
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            /*var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);*/
            //Commenting the above code and using the below line gets rid of the master mobile site.
            routes.EnableFriendlyUrls();
        }
    }
}

Disable the master mobile site.

Disable the master mobile site.


/*
 * Copyright (c) 2013, SteamDB. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 *
 * Future non-SteamKit stuff should go in this file.
 */
using System;
using System.Threading;

namespace PICSUpdater
{
    class Program
    {
        static void Main(string[] args)
        {
            new Thread(new ThreadStart(Steam.Run)).Start();
            //Steam.GetPICSChanges();
        }
    }
}

/*
 * Copyright (c) 2013, SteamDB. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 *
 * Future non-SteamKit stuff should go in this file.
 */
using System;
using System.Configuration;
using System.Threading;

namespace PICSUpdater
{
    class Program
    {
        static void Main(string[] args)
        {
            if (ConfigurationManager.AppSettings["steam-username"] == null || ConfigurationManager.AppSettings["steam-password"] == null)
            {
                Console.WriteLine("Is config missing? It should be in " + ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);
                return;
            }

            //new Thread(new ThreadStart(Steam.Run)).Start();
            Steam.Run();
        }
    }
}

Make sure config exists by checking steam credentials


Welcome! Codingteam is an open community of engineers and programmers.

And here're today's conference logs:

Older logs (mostly actual in period 2008-08-22 — 2016-12-09)

Welcome! Codingteam is an open community of engineers and programmers.

And here're today's conference logs:

Older logs (mostly actual in period 2009-08-22 — 2016-12-09)

Fix date 2008 -> 2009

Fix date 2008 -> 2009

I believe it's 2009


namespace Bakery.Logging
{
	using System;
	using Time;

	public class ConsoleLog
		: ILog
	{
		private readonly IClock clock;

		public ConsoleLog(IClock clock)
		{
			this.clock = clock;
		}

		public void Write(Level logLevel, String message)
		{
			const String FORMAT = "{0}: [{1}] {2}";

			var textWriter = logLevel >= Level.Warning
				? Console.Error
				: Console.Out;

			textWriter.WriteLine(
				String.Format(
					FORMAT,
					clock.GetUniversalTime().ToString(),
					logLevel,
					message));
		}
	}
}

namespace Bakery.Logging
{
	using System;

	public class ConsoleLog
		: ILog
	{
		public void Write(Level logLevel, String message)
		{
			var textWriter = logLevel >= Level.Warning
				? Console.Error
				: Console.Out;

			textWriter.WriteLine(message);
		}
	}
}

Enforce single responsibility principle -- decorators can implement additional functionality.


using System.Reflection;

[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("NuProj")]
[assembly: AssemblyCopyright("Copyright © Immo Landwerth")]
[assembly: AssemblyTrademark("")]

[assembly : AssemblyMetadata("PreRelease", "Beta")]
[assembly : AssemblyMetadata("ProjectUrl", "http://nuproj.net")]
[assembly : AssemblyMetadata("LicenseUrl", "http://nuproj.net/LICENSE")]

// NOTE: When updating the version, you also need to update the Identity/@Version
//       attribtute in src\NuProj.ProjectSystem.12\source.extension.vsixmanifest.

[assembly: AssemblyVersion("0.10.0.0")]
[assembly: AssemblyFileVersion("0.10.0.0")]

using System.Reflection;

[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("NuProj")]
[assembly: AssemblyCopyright("Copyright © Immo Landwerth")]
[assembly: AssemblyTrademark("")]

[assembly : AssemblyMetadata("PreRelease", "Beta")]
[assembly : AssemblyMetadata("ProjectUrl", "http://nuproj.net")]
[assembly : AssemblyMetadata("LicenseUrl", "http://nuproj.net/LICENSE")]

// NOTE: When updating the version, you also need to update the Identity/@Version
//       attribtute in:
//
//          src\NuProj.ProjectSystem.12\source.extension.vsixmanifest
//          src\NuProj.ProjectSystem.14\source.extension.vsixmanifest

[assembly: AssemblyVersion("0.10.0.0")]
[assembly: AssemblyFileVersion("0.10.0.0")]

Add note to change the version number for both VSIX files


namespace Parsley.Tests;

class ParsedTests
{
    public void HasAParsedValue()
    {
        new Parsed<string>("parsed", new(1, 1)).Value.ShouldBe("parsed");
    }

    public void HasNoErrorMessageByDefault()
    {
        new Parsed<string>("x", new(1, 1)).ErrorMessages.ShouldBe(ErrorMessageList.Empty);
    }

    public void CanIndicatePotentialErrors()
    {
        var potentialErrors = ErrorMessageList.Empty
            .With(ErrorMessage.Expected("A"))
            .With(ErrorMessage.Expected("B"));

        new Parsed<object>("x", new(1, 1), potentialErrors).ErrorMessages.ShouldBe(potentialErrors);
    }

    public void HasRemainingUnparsedInput()
    {
        var parsed = new Parsed<string>("parsed", new(12, 34));
        parsed.Position.ShouldBe(new (12, 34));
    }

    public void ReportsNonerrorState()
    {
        new Parsed<string>("parsed", new(1, 1)).Success.ShouldBeTrue();
    }
}

namespace Parsley.Tests;

class ParsedTests
{
    public void CanIndicateSuccessfullyParsedValueAtTheCurrentPosition()
    {
        var parsed = new Parsed<string>("parsed", new(12, 34));
        parsed.Success.ShouldBe(true);
        parsed.Value.ShouldBe("parsed");
        parsed.ErrorMessages.ShouldBe(ErrorMessageList.Empty);
        parsed.Position.ShouldBe(new(12, 34));
    }

    public void CanIndicatePotentialErrorMessagesAtTheCurrentPosition()
    {
        var potentialErrors = ErrorMessageList.Empty
            .With(ErrorMessage.Expected("A"))
            .With(ErrorMessage.Expected("B"));

        var parsed = new Parsed<object>("parsed", new(12, 34), potentialErrors);
        parsed.Success.ShouldBe(true);
        parsed.Value.ShouldBe("parsed");
        parsed.ErrorMessages.ShouldBe(potentialErrors);
        parsed.Position.ShouldBe(new(12, 34));
    }
}

Improve test coverage for Parsed<T> by mirroring the test coverage for Error<T>.


using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;

namespace clipr.Utils
{
    /// <summary>
    /// <para>
    /// A TypeConverter that allows conversion of any object to System.Object.
    /// Does not actually perform a conversion, just passes the value on
    /// through.
    /// </para>
    /// <para>
    /// Must be registered before parsing.
    /// </para>
    /// </summary>
    internal class ObjectTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(String) || base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            return value is string
                ? value
                : base.ConvertFrom(context, culture, value);
        }

        public override bool IsValid(ITypeDescriptorContext context, object value)
        {
            return value is string || base.IsValid(context, value);
        }

        public static void Register()
        {
            var attr = new Attribute[]
                {
                    new TypeConverterAttribute(typeof(ObjectTypeConverter))
                };
            TypeDescriptor.AddAttributes(typeof(object), attr);
        }
    }
}

using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;

namespace clipr.Utils
{
    /// <summary>
    /// <para>
    /// A TypeConverter that allows conversion of any object to System.Object.
    /// Does not actually perform a conversion, just passes the value on
    /// through.
    /// </para>
    /// <para>
    /// Must be registered before parsing.
    /// </para>
    /// </summary>
    internal class ObjectTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(String) || base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            return value is string
                ? value
                : base.ConvertFrom(context, culture, value);
        }

        public override bool IsValid(ITypeDescriptorContext context, object value)
        {
            return value is string || base.IsValid(context, value);
        }

        public static void Register()
        {
            var attr = new Attribute[]
                {
                    new TypeConverterAttribute(typeof(ObjectTypeConverter))
                };
            //TypeDescriptor.AddAttributes(typeof(object), attr);  //TODO this breaks most type conversion since we override object...
        }
    }
}

Fix accidental type conversion breakage.


namespace clipr.Core
{
    /// <summary>
    /// Parsing config for a verb, includes a way to "set" the resulting
    /// verb on the original options object.
    /// </summary>
    public interface IVerbParserConfig: IParserConfig
    {
        /// <summary>
        /// Store the verb on the options objcet.
        /// </summary>
        IValueStoreDefinition Store { get; }
    }

    internal class VerbParserConfig<TVerb> : ParserConfig<TVerb>, IVerbParserConfig where TVerb : class
    {
        public VerbParserConfig(IParserConfig internalParserConfig, IValueStoreDefinition store, ParserOptions options)
            : base(options, null)
        {
            InternalParserConfig = internalParserConfig;
            Store = store;

            LongNameArguments = InternalParserConfig.LongNameArguments;
            ShortNameArguments = InternalParserConfig.ShortNameArguments;
            PositionalArguments = InternalParserConfig.PositionalArguments;
            Verbs = InternalParserConfig.Verbs;
            PostParseMethods = InternalParserConfig.PostParseMethods;
            RequiredMutuallyExclusiveArguments = InternalParserConfig.RequiredMutuallyExclusiveArguments;
            RequiredNamedArguments = InternalParserConfig.RequiredNamedArguments;
        }

        public IValueStoreDefinition Store { get; set; }

        public IParserConfig InternalParserConfig { get; set; }
    }
}

namespace clipr.Core
{
    /// <summary>
    /// Parsing config for a verb, includes a way to "set" the resulting
    /// verb on the original options object.
    /// </summary>
    public interface IVerbParserConfig: IParserConfig
    {
        /// <summary>
        /// Store the verb on the options objcet.
        /// </summary>
        IValueStoreDefinition Store { get; }
    }

    internal class VerbParserConfig<TVerb> : ParserConfig<TVerb>, IVerbParserConfig where TVerb : class
    {
        public VerbParserConfig(IParserConfig internalParserConfig, IValueStoreDefinition store, ParserOptions options)
            : base(options, null)
        {
            InternalParserConfig = internalParserConfig;
            Store = store;

            LongNameArguments = InternalParserConfig.LongNameArguments;
            ShortNameArguments = InternalParserConfig.ShortNameArguments;
            PositionalArguments = InternalParserConfig.PositionalArguments;
            Verbs = InternalParserConfig.Verbs;
            PostParseMethods = InternalParserConfig.PostParseMethods;
            RequiredMutuallyExclusiveArguments = InternalParserConfig.RequiredMutuallyExclusiveArguments;
            RequiredNamedArguments = InternalParserConfig.RequiredNamedArguments;
        }

        public IValueStoreDefinition Store { get; set; }

        private IParserConfig InternalParserConfig { get; set; }
    }
}

Hide InternalParserConfig because it shouldn't be public.


using System;
using System.Collections.Generic;
using System.Globalization;
using Umbraco.Core;
using UmbracoVault.Comparers;
using UmbracoVault.Extensions;

namespace UmbracoVault.Collections
{
    public class TypeAliasSet : ReadOnlySet<string>
    {
        private TypeAliasSet()
            : base(new HashSet<string>(new InvariantCultureCamelCaseStringComparer()))
        {
        }

        public static TypeAliasSet GetAliasesForUmbracoEntityType<T>()
        {
            return GetAliasesForUmbracoEntityType(typeof(T));
        }

        public static TypeAliasSet GetAliasesForUmbracoEntityType(Type type)
        {
            var set = new TypeAliasSet();
            var attributes = type.GetUmbracoEntityAttributes();

            foreach (var attribute in attributes)
            {
                var alias = attribute.Alias;
                if (string.IsNullOrWhiteSpace(alias))
                {
                    // account for doc type models use naming convention of [DocumentTypeAlias]ViewModel
                    alias = type.Name.TrimEnd("ViewModel");
                }

                set.BackingSet.Add(alias.ToCamelCase(CultureInfo.InvariantCulture));
            }

            return set;
        }

    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using Umbraco.Core;
using UmbracoVault.Comparers;
using UmbracoVault.Extensions;

namespace UmbracoVault.Collections
{
    public class TypeAliasSet : ReadOnlySet<string>
    {
        private TypeAliasSet()
            : base(new HashSet<string>(new InvariantCultureCamelCaseStringComparer()))
        {
        }

        public static TypeAliasSet GetAliasesForUmbracoEntityType<T>()
        {
            return GetAliasesForUmbracoEntityType(typeof(T));
        }

        public static TypeAliasSet GetAliasesForUmbracoEntityType(Type type)
        {
            var set = new TypeAliasSet();
            var attributes = type.GetUmbracoEntityAttributes();

            foreach (var attribute in attributes)
            {
                var alias = attribute.Alias;
                if (string.IsNullOrWhiteSpace(alias))
                {
                    // account for doc type models using naming convention of [DocumentTypeAlias]ViewModel
                    alias = type.Name.TrimEnd("ViewModel");
                }

                set.BackingSet.Add(alias.ToCamelCase(CultureInfo.InvariantCulture));
            }

            return set;
        }

    }
}

Correct grammar error in comment.

Correct grammar error in comment.


using System;

namespace Renci.SshNet.Abstractions
{
    internal static class ThreadAbstraction
    {
        /// <summary>
        /// Suspends the current thread for the specified number of milliseconds.
        /// </summary>
        /// <param name="millisecondsTimeout">The number of milliseconds for which the thread is suspended.</param>
        public static void Sleep(int millisecondsTimeout)
        {
#if FEATURE_THREAD_SLEEP
            System.Threading.Thread.Sleep(millisecondsTimeout);
#elif FEATURE_THREAD_TAP
            System.Threading.Tasks.Task.Delay(millisecondsTimeout).Wait();
#else
            #error Suspend of the current thread is not implemented.
#endif
        }

        public static void ExecuteThreadLongRunning(Action action)
        {
#if FEATURE_THREAD_TAP
            var taskCreationOptions = System.Threading.Tasks.TaskCreationOptions.LongRunning;
            System.Threading.Tasks.Task.Factory.StartNew(action, taskCreationOptions);
#else
            var thread = new System.Threading.Thread(() => action());
            thread.Start();
#endif
        }

        /// <summary>
        /// Executes the specified action in a separate thread.
        /// </summary>
        /// <param name="action">The action to execute.</param>
        public static void ExecuteThread(Action action)
        {
            if (action == null)
                throw new ArgumentNullException("action");
#if FEATURE_THREAD_THREADPOOL
            System.Threading.ThreadPool.QueueUserWorkItem(o => action());
#elif FEATURE_THREAD_TAP
            System.Threading.Tasks.Task.Run(action);
#else
            #error Execution of action in a separate thread is not implemented.
#endif
        }
    }
}

using System;

namespace Renci.SshNet.Abstractions
{
    internal static class ThreadAbstraction
    {
        /// <summary>
        /// Suspends the current thread for the specified number of milliseconds.
        /// </summary>
        /// <param name="millisecondsTimeout">The number of milliseconds for which the thread is suspended.</param>
        public static void Sleep(int millisecondsTimeout)
        {
#if FEATURE_THREAD_SLEEP
            System.Threading.Thread.Sleep(millisecondsTimeout);
#elif FEATURE_THREAD_TAP
            System.Threading.Tasks.Task.Delay(millisecondsTimeout).Wait();
#else
            #error Suspend of the current thread is not implemented.
#endif
        }

        public static void ExecuteThreadLongRunning(Action action)
        {
#if FEATURE_THREAD_TAP
            var taskCreationOptions = System.Threading.Tasks.TaskCreationOptions.LongRunning;
            System.Threading.Tasks.Task.Factory.StartNew(action, taskCreationOptions);
#else
            var thread = new System.Threading.Thread(() => action());
            thread.Start();
#endif
        }

        /// <summary>
        /// Executes the specified action in a separate thread.
        /// </summary>
        /// <param name="action">The action to execute.</param>
        public static void ExecuteThread(Action action)
        {
#if FEATURE_THREAD_THREADPOOL
            if (action == null)
                throw new ArgumentNullException("action");

            System.Threading.ThreadPool.QueueUserWorkItem(o => action());
#elif FEATURE_THREAD_TAP
            System.Threading.Tasks.Task.Run(action);
#else
            #error Execution of action in a separate thread is not implemented.
#endif
        }
    }
}

Move null check into FEATURE_THREAD_THREADPOOL section.


using System;
using SourceSafeTypeLib;

namespace vsslib
{
	public static class VssItemExtensions
	{
		/// <summary>
		/// If VSS conatins $/Project1 but requested $/project1, then case will not be fixed and $/project1 will be retuned.
		/// This methor return case to normal -> $/Project1
		/// </summary>
		/// <param name="item">Item for normalize</param>
		/// <returns>Normalized item</returns>
		public static IVSSItem Normalize(this IVSSItem item, IVSSDatabase db)
		{
			IVSSItem current = db.VSSItem["$/"];

			foreach (var pathPart in item.Spec.Replace('\\', '/').TrimStart("$/".ToCharArray()).TrimEnd('/').Split('/'))
			{
				IVSSItem next = null;
				foreach (IVSSItem child in current.Items)
				{
					var parts = child.Spec.TrimEnd('/').Split('/');
					var lastPart = parts[parts.Length - 1];

					if(String.Compare(pathPart, lastPart, StringComparison.OrdinalIgnoreCase) == 0)
					{
						next = child;
						break;
					}
				}

				if(next == null)
					throw new ApplicationException("Can't normalize: " + item.Spec);

				current = next;
			}

			return current;
		}
	}
}

using System;
using SourceSafeTypeLib;

namespace vsslib
{
	public static class VssItemExtensions
	{
		/// <summary>
		/// If VSS conatins $/Project1 but requested $/project1, then case will not be fixed and $/project1 will be retuned.
		/// This methor return case to normal -> $/Project1
		/// </summary>
		/// <param name="item">Item for normalize</param>
		/// <returns>Normalized item</returns>
		public static IVSSItem Normalize(this IVSSItem item, IVSSDatabase db)
		{
			IVSSItem current = db.VSSItem["$/"];

			if (item.Spec.Replace('\\', '/').TrimEnd("/".ToCharArray()) == "$")
				return current;

			foreach (var pathPart in item.Spec.Replace('\\', '/').TrimStart("$/".ToCharArray()).TrimEnd('/').Split('/'))
			{
				IVSSItem next = null;
				foreach (IVSSItem child in current.Items)
				{
					var parts = child.Spec.TrimEnd('/').Split('/');
					var lastPart = parts[parts.Length - 1];

					if(String.Compare(pathPart, lastPart, StringComparison.OrdinalIgnoreCase) == 0)
					{
						next = child;
						break;
					}
				}

				if(next == null)
					throw new ApplicationException("Can't normalize: " + item.Spec);

				current = next;
			}

			return current;
		}
	}
}

Allow $ as import root

Allow $ as import root


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace DemoWcfRest
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DemoService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        [WebGet(UriTemplate = "hi/{name}")]
        public string Hello(string name)
        {
            return string.Format("Hello, {0}", name);
        }

        // Add more operations here and mark them with [OperationContract]
        [OperationContract]
        [WebInvoke(Method = "POST")]
        public void PostSample(string postBody)
        {
            // DO NOTHING
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace DemoWcfRest
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DemoService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        [WebGet(UriTemplate = "hi/{name}", ResponseFormat = WebMessageFormat.Json)]
        public string Hello(string name)
        {
            return string.Format("Hello, {0}", name);
        }

        // Add more operations here and mark them with [OperationContract]
        [OperationContract]
        [WebInvoke(Method = "POST")]
        public void PostSample(string postBody)
        {
            // DO NOTHING
        }
    }
}

Use json in WCF REST response.

Use json in WCF REST response.


#region

using System.Windows;

#endregion

namespace SteamAccountSwitcher
{
    internal class Popup
    {
        public static MessageBoxResult Show(string text, MessageBoxButton btn = MessageBoxButton.OK,
            MessageBoxImage img = MessageBoxImage.Information, MessageBoxResult defaultbtn = MessageBoxResult.OK)
        {
            return MessageBox.Show(text, "SteamAccountSwitcher", btn, img, defaultbtn);
        }
    }
}

#region

using System.Windows;

#endregion

namespace SteamAccountSwitcher
{
    internal class Popup
    {
        public static MessageBoxResult Show(string text, MessageBoxButton btn = MessageBoxButton.OK,
            MessageBoxImage img = MessageBoxImage.Information, MessageBoxResult defaultbtn = MessageBoxResult.OK)
        {
            return MessageBox.Show(text, "Steam Account Switcher", btn, img, defaultbtn);
        }
    }
}

Change default popup title text

Change default popup title text


// 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.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Overlays.Profile.Header.Components
{
    public class ProfileRulesetTabItem : OverlayRulesetTabItem
    {
        private bool isDefault;

        public bool IsDefault
        {
            get => isDefault;
            set
            {
                if (isDefault == value)
                    return;

                isDefault = value;

                icon.FadeTo(isDefault ? 1 : 0, 200, Easing.OutQuint);
            }
        }

        protected override Color4 AccentColour
        {
            get => base.AccentColour;
            set
            {
                base.AccentColour = value;
                icon.FadeColour(value, 120, Easing.OutQuint);
            }
        }

        private readonly SpriteIcon icon;

        public ProfileRulesetTabItem(RulesetInfo value)
            : base(value)
        {
            Add(icon = new SpriteIcon
            {
                Origin = Anchor.Centre,
                Anchor = Anchor.Centre,
                Alpha = 0,
                AlwaysPresent = true,
                Icon = FontAwesome.Solid.Star,
                Size = new Vector2(12),
            });
        }
    }
}

// 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.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Overlays.Profile.Header.Components
{
    public class ProfileRulesetTabItem : OverlayRulesetTabItem
    {
        private bool isDefault;

        public bool IsDefault
        {
            get => isDefault;
            set
            {
                if (isDefault == value)
                    return;

                isDefault = value;

                icon.Alpha = isDefault ? 1 : 0;
            }
        }

        protected override Color4 AccentColour
        {
            get => base.AccentColour;
            set
            {
                base.AccentColour = value;
                icon.FadeColour(value, 120, Easing.OutQuint);
            }
        }

        private readonly SpriteIcon icon;

        public ProfileRulesetTabItem(RulesetInfo value)
            : base(value)
        {
            Add(icon = new SpriteIcon
            {
                Origin = Anchor.Centre,
                Anchor = Anchor.Centre,
                Alpha = 0,
                Icon = FontAwesome.Solid.Star,
                Size = new Vector2(12),
            });
        }
    }
}

Adjust profile ruleset selector to new design

Looks weird with `AlwaysPresent`.


using System.Linq;
using System.Reflection;

// ReSharper disable once CheckNamespace
internal class Program
{
    private static void Main(string[] args)
    {
        var mainAsm = Assembly.Load("citizenmp_server_updater");

        mainAsm.GetType("Costura.AssemblyLoader")
            .GetMethod("Attach")
            .Invoke(null, null);

        mainAsm.GetType("CitizenMP.Server.Installer.Program")
            .GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static)
            .Invoke(null, new object[] {args});
    }
}

using System;
using System.IO;
using System.Reflection;

// ReSharper disable once CheckNamespace
internal static class Program
{
    private static int Main(string[] args)
    {
        // Mono's XBuild uses assembly redirects to make sure it uses .NET 4.5 target binaries.
        // We emulate it using our own assembly redirector.
        AppDomain.CurrentDomain.AssemblyLoad += (sender, e) =>
        {
            var assemblyName = e.LoadedAssembly.GetName();
            Console.WriteLine("Assembly load: {0}", assemblyName);
        };

        var mainAsm = Assembly.Load("citizenmp_server_updater");

        mainAsm.GetType("Costura.AssemblyLoader")
            .GetMethod("Attach")
            .Invoke(null, null);

        return (int) mainAsm.GetType("CitizenMP.Server.Installer.Program")
            .GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static)
            .Invoke(null, new object[] {args});
    }
}

Return exit values through wrapper.

Return exit values through wrapper.


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Containers;
using osu.Framework.Platform;
using osu.Framework.Testing;

namespace osu.Framework.Tests
{
    internal class VisualTestGame : TestGame
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            Child = new SafeAreaSnappingContainer
            {
                SafeEdges = Edges.Left | Edges.Top | Edges.Right,
                Child = new DrawSizePreservingFillContainer
                {
                    Children = new Drawable[]
                    {
                        new TestBrowser(),
                        new CursorContainer(),
                    },
                }
            };
        }

        public override void SetHost(GameHost host)
        {
            base.SetHost(host);
            host.Window.CursorState |= CursorState.Hidden;
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Containers;
using osu.Framework.Platform;
using osu.Framework.Testing;

namespace osu.Framework.Tests
{
    internal class VisualTestGame : TestGame
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            Child = new SafeAreaSnappingContainer
            {
                RelativeSizeAxes = Axes.Both,
                SafeEdges = Edges.Left | Edges.Top | Edges.Right,
                Child = new DrawSizePreservingFillContainer
                {
                    Children = new Drawable[]
                    {
                        new TestBrowser(),
                        new CursorContainer(),
                    },
                }
            };
        }

        public override void SetHost(GameHost host)
        {
            base.SetHost(host);
            host.Window.CursorState |= CursorState.Hidden;
        }
    }
}

Fix zero size parent container in visual tests


using Ninject;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ninject.Extensions.Conventions;

namespace FunWithNinject.Conventions
{
    [TestFixture]
    public class ConventionsTests
    {
        [Test]
        public void Bind_OneClassWithMultipleInterfaces_BindsOneInstanceToAll()
        {
            // Assemble
            using (var kernel = new StandardKernel())
            {
                kernel.Bind(k => k.FromThisAssembly()
                                  .SelectAllClasses()
                                  .InNamespaceOf<ConventionsTests>()
                                  .BindAllInterfaces()
                                  .Configure(b => b.InSingletonScope()));

                // Act
                var face1 = kernel.Get<IFace1>();
                var face2 = kernel.Get<IFace2>();

                // Assemble
                Assert.AreSame(face1, face2);
            }
        }
    }

    public interface IFace1 { }
    public interface IFace2 { }
    public class AllFaces : IFace1, IFace2 { }
}

using Ninject;
using Ninject.Extensions.Conventions;
using NUnit.Framework;

namespace FunWithNinject.Conventions
{
    [TestFixture]
    public class ConventionsTests
    {
        [Test]
        public void Bind_OneClassWithMultipleInterfaces_BindsOneInstanceToAll()
        {
            // Assemble
            using (var kernel = new StandardKernel())
            {
                kernel.Bind(k => k.FromThisAssembly()
                                  .SelectAllClasses()
                                  .InNamespaceOf<ConventionsTests>()
                                  .BindAllInterfaces()
                                  .Configure(b => b.InSingletonScope()));

                // Act
                var face1 = kernel.Get<IFace1>();
                var face2 = kernel.Get<IFace2>();

                // Assemble
                Assert.AreSame(face1, face2);
            }
        }

        [Test]
        public void Bind_ResolveGenericType_Works()
        {
            // Assemble
            using (var kernel = new StandardKernel())
            {
                kernel.Bind(k => k.FromThisAssembly()
                                  .SelectAllClasses()
                                  .InNamespaceOf<ConventionsTests>()
                                  .BindAllInterfaces()
                                  .Configure(b => b.InSingletonScope()));

                kernel.Bind<int>().ToConstant(27);
                kernel.Bind<string>().ToConstant("twenty seven");

                // Act
                var generic = kernel.Get<IGeneric<int, string>>();

                // Assemble
                Assert.AreEqual(27, generic.FirstProp);
                Assert.AreEqual("twenty seven", generic.SecondProp);
            }
        }

        #region Helper Classes/Interfaces

        public interface IFace1 { }

        public interface IFace2 { }

        public interface IGeneric<T1, T2>
        {
            T1 FirstProp { get; set; }
            T2 SecondProp { get; set; }
        }

        public class AllFaces : IFace1, IFace2 { }

        public class Generic<T1, T2> : IGeneric<T1, T2>
        {
            public Generic(T1 first, T2 second)
            {
                FirstProp = first;
                SecondProp = second;
            }

            public T1 FirstProp { get; set; }
            public T2 SecondProp { get; set; }
        }

        #endregion Helper Classes/Interfaces
    }
}

Add test case for open generics

Add test case for open generics


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

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

[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.DomainServices 3.0.0")]

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

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

[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.DomainServices 3.0.0")]

Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.


using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Cogito.Web.Razor.Tests
{

    [TestClass]
    public class RazorTemplateBuilderTests
    {

        TextReader LoadTemplateText(string name)
        {
            return new StreamReader(typeof(RazorTemplateBuilderTests).Assembly
                .GetManifestResourceStream(typeof(RazorTemplateBuilderTests).Namespace + ".Templates." + name));
        }

        [TestMethod]
        public void Test_simple_code_generation()
        {
            var t = RazorTemplateBuilder.ToCode(() => LoadTemplateText("Simple.cshtml"));
            Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
        }

        [TestMethod]
        public void Test_simple_helper_code_generation()
        {
            var t = RazorTemplateBuilder.ToCode(() => LoadTemplateText("SimpleWithHelper.cshtml"));
            Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
        }

    }

}

using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Cogito.Web.Razor.Tests
{

    [TestClass]
    public class RazorTemplateBuilderTests
    {

        TextReader LoadTemplateText(string name)
        {
            return new StreamReader(typeof(RazorTemplateBuilderTests).Assembly
                .GetManifestResourceStream(typeof(RazorTemplateBuilderTests).Namespace + ".Templates." + name));
        }

        [TestMethod]
        public void Test_simple_code_generation()
        {
            var t = RazorTemplateBuilder.ToCode(LoadTemplateText("Simple.cshtml").ReadToEnd());
            Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
        }

        [TestMethod]
        public void Test_simple_helper_code_generation()
        {
            var t = RazorTemplateBuilder.ToCode(LoadTemplateText("SimpleWithHelper.cshtml").ReadToEnd());
            Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
        }

    }

}

Fix Razor tests broken by change to full string passing.


@model IEnumerable<BatteryCommander.Common.Models.Soldier>

@{
    ViewBag.Title = "List";
}

List

            @Html.DisplayNameFor(model => model.LastName)

            @Html.DisplayNameFor(model => model.FirstName)

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.LastName)

                @Html.DisplayFor(modelItem => item.FirstName)

                @Html.ActionLink("Edit", "Edit", new { id = item.Id })

    }

@model IEnumerable<BatteryCommander.Common.Models.Soldier>

@{
    ViewBag.Title = "List";
}

@ViewBag.Title

                @Html.DisplayNameFor(model => model.FirstOrDefault().LastName)

                @Html.DisplayNameFor(model => model.FirstOrDefault().FirstName)

                @Html.DisplayNameFor(model => model.FirstOrDefault().Rank)

                @Html.DisplayNameFor(model => model.FirstOrDefault().Status)

        @foreach (var item in Model)
        {

                    @Html.DisplayFor(modelItem => item.LastName)

                    @Html.DisplayFor(modelItem => item.FirstName)

                    @Html.DisplayFor(modelItem => item.Rank)

                    @Html.DisplayFor(modelItem => item.Status)

                    @Html.ActionLink("Edit", "Edit", new { soldierId = item.Id })

        }

Fix list view template for soldiers

Fix list view template for soldiers


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

using System.Collections.Immutable;

namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
    internal partial class TypeSymbol
    {
        /// <summary>
        /// Represents the method by which this type implements a given interface type
        /// and/or the corresponding diagnostics.
        /// </summary>
        protected class SymbolAndDiagnostics
        {
            public static readonly SymbolAndDiagnostics Empty = new SymbolAndDiagnostics(null, ImmutableArray<Diagnostic>.Empty);

            public readonly Symbol Symbol;
            public readonly ImmutableArray<Diagnostic> Diagnostics;

            public SymbolAndDiagnostics(Symbol symbol, ImmutableArray<Diagnostic> diagnostics)
            {
                this.Symbol = symbol;
                this.Diagnostics = diagnostics;
            }
        }
    }
}

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

using System.Collections.Immutable;

#pragma warning disable CS0660 // Warning is reported only for Full Solution Analysis

namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
    internal partial class TypeSymbol
    {
        /// <summary>
        /// Represents the method by which this type implements a given interface type
        /// and/or the corresponding diagnostics.
        /// </summary>
        protected class SymbolAndDiagnostics
        {
            public static readonly SymbolAndDiagnostics Empty = new SymbolAndDiagnostics(null, ImmutableArray<Diagnostic>.Empty);

            public readonly Symbol Symbol;
            public readonly ImmutableArray<Diagnostic> Diagnostics;

            public SymbolAndDiagnostics(Symbol symbol, ImmutableArray<Diagnostic> diagnostics)
            {
                this.Symbol = symbol;
                this.Diagnostics = diagnostics;
            }
        }
    }
}

Disable CS0660 where Full Solution Analysis produces a different result


using System;

namespace ChamberLib.Content
{
    public delegate IModel ModelProcessor(ModelContent asset, IContentProcessor processor);
    public delegate ITexture2D TextureProcessor(TextureContent asset, IContentProcessor processor);
    public delegate IShaderStage ShaderStageProcessor(ShaderContent asset, IContentProcessor processor, object bindattrs=null);
    public delegate IFont FontProcessor(FontContent asset, IContentProcessor processor);
    public delegate ISong SongProcessor(SongContent asset, IContentProcessor processor);
    public delegate ISoundEffect SoundEffectProcessor(SoundEffectContent asset, IContentProcessor processor);
}

using System;

namespace ChamberLib.Content
{
    public delegate IModel ModelProcessor(ModelContent asset, IContentProcessor processor);
    public delegate ITexture2D TextureProcessor(TextureContent asset, IContentProcessor processor);
    public delegate IShaderStage ShaderStageProcessor(ShaderContent asset, IContentProcessor processor);
    public delegate IFont FontProcessor(FontContent asset, IContentProcessor processor);
    public delegate ISong SongProcessor(SongContent asset, IContentProcessor processor);
    public delegate ISoundEffect SoundEffectProcessor(SoundEffectContent asset, IContentProcessor processor);
}

Remove the unused bindattrs parameter from the ShaderStageProcessor delegate.


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

namespace osu.Game.Tournament.Components
{
    public class DateTextBox : SettingsTextBox
    {
        public new Bindable<DateTimeOffset> Bindable
        {
            get => bindable;
            set
            {
                bindable = value.GetBoundCopy();
                bindable.BindValueChanged(dto =>
                    base.Bindable.Value = dto.NewValue.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"), true);
            }
        }

        // hold a reference to the provided bindable so we don't have to in every settings section.
        private Bindable<DateTimeOffset> bindable;

        public DateTextBox()
        {
            base.Bindable = new Bindable<string>();
            ((OsuTextBox)Control).OnCommit = (sender, newText) =>
            {
                try
                {
                    bindable.Value = DateTimeOffset.Parse(sender.Text);
                }
                catch
                {
                    // reset textbox content to its last valid state on a parse failure.
                    bindable.TriggerChange();
                }
            };
        }
    }
}

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

namespace osu.Game.Tournament.Components
{
    public class DateTextBox : SettingsTextBox
    {
        public new Bindable<DateTimeOffset> Bindable
        {
            get => bindable;
            set
            {
                bindable = value.GetBoundCopy();
                bindable.BindValueChanged(dto =>
                    base.Bindable.Value = dto.NewValue.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"), true);
            }
        }

        // hold a reference to the provided bindable so we don't have to in every settings section.
        private Bindable<DateTimeOffset> bindable = new Bindable<DateTimeOffset>();

        public DateTextBox()
        {
            base.Bindable = new Bindable<string>();

            ((OsuTextBox)Control).OnCommit = (sender, newText) =>
            {
                try
                {
                    bindable.Value = DateTimeOffset.Parse(sender.Text);
                }
                catch
                {
                    // reset textbox content to its last valid state on a parse failure.
                    bindable.TriggerChange();
                }
            };
        }
    }
}

Fix nullref in date text box

Fix nullref in date text box


using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace ExcelDna.IntelliSense
{
    static class FormulaParser
    {
        // Set from IntelliSenseDisplay.Initialize
        public static char ListSeparator = ',';

        internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex)
        {
            formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty);

            while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)"))
            {
                formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty);
            }

            int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal);

            if (lastOpeningParenthesis > -1)
            {
                var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), @"[^\w.](?<functionName>[\w.]*)$");
                if (match.Success)
                {
                    functionName = match.Groups["functionName"].Value;
                    currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator);
                    return true;
                }
            }

            functionName = null;
            currentArgIndex = -1;
            return false;
        }
    }
}

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace ExcelDna.IntelliSense
{
    static class FormulaParser
    {
        // Set from IntelliSenseDisplay.Initialize
        public static char ListSeparator = ',';
        // TODO: What's the Unicode situation?
        public static string forbiddenNameCharacters = @"\ /\-:;!@\#\$%\^&\*\(\)\+=,<>\[\]{}|'\""";
        public static string functionNameRegex = "[" + forbiddenNameCharacters + "](?<functionName>[^" + forbiddenNameCharacters + "]*)$";
        public static string functionNameGroupName = "functionName";

        internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex)
        {
            formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty);

            while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)"))
            {
                formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty);
            }

            int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal);

            if (lastOpeningParenthesis > -1)
            {
                var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), functionNameRegex);
                if (match.Success)
                {
                    functionName = match.Groups[functionNameGroupName].Value;
                    currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator);
                    return true;
                }
            }

            functionName = null;
            currentArgIndex = -1;
            return false;
        }
    }
}

Extend character set of function names (including ".") (again)


using UnityEngine;
using System.Collections;

public class ColliderFriction : GameObjectBehavior {

    public float frictionValue=0;

	// Use this for initialization
	void Start () {
        collider.material.staticFriction = frictionValue;
        collider.material.staticFriction2 = frictionValue;
        collider.material.dynamicFriction = frictionValue;
        collider.material.dynamicFriction2 = frictionValue;
	}

}

using UnityEngine;
using System.Collections;

public class ColliderFriction : GameObjectBehavior {

    public float frictionValue=0;

	// Use this for initialization
	void Start () {
        collider.material.staticFriction = frictionValue;
        //collider.material.staticFriction2 = frictionValue;
        collider.material.dynamicFriction = frictionValue;
        //collider.material.dynamicFriction2 = frictionValue;
	}

}

Update to Unity 5.2 cleanup.

Update to Unity 5.2 cleanup.


using System.Collections.Generic;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using AshMind.Extensions;
using System;
using SharpLab.Server.Common.Internal;

namespace SharpLab.Server.Owin.Platform {
    public class Net48AssemblyDocumentationResolver : IAssemblyDocumentationResolver {
        private static readonly string ReferenceAssemblyRootPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
            + @"\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7";

        public DocumentationProvider? GetDocumentation([NotNull] Assembly assembly) {
            foreach (var xmlPath in GetCandidatePaths(assembly)) {
                if (File.Exists(xmlPath))
                    return XmlDocumentationProvider.CreateFromFile(xmlPath);
            }

            return null;
        }

        private IEnumerable<string> GetCandidatePaths(Assembly assembly) {
            var file = assembly.GetAssemblyFileFromCodeBase();

            yield return Path.ChangeExtension(file.FullName, ".xml");
            yield return Path.Combine(ReferenceAssemblyRootPath, Path.ChangeExtension(file.Name, ".xml"));
        }
    }
}

using System.Collections.Generic;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using AshMind.Extensions;
using System;
using SharpLab.Server.Common.Internal;

namespace SharpLab.Server.Owin.Platform {
    public class Net48AssemblyDocumentationResolver : IAssemblyDocumentationResolver {
        private static readonly string ReferenceAssemblyRootPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
            + @"\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8";

        public DocumentationProvider? GetDocumentation([NotNull] Assembly assembly) {
            foreach (var xmlPath in GetCandidatePaths(assembly)) {
                if (File.Exists(xmlPath))
                    return XmlDocumentationProvider.CreateFromFile(xmlPath);
            }

            return null;
        }

        private IEnumerable<string> GetCandidatePaths(Assembly assembly) {
            var file = assembly.GetAssemblyFileFromCodeBase();

            yield return Path.ChangeExtension(file.FullName, ".xml");
            yield return Path.Combine(ReferenceAssemblyRootPath, Path.ChangeExtension(file.Name, ".xml"));
        }
    }
}

Fix version of .NET Framework used to look up XML documentation