using System;

namespace NFig
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
    public abstract class DefaultSettingValueAttribute : Attribute
    {
        public object DefaultValue { get; protected set; }
        public object SubApp { get; protected set; }
        public object Tier { get; protected set; }
        public object DataCenter { get; protected set; }
        public bool AllowOverrides { get; protected set; } = true;
    }
}

using System;

namespace NFig
{
    /// <summary>
    /// This is the base class for all NFig attributes which specify default values, except for the <see cref="SettingAttribute"/> itself. This attribute is
    /// abstract because you should provide the attributes which make sense for your individual setup. The subApp/tier/dataCenter parameters in inheriting
    /// attributes should be strongly typed (rather than using "object"), and match the generic parameters used for the NFigStore and Settings object.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
    public abstract class DefaultSettingValueAttribute : Attribute
    {
        /// <summary>
        /// The value of the default being applied. This must be either a convertable string, or a literal value whose type matches that of the setting. For
        /// encrypted settings, a default value must always be an encrypted string.
        /// </summary>
        public object DefaultValue { get; protected set; }
        /// <summary>
        /// The sub-app which the default is applicable to. If null or the zero-value, it is considered applicable to the "Global" app, as well as any sub-app
        /// which does not have another default applied. If your application only uses the Global app (no sub-apps), then you should not include this parameter
        /// in inheriting attributes.
        /// </summary>
        public object SubApp { get; protected set; }
        /// <summary>
        /// The deployment tier (e.g. local/dev/prod) which the default is applicable to. If null or the zero-value, the default is applicable to any tier.
        /// </summary>
        public object Tier { get; protected set; }
        /// <summary>
        /// The data center which the default is applicable to. If null or the zero-value, the default is applicable to any data center.
        /// </summary>
        public object DataCenter { get; protected set; }
        /// <summary>
        /// Specifies whether NFig should accept runtime overrides for this default. Note that this only applies to environments where this particular default
        /// is the active default. For example, if you set an default for Tier=Prod/DataCenter=Any which DOES NOT allow defaults, and another default for
        /// Tier=Prod/DataCenter=East which DOES allow overrides, then you will be able to set overrides in Prod/East, but you won't be able to set overrides
        /// in any other data center.
        /// </summary>
        public bool AllowOverrides { get; protected set; } = true;
    }
}

Add XML docs for DefaultSettingValueAttribute


using System;

namespace SteamShutdown
{
    public class App
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int State { get; set; }

        /// <summary>
        /// Returns a value indicating whether the game is being downloaded. Includes games in queue for download.
        /// </summary>
        public bool IsDownloading
        {
            get { return CheckDownloading(State); }
        }

        /// <summary>
        /// Returns a value indicating whether the game is being downloaded. Includes games in queue for download.
        /// </summary>
        /// <param name="appState"></param>
        /// <returns></returns>
        public static bool CheckDownloading(int appState)
        {
            // 6: In queue for update
            // 1026: In queue
            // 1042: download running
            return appState == 6 || appState == 1026 || appState == 1042 || appState == 1062 || appState == 1030;
        }

        public override string ToString()
        {
            return Name;
        }
    }
}

namespace SteamShutdown
{
    public class App
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int State { get; set; }

        /// <summary>
        /// Returns a value indicating whether the game is being downloaded.
        /// </summary>
        public bool IsDownloading => CheckDownloading(State);

        /// <summary>
        /// Returns a value indicating whether the game is being downloaded.
        /// </summary>
        public static bool CheckDownloading(int appState)
        {
            // The second bit defines if anything for the app needs to be downloaded
            // Doesn't matter if queued, download running and so on
            return IsBitSet(appState, 1);
        }

        public override string ToString()
        {
            return Name;
        }

        private static bool IsBitSet(int b, int pos)
        {
            return (b & (1 << pos)) != 0;
        }
    }
}

Check for specific bit now to check if a game is downloaded at the moment


using System.Diagnostics;
using System.IO;

namespace Microsoft.Build.Logging.StructuredLogger
{
    public class BinaryLog
    {
        public static Build ReadBuild(string filePath)
        {
            var eventSource = new BinaryLogReplayEventSource();

            byte[] sourceArchive = null;

            eventSource.OnBlobRead += (kind, bytes) =>
            {
                if (kind == BinaryLogRecordKind.ProjectImportArchive)
                {
                    sourceArchive = bytes;
                }
            };

            StructuredLogger.SaveLogToDisk = false;
            StructuredLogger.CurrentBuild = null;
            var structuredLogger = new StructuredLogger();
            structuredLogger.Parameters = "build.buildlog";
            structuredLogger.Initialize(eventSource);

            var sw = Stopwatch.StartNew();
            eventSource.Replay(filePath);
            var elapsed = sw.Elapsed;

            var build = StructuredLogger.CurrentBuild;
            StructuredLogger.CurrentBuild = null;

            if (build == null)
            {
                build = new Build() { Succeeded = false };
                build.AddChild(new Error() { Text = "Error when opening the file: " + filePath });
            }

            var projectImportsZip = Path.ChangeExtension(filePath, ".ProjectImports.zip");
            if (sourceArchive == null && File.Exists(projectImportsZip))
            {
                sourceArchive = File.ReadAllBytes(projectImportsZip);
            }

            build.SourceFilesArchive = sourceArchive;
            // build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });

            return build;
        }
    }
}

using System.Diagnostics;
using System.IO;

namespace Microsoft.Build.Logging.StructuredLogger
{
    public class BinaryLog
    {
        public static Build ReadBuild(string filePath)
        {
            var eventSource = new BinaryLogReplayEventSource();

            byte[] sourceArchive = null;

            eventSource.OnBlobRead += (kind, bytes) =>
            {
                if (kind == BinaryLogRecordKind.ProjectImportArchive)
                {
                    sourceArchive = bytes;
                }
            };

            StructuredLogger.SaveLogToDisk = false;
            StructuredLogger.CurrentBuild = null;
            var structuredLogger = new StructuredLogger();
            structuredLogger.Parameters = "build.buildlog";
            structuredLogger.Initialize(eventSource);

            var sw = Stopwatch.StartNew();
            eventSource.Replay(filePath);
            var elapsed = sw.Elapsed;

            structuredLogger.Shutdown();

            var build = StructuredLogger.CurrentBuild;
            StructuredLogger.CurrentBuild = null;

            if (build == null)
            {
                build = new Build() { Succeeded = false };
                build.AddChild(new Error() { Text = "Error when opening the file: " + filePath });
            }

            var projectImportsZip = Path.ChangeExtension(filePath, ".ProjectImports.zip");
            if (sourceArchive == null && File.Exists(projectImportsZip))
            {
                sourceArchive = File.ReadAllBytes(projectImportsZip);
            }

            build.SourceFilesArchive = sourceArchive;
            // build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });

            return build;
        }
    }
}

Fix a bug where it didn't read .binlog files correctly.


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

using System;
using System.Diagnostics;
using Wave.Defaults;

namespace Wave.ServiceHosting.IIS
{
    /// <summary>
    /// This queue resolver tags queue names with the machine name (TEMP REMOVED UNTIL CLEANUP STRATEGY IN PLACE: and worker process Id) listening on this queue.
    /// </summary>
    public class IISQueueNameResolver : DefaultQueueNameResolver
    {
        public IISQueueNameResolver(IAssemblyLocator assemblyLocator) : base(assemblyLocator) { }

        public override string GetPrimaryQueueName()
        {
            return String.Format("{0}_{1}",
                base.GetPrimaryQueueName(),
                Environment.MachineName);
        }
    }
}

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

using System;
using System.Diagnostics;
using Wave.Defaults;

namespace Wave.ServiceHosting.IIS
{
    /// <summary>
    /// This queue resolver tags queue names with the machine name (TEMP REMOVED UNTIL CLEANUP STRATEGY IN PLACE: and worker process Id) listening on this queue.
    /// </summary>
    public class IISQueueNameResolver : DefaultQueueNameResolver
    {
        public IISQueueNameResolver(IAssemblyLocator assemblyLocator) : base(assemblyLocator) { }

        public override string GetPrimaryQueueName()
        {
            return String.Format("{0}_{1}_{2}",
                base.GetPrimaryQueueName(),
                Environment.MachineName,
                Process.GetCurrentProcess().Id
                );
        }
    }
}

Append IIS queues with worker PID.

Append IIS queues with worker PID.


namespace JustCli.Commands
{
    public class CommandLineHelpCommand : ICommand
    {
        public ICommandRepository CommandRepository { get; set; }
        public IOutput Output { get; set; }

        public CommandLineHelpCommand(ICommandRepository commandRepository, IOutput output)
        {
            CommandRepository = commandRepository;
            Output = output;
        }

        public bool Execute()
        {
            var commandsInfo = CommandRepository.GetCommandsInfo();

            Output.WriteInfo("Command list:");
            foreach (var commandInfo in commandsInfo)
            {
                Output.WriteInfo(string.Format("{0} - {1}", commandInfo.Name, commandInfo.Description));
            }

            return true;
        }
    }
}

namespace JustCli.Commands
{
    public class CommandLineHelpCommand : ICommand
    {
        public ICommandRepository CommandRepository { get; set; }
        public IOutput Output { get; set; }

        public CommandLineHelpCommand(ICommandRepository commandRepository, IOutput output)
        {
            CommandRepository = commandRepository;
            Output = output;
        }

        public bool Execute()
        {
            var commandsInfo = CommandRepository.GetCommandsInfo();

            if (commandsInfo.Count == 0)
            {
                Output.WriteInfo("There are no commands.");
                return true;
            }

            Output.WriteInfo("Command list:");
            foreach (var commandInfo in commandsInfo)
            {
                Output.WriteInfo(string.Format("{0} - {1}", commandInfo.Name, commandInfo.Description));
            }

            return true;
        }
    }
}

Add "There are no commands".

Add "There are no commands".


using System;
using Newtonsoft.Json.Linq;

namespace DevLab.JmesPath.Utils
{
    public static class JTokens
    {
        public static JToken Null = JToken.Parse("null");
        public static JToken True = JToken.Parse("true");
        public static JToken False = JToken.Parse("false");

        public static bool IsFalse(JToken token)
        {
            // A false value corresponds to any of the following conditions:
            // Empty list: ``[]``
            // Empty object: ``{}``
            // Empty string: ``""``
            // False boolean: ``false``
            // Null value: ``null``

            var array = token as JArray;
            if (array != null && array.Count == 0)
                return true;

            var @object = token as JObject;
            if (@object != null && @object.Count == 0)
                return true;

            var value = token as JValue;
            if (value != null)
            {
                switch (token.Type)
                {
                    case JTokenType.Bytes:
                    case JTokenType.Date:
                    case JTokenType.Guid:
                    case JTokenType.String:
                        return token.Value<String>() == "";

                    case JTokenType.Boolean:
                        return token.Value<Boolean>() == false;

                    case JTokenType.Null:
                        return true;
                }
            }

            return false;
        }
    }
}

using System;
using Newtonsoft.Json.Linq;

namespace DevLab.JmesPath.Utils
{
    public static class JTokens
    {
        public static JToken Null = JToken.Parse("null");
        public static JToken True = JToken.Parse("true");
        public static JToken False = JToken.Parse("false");

        public static bool IsFalse(JToken token)
        {
            // A false value corresponds to any of the following conditions:
            // Empty list: ``[]``
            // Empty object: ``{}``
            // Empty string: ``""``
            // False boolean: ``false``
            // Null value: ``null``

            var array = token as JArray;
            if (array != null && array.Count == 0)
                return true;

            var @object = token as JObject;
            if (@object != null && @object.Count == 0)
                return true;

            var value = token as JValue;
            if (value != null)
            {
                switch (token.Type)
                {
                    case JTokenType.Bytes:
                    case JTokenType.Date:
                    case JTokenType.Guid:
                    case JTokenType.String:
                    case JTokenType.TimeSpan:
                    case JTokenType.Uri:
                        return token.Value<String>() == "";

                    case JTokenType.Boolean:
                        return token.Value<Boolean>() == false;

                    case JTokenType.Null:
                        return true;
                }
            }

            return false;
        }
    }
}

Fix - Included some missing cases for JSON string types.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Framework.Rpc;
using Hadouken.Plugins.Torrents.BitTorrent;

namespace Hadouken.Plugins.Torrents.Rpc
{
    public class TorrentsServices : IJsonRpcService
    {
        private readonly IBitTorrentEngine _torrentEngine;

        public TorrentsServices(IBitTorrentEngine torrentEngine)
        {
            _torrentEngine = torrentEngine;
        }

        [JsonRpcMethod("torrents.start")]
        public bool Start(string infoHash)
        {
            var manager = _torrentEngine.Get(infoHash);

            if (manager == null)
                return false;

            manager.Start();

            return true;
        }

        [JsonRpcMethod("torrents.stop")]
        public bool Stop(string infoHash)
        {
            var manager = _torrentEngine.Get(infoHash);

            if (manager == null)
                return false;

            manager.Stop();

            return true;
        }

        [JsonRpcMethod("torrents.list")]
        public object List()
        {
            var torrents = _torrentEngine.TorrentManagers;

            return (from t in torrents
                select new
                {
                    t.Torrent.Name,
                    t.Torrent.Size
                }).ToList();
        }

        [JsonRpcMethod("torrents.addFile")]
        public object AddFile(byte[] data, string savePath, string label)
        {
            var torrent = _torrentEngine.Add(data, savePath, label);
            return torrent;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Framework.Rpc;
using Hadouken.Plugins.Torrents.BitTorrent;

namespace Hadouken.Plugins.Torrents.Rpc
{
    public class TorrentsServices : IJsonRpcService
    {
        private readonly IBitTorrentEngine _torrentEngine;

        public TorrentsServices(IBitTorrentEngine torrentEngine)
        {
            _torrentEngine = torrentEngine;
        }

        [JsonRpcMethod("torrents.start")]
        public bool Start(string infoHash)
        {
            var manager = _torrentEngine.Get(infoHash);

            if (manager == null)
                return false;

            manager.Start();

            return true;
        }

        [JsonRpcMethod("torrents.stop")]
        public bool Stop(string infoHash)
        {
            var manager = _torrentEngine.Get(infoHash);

            if (manager == null)
                return false;

            manager.Stop();

            return true;
        }

        [JsonRpcMethod("torrents.list")]
        public object List()
        {
            var torrents = _torrentEngine.TorrentManagers;

            return (from t in torrents
                select new
                {
                    t.Torrent.Name,
                    t.Torrent.Size
                }).ToList();
        }

        [JsonRpcMethod("torrents.addFile")]
        public object AddFile(byte[] data, string savePath, string label)
        {
            var manager = _torrentEngine.Add(data, savePath, label);
            return new
                {
                    manager.Torrent.Name,
                    manager.Torrent.Size
                };
        }
    }
}

Return simple object representing the torrent.


namespace NuGet.VisualStudio {
    public class PowerShellScripts {
        public static readonly string Install = "install.ps1";
        public static readonly string Uninstall = "uninstall.ps1";
        public static readonly string Init = "init.ps1";
    }
}

namespace NuGet.VisualStudio {
    public static class PowerShellScripts {
        public static readonly string Install = "install.ps1";
        public static readonly string Uninstall = "uninstall.ps1";
        public static readonly string Init = "init.ps1";
    }
}

Make PowerShellScripts class static per review.


// Copyright(c) 2015 Google Inc.

// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;

namespace GoogleCloudSamples
{
    public class Startup
    {
        // This method gets called by the runtime.
        // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

        // Entry point for the application.
        public static void Main(string[] args) =>
            WebApplication.Run<Startup>(args);
    }
}

// Copyright(c) 2015 Google Inc.

// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START sample]
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;

namespace GoogleCloudSamples
{
    public class Startup
    {
        // This method gets called by the runtime.
        // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

        // Entry point for the application.
        public static void Main(string[] args) =>
            WebApplication.Run<Startup>(args);
    }
}
// [END sample]

Add a regionTag for document inclusion.

Add a regionTag for document inclusion.

Change-Id: Ia86062b8fbf5afd1c455ea848da47be0e22d5b43


using System.Threading.Tasks;

namespace Discord.Commands
{
    public abstract class ModuleBase
    {
        public CommandContext Context { get; internal set; }

        protected virtual async Task ReplyAsync(string message, bool isTTS = false, RequestOptions options = null)
        {
            await Context.Channel.SendMessageAsync(message, isTTS, options).ConfigureAwait(false);
        }
    }
}

using System.Threading.Tasks;

namespace Discord.Commands
{
    public abstract class ModuleBase
    {
        public CommandContext Context { get; internal set; }

        protected virtual async Task<IUserMessage> ReplyAsync(string message, bool isTTS = false, RequestOptions options = null)
        {
            return await Context.Channel.SendMessageAsync(message, isTTS, options).ConfigureAwait(false);
        }
    }
}

Update ReplyAsync Task to return the sent message.


using UnityEngine;
using UnityEngine.UI;

public class SceneSelector : MonoBehaviour
{
    [SerializeField] private Text _levelName;
    [SerializeField] private string[] _levels;
    [SerializeField] private Button _leftArrow;
    [SerializeField] private Button _rightArrow;
    private int pos = 0;
    private LeaderboardUI _leaderboardUI;

    private void Start()
    {
        _leaderboardUI = FindObjectOfType<LeaderboardUI>();
        _levelName.text = _levels[pos];
        _leftArrow.gameObject.SetActive(false);
        if (_levels.Length <= 1) _rightArrow.gameObject.SetActive(false);
    }

    public void LeftArrowClick()
    {
        _levelName.text = _levels[--pos];
        if (pos == 0) _leftArrow.gameObject.SetActive(false);
        if (_levels.Length > 1) _rightArrow.gameObject.SetActive(true);
        _leaderboardUI.LoadScene(_levels[pos]);
    }

    public void RightArrowClick()
    {
        _levelName.text = _levels[++pos];
        if (_levels.Length <= pos + 1)_rightArrow.gameObject.SetActive(false);
        _leftArrow.gameObject.SetActive(true);
        _leaderboardUI.LoadScene(_levels[pos]);
    }
}

using System;
using UnityEngine;
using UnityEngine.UI;

public class SceneSelector : MonoBehaviour
{
    [SerializeField] private Text _levelName;
    [SerializeField] private string[] _levels;
    [SerializeField] private Button _leftArrow;
    [SerializeField] private Button _rightArrow;
    private int pos = 0;
    private LeaderboardUI _leaderboardUI;

    private void Start()
    {
        _leaderboardUI = FindObjectOfType<LeaderboardUI>();
        var levelShown = FindObjectOfType<LevelToLoad>().GetLevelToLoad();
        pos = GetPosOfLevelShown(levelShown);
        _levelName.text = _levels[pos];
        UpdateArrows();
    }

    private int GetPosOfLevelShown(string levelShown)
    {
        for (var i = 0; i < _levels.Length; ++i)
        {
            var level = _levels[i];
            if (level.IndexOf(levelShown, StringComparison.InvariantCultureIgnoreCase) > -1)
                return i;
        }
        //Defaults at loading the first entry if nothing found
        return 0;
    }

    public void LeftArrowClick()
    {
        _levelName.text = _levels[--pos];
        _leaderboardUI.LoadScene(_levels[pos]);
        UpdateArrows();
    }

    public void RightArrowClick()
    {
        _levelName.text = _levels[++pos];
        _leaderboardUI.LoadScene(_levels[pos]);
        UpdateArrows();
    }

    private void UpdateArrows()
    {
        _leftArrow.gameObject.SetActive(true);
        _rightArrow.gameObject.SetActive(true);
        if (pos == 0) _leftArrow.gameObject.SetActive(false);
        if (_levels.Length <= pos + 1)_rightArrow.gameObject.SetActive(false);
    }
}

Update the level selector input at the bottom of the leaderboard


namespace AngleSharp
{
    using System.Collections.Generic;
    using System.Threading.Tasks;

    /// <summary>
    /// Simple wrapper for static methods of Task, which are missing in older
    /// versions of the .NET-Framework.
    /// </summary>
    static class TaskEx
    {
        /// <summary>
        /// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
        /// same naming as TaskEx in BCL.Async.
        /// </summary>
        public static Task WhenAll(params Task[] tasks)
        {
            return Task.WhenAll(tasks);
        }

        /// <summary>
        /// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
        /// same naming as TaskEx in BCL.Async.
        /// </summary>
        public static Task WhenAll(IEnumerable<Task> tasks)
        {
            return Task.WhenAll(tasks);
        }

        /// <summary>
        /// Wrapper for Task.FromResult, but also works with .NET 4 and SL due
        /// to same naming as TaskEx in BCL.Async.
        /// </summary>
        public static Task<TResult> FromResult<TResult>(TResult result)
        {
            return Task.FromResult(result);
        }
    }
}

namespace System.Threading.Tasks
{
    using System.Collections.Generic;

    /// <summary>
    /// Simple wrapper for static methods of Task, which are missing in older
    /// versions of the .NET-Framework.
    /// </summary>
    static class TaskEx
    {
        /// <summary>
        /// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
        /// same naming as TaskEx in BCL.Async.
        /// </summary>
        public static Task WhenAll(params Task[] tasks)
        {
            return Task.WhenAll(tasks);
        }

        /// <summary>
        /// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
        /// same naming as TaskEx in BCL.Async.
        /// </summary>
        public static Task WhenAll(IEnumerable<Task> tasks)
        {
            return Task.WhenAll(tasks);
        }

        /// <summary>
        /// Wrapper for Task.FromResult, but also works with .NET 4 and SL due
        /// to same naming as TaskEx in BCL.Async.
        /// </summary>
        public static Task<TResult> FromResult<TResult>(TResult result)
        {
            return Task.FromResult(result);
        }
    }
}

Use official namespace (better for fallback)


using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Services
{
    public class UnitService
    {
        public static async Task<Unit> Get(Database db, int unitId)
        {
            return (await List(db, includeIgnored: true)).Single(unit => unit.Id == unitId);
        }

        public static async Task<IEnumerable<Unit>> List(Database db, Boolean includeIgnored = false)
        {
            return
                await db
                .Units
                .Include(unit => unit.Vehicles)
                .Include(unit => unit.Soldiers)
                    .ThenInclude(soldier => soldier.ABCPs)
                .Include(unit => unit.Soldiers)
                    .ThenInclude(soldier => soldier.APFTs)
                .Include(unit => unit.Soldiers)
                    .ThenInclude(soldier => soldier.SSDSnapshots)
                .Where(unit => includeIgnored || !unit.IgnoreForReports)
                .OrderBy(unit => unit.Name)
                .ToListAsync();
        }
    }
}

using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Services
{
    public class UnitService
    {
        public static async Task<Unit> Get(Database db, int unitId)
        {
            return (await List(db)).Single(unit => unit.Id == unitId);
        }

        public static async Task<IEnumerable<Unit>> List(Database db)
        {
            return
                await db
                .Units
                .Include(unit => unit.Vehicles)
                .Include(unit => unit.Soldiers)
                    .ThenInclude(soldier => soldier.ABCPs)
                .Include(unit => unit.Soldiers)
                    .ThenInclude(soldier => soldier.APFTs)
                .Include(unit => unit.Soldiers)
                    .ThenInclude(soldier => soldier.SSDSnapshots)
                .OrderBy(unit => unit.Name)
                .ToListAsync();
        }
    }
}

Remove unit service reference to ignore for reporting


using System;
using System.Windows.Controls;

namespace PackageExplorer {
    public class PublishUrlValidationRule : ValidationRule {

        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
            string stringValue = (string)value;
            Uri url;
            if (Uri.TryCreate(stringValue, UriKind.Absolute, out url)) {
                if (url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
                    url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase)) {
                    return ValidationResult.ValidResult;
                }
                else {
                    return new ValidationResult(false, "Publish url must be an HTTP or HTTPS address.");
                }
            }
            else {
                return new ValidationResult(false, "Invalid publish url.");
            }
        }
    }
}

using System;
using System.Windows.Controls;

namespace PackageExplorer {
    public class PublishUrlValidationRule : ValidationRule {

        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
            string stringValue = (string)value;
            Uri url;
            if (Uri.TryCreate(stringValue, UriKind.Absolute, out url)) {
                if (url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
                    url.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) {
                    return ValidationResult.ValidResult;
                }
                else {
                    return new ValidationResult(false, "Publish url must be an HTTP or HTTPS address.");
                }
            }
            else {
                return new ValidationResult(false, "Invalid publish url.");
            }
        }
    }
}

Fix binding validation which disallow publishing to HTTPS addresses.


using System;

namespace DDSReader.Console
{
	class Program
	{
		static void Main(string[] args)
		{
			var dds = new DDSImage(args[0]);
			dds.Save(args[1]);
		}
	}
}

using System;
using System.IO;

namespace DDSReader.Console
{
	class Program
	{
		static void Main(string[] args)
		{
			if (args.Length != 2)
			{
				System.Console.WriteLine("ERROR: input and output file required\n");
				Environment.Exit(1);
			}

			var input = args[0];
			var output = args[1];

			if (!File.Exists(input))
			{
				System.Console.WriteLine("ERROR: input file does not exist\n");
				Environment.Exit(1);
			}

			try
			{
				var dds = new DDSImage(input);
				dds.Save(output);
			}
			catch (Exception e)
			{
				System.Console.WriteLine("ERROR: failed to convert DDS file\n");
				System.Console.WriteLine(e);
				Environment.Exit(1);
			}

			if (File.Exists(output))
			{
				System.Console.WriteLine("Successfully created " + output);
			}
			else
			{
				System.Console.WriteLine("ERROR: something went wrong!\n");
				Environment.Exit(1);
			}
		}
	}
}

Add exception handling to console

Add exception handling to console


using System;
using System.Collections.Generic;
using CIV.Common;

namespace CIV.Ccs
{
    class PrefixProcess : CcsProcess
    {
        public String Label { get; set; }
        public CcsProcess Inner { get; set; }

		protected override IEnumerable<Transition> EnumerateTransitions()
		{
            return new List<Transition>{
                new Transition{
                    Label = Label,
                    Process = Inner
                }
            };
        }
		protected override string BuildRepr()
		{
            return $"{Label}{Const.prefix}{Inner}";
        }

    }
}

using System;
using System.Collections.Generic;
using CIV.Common;

namespace CIV.Ccs
{
    class PrefixProcess : CcsProcess
    {
        public String Label { get; set; }
        public CcsProcess Inner { get; set; }

        protected override IEnumerable<Transition> EnumerateTransitions()
        {
			yield return new Transition
			{
			    Label = Label,
			    Process = Inner
			};
			}
        protected override string BuildRepr()
        {
            return $"{Label}{Const.prefix}{Inner}";
        }

    }
}

Use “yield” instead of List for GetTransitions


using System.Net.Http;
using System.Threading.Tasks;

namespace FluentMetacritic.Net
{
    public class HttpClientWrapper : IHttpClient
    {
        private static readonly HttpClient Client = new HttpClient();

        public async Task<string> GetContentAsync(string address)
        {
            return await Client.GetStringAsync(address);
        }
    }
}

using System.Net.Http;
using System.Threading.Tasks;

namespace FluentMetacritic.Net
{
    public class HttpClientWrapper : IHttpClient
    {
        private static readonly HttpClient Client;

        static HttpClientWrapper()
        {
            Client = new HttpClient();
            Client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.11 Safari/537.36");
        }

        public async Task<string> GetContentAsync(string address)
        {
            return await Client.GetStringAsync(address);
        }
    }
}

Set UserAgent on HTTP Client.

Set UserAgent on HTTP Client.


namespace AgileObjects.AgileMapper.ObjectPopulation
{
    using System.Linq.Expressions;
    using DataSources;
    using Extensions;
    using Members;

    internal class ExistingOrDefaultValueDataSourceFactory : IDataSourceFactory
    {
        public static readonly IDataSourceFactory Instance = new ExistingOrDefaultValueDataSourceFactory();

        public IDataSource Create(IMemberMappingData mappingData)
            => mappingData.MapperData.TargetMember.IsReadable
                ? new ExistingMemberValueOrEmptyDataSource(mappingData.MapperData)
                : DefaultValueDataSourceFactory.Instance.Create(mappingData);

        private class ExistingMemberValueOrEmptyDataSource : DataSourceBase
        {
            public ExistingMemberValueOrEmptyDataSource(IMemberMapperData mapperData)
                : base(mapperData.SourceMember, GetValue(mapperData), mapperData)
            {
            }

            private static Expression GetValue(IMemberMapperData mapperData)
            {
                var existingValue = mapperData.GetTargetMemberAccess();

                if (!mapperData.TargetMember.IsEnumerable)
                {
                    return existingValue;
                }

                var existingValueNotNull = existingValue.GetIsNotDefaultComparison();
                var emptyEnumerable = mapperData.TargetMember.GetEmptyInstanceCreation();

                return Expression.Condition(
                    existingValueNotNull,
                    existingValue,
                    emptyEnumerable,
                    existingValue.Type);
            }
        }
    }
}

namespace AgileObjects.AgileMapper.ObjectPopulation
{
    using System.Linq.Expressions;
    using DataSources;
    using Members;

    internal class ExistingOrDefaultValueDataSourceFactory : IDataSourceFactory
    {
        public static readonly IDataSourceFactory Instance = new ExistingOrDefaultValueDataSourceFactory();

        public IDataSource Create(IMemberMappingData mappingData)
            => mappingData.MapperData.TargetMember.IsReadable
                ? new ExistingMemberValueOrEmptyDataSource(mappingData.MapperData)
                : DefaultValueDataSourceFactory.Instance.Create(mappingData);

        private class ExistingMemberValueOrEmptyDataSource : DataSourceBase
        {
            public ExistingMemberValueOrEmptyDataSource(IMemberMapperData mapperData)
                : base(mapperData.SourceMember, GetValue(mapperData), mapperData)
            {
            }

            private static Expression GetValue(IMemberMapperData mapperData)
            {
                var existingValue = mapperData.GetTargetMemberAccess();

                if (!mapperData.TargetMember.IsEnumerable)
                {
                    return existingValue;
                }

                var emptyEnumerable = mapperData.TargetMember.GetEmptyInstanceCreation();

                return Expression.Coalesce(existingValue, emptyEnumerable);
            }
        }
    }
}

Revert "Using ternary instead of coalesce in fallback enumerable value selection"

This reverts commit 1f2b459fd70323866b9443e388a77368e194e5ed.


using BeekmanLabs.UnitTesting;
using IntegrationEngine.JobProcessor;
using NUnit.Framework;
using Moq;
using System;
using System.Threading;

namespace IntegrationEngine.Tests.JobProcessor
{
    public class MessageQueueListenerManagerTest : TestBase<MessageQueueListenerManager>
    {
        public Mock<MessageQueueListenerFactory> MockMessageQueueListenerFactory { get; set; }

        [SetUp]
        public void Setup()
        {
            MockMessageQueueListenerFactory = new Mock<MessageQueueListenerFactory>();
            MockMessageQueueListenerFactory.Setup(x => x.CreateRabbitMQListener())
                .Returns<IMessageQueueListener>(null);
            Subject.MessageQueueListenerFactory = MockMessageQueueListenerFactory.Object;
        }

        [Test]
        public void ShouldStartListener()
        {
            Subject.ListenerTaskCount = 1;

            Subject.StartListener();

            MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(), Times.Once);
        }

        [Test]
        public void ShouldStartMultipleListeners()
        {
            var listenerTaskCount = 3;
            Subject.ListenerTaskCount = listenerTaskCount;

            Subject.StartListener();

            MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(),
                Times.Exactly(listenerTaskCount));
        }

        [Test]
        public void ShouldSetCancellationTokenOnDispose()
        {
            Subject.CancellationTokenSource = new CancellationTokenSource();

            Subject.Dispose();

            Assert.That(Subject.CancellationTokenSource.IsCancellationRequested, Is.True);
        }
    }
}

using BeekmanLabs.UnitTesting;
using IntegrationEngine.JobProcessor;
using NUnit.Framework;
using Moq;
using System;
using System.Threading;

namespace IntegrationEngine.Tests.JobProcessor
{
    public class MessageQueueListenerManagerTest : TestBase<MessageQueueListenerManager>
    {
        public Mock<MessageQueueListenerFactory> MockMessageQueueListenerFactory { get; set; }

        [SetUp]
        public void Setup()
        {
            MockMessageQueueListenerFactory = new Mock<MessageQueueListenerFactory>();
            MockMessageQueueListenerFactory.Setup(x => x.CreateRabbitMQListener())
                .Returns<IMessageQueueListener>(null);
            Subject.MessageQueueListenerFactory = MockMessageQueueListenerFactory.Object;
        }

        [Test]
        public void ShouldStartListener()
        {
            Subject.ListenerTaskCount = 1;

            Subject.StartListener();

            MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(), Times.Once);
        }

        [Test]
        public void ShouldStartMultipleListeners()
        {
            var listenerTaskCount = 10;
            Subject.ListenerTaskCount = listenerTaskCount;

            Subject.StartListener();

            MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(),
                Times.Exactly(listenerTaskCount));
        }

        [Test]
        public void ShouldSetCancellationTokenOnDispose()
        {
            Subject.CancellationTokenSource = new CancellationTokenSource();

            Subject.Dispose();

            Assert.That(Subject.CancellationTokenSource.IsCancellationRequested, Is.True);
        }
    }
}

Test launching 10 listeners in CI

Test launching 10 listeners in CI


namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
    using Basic;
    using Newtonsoft.Json;

    /// <summary>
    /// A collection of images for a Trakt season.
    /// </summary>
    public class TraktSeasonImages
    {
        /// <summary>
        /// A poster image set for various sizes.
        /// </summary>
        [JsonProperty(PropertyName = "poster")]
        public TraktImageSet Poster { get; set; }

        /// <summary>
        /// A thumbnail image.
        /// </summary>
        [JsonProperty(PropertyName = "thumb")]
        public TraktImage Thumb { get; set; }
    }
}

namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
    using Basic;
    using Newtonsoft.Json;

    /// A collection of images and image sets for a Trakt season.
    public class TraktSeasonImages
    {
        /// Gets or sets the screenshot image set.
        [JsonProperty(PropertyName = "poster")]
        public TraktImageSet Poster { get; set; }

        /// Gets or sets the thumb image.
        [JsonProperty(PropertyName = "thumb")]
        public TraktImage Thumb { get; set; }
    }
}

Add get best id method for season images.


using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;

[assembly: RequiresSTA]

namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
    [ZoneDefinition]
    public interface IYamlTestZone : ITestsEnvZone, IRequire<PsiFeatureTestZone>
    {
    }

    [SetUpFixture]
    public class TestEnvironment : ExtensionTestEnvironmentAssembly<IYamlTestZone>
    {
    }
}

using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;

[assembly: RequiresSTA]

// This attribute is marked obsolete but is still supported. Use is discouraged in preference to convention, but the
// convention doesn't work for us. That convention is to walk up the tree from the executing assembly and look for a
// relative path called "test/data". This doesn't work because our common "build" folder is one level above our
// "test/data" folder, so it doesn't get found. We want to keep the common "build" folder, but allow multiple "modules"
// with separate "test/data" folders. E.g. "resharper-unity" and "resharper-yaml"

// TODO: This makes things work when building as part of the Unity project, but breaks standalone
// Maybe it should be using product/subplatform markers?
#pragma warning disable 618
[assembly: TestDataPathBase("resharper-yaml/test/data")]
#pragma warning restore 618

namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
    [ZoneDefinition]
    public interface IYamlTestZone : ITestsEnvZone, IRequire<PsiFeatureTestZone>
    {
    }

    [SetUpFixture]
    public class TestEnvironment : ExtensionTestEnvironmentAssembly<IYamlTestZone>
    {
    }
}

Fix test data path when building in Unity plugin


using Newtonsoft.Json;

namespace SurveyMonkey.Containers
{
    [JsonConverter(typeof(TolerantJsonConverter))]
    public class ResponseAnswer
    {
        public long? ChoiceId { get; set; }
        public long? RowId { get; set; }
        public long? ColId { get; set; }
        public long? OtherId { get; set; }
        public string Text { get; set; }
        public bool? IsCorrect { get; set; }
        public int? Score { get; set; }
        public string SimpleText { get; set; }
        [JsonIgnore]
        internal object TagData { get; set; }
        public ChoiceMetadata ChoiceMetadata { get; set; }
    }
}

using Newtonsoft.Json;

namespace SurveyMonkey.Containers
{
    [JsonConverter(typeof(TolerantJsonConverter))]
    public class ResponseAnswer
    {
        public long? ChoiceId { get; set; }
        public long? RowId { get; set; }
        public long? ColId { get; set; }
        public long? OtherId { get; set; }
        public string Text { get; set; }
        public bool? IsCorrect { get; set; }
        public int? Score { get; set; }
        public string DownloadUrl { get; set; }
        public string ContentType { get; set; }
        public string SimpleText { get; set; }
        [JsonIgnore]
        internal object TagData { get; set; }
        public ChoiceMetadata ChoiceMetadata { get; set; }
    }
}

Add download_url and content_type for file upload questions


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WPAppStudio.Services.Interfaces;

namespace WPAppStudio.Services
{
    public class WordWrapService
    {
        private readonly ITextMeasurementService _tms;

        public WordWrapService(ITextMeasurementService textMeasurementService)
        {
            _tms = textMeasurementService;
        }

        public string GetWords(string text, int wordCount)
        {

            StringBuilder result = new StringBuilder();

            for (int word = 0; word < wordCount; word++)
            {
                int space = text.IndexOf(' ', 1);
                //return text.Substring(0, space);
                if (space == -1)
                {
                    result.Append(text);
                    return result.ToString();
                }
                result.Append(text.Substring(0, space));
                text = text.Substring(space);

            }

            return result.ToString();
        }

        public string GetLine(string text, int lineLength)
        {
            for (int wordCount = 10; wordCount > 0; wordCount--)
            {
                string line = GetWords(text, wordCount);

                int width = _tms.GetTextWidth(line);

                if (width <= lineLength)
                {
                    return line;
                }
            }

            return GetWords(text, 1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WPAppStudio.Services.Interfaces;

namespace WPAppStudio.Services
{
    public class WordWrapService
    {
        private readonly ITextMeasurementService _tms;

        public WordWrapService(ITextMeasurementService textMeasurementService)
        {
            _tms = textMeasurementService;
        }

        public string GetWords(string text, int wordCount)
        {

            StringBuilder result = new StringBuilder();

            for (int word = 0; word < wordCount; word++)
            {
                int space = text.IndexOf(' ', 1);
                //return text.Substring(0, space);
                if (space == -1)
                {
                    result.Append(text);
                    return result.ToString();
                }
                result.Append(text.Substring(0, space));
                text = text.Substring(space);

            }

            return result.ToString();
        }

        public string GetLine(string text, int lineLength)
        {
            string line = GetWords(text, 3);

            int width = _tms.GetTextWidth(line);

            if (width <= lineLength)
            {
                return line;
            }

            return GetWords(text, 1);
        }
    }
}

Revert "And we have the medium line working!"

This reverts commit 2c642200074b3a3d882a95530f053656346ac05d.


using System;
using System.Linq;

namespace Smartrak.Collections.Paging
{
	public static class PagingHelpers
	{
		/// <summary>
		/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
		/// </summary>
		/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
		/// <param name="entities">A queryable of entities</param>
		/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
		/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
		/// <returns>A queryable of the page of entities with counts appended.</returns>
		public static IQueryable<EntityWithCount<T>> GetPageWithTotal<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
		{
			if (entities == null)
			{
				throw new ArgumentNullException("entities");
			}
			if (page < 1)
			{
				throw new ArgumentException("Must be positive", "page");
			}
			if (pageSize < 1)
			{
				throw new ArgumentException("Must be positive", "pageSize");
			}

			return entities
				.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
				.Skip(page - 1 * pageSize)
				.Take(pageSize);
		}
	}
}

using System;
using System.Linq;

namespace Smartrak.Collections.Paging
{
	public static class PagingHelpers
	{
		/// <summary>
		/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
		/// </summary>
		/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
		/// <param name="entities">A queryable of entities</param>
		/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
		/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
		/// <returns>A queryable of the page of entities with counts appended.</returns>
		public static IQueryable<EntityWithCount<T>> GetPageWithTotalzzz<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
		{
			if (entities == null)
			{
				throw new ArgumentNullException("entities");
			}
			if (page < 1)
			{
				throw new ArgumentException("Must be positive", "page");
			}
			if (pageSize < 1)
			{
				throw new ArgumentException("Must be positive", "pageSize");
			}

			return entities
				.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
				.Skip(page - 1 * pageSize)
				.Take(pageSize);
		}
	}
}

Revert "Removing 'zzz' from method name"

This reverts commit e32baff273074950f07a718edfac63933a00a420.


using System;
using System.Diagnostics;
using System.Threading;

namespace ProcessRelauncher
{
    public class ProcessMonitor : IDisposable
    {
        private Timer _timer;
        private readonly int _monitoringPollingIntervalMs;
        private readonly ProcessStartInfo _processStartInfo;
        private readonly string _processName;

        public ProcessMonitor(string processName, ProcessStartInfo launcher, int monitoringPollingIntervalMs)
        {
            _processStartInfo = launcher;
            _processName = processName.ToLower();
            _monitoringPollingIntervalMs = monitoringPollingIntervalMs;
        }

        public void Monitor(object o)
        {
            Process[] processlist = Process.GetProcesses();

            foreach(var p in processlist)
            {
                if (p.ProcessName.ToLower().Equals(_processName)) return;
            }

            Process.Start(_processStartInfo);

            GC.Collect();
        }

        public void Start()
        {
            if (_timer != null) return;

            _timer = new Timer(this.Monitor, null, 0, _monitoringPollingIntervalMs);
        }

        public void Dispose()
        {
            _timer.Dispose();
        }
    }
}

using System;
using System.Diagnostics;
using System.Threading;

namespace ProcessRelauncher
{
    public class ProcessMonitor : IDisposable
    {
        private Timer _timer;
        private readonly int _monitoringPollingIntervalMs;
        private readonly ProcessStartInfo _processStartInfo;
        private readonly string _processName;

        public ProcessMonitor(string processName, ProcessStartInfo launcher, int monitoringPollingIntervalMs)
        {
            _processStartInfo = launcher;
            _processName = processName.ToLower();
            _monitoringPollingIntervalMs = monitoringPollingIntervalMs;
        }

        public void Monitor(object o)
        {
            Process[] processlist = Process.GetProcesses();

            foreach (var p in processlist)
            {
                if (p.ProcessName.ToLower().Equals(_processName)) return;
            }

            Process.Start(_processStartInfo);
            processlist = null;

            GC.Collect();
        }

        public void Start()
        {
            if (_timer != null) return;

            _timer = new Timer(this.Monitor, null, 0, _monitoringPollingIntervalMs);
        }

        public void Dispose()
        {
            if (_timer == null) return;

            _timer.Dispose();
        }
    }
}

Enable the GC to clean up the process list immediately. Fixed potential null reference when disposing before starting.


using System;

namespace Hangman {
  public class Hangman {
    public static void Main(string[] args) {
      Table table = new Table(2, 3);
      string output = table.Draw();

      Console.WriteLine(output);
    }
  }
}

using System;

namespace Hangman {
  public class Hangman {
    public static void Main(string[] args) {
      // Table table = new Table(2, 3);
      // string output = table.Draw();

      // Console.WriteLine(output);
    }
  }
}

Comment out the code in Hangman that uses Table

To focus on the development of game logic


namespace BaiduHiCrawler
{
    using System;

    static class Constants
    {
        public const string CommentRetrivalUrlPattern =
            "http://hi.baidu.com/qcmt/data/cmtlist?qing_request_source=new_request&thread_id_enc={0}&start={1}&count={2}&orderby_type=0&favor=2&type=smblog";

        public const string LocalArchiveFolder = @".\Archive\";

        public const string LogsFolder = @".\Logs\";

        public static readonly Uri LoginUri = new Uri("http://hi.baidu.com/go/login");

        public static readonly Uri HomeUri = new Uri("http://hi.baidu.com/home");

        public static readonly DateTime CommentBaseDateTime = new DateTime(1970, 1, 1, 0, 0, 0);

        public static readonly LogLevel LogLevel = LogLevel.Verbose;
    }
}

namespace BaiduHiCrawler
{
    using System;

    static class Constants
    {
        public const string CommentRetrivalUrlPattern =
            "http://hi.baidu.com/qcmt/data/cmtlist?qing_request_source=new_request&thread_id_enc={0}&start={1}&count={2}&orderby_type=0&favor=2&type=smblog";

        public const string LocalArchiveFolder = @".\Archive\";

        public const string LogsFolder = @".\Logs\";

        public static readonly Uri LoginUri = new Uri("http://hi.baidu.com/go/login");

        public static readonly Uri HomeUri = new Uri("http://hi.baidu.com/home");

        public static readonly DateTime CommentBaseDateTime = new DateTime(1970, 1, 1, 0, 0, 0);

        public static readonly LogLevel LogLevel = LogLevel.Warning;
    }
}

Set LogLevel in master branch to Warning


using System.Collections.Generic;
using Rocket.API;
using RocketRegions.Model;

namespace RocketRegions
{
    public class RegionsConfiguration : IRocketPluginConfiguration
    {
        public int UpdateFrameCount;
        public List<Region> Regions;
        public string UrlOpenMessage;

        public void LoadDefaults()
        {
            Regions = new List<Region>();
            UpdateFrameCount = 1;
            UrlOpenMessage = "Visit webpage";
        }
    }
}

using System.Collections.Generic;
using Rocket.API;
using RocketRegions.Model;

namespace RocketRegions
{
    public class RegionsConfiguration : IRocketPluginConfiguration
    {
        public int UpdateFrameCount;
        public List<Region> Regions;
        public string UrlOpenMessage;

        public void LoadDefaults()
        {
            Regions = new List<Region>();
            UpdateFrameCount = 10;
            UrlOpenMessage = "Visit webpage";
        }
    }
}

Set default <UpdateFrameCount> to 10

Set default <UpdateFrameCount> to 10


using System.ComponentModel;
using System.Windows;

namespace DesktopWidgets.Actions
{
    internal class PopupAction : ActionBase
    {
        [DisplayName("Text")]
        public string Text { get; set; } = "";

        [DisplayName("Title")]
        public string Title { get; set; } = "";

        [DisplayName("Image")]
        public MessageBoxImage Image { get; set; }

        protected override void ExecuteAction()
        {
            base.ExecuteAction();
            MessageBox.Show(Text, Title, MessageBoxButton.OK, Image);
        }
    }
}

using System.ComponentModel;
using System.IO;
using System.Windows;
using DesktopWidgets.Classes;

namespace DesktopWidgets.Actions
{
    internal class PopupAction : ActionBase
    {
        public FilePath FilePath { get; set; } = new FilePath();

        [DisplayName("Text")]
        public string Text { get; set; } = "";

        [DisplayName("Input Mode")]
        public InputMode InputMode { get; set; } = InputMode.Text;

        [DisplayName("Title")]
        public string Title { get; set; } = "";

        [DisplayName("Image")]
        public MessageBoxImage Image { get; set; }

        protected override void ExecuteAction()
        {
            base.ExecuteAction();
            var input = string.Empty;
            switch (InputMode)
            {
                case InputMode.Clipboard:
                    input = Clipboard.GetText();
                    break;
                case InputMode.File:
                    input = File.ReadAllText(FilePath.Path);
                    break;
                case InputMode.Text:
                    input = Text;
                    break;
            }
            MessageBox.Show(input, Title, MessageBoxButton.OK, Image);
        }
    }
}

Add "Input Mode", "File" options to "Popup" action


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace GarrysMod.AddonCreator
{
    public class AddonJson
    {
        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("tags")]
        public List<string> Tags { get; set; }

        [JsonProperty("ignore")]
        public List<string> Ignores { get; set; }

        public void CheckForErrors()
        {
            if (string.IsNullOrEmpty(Title))
            {
                throw new MissingFieldException("Title is empty or not specified.");
            }

            if (!string.IsNullOrEmpty(Description) && Description.Contains('\0'))
            {
                throw new InvalidDataException("Description contains NULL character.");
            }

            if (string.IsNullOrEmpty(Type))
            {
                throw new MissingFieldException("Type is empty or not specified.");
            }
        }

        public void RemoveIgnoredFiles(ref Dictionary<string, AddonFileInfo> files)
        {
            foreach (var key in files.Keys.ToArray())
                // ToArray makes a shadow copy of Keys to avoid "mid-loop-removal" conflicts
            {
                if (Ignores.Any(w => w.WildcardRegex().IsMatch(key)))
                    files.Remove(key);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace GarrysMod.AddonCreator
{
    public class AddonJson
    {
        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("tags")]
        public List<string> Tags { get; set; }

        [JsonProperty("ignore")]
        public List<string> Ignores { get; set; }

        [JsonProperty("version")]
        public int Version { get; set; }

        internal void CheckForErrors()
        {
            if (string.IsNullOrEmpty(Title))
            {
                throw new MissingFieldException("Title is empty or not specified.");
            }

            if (!string.IsNullOrEmpty(Description) && Description.Contains('\0'))
            {
                throw new InvalidDataException("Description contains NULL character.");
            }

            if (string.IsNullOrEmpty(Type))
            {
                throw new MissingFieldException("Type is empty or not specified.");
            }
        }

        public void RemoveIgnoredFiles(ref Dictionary<string, AddonFileInfo> files)
        {
            foreach (var key in files.Keys.ToArray())
                // ToArray makes a shadow copy of Keys to avoid "mid-loop-removal" conflicts
            {
                if (Ignores.Any(w => w.WildcardRegex().IsMatch(key)))
                    files.Remove(key);
            }
        }
    }
}

Add version field and make CheckForErrors less accessible from outside.


using System;
using System.Diagnostics;

using Xamarin.Forms;

using InteractApp;

namespace InteractApp
{
	public class EventListPageBase : ViewPage<EventListPageViewModel>
	{

	}

	public partial class EventListPage : EventListPageBase
	{
		public EventListPage ()
		{
			InitializeComponent ();

			this.Title = "Events";
			Padding = new Thickness (0, 0, 0, 0);

			ToolbarItems.Add (new ToolbarItem {
				Text = "My Info",
				Order = ToolbarItemOrder.Primary,
				Command = new Command (this.ShowMyInfoPage),
			});

			ToolbarItems.Add (new ToolbarItem {
				Text = "My Events",
				Order = ToolbarItemOrder.Primary,
			});

			//To hide iOS list seperator
			EventList.SeparatorVisibility = SeparatorVisibility.None;

			ViewModel.LoadEventsCommand.Execute (null);

			EventList.ItemTapped += async (sender, e) => {
				Event evt = (Event)e.Item;
				Debug.WriteLine ("Tapped: " + (evt.Name));
				var page = new EventInfoPage (evt);
				((ListView)sender).SelectedItem = null;
				await Navigation.PushAsync (page);
			};
		}

		private void ShowMyInfoPage ()
		{
			Navigation.PushAsync (new MyInfoPage ());
		}
	}
}

using System;
using System.Diagnostics;

using Xamarin.Forms;

using InteractApp;

namespace InteractApp
{
	public class EventListPageBase : ViewPage<EventListPageViewModel>
	{

	}

	public partial class EventListPage : EventListPageBase
	{
		public EventListPage ()
		{
			InitializeComponent ();

			this.Title = "Events";
			Padding = new Thickness (0, 0, 0, 0);

//			ToolbarItems.Add (new ToolbarItem {
//				Text = "My Info",
//				Order = ToolbarItemOrder.Primary,
//				Command = new Command (this.ShowMyInfoPage),
//			});

//			ToolbarItems.Add (new ToolbarItem {
//				Text = "My Events",
//				Order = ToolbarItemOrder.Primary,
//			});

			//To hide iOS list seperator
			EventList.SeparatorVisibility = SeparatorVisibility.None;

			ViewModel.LoadEventsCommand.Execute (null);

			EventList.ItemTapped += async (sender, e) => {
				Event evt = (Event)e.Item;
				Debug.WriteLine ("Tapped: " + (evt.Name));
				var page = new EventInfoPage (evt);
				((ListView)sender).SelectedItem = null;
				await Navigation.PushAsync (page);
			};
		}

		private void ShowMyInfoPage ()
		{
			Navigation.PushAsync (new MyInfoPage ());
		}
	}
}

Remove unused Toolbar options until we actually make use of them


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using PolarisServer.Packets;

namespace PolarisServer.Models
{
    public class PSOObject
    {
        public struct PSOObjectThing
        {
            public UInt32 data;
        }

        public EntityHeader Header { get; set; }
        public MysteryPositions Position { get; set; }
        public string Name { get; set; }
        public UInt32 ThingFlag { get; set; }
        public PSOObjectThing[] things { get; set; }

        public byte[] GenerateSpawnBlob()
        {
            PacketWriter writer = new PacketWriter();
            writer.WriteStruct(Header);
            writer.WriteStruct(Position);
            writer.Seek(2, SeekOrigin.Current); // Padding I guess...
            writer.WriteFixedLengthASCII(Name, 0x34);
            writer.Write(ThingFlag);
            writer.Write(things.Length);
            foreach (PSOObjectThing thing in things)
            {
                writer.WriteStruct(thing);
            }

            return writer.ToArray();

        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using PolarisServer.Packets;

namespace PolarisServer.Models
{
    public class PSOObject
    {
        public struct PSOObjectThing
        {
            public UInt32 data;
        }

        public EntityHeader Header { get; set; }
        public MysteryPositions Position { get; set; }
        public string Name { get; set; }
        public UInt32 ThingFlag { get; set; }
        public PSOObjectThing[] things { get; set; }

        public byte[] GenerateSpawnBlob()
        {
            PacketWriter writer = new PacketWriter();
            writer.WriteStruct(Header);
            writer.Write(Position);
            writer.Seek(2, SeekOrigin.Current); // Padding I guess...
            writer.WriteFixedLengthASCII(Name, 0x34);
            writer.Write(ThingFlag);
            writer.Write(things.Length);
            foreach (PSOObjectThing thing in things)
            {
                writer.WriteStruct(thing);
            }

            return writer.ToArray();

        }
    }
}

Write Position using the Position Writer Function


using System;
using System.IO;
using System.Linq;
using Villermen.RuneScapeCacheTools.Audio.Vorbis;
using Xunit;
using Xunit.Abstractions;

namespace RuneScapeCacheToolsTests
{
    public class VorbisTests : IDisposable
    {
        private ITestOutputHelper Output { get; }

        private VorbisReader Reader1 { get; }
        private VorbisReader Reader2 { get; }
        private VorbisWriter Writer { get; }

        public VorbisTests(ITestOutputHelper output)
        {
            Output = output;

            Reader1 = new VorbisReader(File.OpenRead("testdata/sample1.ogg"));
            Reader2 = new VorbisReader(File.OpenRead("testdata/sample2.ogg"));

            Writer = new VorbisWriter(File.OpenWrite("out.ogg"));
        }

        [Fact]
        public void TestReadComments()
        {
            Reader1.ReadPacket();
            var commentPacket = Reader1.ReadPacket();

            Output.WriteLine($"Type of packet: {commentPacket.GetType().FullName}");

            Assert.IsType<VorbisCommentHeader>(commentPacket);

            var commentHeader = (VorbisCommentHeader)commentPacket;

            Output.WriteLine("Comments in header:");
            foreach (var userComment in commentHeader.UserComments)
            {
                Output.WriteLine($" - {userComment.Item1}: {userComment.Item2}");
            }

            Assert.True(commentHeader.UserComments.Contains(new Tuple<string, string>("genre", "Soundtrack")));
        }

        public void Dispose()
        {
            Reader1?.Dispose();
            Reader2?.Dispose();
            Writer?.Dispose();
        }
    }
}

using System;
using System.IO;
using System.Linq;
using Villermen.RuneScapeCacheTools.Audio.Vorbis;
using Xunit;
using Xunit.Abstractions;

namespace RuneScapeCacheToolsTests
{
    public class VorbisTests : IDisposable
    {
        private ITestOutputHelper Output { get; }

        private VorbisReader Reader1 { get; }
        private VorbisReader Reader2 { get; }
        private VorbisWriter Writer { get; }

        public VorbisTests(ITestOutputHelper output)
        {
            Output = output;

            Reader1 = new VorbisReader(File.OpenRead("testdata/sample1.ogg"));
            Reader2 = new VorbisReader(File.OpenRead("testdata/sample2.ogg"));

            Writer = new VorbisWriter(File.OpenWrite("out.ogg"));
        }

        [Fact]
        public void TestReadComments()
        {
            Reader1.ReadPacket();
            var commentPacket = Reader1.ReadPacket();

            Output.WriteLine($"Type of packet: {commentPacket.GetType().FullName}");

            Assert.IsType<VorbisCommentHeader>(commentPacket);

            var commentHeader = (VorbisCommentHeader)commentPacket;

            Output.WriteLine("Comments in header:");
            foreach (var userComment in commentHeader.UserComments)
            {
                Output.WriteLine($" - {userComment.Item1}: {userComment.Item2}");
            }

            Assert.True(commentHeader.UserComments.Contains(new Tuple<string, string>("DATE", "2012")));
        }

        public void Dispose()
        {
            Reader1?.Dispose();
            Reader2?.Dispose();
            Writer?.Dispose();
        }
    }
}

Change comment test to reflect changed samples


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

using DAQ.Environment;

namespace DAQ.HAL
{
    public class Agilent53131A : FrequencyCounter
    {
        public Agilent53131A(String visaAddress) : base(visaAddress)
		{}

        public override double Frequency
        {
            get
            {
                if (!Environs.Debug)
                {
                    Write(":FUNC 'FREQ 1'");
                    Write(":FREQ:ARM:STAR:SOUR IMM");
                    Write(":FREQ:ARM:STOP:SOUR TIM");
                    Write(":FREQ:ARM:STOP:TIM 1.0");
                    Write("READ:FREQ?");
                    string fr = Read();
                    return Double.Parse(fr);
                }
                else
                {
                    return 170.730 + (new Random()).NextDouble();
                }
            }
        }

        public override double Amplitude
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }
    }
}

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

using DAQ.Environment;

namespace DAQ.HAL
{
    public class Agilent53131A : FrequencyCounter
    {
        public Agilent53131A(String visaAddress) : base(visaAddress)
		{}

        public override double Frequency
        {
            get
            {
                if (!Environs.Debug)
                {
                    Connect();
                    Write(":FUNC 'FREQ 1'");
                    Write(":FREQ:ARM:STAR:SOUR IMM");
                    Write(":FREQ:ARM:STOP:SOUR TIM");
                    Write(":FREQ:ARM:STOP:TIM 1.0");
                    Write("READ:FREQ?");
                    string fr = Read();
                    Disconnect();
                    return Double.Parse(fr);
                }
                else
                {
                    return 170.730 + (new Random()).NextDouble();
                }
            }
        }

        public override double Amplitude
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }
    }
}

Fix a little bug with the new counter. The rf frequency measurement is now tested and works.


@model Vaskelista.Models.Household

@{
    ViewBag.Title = "Create";
}

Velkommen til vaskelista

Her kan du velge hva vaskelisten din skal hete:

@Request.Url.ToString()

                        @foreach (string randomUrl in ViewBag.RandomUrls)
                        {

                                @using (Html.BeginForm("Create", "Household", FormMethod.Post))
                                {
                                    @Html.AntiForgeryToken()
                                    @Html.HiddenFor(model => model.Token, new { Value = randomUrl })
                                    <input type="submit" value="@randomUrl" class="btn btn-default" />
                                }

                        }

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Decrease bootstrap column sizes to improve mobile experience


namespace TAUtil.Gaf.Structures
{
    using System.IO;

    public struct GafFrameData
    {
        public ushort Width;
        public ushort Height;
        public ushort XPos;
        public ushort YPos;
        public byte Unknown1;
        public bool Compressed;
        public ushort FramePointers;
        public uint Unknown2;
        public uint PtrFrameData;
        public uint Unknown3;

        public static void Read(BinaryReader b, ref GafFrameData e)
        {
            e.Width = b.ReadUInt16();
            e.Height = b.ReadUInt16();
            e.XPos = b.ReadUInt16();
            e.YPos = b.ReadUInt16();
            e.Unknown1 = b.ReadByte();
            e.Compressed = b.ReadBoolean();
            e.FramePointers = b.ReadUInt16();
            e.Unknown2 = b.ReadUInt32();
            e.PtrFrameData = b.ReadUInt32();
            e.Unknown3 = b.ReadUInt32();
        }
    }
}

namespace TAUtil.Gaf.Structures
{
    using System.IO;

    public struct GafFrameData
    {
        public ushort Width;
        public ushort Height;
        public ushort XPos;
        public ushort YPos;
        public byte TransparencyIndex;
        public bool Compressed;
        public ushort FramePointers;
        public uint Unknown2;
        public uint PtrFrameData;
        public uint Unknown3;

        public static void Read(BinaryReader b, ref GafFrameData e)
        {
            e.Width = b.ReadUInt16();
            e.Height = b.ReadUInt16();
            e.XPos = b.ReadUInt16();
            e.YPos = b.ReadUInt16();
            e.TransparencyIndex = b.ReadByte();
            e.Compressed = b.ReadBoolean();
            e.FramePointers = b.ReadUInt16();
            e.Unknown2 = b.ReadUInt32();
            e.PtrFrameData = b.ReadUInt32();
            e.Unknown3 = b.ReadUInt32();
        }
    }
}

Rename previously unknown GAF field

Rename previously unknown GAF field


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

using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.UserInterfaceV2;

namespace osu.Game.Screens.Edit.Timing
{
    internal class SampleSection : Section<SampleControlPoint>
    {
        private LabelledTextBox bank;
        private SliderWithTextBoxInput<int> volume;

        [BackgroundDependencyLoader]
        private void load()
        {
            Flow.AddRange(new Drawable[]
            {
                bank = new LabelledTextBox
                {
                    Label = "Bank Name",
                },
                volume = new SliderWithTextBoxInput<int>("Volume")
                {
                    Current = new SampleControlPoint().SampleVolumeBindable,
                }
            });
        }

        protected override void OnControlPointChanged(ValueChangedEvent<SampleControlPoint> point)
        {
            if (point.NewValue != null)
            {
                bank.Current = point.NewValue.SampleBankBindable;
                volume.Current = point.NewValue.SampleVolumeBindable;
            }
        }

        protected override SampleControlPoint CreatePoint()
        {
            var reference = Beatmap.Value.Beatmap.ControlPointInfo.SamplePointAt(SelectedGroup.Value.Time);

            return new SampleControlPoint
            {
                SampleBank = reference.SampleBank,
                SampleVolume = reference.SampleVolume,
            };
        }
    }
}

// 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.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.UserInterfaceV2;

namespace osu.Game.Screens.Edit.Timing
{
    internal class SampleSection : Section<SampleControlPoint>
    {
        private LabelledTextBox bank;
        private SliderWithTextBoxInput<int> volume;

        [BackgroundDependencyLoader]
        private void load()
        {
            Flow.AddRange(new Drawable[]
            {
                bank = new LabelledTextBox
                {
                    Label = "Bank Name",
                },
                volume = new SliderWithTextBoxInput<int>("Volume")
                {
                    Current = new SampleControlPoint().SampleVolumeBindable,
                }
            });
        }

        protected override void OnControlPointChanged(ValueChangedEvent<SampleControlPoint> point)
        {
            if (point.NewValue != null)
            {
                bank.Current = point.NewValue.SampleBankBindable;
                bank.Current.BindValueChanged(_ => ChangeHandler?.SaveState());

                volume.Current = point.NewValue.SampleVolumeBindable;
                volume.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
            }
        }

        protected override SampleControlPoint CreatePoint()
        {
            var reference = Beatmap.Value.Beatmap.ControlPointInfo.SamplePointAt(SelectedGroup.Value.Time);

            return new SampleControlPoint
            {
                SampleBank = reference.SampleBank,
                SampleVolume = reference.SampleVolume,
            };
        }
    }
}

Add change handling for sample section

Add change handling for sample section


using System;
using NServiceBus;
using SFA.DAS.AutoConfiguration;
using SFA.DAS.EmployerFinance.Messages.Commands;
using SFA.DAS.Notifications.Messages.Commands;
using SFA.DAS.NServiceBus.Configuration.AzureServiceBus;
using StructureMap;

namespace SFA.DAS.EmployerAccounts.Extensions
{
    public static class EndpointConfigurationExtensions
    {
        public static EndpointConfiguration UseAzureServiceBusTransport(this EndpointConfiguration config, Func<string> connectionStringBuilder, IContainer container)
        {
            var isDevelopment = container.GetInstance<IEnvironmentService>().IsCurrent(DasEnv.LOCAL);

            if (isDevelopment)
            {
                var transport = config.UseTransport<LearningTransport>();
                transport.Transactions(TransportTransactionMode.ReceiveOnly);
                ConfigureRouting(transport.Routing());
            }

            else
            {
                config.UseAzureServiceBusTransport(connectionStringBuilder(), ConfigureRouting);
            }

            return config;
        }

        private static void ConfigureRouting(RoutingSettings routing)
        {
            routing.RouteToEndpoint(
                    typeof(ImportLevyDeclarationsCommand).Assembly,
                    typeof(ImportLevyDeclarationsCommand).Namespace,
                    "SFA.DAS.EmployerFinance.MessageHandlers"
            );

            routing.RouteToEndpoint(
                typeof(SendEmailCommand).Assembly,
                typeof(SendEmailCommand).Namespace,
                "SFA.DAS.Notifications.MessageHandlers"
            );
        }
    }
}

using System;
using NServiceBus;
using SFA.DAS.AutoConfiguration;
using SFA.DAS.EmployerFinance.Messages.Commands;
using SFA.DAS.Notifications.Messages.Commands;
using SFA.DAS.NServiceBus.Configuration.AzureServiceBus;
using StructureMap;

namespace SFA.DAS.EmployerAccounts.Extensions
{
    public static class EndpointConfigurationExtensions
    {
        public static EndpointConfiguration UseAzureServiceBusTransport(this EndpointConfiguration config, Func<string> connectionStringBuilder, IContainer container)
        {
            var isDevelopment = container.GetInstance<IEnvironmentService>().IsCurrent(DasEnv.LOCAL);

            if (isDevelopment)
            {
                var transport = config.UseTransport<LearningTransport>();
                transport.Transactions(TransportTransactionMode.ReceiveOnly);
                ConfigureRouting(transport.Routing());
            }

            else
            {
                config.UseAzureServiceBusTransport(connectionStringBuilder(), ConfigureRouting);
                var conventions = config.Conventions();
                conventions.DefiningCommandsAs(type =>
                {
                    return type.Namespace == typeof(SendEmailCommand).Namespace || type.Namespace == typeof(ImportLevyDeclarationsCommand).Namespace;
                });
            }

            return config;
        }

        private static void ConfigureRouting(RoutingSettings routing)
        {
            routing.RouteToEndpoint(
                    typeof(ImportLevyDeclarationsCommand).Assembly,
                    typeof(ImportLevyDeclarationsCommand).Namespace,
                    "SFA.DAS.EmployerFinance.MessageHandlers"
            );

            routing.RouteToEndpoint(
                typeof(SendEmailCommand).Assembly,
                typeof(SendEmailCommand).Namespace,
                "SFA.DAS.Notifications.MessageHandlers"
            );
        }
    }
}

Tweak conventions for nservicebus messages to work in unobtrusive and normal mode


using System;
using System.Threading;
using Flood.Editor.Server;

namespace Flood.Editor
{
    public class ServerManager
    {
        public EditorServer Server { get; private set; }
        private ManualResetEventSlim serverCreatedEvent;

        private void RunBuiltinServer()
        {
            serverCreatedEvent.Set();
            Server.Serve();
        }

        public void CreateBuiltinServer()
        {
            Console.WriteLine("Initializing the built-in editor server...");

            serverCreatedEvent = new ManualResetEventSlim();
            Server = new EditorServer();

            System.Threading.Tasks.Task.Run((Action)RunBuiltinServer);
            serverCreatedEvent.Wait();
        }
    }
}

using System;
using System.Threading;
using Flood.Editor.Server;

namespace Flood.Editor
{
    public class ServerManager
    {
        public EditorServer Server { get; private set; }
        private ManualResetEventSlim serverCreatedEvent;

        private void RunBuiltinServer()
        {
            serverCreatedEvent.Set();
            Server.Serve();
        }

        public void CreateBuiltinServer()
        {
            Log.Info("Initializing the built-in editor server...");

            serverCreatedEvent = new ManualResetEventSlim();
            Server = new EditorServer();

            System.Threading.Tasks.Task.Run((Action)RunBuiltinServer);
            serverCreatedEvent.Wait();
        }
    }
}

Use the logger for writing to the console.


using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media.Imaging;

namespace WPFConverters
{
    public class BitmapImageConverter : BaseConverter
    {
        protected override object OnConvert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string)
                return new BitmapImage(new Uri((string)value, UriKind.RelativeOrAbsolute));

            if (value is Uri)
                return new BitmapImage((Uri)value);

            return DependencyProperty.UnsetValue;
        }
    }
}

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media.Imaging;

namespace WPFConverters
{
    public class BitmapImageConverter : BaseConverter
    {
        protected override object OnConvert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string)
                return LoadImage(new Uri((string)value, UriKind.RelativeOrAbsolute));

            if (value is Uri)
                return LoadImage((Uri)value);

            return DependencyProperty.UnsetValue;
        }

        private BitmapImage LoadImage(Uri uri)
        {
            var image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = uri;
            image.EndInit();
            return image;
        }
    }
}

Make bitmap loading cache the image

Make bitmap loading cache the image


using System.Linq;
using Geocoding.Google;
using Xunit;
using Xunit.Extensions;

namespace Geocoding.Tests
{
	public class GoogleAsyncGeocoderTest : AsyncGeocoderTest
	{
		GoogleGeocoder geoCoder;

		protected override IAsyncGeocoder CreateAsyncGeocoder()
		{
			geoCoder = new GoogleGeocoder();
			return geoCoder;
		}

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

using System.Configuration;
using System.Linq;
using Geocoding.Google;
using Xunit;
using Xunit.Extensions;

namespace Geocoding.Tests
{
	public class GoogleAsyncGeocoderTest : AsyncGeocoderTest
	{
		GoogleGeocoder geoCoder;

		protected override IAsyncGeocoder CreateAsyncGeocoder()
		{
			geoCoder = new GoogleGeocoder
			{
				ApiKey = ConfigurationManager.AppSettings["googleApiKey"]
			};
			return geoCoder;
		}

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

Use google API key in async test.

Use google API key in async test.


using System.Configuration;

namespace StackExchange.Redis.Extensions.Core.Configuration
{
	/// <summary>
	/// Configuration Element Collection for <see cref="RedisHost"/>
	/// </summary>
	public class RedisHostCollection : ConfigurationElementCollection
	{
		/// <summary>
		/// Gets or sets the <see cref="RedisHost"/> at the specified index.
		/// </summary>
		/// <value>
		/// The <see cref="RedisHost"/>.
		/// </value>
		/// <param name="index">The index.</param>
		/// <returns></returns>
		public RedisHost this[int index]
		{
			get
			{
				return BaseGet(index) as RedisHost;
			}
			set
			{
				if (BaseGet(index) != null)
				{
					BaseRemoveAt(index);
				}

				BaseAdd(index, value);
			}
		}

		/// <summary>
		/// Creates the new element.
		/// </summary>
		/// <returns></returns>
		protected override ConfigurationElement CreateNewElement()
		{
			return new RedisHost();
		}

		/// <summary>
		/// Gets the element key.
		/// </summary>
		/// <param name="element">The element.</param>
		/// <returns></returns>
		protected override object GetElementKey(ConfigurationElement element)
		{
			return ((RedisHost)element).Host;
		}
	}
}

using System.Configuration;

namespace StackExchange.Redis.Extensions.Core.Configuration
{
	/// <summary>
	/// Configuration Element Collection for <see cref="RedisHost"/>
	/// </summary>
	public class RedisHostCollection : ConfigurationElementCollection
	{
		/// <summary>
		/// Gets or sets the <see cref="RedisHost"/> at the specified index.
		/// </summary>
		/// <value>
		/// The <see cref="RedisHost"/>.
		/// </value>
		/// <param name="index">The index.</param>
		/// <returns></returns>
		public RedisHost this[int index]
		{
			get
			{
				return BaseGet(index) as RedisHost;
			}
			set
			{
				if (BaseGet(index) != null)
				{
					BaseRemoveAt(index);
				}

				BaseAdd(index, value);
			}
		}

		/// <summary>
		/// Creates the new element.
		/// </summary>
		/// <returns></returns>
		protected override ConfigurationElement CreateNewElement()
		{
			return new RedisHost();
		}

		/// <summary>
		/// Gets the element key.
		/// </summary>
		/// <param name="element">The element.</param>
		/// <returns></returns>
		protected override object GetElementKey(ConfigurationElement element)
		{
			return string.Format("{0}:{1}", ((RedisHost)element).Host, ((RedisHost)element).CachePort);
		}
	}
}

Allow for multiple instances of redis running on the same server but different ports.


using System;
using System.Diagnostics;
using System.Linq.Expressions;
using LINQToTTreeLib.Expressions;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace LINQToTTreeLib.Tests.ResultOperators
{
    [TestClass]
    [PexClass(typeof(SubExpressionReplacement))]
    public partial class SubExpressionReplacementTest
    {
        [TestInitialize]
        public void TestInit()
        {
            TestUtils.ResetLINQLibrary();
        }

        [TestCleanup]
        public void TestDone()
        {
            MEFUtilities.MyClassDone();
        }

        [PexMethod, PexAllowedException(typeof(ArgumentNullException))]
        public Expression TestReplacement(Expression source, Expression pattern, Expression replacement)
        {
            return source.ReplaceSubExpression(pattern, replacement);
        }

        [TestMethod]
        public void TestSimpleReplacement()
        {
            var arr = Expression.Parameter(typeof(int[]), "myarr");
            var param = Expression.Parameter(typeof(int), "dude");

            var expr = Expression.ArrayIndex(arr, param);

            var rep = Expression.Parameter(typeof(int), "fork");
            var result = expr.ReplaceSubExpression(param, rep);

            Debg.WriteLine("Expression: " + result.ToString());
            Assert.IsFalse(result.ToString().Contains("dude"), "Contains the dude variable");
        }
    }
}

using LINQToTTreeLib.Expressions;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.Linq.Expressions;

namespace LINQToTTreeLib.Tests.ResultOperators
{
    [TestClass]
    [PexClass(typeof(SubExpressionReplacement))]
    public partial class SubExpressionReplacementTest
    {
        [TestInitialize]
        public void TestInit()
        {
            TestUtils.ResetLINQLibrary();
        }

        [TestCleanup]
        public void TestDone()
        {
            MEFUtilities.MyClassDone();
        }

        [PexMethod, PexAllowedException(typeof(ArgumentNullException))]
        public Expression TestReplacement(Expression source, Expression pattern, Expression replacement)
        {
            return source.ReplaceSubExpression(pattern, replacement);
        }

        [TestMethod]
        public void TestSimpleReplacement()
        {
            var arr = Expression.Parameter(typeof(int[]), "myarr");
            var param = Expression.Parameter(typeof(int), "dude");

            var expr = Expression.ArrayIndex(arr, param);

            var rep = Expression.Parameter(typeof(int), "fork");
            var result = expr.ReplaceSubExpression(param, rep);

            Debug.WriteLine("Expression: " + result.ToString());
            Assert.IsFalse(result.ToString().Contains("dude"), "Contains the dude variable");
        }
    }
}

Fix up badly spelled test

Fix up badly spelled test


using System.Reflection;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

using System.Reflection;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

Increase nuget package version to 1.0.0-beta05


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MediaCentreServer.Controllers
{
	// Controller for running an application.
	public class RunController : ApiController
	{
		// POST /api/run?path=...
		public void Post(string path)
		{
			var startInfo = new ProcessStartInfo(path);
			startInfo.UseShellExecute = false;
			Process.Start(startInfo);
		}
	}
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MediaCentreServer.Controllers
{
	// Controller for running an application.
	public class RunController : ApiController
	{
		// POST /api/run?path=...
		public HttpResponseMessage Post(string path)
		{
			var startInfo = new ProcessStartInfo(path);
			try
			{
				Process.Start(startInfo);
				return Request.CreateResponse(HttpStatusCode.NoContent);
			}
			catch (Exception)
			{
				return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Failed to launch process");
			}
		}
	}
}

Use shell execute for run action.

Use shell execute for run action.

Enables launching URLs as well as apps. Probably a major security issue,
but fuck it, right? Also improved error handling.