using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Deployment.Common.ActionModel;
using Microsoft.Deployment.Common.Actions;
using Microsoft.Deployment.Common.Helpers;

namespace Microsoft.Deployment.Actions.AzureCustom.Twitter
{
    [Export(typeof(IAction))]
    public class ValidateCognitiveKey : BaseAction
    {
        public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            //Request headers
            var subscriptionKey = request.DataStore.GetValue("subscriptionKey");
            Dictionary<string, string> customHeader = new Dictionary<string, string>();
            customHeader.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

            HttpClientUtility client = new HttpClientUtility();
            //Request body
            var result = await client.ExecuteGenericAsync(HttpMethod.Post, $"https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment", "", "", customHeader);

            var responseString = await result.Content.ReadAsStringAsync();

            if (result.StatusCode == HttpStatusCode.BadRequest)
            {
                var obj = JsonUtility.GetJObjectFromJsonString(responseString);
                return new ActionResponse(ActionStatus.Success);
            }

            if (result.StatusCode == HttpStatusCode.Unauthorized)
            {
                var obj = JsonUtility.GetJObjectFromJsonString(responseString);
                return new ActionResponse(ActionStatus.FailureExpected);
            }

            return new ActionResponse(ActionStatus.Failure);

        }
    }
}

using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Deployment.Common.ActionModel;
using Microsoft.Deployment.Common.Actions;
using Microsoft.Deployment.Common.Helpers;

namespace Microsoft.Deployment.Actions.AzureCustom.Twitter
{
    [Export(typeof(IAction))]
    public class ValidateCognitiveKey : BaseAction
    {
        public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            //Request headers
            var subscriptionKey = request.DataStore.GetValue("CognitiveServiceKey");
            Dictionary<string, string> customHeader = new Dictionary<string, string>();
            customHeader.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

            HttpClientUtility client = new HttpClientUtility();
            //Request body
            var result = await client.ExecuteGenericAsync(HttpMethod.Post, $"https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment", "", "", customHeader);

            var responseString = await result.Content.ReadAsStringAsync();

            if (result.StatusCode == HttpStatusCode.BadRequest)
            {
                var obj = JsonUtility.GetJObjectFromJsonString(responseString);
                return new ActionResponse(ActionStatus.Success);
            }

            if (result.StatusCode == HttpStatusCode.Unauthorized)
            {
                var obj = JsonUtility.GetJObjectFromJsonString(responseString);
                return new ActionResponse(ActionStatus.FailureExpected);
            }

            return new ActionResponse(ActionStatus.Failure);

        }
    }
}

Fix cognitive service key validation

Fix cognitive service key validation


using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Documents;
using System.Linq;
using System.Threading.Tasks;
using TheCollection.Business.Tea;
using TheCollection.Web.Constants;
using TheCollection.Web.Extensions;
using TheCollection.Web.Models;
using TheCollection.Web.Services;

namespace TheCollection.Web.Commands
{
    public class SearchBagsCommand : IAsyncCommand<Search>
    {
        private readonly IDocumentClient documentDbClient;

        public SearchBagsCommand(IDocumentClient documentDbClient)
        {
            this.documentDbClient = documentDbClient;
        }

        public async Task<IActionResult> ExecuteAsync(Search search)
        {
            if (search.searchterm.IsNullOrWhiteSpace())
            {
                return new BadRequestResult();
            }

            var bagsRepository = new SearchRepository<Bag>(documentDbClient, DocumentDB.DatabaseId, DocumentDB.BagsCollectionId);
            var bags = await bagsRepository.SearchAsync(search.searchterm, search.pagesize);
            var result = new SearchResult<Bag>
            {
                count = await bagsRepository.SearchRowCountAsync(search.searchterm),
                data = bags.OrderBy(bag => bag.Brand.Name)
                        .ThenBy(bag => bag.Hallmark)
                        .ThenBy(bag => bag.Serie)
                        .ThenBy(bag => bag.BagType?.Name)
                        .ThenBy(bag => bag.Flavour)
            };

            return new OkObjectResult(result);
        }
    }
}

using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Documents;
using System.Linq;
using System.Threading.Tasks;
using TheCollection.Business.Tea;
using TheCollection.Web.Constants;
using TheCollection.Web.Extensions;
using TheCollection.Web.Models;
using TheCollection.Web.Services;

namespace TheCollection.Web.Commands
{
    public class SearchBagsCommand : IAsyncCommand<Search>
    {
        private readonly IDocumentClient documentDbClient;

        public SearchBagsCommand(IDocumentClient documentDbClient)
        {
            this.documentDbClient = documentDbClient;
        }

        public async Task<IActionResult> ExecuteAsync(Search search)
        {
            if (search.searchterm.IsNullOrWhiteSpace())
            {
                return new BadRequestResult();
            }

            var bagsRepository = new SearchRepository<Bag>(documentDbClient, DocumentDB.DatabaseId, DocumentDB.BagsCollectionId);
            var bags = await bagsRepository.SearchAsync(search.searchterm, search.pagesize);
            var result = new SearchResult<Bag>
            {
                count = await bagsRepository.SearchRowCountAsync(search.searchterm),
                data = bags.OrderBy(bag => bag.Brand.Name)
                        .ThenBy(bag => bag.Serie)
                        .ThenBy(bag => bag.Hallmark)
                        .ThenBy(bag => bag.BagType?.Name)
                        .ThenBy(bag => bag.Flavour)
            };

            return new OkObjectResult(result);
        }
    }
}

Fix sorting of search bags

Fix sorting of search bags


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

using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Diagnostics;

namespace Microsoft.CodeAnalysis.Options
{
    internal static class EditorConfigStorageLocationExtensions
    {
        public static bool TryGetOption(this IEditorConfigStorageLocation editorConfigStorageLocation, AnalyzerConfigOptions analyzerConfigOptions, Type type, out object value)
        {
            // This is a workaround until we have an API for enumeratings AnalyzerConfigOptions.
            var backingField = analyzerConfigOptions.GetType().GetField("_backing", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            var backing = backingField?.GetValue(analyzerConfigOptions);

            if (backing is IReadOnlyDictionary<string, string> backingDictionary)
            {
                return editorConfigStorageLocation.TryGetOption(backingDictionary, type, out value);
            }

            value = null;
            return false;
        }
    }
}

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

using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Diagnostics;

namespace Microsoft.CodeAnalysis.Options
{
    internal static class EditorConfigStorageLocationExtensions
    {
        public static bool TryGetOption(this IEditorConfigStorageLocation editorConfigStorageLocation, AnalyzerConfigOptions analyzerConfigOptions, Type type, out object value)
        {
            // This is a workaround until we have an API for enumeratings AnalyzerConfigOptions. See https://github.com/dotnet/roslyn/issues/41840
            var backingField = analyzerConfigOptions.GetType().GetField("_backing", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            var backing = backingField?.GetValue(analyzerConfigOptions);

            if (backing is IReadOnlyDictionary<string, string> backingDictionary)
            {
                return editorConfigStorageLocation.TryGetOption(backingDictionary, type, out value);
            }

            value = null;
            return false;
        }
    }
}

Add link to explanatory comment

Add link to explanatory comment


using CommandLineParser;
using Saucy.Actions;
using Saucy.Providers.GitHub;

namespace Saucy
{
   public class Program
   {
      public static int Main(string[] args)
      {
         var settings = new SaucySettings();

         ILogger logger = new VerboseLogger();

         var restoreVerb = new SaucyCommandLine(
            new PackagesRestorer(
               new JsonLoader(),
               new ProviderMatcher(new GitHubProvider(new FolderSync(logger))),
               new ConsoleWriter(),
               settings),
            settings);

         var runner = new Runner();
         runner.Register(restoreVerb);

         var exitCode = runner.Run(args);
         return exitCode;
      }
   }
}

using CommandLineParser;
using Saucy.Actions;
using Saucy.Providers.GitHub;

namespace Saucy
{
   using System;

   public class Program
   {
      public static int Main(string[] args)
      {
         var consoleWriter = new ConsoleWriter();

         try
         {
            var settings = new SaucySettings();

            ILogger logger = new VerboseLogger();

            var restoreVerb = new SaucyCommandLine(
               new PackagesRestorer(
                  new JsonLoader(),
                  new ProviderMatcher(new GitHubProvider(new FolderSync(logger))),
                  consoleWriter,
                  settings),
               settings);

            var runner = new Runner();
            runner.Register(restoreVerb);

            var exitCode = runner.Run(args);
            return exitCode;
         }
         catch (Exception e)
         {
            consoleWriter.Write(e.Message);
            consoleWriter.Write(e.StackTrace);
            return -1;
         }
      }
   }
}

Add exception handler to main()

Add exception handler to main()


using System;

namespace Watts
{
    internal class Program
    {
        private static int Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: Watts.exe <\"Path/To/Config.json\">");
                return 1;
            }

            var watts = new WebApiToTypeScript.WebApiToTypeScript
            {
                ConfigFilePath = args[0]
            };

            watts.Execute();

#if DEBUG
            Console.ReadLine();
#endif

            return 0;
        }
    }
}

using System;
using System.Diagnostics;
using System.IO;

namespace Watts
{
    internal class Program
    {
        private static int Main(string[] args)
        {
            var watts = new WebApiToTypeScript.WebApiToTypeScript();
            if (args.Length == 0)
            {
                var path = Path.Combine(Environment.CurrentDirectory, "watts.config.json");
                if (File.Exists(path))
                    watts.ConfigFilePath = path;
            }
            else if (args.Length > 0 && File.Exists(args[0]))
            {
                watts.ConfigFilePath = args[1];
            }

            int status = 0;
            if (watts.ConfigFilePath == null)
            {
                Console.WriteLine("Usage: Watts.exe <\"Path/To/Config.json\">");
                status = -1;
            }
            else
            {
                status = watts.Execute() ? 0 : -1;
            }

            if (Debugger.IsAttached)
            {
                Console.WriteLine("Press any key to continue . . .");
                Console.ReadLine();
            }

            return 0;
        }
    }
}

Add option to use current dir.

Add option to use current dir.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
using WinMasto.Tools.Extensions;

namespace WinMasto.Tools.Converters
{
    public class StripHtmlConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var accountNameValue = value as string;
            return accountNameValue == null ? value : HtmlRemoval.StripTagsCharArray(accountNameValue);
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
using WinMasto.Tools.Extensions;

namespace WinMasto.Tools.Converters
{
    public class StripHtmlConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var accountNameValue = value as string;
            return accountNameValue == null ? value : HtmlRemoval.StripTagsCharArray(WebUtility.HtmlDecode(accountNameValue));
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}

Fix encoding of HTML in status

Fix encoding of HTML in status


namespace Bakery.Security
{
	using System;
	using System.Text;
	using Text;

	public class BasicAuthenticationPrinter
		: IBasicAuthenticationPrinter
	{
		private readonly IBase64Printer base64Printer;
		private readonly Encoding encoding;

		public BasicAuthenticationPrinter(IBase64Printer base64Printer, Encoding encoding)
		{
			if (base64Printer == null)
				throw new ArgumentNullException(nameof(base64Printer));

			if (encoding == null)
				throw new ArgumentNullException(nameof(encoding));

			this.base64Printer = base64Printer;
			this.encoding = encoding;
		}

		public String Print(IBasicAuthentication basicAuthentication)
		{
			if (basicAuthentication == null)
				throw new ArgumentNullException(nameof(basicAuthentication));

			return $"Basic {base64Printer.Print(encoding.GetBytes($"{basicAuthentication.Username}:{basicAuthentication.Password}"))}";
		}
	}
}

namespace Bakery.Security
{
	using System;
	using System.Text;
	using Text;

	public class BasicAuthenticationPrinter
		: IBasicAuthenticationPrinter
	{
		private readonly IBase64Printer base64Printer;
		private readonly Encoding encoding;

		public BasicAuthenticationPrinter(IBase64Printer base64Printer, Encoding encoding)
		{
			if (base64Printer == null)
				throw new ArgumentNullException(nameof(base64Printer));

			if (encoding == null)
				throw new ArgumentNullException(nameof(encoding));

			this.base64Printer = base64Printer;
			this.encoding = encoding;
		}

		public String Print(IBasicAuthentication basicAuthentication)
		{
			if (basicAuthentication == null)
				throw new ArgumentNullException(nameof(basicAuthentication));

			var credentials =
				String.Format("{0}:{1}",
					basicAuthentication.Username,
					basicAuthentication.Password);

			var credentialsBase64 = base64Printer.Print(encoding.GetBytes(credentials));

			return $"Basic {credentialsBase64}";
		}
	}
}

Use intermediate variables to improve readability.


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

using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
using Vipr.Core;

namespace Vipr
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var bootstrapper = new Bootstrapper();

            bootstrapper.Start(args);
        }
    }
}

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

using System.Collections.Generic;
using System.IO;
namespace Vipr
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var bootstrapper = new Bootstrapper();

            bootstrapper.Start(args);
        }
    }
}

Enable automatic versioning and Nuget packaging of shippable Vipr binaries


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;

namespace MabWeb
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseSetting("detailedErrors", "true")
                .CaptureStartupErrors(true)
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;

namespace MabWeb
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

Revert "Enabling startup error logging"

Revert "Enabling startup error logging"

This reverts commit cf2d991dde18740bf4d99058b5e8b717b7df68a4.


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

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

namespace ShiftDrive {

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

        public static SpriteFont
            fontDefault,
            fontBold;

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

        public static Model
            mdlSkybox;

        public static Effect
            fxUnlit;

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

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

    }

}

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

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

namespace ShiftDrive {

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

        public static SpriteFont
            fontDefault,
            fontBold;

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

        public static Model
            mdlSkybox;

        public static Effect
            fxUnlit;

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

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

    }

}

Use string interpolation in key error

Use string interpolation in key error


using osu_StreamCompanion.Code.Core.DataTypes;
using osu_StreamCompanion.Code.Interfaces;
using osu_StreamCompanion.Code.Windows;

namespace osu_StreamCompanion.Code.Modules.MapDataGetters.Window
{
    public class WindowDataGetter :IModule,IMapDataGetter,IMainWindowUpdater
    {
        private MainWindowUpdater _mainwindowHandle;
        public bool Started { get; set; }
        public void Start(ILogger logger)
        {
            Started = true;
        }

        public void SetNewMap(MapSearchResult map)
        {
            if (map.FoundBeatmaps)
            {
                var nowPlaying = string.Format("{0} - {1}", map.BeatmapsFound[0].ArtistRoman,map.BeatmapsFound[0].TitleRoman);
                if (map.Action == OsuStatus.Playing || map.Action == OsuStatus.Watching)
                {
                    nowPlaying += string.Format(" [{0}] {1}", map.BeatmapsFound[0].DiffName, map.Mods?.Item2 ?? "");
                    nowPlaying += string.Format("{0:##.###}", map.BeatmapsFound[0].StarsNomod);
                }
                _mainwindowHandle.NowPlaying = nowPlaying;
            }
            else
            {
                _mainwindowHandle.NowPlaying = "notFound:( " + map.MapSearchString;
            }
        }

        public void GetMainWindowHandle(MainWindowUpdater mainWindowHandle)
        {
            _mainwindowHandle = mainWindowHandle;
        }
    }
}

using System;
using CollectionManager.DataTypes;
using CollectionManager.Enums;
using osu_StreamCompanion.Code.Core.DataTypes;
using osu_StreamCompanion.Code.Interfaces;
using osu_StreamCompanion.Code.Windows;

namespace osu_StreamCompanion.Code.Modules.MapDataGetters.Window
{
    public class WindowDataGetter :IModule,IMapDataGetter,IMainWindowUpdater
    {
        private MainWindowUpdater _mainwindowHandle;
        public bool Started { get; set; }
        public void Start(ILogger logger)
        {
            Started = true;
        }

        public void SetNewMap(MapSearchResult map)
        {
            if (map.FoundBeatmaps)
            {
                var foundMap = map.BeatmapsFound[0];
                var nowPlaying = string.Format("{0} - {1}", foundMap.ArtistRoman, foundMap.TitleRoman);
                if (map.Action == OsuStatus.Playing || map.Action == OsuStatus.Watching)
                {
                    nowPlaying += string.Format(" [{0}] {1}", foundMap.DiffName, map.Mods?.Item2 ?? "");
                    nowPlaying += string.Format(Environment.NewLine+"NoMod:{0:##.###}", foundMap.StarsNomod);
                    var mods = map.Mods?.Item1 ?? Mods.Omod;
                    nowPlaying += string.Format(" Modded: {0:##.###}", foundMap.Stars(PlayMode.Osu, mods));
                }
                _mainwindowHandle.NowPlaying = nowPlaying;
            }
            else
            {
                _mainwindowHandle.NowPlaying = "notFound:( " + map.MapSearchString;
            }
        }

        public void GetMainWindowHandle(MainWindowUpdater mainWindowHandle)
        {
            _mainwindowHandle = mainWindowHandle;
        }
    }
}

Update main window text to include nomod/modded star rating


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

using System.ComponentModel;

namespace osu.Game.Scoring
{
    public enum ScoreRank
    {
        [Description(@"F")]
        F,
        [Description(@"F")]
        D,
        [Description(@"C")]
        C,
        [Description(@"B")]
        B,
        [Description(@"A")]
        A,
        [Description(@"S")]
        S,
        [Description(@"SPlus")]
        SH,
        [Description(@"SS")]
        X,
        [Description(@"SSPlus")]
        XH,
    }
}

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

using System.ComponentModel;

namespace osu.Game.Scoring
{
    public enum ScoreRank
    {
        [Description(@"F")]
        F,
        [Description(@"D")]
        D,
        [Description(@"C")]
        C,
        [Description(@"B")]
        B,
        [Description(@"A")]
        A,
        [Description(@"S")]
        S,
        [Description(@"SPlus")]
        SH,
        [Description(@"SS")]
        X,
        [Description(@"SSPlus")]
        XH,
    }
}

Fix D rank displaying as F

Fix D rank displaying as F


using System.Text.RegularExpressions;
using ChatExchangeDotNet;

namespace Hatman.Commands
{
    class Should : ICommand
    {
        private readonly Regex ptn = new Regex(@"(?i)^((sh|[cw])ould|can|will|is)", Extensions.RegOpts);
        private readonly string[] phrases = new[]
        {
            "No.",
            "Yes.",
            "Yup.",
            "Nope.",
            "Indubitably",
            "Never. Ever. *EVER*.",
            "Only if I get my coffee.",
            "Nah.",
            "Ask The Skeet.",
            "... do I look like I know everything?",
            "Ask me no questions, and I shall tell no lies.",
            "Sure, when it rains imaginary internet points.",
            "Yeah.",
            "Ofc.",
            "NOOOOOOOOOOOOOOOO",
            "Sure, ok."
        };

        public Regex CommandPattern
        {
            get
            {
                return ptn;
            }
        }

        public string Description
        {
            get
            {
                return "Decides whether or not something should happen.";
            }
        }

        public string Usage
        {
            get
            {
                return "(sh|[wc])ould|will|can|is";
            }
        }

        public void ProcessMessage(Message msg, ref Room rm)
        {
            rm.PostReplyFast(msg, phrases.PickRandom());
        }
    }
}

using System.Text.RegularExpressions;
using ChatExchangeDotNet;

namespace Hatman.Commands
{
    class Should : ICommand
    {
        private readonly Regex ptn = new Regex(@"(?i)^((sh|[cw])ould|can|are|will|is)", Extensions.RegOpts);
        private readonly string[] phrases = new[]
        {
            "No.",
            "Yes.",
            "Yup.",
            "Nope.",
            "Indubitably",
            "Never. Ever. *EVER*.",
            "Only if I get my coffee.",
            "Nah.",
            "Ask The Skeet.",
            "... do I look like I know everything?",
            "Ask me no questions, and I shall tell no lies.",
            "Sure, when it rains imaginary internet points.",
            "Yeah.",
            "Ofc.",
            "NOOOOOOOOOOOOOOOO",
            "Sure, ok."
        };

        public Regex CommandPattern
        {
            get
            {
                return ptn;
            }
        }

        public string Description
        {
            get
            {
                return "Decides whether or not something should happen.";
            }
        }

        public string Usage
        {
            get
            {
                return "(sh|[wc])ould|will|are|can|is";
            }
        }

        public void ProcessMessage(Message msg, ref Room rm)
        {
            rm.PostReplyFast(msg, phrases.PickRandom());
        }
    }
}

Add "are" to the command pattern

Add "are" to the command pattern


@{
    ViewBag.Title = "Home Page";
}

ASP.NET

ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.

Learn more »

Getting started

            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.

Learn more »

Get more libraries

NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.

Learn more »

Web Hosting

You can easily find a web hosting company that offers the right mix of features and price for your applications.

Learn more »

Remove template contents from the home/index view


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

using osu.Framework.Graphics.Sprites;

namespace osu.Game.Graphics.Sprites
{
    class OsuSpriteText : SpriteText
    {
        public const float FONT_SIZE = 16;

        public OsuSpriteText()
        {
            Shadow = true;
            TextSize = FONT_SIZE;
        }
    }
}

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

using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.MathUtils;
using OpenTK;
using OpenTK.Graphics;

namespace osu.Game.Graphics.Sprites
{
    class OsuSpriteText : SpriteText
    {
        public const float FONT_SIZE = 16;

        public OsuSpriteText()
        {
            Shadow = true;
            TextSize = FONT_SIZE;
        }

        protected override Drawable GetUndrawableCharacter()
        {
            var tex = GetTextureForCharacter('?');

            if (tex != null)
            {
                float adjust = (RNG.NextSingle() - 0.5f) * 2;
                return new Sprite
                {
                    Texture = tex,
                    Origin = Anchor.Centre,
                    Anchor = Anchor.Centre,
                    Scale = new Vector2(1 + adjust * 0.2f),
                    Rotation = adjust * 15,
                    Colour = Color4.White,
                };
            }

            return base.GetUndrawableCharacter();
        }
    }
}

Add custom representation of unrenderable unicode characters.


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;

namespace osu.Game.Users.Drawables
{
    [LongRunningLoad]
    public class DrawableAvatar : Sprite
    {
        private readonly User user;

        /// <summary>
        /// A simple, non-interactable avatar sprite for the specified user.
        /// </summary>
        /// <param name="user">The user. A null value will get a placeholder avatar.</param>
        public DrawableAvatar(User user = null)
        {
            this.user = user;

            RelativeSizeAxes = Axes.Both;
            FillMode = FillMode.Fit;
            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;
        }

        [BackgroundDependencyLoader]
        private void load(LargeTextureStore textures)
        {
            if (user != null && user.Id > 1)
                Texture = textures.Get(user.AvatarUrl);

            Texture ??= textures.Get(@"Online/avatar-guest");
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();
            this.FadeInFromZero(300, Easing.OutQuint);
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;

namespace osu.Game.Users.Drawables
{
    [LongRunningLoad]
    public class DrawableAvatar : Sprite
    {
        private readonly User user;

        /// <summary>
        /// A simple, non-interactable avatar sprite for the specified user.
        /// </summary>
        /// <param name="user">The user. A null value will get a placeholder avatar.</param>
        public DrawableAvatar(User user = null)
        {
            this.user = user;

            RelativeSizeAxes = Axes.Both;
            FillMode = FillMode.Fit;
            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;
        }

        [BackgroundDependencyLoader]
        private void load(LargeTextureStore textures)
        {
            if (user != null && user.Id > 1)
                // TODO: The fallback here should not need to exist. Users should be looked up and populated via UserLookupCache or otherwise
                // in remaining cases where this is required (chat tabs, local leaderboard), at which point this should be removed.
                Texture = textures.Get(user.AvatarUrl ?? $@"https://a.ppy.sh/{user.Id}");

            Texture ??= textures.Get(@"Online/avatar-guest");
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();
            this.FadeInFromZero(300, Easing.OutQuint);
        }
    }
}

Fix avatars missing in private message channel tabs / local leaderboards

Regressed in https://github.com/ppy/osu/pull/12204.

Adding this back in a central location for now, as each of the remaining cases will
need a local solution.


using System;
using Newtonsoft.Json.Linq;

namespace Chronological
{
    public class DataType
    {
        public string TimeSeriesInsightsType { get; }

        internal DataType(string dataType)
        {
            TimeSeriesInsightsType = dataType;
        }

        internal JProperty ToJProperty()
        {
            return new JProperty("type", TimeSeriesInsightsType);
        }

        internal static DataType FromType(Type type)
        {
            switch (type)
            {
                case Type doubleType when doubleType == typeof(double) || doubleType == typeof(double?):
                    return Double;
                case Type stringType when stringType == typeof(string):
                    return String;
                case Type dateTimeType when dateTimeType == typeof(DateTime):
                    return DateTime;
                case Type boolType when boolType == typeof(bool) || boolType == typeof(bool?):
                    return Boolean;
                default:
                    //Todo: Better exceptions
                    throw new Exception("Unexpected Type");
            }
        }

        public static DataType Double => new DataType("Double");
        public static DataType String => new DataType("String");
        public static DataType DateTime => new DataType("DateTime");
        public static DataType Boolean => new DataType("Boolean");
    }
}

using System;
using Newtonsoft.Json.Linq;

namespace Chronological
{
    public class DataType
    {
        public string TimeSeriesInsightsType { get; }

        internal DataType(string dataType)
        {
            TimeSeriesInsightsType = dataType;
        }

        internal JProperty ToJProperty()
        {
            return new JProperty("type", TimeSeriesInsightsType);
        }

        internal static DataType FromType(Type type)
        {
            switch (type)
            {
                case Type doubleType when doubleType == typeof(double) || doubleType == typeof(double?):
                    return Double;
                case Type stringType when stringType == typeof(string):
                    return String;
                case Type dateTimeType when dateTimeType == typeof(DateTime) || dateTimeType == typeof(DateTime?):
                    return DateTime;
                case Type boolType when boolType == typeof(bool) || boolType == typeof(bool?):
                    return Boolean;
                default:
                    //Todo: Better exceptions
                    throw new Exception("Unexpected Type");
            }
        }

        public static DataType Double => new DataType("Double");
        public static DataType String => new DataType("String");
        public static DataType DateTime => new DataType("DateTime");
        public static DataType Boolean => new DataType("Boolean");
    }
}

Add the nullable DateTime type

Add the nullable DateTime type


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

namespace Mono.Debugging.Client
{
	[Serializable]
	public class SourceLink
	{
		// Keep the / character to use as a path separator to help group related symbols
		static readonly HashSet<char> invalids = new HashSet<char>(Path.GetInvalidFileNameChars ().Except (new char[] { '/' }));

		public string Uri { get; }

		public string RelativeFilePath { get; }

		public SourceLink (string uri, string relativeFilePath)
		{
			RelativeFilePath = relativeFilePath;
			Uri = uri;
		}

		public string GetDownloadLocation (string cachePath)
		{
			var uri = new Uri (Uri);
			return Path.Combine (cachePath, MakeValidFileName (uri));
		}

		static string MakeValidFileName (Uri uri)
		{
			// Remove scheme from uri
			var text = uri.Host + uri.PathAndQuery;
			var sb = new StringBuilder (text.Length);
			for (int i = 0; i < text.Length; i++) {
				char c = text[i];
				if (invalids.Contains (c)) {
					sb.Append ('_');
				} else
					sb.Append (c);
			}
			if (sb.Length == 0)
				return "_";
			return sb.ToString ();
		}
	}
}

using System;
using System.IO;

namespace Mono.Debugging.Client
{
	[Serializable]
	public class SourceLink
	{
		public string Uri { get; }

		public string RelativeFilePath { get; }

		public SourceLink (string uri, string relativeFilePath)
		{
			RelativeFilePath = relativeFilePath;
			Uri = uri;
		}

		public string GetDownloadLocation (string cachePath)
		{
			var uri = new Uri (Uri);
			return Path.Combine (cachePath, uri.Host + uri.PathAndQuery);
		}
	}
}

Simplify uri -> filename conversion

Simplify uri -> filename conversion


using CsvHelper.Configuration;
using MyAccounts.Business.AccountOperations.Contracts;

namespace MyAccounts.Business.AccountOperations.Fortis
{
    public sealed class FortisOperationExportCsvMap : ClassMap<FortisOperation>
    {
        public FortisOperationExportCsvMap()
        {
            Map(m => m.Reference).Name("Numro de squence");
            Map(m => m.ExecutionDate).Name("Date d'excution").TypeConverterOption.Format("dd/MM/yyyy");
            Map(m => m.ValueDate).Name("Date valeur").TypeConverterOption.Format("dd/MM/yyyy");
            Map(m => m.Amount).Name("Montant");
            Map(m => m.Currency).Name("Devise du compte");
            Map(m => m.CounterpartyOfTheTransaction).Name("CONTREPARTIE DE LA TRANSACTION");
            Map(m => m.Detail).Name("Dtails");
            Map(m => m.Account).Name("Numro de compte");
            Map(m => m.SourceKind).Default(SourceKind.Unknwon);
        }
    }
}

using CsvHelper.Configuration;
using MyAccounts.Business.AccountOperations.Contracts;

namespace MyAccounts.Business.AccountOperations.Fortis
{
    public sealed class FortisOperationExportCsvMap : ClassMap<FortisOperation>
    {
        public FortisOperationExportCsvMap()
        {
            Map(m => m.Reference).Name("Numro de squence", "N de squence");
            Map(m => m.ExecutionDate).Name("Date d'excution").TypeConverterOption.Format("dd/MM/yyyy");
            Map(m => m.ValueDate).Name("Date valeur").TypeConverterOption.Format("dd/MM/yyyy");
            Map(m => m.Amount).Name("Montant");
            Map(m => m.Currency).Name("Devise du compte");
            Map(m => m.CounterpartyOfTheTransaction).Name("CONTREPARTIE DE LA TRANSACTION");
            Map(m => m.Detail).Name("Dtails");
            Map(m => m.Account).Name("Numro de compte");
            Map(m => m.SourceKind).Default(SourceKind.Unknwon);
        }
    }
}

Add support for new column name in fortis export


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

namespace DesktopWidgets.Classes
{
    [ExpandableObject]
    public class ForegroundMatchData
    {
        [DisplayName("Title")]
        public string Title { get; set; }

        [DisplayName("Title Match Mode")]
        public StringMatchMode TitleMatchMode { get; set; } = StringMatchMode.Any;

        [DisplayName("Fullscreen")]
        public YesNoAny Fullscreen { get; set; } = YesNoAny.Any;
    }
}

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

namespace DesktopWidgets.Classes
{
    [ExpandableObject]
    public class ForegroundMatchData
    {
        [DisplayName("Title")]
        public string Title { get; set; }

        [DisplayName("Title Match Mode")]
        public StringMatchMode TitleMatchMode { get; set; } = StringMatchMode.Equals;

        [DisplayName("Fullscreen")]
        public YesNoAny Fullscreen { get; set; } = YesNoAny.Any;
    }
}

Change Foreground Match Data "Title Match Mode" default value


// MvxJsonConverter.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com

using System;
using System.Collections.Generic;
using Cirrious.CrossCore.Platform;
using Newtonsoft.Json;

namespace Cirrious.MvvmCross.Plugins.Json
{
    public class MvxJsonConverter : IMvxJsonConverter
    {
        private static readonly JsonSerializerSettings Settings;

        static MvxJsonConverter()
        {
            Settings = new JsonSerializerSettings
                {
                    Converters = new List<JsonConverter>
                        {
                            new MvxEnumJsonConverter(),
                        },
                    DateFormatHandling = DateFormatHandling.IsoDateFormat,
                };
        }

        public T DeserializeObject<T>(string inputText)
        {
            return JsonConvert.DeserializeObject<T>(inputText, Settings);
        }

        public string SerializeObject(object toSerialise)
        {
            return JsonConvert.SerializeObject(toSerialise, Formatting.None, Settings);
        }

        public object DeserializeObject(Type type, string inputText)
        {
            return JsonConvert.DeserializeObject(inputText, type, Settings);
        }
    }
}

// MvxJsonConverter.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com

using System;
using System.Collections.Generic;
using Cirrious.CrossCore.Platform;
using Newtonsoft.Json;

namespace Cirrious.MvvmCross.Plugins.Json
{
    public class MvxJsonConverter : IMvxJsonConverter
    {
        private static readonly JsonSerializerSettings Settings;

        static MvxJsonConverter()
        {
            Settings = new JsonSerializerSettings
                {
                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
                    Converters = new List<JsonConverter>
                        {
                            new MvxEnumJsonConverter(),
                        },
                    DateFormatHandling = DateFormatHandling.IsoDateFormat,
                };
        }

        public T DeserializeObject<T>(string inputText)
        {
            return JsonConvert.DeserializeObject<T>(inputText, Settings);
        }

        public string SerializeObject(object toSerialise)
        {
            return JsonConvert.SerializeObject(toSerialise, Formatting.None, Settings);
        }

        public object DeserializeObject(Type type, string inputText)
        {
            return JsonConvert.DeserializeObject(inputText, type, Settings);
        }
    }
}

Add serialize loop handling to prevent crashing for circular loops


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) {
      Game game = new Game();
      Console.WriteLine("Made a new Game object");

      // Table table = new Table(2, 3);
      // string output = table.Draw();

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

Create an instance of Game

Create an instance of Game


using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Web.Scheduling;

namespace Umbraco.Web.Telemetry
{
    public class TelemetryComponent : IComponent
    {
        private IProfilingLogger _logger;
        private IRuntimeState _runtime;
        private BackgroundTaskRunner<IBackgroundTask> _telemetryReporterRunner;

        public TelemetryComponent(IProfilingLogger logger, IRuntimeState runtime)
        {
            _logger = logger;
            _runtime = runtime;
            _telemetryReporterRunner = new BackgroundTaskRunner<IBackgroundTask>("TelemetryReporter", _logger);
        }

        public void Initialize()
        {
            int delayBeforeWeStart = 60 * 1000; // 60 * 1000ms = 1min (60,000)
            int howOftenWeRepeat = 60 * 1000 * 60 * 24; // 60 * 1000 * 60 * 24 = 24hrs (86400000)

            // As soon as we add our task to the runner it will start to run (after its delay period)
            var task = new ReportSiteTask(_telemetryReporterRunner, delayBeforeWeStart, howOftenWeRepeat, _runtime, _logger);
            _telemetryReporterRunner.TryAdd(task);
        }

        public void Terminate()
        {
        }
    }
}

using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Web.Scheduling;

namespace Umbraco.Web.Telemetry
{
    public class TelemetryComponent : IComponent
    {
        private IProfilingLogger _logger;
        private IRuntimeState _runtime;
        private BackgroundTaskRunner<IBackgroundTask> _telemetryReporterRunner;

        public TelemetryComponent(IProfilingLogger logger, IRuntimeState runtime)
        {
            _logger = logger;
            _runtime = runtime;
        }

        public void Initialize()
        {
            // backgrounds runners are web aware, if the app domain dies, these tasks will wind down correctly
            _telemetryReporterRunner = new BackgroundTaskRunner<IBackgroundTask>("TelemetryReporter", _logger);

            int delayBeforeWeStart = 60 * 1000; // 60 * 1000ms = 1min (60,000)
            int howOftenWeRepeat = 60 * 1000 * 60 * 24; // 60 * 1000 * 60 * 24 = 24hrs (86400000)

            // As soon as we add our task to the runner it will start to run (after its delay period)
            var task = new ReportSiteTask(_telemetryReporterRunner, delayBeforeWeStart, howOftenWeRepeat, _runtime, _logger);
            _telemetryReporterRunner.TryAdd(task);
        }

        public void Terminate()
        {
        }
    }
}

Move the backgroundtask runner into Initialize method to follow same practise as SchedulerComponent


using System;
using System.Reflection;
using Newtonsoft.Json;

namespace TrackableData.Json
{
    public class TrackableContainerTrackerJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(IContainerTracker).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.StartObject)
                return null;

            var tracker = (ITracker)Activator.CreateInstance(objectType);
            reader.Read();
            while (true)
            {
                if (reader.TokenType != JsonToken.PropertyName)
                    break;

                var pi = objectType.GetProperty((string)reader.Value + "Tracker");
                reader.Read();

                var subTracker = serializer.Deserialize(reader, pi.PropertyType);
                reader.Read();

                pi.SetValue(tracker, subTracker);
            }

            return tracker;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var tracker = (ITracker)value;

            writer.WriteStartObject();

            foreach (var pi in value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                if (typeof(ITracker).IsAssignableFrom(pi.PropertyType) == false)
                    continue;

                var subTracker = (ITracker)pi.GetValue(value);
                if (subTracker != null && subTracker.HasChange)
                {
                    writer.WritePropertyName(pi.Name.Substring(0, pi.Name.Length - 7));
                    serializer.Serialize(writer, subTracker);
                }
            }

            writer.WriteEndObject();
        }
    }
}

using System;
using System.Reflection;
using Newtonsoft.Json;

namespace TrackableData.Json
{
    public class TrackableContainerTrackerJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(IContainerTracker).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.StartObject)
                return null;

            var tracker = (ITracker)Activator.CreateInstance(objectType);
            reader.Read();
            while (true)
            {
                if (reader.TokenType != JsonToken.PropertyName)
                    break;

                var pi = objectType.GetProperty((string)reader.Value + "Tracker");
                reader.Read();

                var subTracker = serializer.Deserialize(reader, pi.PropertyType);
                reader.Read();

                pi.SetValue(tracker, subTracker, null);
            }

            return tracker;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var tracker = (ITracker)value;

            writer.WriteStartObject();

            foreach (var pi in value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                if (typeof(ITracker).IsAssignableFrom(pi.PropertyType) == false)
                    continue;

                var subTracker = (ITracker)pi.GetValue(value, null);
                if (subTracker != null && subTracker.HasChange)
                {
                    writer.WritePropertyName(pi.Name.Substring(0, pi.Name.Length - 7));
                    serializer.Serialize(writer, subTracker);
                }
            }

            writer.WriteEndObject();
        }
    }
}

Fix .NET 3.5 build error

Fix .NET 3.5 build error


// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ApiResponse.cs" company="Dan Barua">
//   (C) Dan Barua and contributors. Licensed under the Mozilla Public License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace NEventSocket.FreeSwitch
{
    using System;

    using NEventSocket.Util;

    /// <summary>
    /// A message representing the response to an Api call.
    /// </summary>
    [Serializable]
    public class ApiResponse : BasicMessage
    {
        internal ApiResponse(BasicMessage basicMessage)
        {
            if (basicMessage.ContentType != ContentTypes.ApiResponse)
            {
                throw new ArgumentException("Expected content type api/response, got {0} instead.".Fmt(basicMessage.ContentType));
            }

            this.Headers = basicMessage.Headers;
            this.BodyText = basicMessage.BodyText;
        }

        /// <summary>
        /// Gets a boolean indicating whether the operation succeeded or not.
        /// </summary>
        public bool Success
        {
            get
            {
                return this.BodyText != null && this.BodyText[0] == '+';
            }
        }

        /// <summary>
        /// Gets the error message for a failed api call.
        /// </summary>
        public string ErrorMessage
        {
            get
            {
                return this.BodyText != null && this.BodyText.StartsWith("-ERR")
                           ? this.BodyText.Substring(5, this.BodyText.Length - 5)
                           : string.Empty;
            }
        }
    }
}

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ApiResponse.cs" company="Dan Barua">
//   (C) Dan Barua and contributors. Licensed under the Mozilla Public License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace NEventSocket.FreeSwitch
{
    using System;

    using NEventSocket.Util;

    /// <summary>
    /// A message representing the response to an Api call.
    /// </summary>
    [Serializable]
    public class ApiResponse : BasicMessage
    {
        internal ApiResponse(BasicMessage basicMessage)
        {
            if (basicMessage.ContentType != ContentTypes.ApiResponse)
            {
                throw new ArgumentException("Expected content type api/response, got {0} instead.".Fmt(basicMessage.ContentType));
            }

            this.Headers = basicMessage.Headers;
            this.BodyText = basicMessage.BodyText;
        }

        /// <summary>
        /// Gets a boolean indicating whether the operation succeeded or not.
        /// </summary>
        public bool Success
        {
            get
            {
                return this.BodyText != null && this.BodyText[0] != '-';
            }
        }

        /// <summary>
        /// Gets the error message for a failed api call.
        /// </summary>
        public string ErrorMessage
        {
            get
            {
                return this.BodyText != null && this.BodyText.StartsWith("-ERR")
                           ? this.BodyText.Substring(5, this.BodyText.Length - 5)
                           : string.Empty;
            }
        }
    }
}

Fix api response success detection (sometimes body contains response, no +OK


using System.Collections.Generic;
using System.Text.RegularExpressions;
using JabbR.ContentProviders.Core;

namespace JabbR.ContentProviders
{
    public class VimeoContentProvider : EmbedContentProvider
    {
        private static readonly Regex _vimeoIdRegex = new Regex(@"(\d+)");

        protected override Regex ParameterExtractionRegex
        {
            get
            {
                return _vimeoIdRegex;
            }
        }

        public override IEnumerable<string> Domains
        {
            get
            {
                yield return "http://vimeo.com";
                yield return "http://www.vimeo.com";
            }
        }

        public override string MediaFormatString
        {
            get
            {
                return "<object width=\"500\" height=\"282  \">" +
                    "<param name=\"allowfullscreen\" value=\"true\" />" +
                    "<param name=\"allowscriptaccess\" value=\"always\" />" +
                    "<param name=\"movie\" value=\"http://vimeo.com/moogaloop.swf?clip_id={0}&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0\" />" +
                    "<embed src=\"http://vimeo.com/moogaloop.swf?clip_id={0}&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0\" " +
                    "type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" allowscriptaccess=\"always\" width=\"500\" height=\"282\">" +
                    "</embed></object>";
            }
        }
    }
}

using System.Collections.Generic;
using System.Text.RegularExpressions;
using JabbR.ContentProviders.Core;

namespace JabbR.ContentProviders
{
    public class VimeoContentProvider : EmbedContentProvider
    {
        private static readonly Regex _vimeoIdRegex = new Regex(@"(\d+)");

        protected override Regex ParameterExtractionRegex
        {
            get
            {
                return _vimeoIdRegex;
            }
        }

        public override IEnumerable<string> Domains
        {
            get
            {
                yield return "http://vimeo.com";
                yield return "http://www.vimeo.com";
            }
        }

        public override string MediaFormatString
        {
            get
            {
                return @"<iframe src=""https://player.vimeo.com/video/{0}?title=0&byline=0&portrait=0&color=c9ff23"" width=""500"" height=""271"" frameborder=""0"" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>";
            }
        }
    }
}

Use new style embed for vimeo links and made it https.


// 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.Testing;
using osu.Game.Graphics;
using osu.Game.Graphics.Backgrounds;

namespace osu.Game.Tournament.Tests
{
    public class TournamentTestBrowser : TournamentGameBase
    {
        protected override void LoadComplete()
        {
            base.LoadComplete();

            LoadComponentAsync(new Background("Menu/menu-background-0")
            {
                Colour = OsuColour.Gray(0.5f),
                Depth = 10
            }, AddInternal);

            // Have to construct this here, rather than in the constructor, because
            // we depend on some dependencies to be loaded within OsuGameBase.load().
            Add(new TestBrowser());
        }
    }
}

// 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.Testing;
using osu.Game.Graphics;
using osu.Game.Graphics.Backgrounds;

namespace osu.Game.Tournament.Tests
{
    public class TournamentTestBrowser : TournamentGameBase
    {
        protected override void LoadComplete()
        {
            base.LoadComplete();

            LoadComponentAsync(new Background("Menu/menu-background-0")
            {
                Colour = OsuColour.Gray(0.5f),
                Depth = 10
            }, AddInternal);

            MenuCursorContainer.Cursor.AlwaysPresent = true;
            MenuCursorContainer.Cursor.Alpha = 0;

            // Have to construct this here, rather than in the constructor, because
            // we depend on some dependencies to be loaded within OsuGameBase.load().
            Add(new TestBrowser());
        }
    }
}

Hide in-game cursor manually in the testbrowser


using Chalmers.ILL.Models;
using Examine;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Chalmers.ILL.Extensions;
using Chalmers.ILL.OrderItems;

namespace Chalmers.ILL.Providers
{
    public class ProviderService : IProviderService
    {
        IOrderItemSearcher _orderItemsSearcher;

        public ProviderService(IOrderItemSearcher orderItemsSearcher)
        {
            _orderItemsSearcher = orderItemsSearcher;
        }

        public List<String> FetchAndCreateListOfUsedProviders()
        {
            var res = new List<String>();

            // NOTE: Should probably only fetch orders that are not too old, to keep the numbers down and to keep the data relevant.
            var allOrders = _orderItemsSearcher.Search("nodeTypeAlias:ChalmersILLOrderItem");

            return allOrders.Where(x => x.ProviderName != "")
                .Select(x => x.ProviderName)
                .GroupBy(x => x)
                .OrderByDescending(x => x.Count())
                .Select(x => x.Key)
                .ToList();
        }

        public int GetSuggestedDeliveryTimeInHoursForProvider(string providerName)
        {
            int res = 168;

            if (!String.IsNullOrWhiteSpace(providerName) && providerName.ToLower().Contains("subito"))
            {
                res = 24;
            }

            return res;
        }
    }
}

using Chalmers.ILL.Models;
using Examine;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Chalmers.ILL.Extensions;
using Chalmers.ILL.OrderItems;

namespace Chalmers.ILL.Providers
{
    public class ProviderService : IProviderService
    {
        IOrderItemSearcher _orderItemsSearcher;

        public ProviderService(IOrderItemSearcher orderItemsSearcher)
        {
            _orderItemsSearcher = orderItemsSearcher;
        }

        public List<String> FetchAndCreateListOfUsedProviders()
        {
            var res = new List<String>();

            // NOTE: Should probably only fetch orders that are not too old, to keep the numbers down and to keep the data relevant.
            var allOrders = _orderItemsSearcher.Search("*:*");

            return allOrders.Where(x => x.ProviderName != "")
                .Select(x => x.ProviderName)
                .GroupBy(x => x)
                .OrderByDescending(x => x.Count())
                .Select(x => x.Key)
                .ToList();
        }

        public int GetSuggestedDeliveryTimeInHoursForProvider(string providerName)
        {
            int res = 168;

            if (!String.IsNullOrWhiteSpace(providerName) && providerName.ToLower().Contains("subito"))
            {
                res = 24;
            }

            return res;
        }
    }
}

Create list of used providers properly.

Create list of used providers properly.


using LiteNetLib.Utils;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

namespace LiteNetLibHighLevel
{
    public class NetFieldStruct<T> : LiteNetLibNetField<T>
        where T : struct
    {
        public override void Deserialize(NetDataReader reader)
        {
            using (MemoryStream memoryStream = new MemoryStream(reader.GetBytesWithLength()))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                // Setup Unity's structs serialization surrogates
                var surrogateSelector = new SurrogateSelector();
                surrogateSelector.AddAllUnitySurrogate();
                binaryFormatter.SurrogateSelector = surrogateSelector;
                // Deserialize
                var data = binaryFormatter.Deserialize(memoryStream);
                Value = (T)data;
            }
        }

        public override void Serialize(NetDataWriter writer)
        {
            using (var memoryStream = new MemoryStream())
            {
                var binaryFormatter = new BinaryFormatter();
                // Setup Unity's structs serialization surrogates
                var surrogateSelector = new SurrogateSelector();
                surrogateSelector.AddAllUnitySurrogate();
                binaryFormatter.SurrogateSelector = surrogateSelector;
                // Serialize and put to packet
                binaryFormatter.Serialize(memoryStream, Value);
                memoryStream.Flush();
                memoryStream.Seek(0, SeekOrigin.Begin);
                var bytes = memoryStream.ToArray();
                writer.PutBytesWithLength(bytes);
            }
        }

        public override bool IsValueChanged(T newValue)
        {
            return !newValue.Equals(Value);
        }
    }
}

using LiteNetLib.Utils;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

namespace LiteNetLibHighLevel
{
    public class NetFieldStruct<T> : LiteNetLibNetField<T>
        where T : struct
    {
        public override void Deserialize(NetDataReader reader)
        {
            using (MemoryStream memoryStream = new MemoryStream(reader.GetBytesWithLength()))
            {
                var binaryFormatter = new BinaryFormatter();
                // Setup Unity's structs serialization surrogates
                var surrogateSelector = new SurrogateSelector();
                surrogateSelector.AddAllUnitySurrogate();
                binaryFormatter.SurrogateSelector = surrogateSelector;
                // Deserialize
                var data = binaryFormatter.Deserialize(memoryStream);
                Value = (T)data;
            }
        }

        public override void Serialize(NetDataWriter writer)
        {
            using (var memoryStream = new MemoryStream())
            {
                var binaryFormatter = new BinaryFormatter();
                // Setup Unity's structs serialization surrogates
                var surrogateSelector = new SurrogateSelector();
                surrogateSelector.AddAllUnitySurrogate();
                binaryFormatter.SurrogateSelector = surrogateSelector;
                // Serialize and put to packet
                binaryFormatter.Serialize(memoryStream, Value);
                memoryStream.Flush();
                memoryStream.Seek(0, SeekOrigin.Begin);
                var bytes = memoryStream.ToArray();
                writer.PutBytesWithLength(bytes);
            }
        }

        public override bool IsValueChanged(T newValue)
        {
            return !newValue.Equals(Value);
        }
    }
}

Use var instead of full type name

Use var instead of full type name


@model IEnumerable<MMLibrarySystem.Models.BorrowRecord>

@{
    ViewBag.Title = "Borrowed Books";
}

            Book Number

            Title

            Borrowed By

            Borrowed Start From

            State

            Operation

    @{
        foreach (var item in Model)
        {

            @item.Book.BookNumber

            @item.Book.BookType.Title

            @item.User.DisplayName

            @item.BorrowedDate

            @(item.IsCheckedOut ? "Checked Out" : "Borrow Accepted")

                @{
            if (item.IsCheckedOut)
            {
                    @Html.ActionLink("Return", "Return", "Admin", new { borrowId = @item.BorrowRecordId }, null)
            }
            else
            {
                    @Html.ActionLink("Check Out", "CheckOut", "Admin", new { borrowId = @item.BorrowRecordId }, null)
            }
                }

      }
    }

@model IEnumerable<MMLibrarySystem.Models.BorrowRecord>

@{
    ViewBag.Title = "Borrowed Books";
}

            Book Number

            Title

            Borrowed By

            Borrowed Start From

            State

            Operation

    @{
        foreach (var item in Model)
        {

            @item.Book.BookNumber

            @item.Book.BookType.Title

            @item.User.DisplayName

            @item.BorrowedDate

            @(item.IsCheckedOut ? "Checked Out" : "Borrow Accepted")

                @{
            if (item.IsCheckedOut)
            {
                    @Html.ActionLink("Return", "Return", "Admin", new { borrowId = @item.BorrowRecordId }, new { onclick = "return confirm('Are you sure to return this book?')" })
            }
            else
            {
                    @Html.ActionLink("Check Out", "CheckOut", "Admin", new { borrowId = @item.BorrowRecordId }, null)
            }
                }

      }
    }

Add a confirm to revert while wrong operation.


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

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;

namespace SimpleCollectionView
{
    [Register ("AppDelegate")]
    public partial class AppDelegate : UIApplicationDelegate
    {
        // class-level declarations
        UIWindow window;
        UICollectionViewController simpleCollectionViewController;
        CircleLayout circleLayout;
        LineLayout lineLayout;
        UICollectionViewFlowLayout flowLayout;

        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            window = new UIWindow (UIScreen.MainScreen.Bounds);

            // Flow Layout
            flowLayout = new UICollectionViewFlowLayout (){
                HeaderReferenceSize = new System.Drawing.SizeF (100, 100),
                SectionInset = new UIEdgeInsets (20,20,20,20),
                ScrollDirection = UICollectionViewScrollDirection.Vertical
            };

            // Line Layout
            lineLayout = new LineLayout (){
                HeaderReferenceSize = new System.Drawing.SizeF (160, 100),
                ScrollDirection = UICollectionViewScrollDirection.Horizontal
            };

            // Circle Layout
            circleLayout = new CircleLayout ();

            simpleCollectionViewController = new SimpleCollectionViewController (flowLayout);
//            simpleCollectionViewController = new SimpleCollectionViewController (lineLayout);
//            simpleCollectionViewController = new SimpleCollectionViewController (circleLayout);

            simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (50, 0, 0, 0);

            window.RootViewController = simpleCollectionViewController;
            window.MakeKeyAndVisible ();

            return true;
        }
    }
}

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

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;

namespace SimpleCollectionView
{
    [Register ("AppDelegate")]
    public partial class AppDelegate : UIApplicationDelegate
    {
        // class-level declarations
        UIWindow window;
        UICollectionViewController simpleCollectionViewController;
        CircleLayout circleLayout;
        LineLayout lineLayout;
        UICollectionViewFlowLayout flowLayout;

        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            window = new UIWindow (UIScreen.MainScreen.Bounds);

            // Flow Layout
            flowLayout = new UICollectionViewFlowLayout (){
                HeaderReferenceSize = new System.Drawing.SizeF (100, 100),
                SectionInset = new UIEdgeInsets (20,20,20,20),
                ScrollDirection = UICollectionViewScrollDirection.Vertical,
				MinimumInteritemSpacing = 50, // minimum spacing between cells
				MinimumLineSpacing = 50 // minimum spacing between rows if ScrollDirection is Vertical or between columns if Horizontal
            };

            // Line Layout
            lineLayout = new LineLayout (){
                HeaderReferenceSize = new System.Drawing.SizeF (160, 100),
                ScrollDirection = UICollectionViewScrollDirection.Horizontal
            };

            // Circle Layout
            circleLayout = new CircleLayout ();

            simpleCollectionViewController = new SimpleCollectionViewController (flowLayout);
//            simpleCollectionViewController = new SimpleCollectionViewController (lineLayout);
//            simpleCollectionViewController = new SimpleCollectionViewController (circleLayout);

            simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (50, 0, 0, 0);

            window.RootViewController = simpleCollectionViewController;
            window.MakeKeyAndVisible ();

            return true;
        }
    }
}

Set MinimumInteritemSpacing and MinimumLineSpacing on flow layout


using System.Threading;
using Xunit;

namespace RockLib.Messaging.NamedPipes.Tests
{
    public class NamedPipesTests
    {
        [Fact]
        public void NamedPipeMessagesAreSentAndReceived()
        {
            var waitHandle = new AutoResetEvent(false);

            using (var receiver = new NamedPipeReceiver("foo", "test-pipe"))
            {
                string payload = null;

                receiver.Start(m =>
                {
                    payload = m.StringPayload;
                    m.Acknowledge();
                    waitHandle.Set();
                });

                using (var sender = new NamedPipeSender("foo", "test-pipe"))
                {
                    sender.Send("Hello, world!");
                }

                waitHandle.WaitOne();

                Assert.Equal("Hello, world!", payload);
            }
        }
    }
}

using System.Threading;
using Xunit;

namespace RockLib.Messaging.NamedPipes.Tests
{
    public class NamedPipesTests
    {
        [Fact]
        public void NamedPipeMessagesAreSentAndReceived()
        {
            var waitHandle = new AutoResetEvent(false);

            using (var receiver = new NamedPipeReceiver("foo", "test-pipe"))
            {
                string payload = null;
                string headerValue = null;

                receiver.Start(m =>
                {
                    payload = m.StringPayload;
                    headerValue = m.Headers.GetValue<string>("bar");
                    m.Acknowledge();
                    waitHandle.Set();
                });

                using (var sender = new NamedPipeSender("foo", "test-pipe"))
                {
                    sender.Send(new SenderMessage("Hello, world!") { Headers = { { "bar", "abc" } } });
                }

                waitHandle.WaitOne();

                Assert.Equal("Hello, world!", payload);
                Assert.Equal("abc", headerValue);
            }
        }
    }
}

Include header in named pipe test

Include header in named pipe test


@model IEnumerable<alert_roster.web.Models.User>

@{
    ViewBag.Title = "View Subscriptions";
}

@ViewBag.Title

    @Html.ActionLink("Create New", "Subscribe")

@if (TempData["Message"] != null)
{

@TempData["Message"]

}

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

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

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

    @foreach (var item in Model)
    {

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

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

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

                @Html.ActionLink("Unsubscribe", "Unsubscribe", new { id = item.ID })

    }

@model IEnumerable<alert_roster.web.Models.User>

@{
    ViewBag.Title = "View Subscriptions";
}

@ViewBag.Title

    @Html.ActionLink("Create New", "Subscribe")

@if (TempData["Message"] != null)
{

@TempData["Message"]

}

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

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

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

    @foreach (var item in Model)
    {

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

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

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

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

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

                @Html.ActionLink("Unsubscribe", "Unsubscribe", new { id = item.ID })

    }

Add SMS to list page

Add SMS to list page


using ClosedXML.Excel;
using NUnit.Framework;
using System;
using System.Data;

namespace ClosedXML_Tests.Excel
{
    public class NumberFormatTests
    {
        [Test]
        public void PreserveCellFormat()
        {
            using (var wb = new XLWorkbook())
            {
                var ws = wb.AddWorksheet("Sheet1");

                var table = new DataTable();
                table.Columns.Add("Date", typeof(DateTime));

                for (int i = 0; i < 10; i++)
                {
                    table.Rows.Add(new DateTime(2017, 1, 1).AddMonths(i));
                }

                ws.Column(1).Style.NumberFormat.Format = "yy-MM-dd";
                ws.Cell("A1").InsertData(table);
                Assert.AreEqual("yy-MM-dd", ws.Cell("A5").Style.DateFormat.Format);

                ws.Row(1).Style.NumberFormat.Format = "yy-MM-dd";
                ws.Cell("A1").InsertData(table.AsEnumerable(), true);
                Assert.AreEqual("yy-MM-dd", ws.Cell("E1").Style.DateFormat.Format);
            }
        }
    }
}

using ClosedXML.Excel;
using NUnit.Framework;
using System;
using System.Data;

namespace ClosedXML_Tests.Excel
{
    public class NumberFormatTests
    {
        [Test]
        public void PreserveCellFormat()
        {
            using (var wb = new XLWorkbook())
            {
                var ws = wb.AddWorksheet("Sheet1");

                var table = new DataTable();
                table.Columns.Add("Date", typeof(DateTime));

                for (int i = 0; i < 10; i++)
                {
                    table.Rows.Add(new DateTime(2017, 1, 1).AddMonths(i));
                }

                ws.Column(1).Style.NumberFormat.Format = "yy-MM-dd";
                ws.Cell("A1").InsertData(table);
                Assert.AreEqual("yy-MM-dd", ws.Cell("A5").Style.DateFormat.Format);

                ws.Row(1).Style.NumberFormat.Format = "yy-MM-dd";
                ws.Cell("A1").InsertData(table.AsEnumerable(), true);
                Assert.AreEqual("yy-MM-dd", ws.Cell("E1").Style.DateFormat.Format);
            }
        }

        [Test]
        public void TestExcelNumberFormats()
        {
            using (var wb = new XLWorkbook())
            {
                var ws = wb.AddWorksheet("Sheet1");
                var c = ws.FirstCell()
                    .SetValue(41573.875)
                    .SetDataType(XLDataType.DateTime);

                c.Style.NumberFormat.SetFormat("m/d/yy\\ h:mm;@");

                Assert.AreEqual("10/26/13 21:00", c.GetFormattedString());
            }
        }
    }
}

Add unit test for at least one previously mistreated formula


using System.Xml.Serialization;

namespace EarTrumpet.Actions.DataModel.Serialization
{
    public class AppRef
    {
        public static readonly string EveryAppId = "EarTrumpet.EveryApp";
        public static readonly string ForegroundAppId = "EarTrumpet.ForegroundApp";

        public string Id { get; set; }

        public override int GetHashCode()
        {
            return Id == null ? 0 : Id.GetHashCode();
        }

        public bool Equals(AppRef other)
        {
            return other.Id == Id;
        }
    }
}

Fix EarTrumpet.Web deps after - to . rename


using System.Web.Routing;
using ConsolR.Hosting.Web;
using SignalR;

namespace ConsolR.Hosting
{
	[assembly: WebActivator.PostApplicationStartMethod(typeof(ConsolR.Hosting.Bootstrapper), "PreApplicationStart")]

	public static class Bootstrapper
	{
		public static void PreApplicationStart()
		{
			var routes = RouteTable.Routes;
			routes.MapHttpHandler<Handler>("consolr/validate");
			routes.MapHttpHandler<Handler>("consolr");
			routes.MapConnection<ExecuteEndPoint>("consolr-execute", "consolr/execute/{*operation}");
		}
	}
}

using System.Web.Routing;
using ConsolR.Hosting.Web;
using SignalR;

[assembly: WebActivator.PostApplicationStartMethod(typeof(ConsolR.Hosting.Bootstrapper), "PreApplicationStart")]

namespace ConsolR.Hosting
{
	public static class Bootstrapper
	{
		public static void PreApplicationStart()
		{
			var routes = RouteTable.Routes;
			routes.MapHttpHandler<Handler>("consolr/validate");
			routes.MapHttpHandler<Handler>("consolr");
			routes.MapConnection<ExecuteEndPoint>("consolr-execute", "consolr/execute/{*operation}");
		}
	}
}

Move assembly directive out of namespace


@using System.Linq;
@using AutoRest.Core.ClientModel
@using AutoRest.Core.Utilities
@using AutoRest.Java.Azure.TemplateModels
@inherits AutoRest.Core.Template<AutoRest.Java.Azure.TemplateModels.AzureServiceClientTemplateModel>
/**
 * The interface defining all the services for @Model.Name to be
 * used by Retrofit to perform actually REST calls.
 */
interface @Model.ServiceClientServiceType {
@foreach (AzureMethodTemplateModel method in Model.MethodTemplateModels)
{
if (method.RequestContentType == "multipart/form-data" || method.RequestContentType == "application/x-www-form-urlencoded")
{
@:    @@Multipart
}
else
{
@:    @@Headers("Content-Type: @method.RequestContentType")
}
if (method.HttpMethod == HttpMethod.Delete)
{
@:    @@HTTP(path = "@(method.Url.TrimStart('/'))", method = "DELETE", hasBody = true)
}
else if (method.IsPagingNextOperation)
{
@:    @@GET
}
else
{
@:    @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))")
}
if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream))
{
@:    @@Streaming
}
@:    Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration);
@EmptyLine
}
}

@using System.Linq;
@using AutoRest.Core.ClientModel
@using AutoRest.Core.Utilities
@using AutoRest.Java.Azure.TemplateModels
@inherits AutoRest.Core.Template<AutoRest.Java.Azure.TemplateModels.AzureServiceClientTemplateModel>
/**
 * The interface defining all the services for @Model.Name to be
 * used by Retrofit to perform actually REST calls.
 */
interface @Model.ServiceClientServiceType {
@foreach (AzureMethodTemplateModel method in Model.MethodTemplateModels)
{
if (method.RequestContentType == "multipart/form-data" || method.RequestContentType == "application/x-www-form-urlencoded")
{
@:    @@Multipart
}
else
{
@:    @@Headers("Content-Type: @method.RequestContentType")
}
if (method.HttpMethod == HttpMethod.Delete)
{
@:    @@HTTP(path = "@(method.Url.TrimStart('/'))", method = "DELETE", hasBody = true)
}
else
{
@:    @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))")
}
if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream))
{
@:    @@Streaming
}
@:    Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration);
@EmptyLine
}
}

Fix paging next in service client level methods


using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Nerdle.AutoConfig.Strategy;
using NUnit.Framework;

namespace Nerdle.AutoConfig.Tests.Unit.Strategy.StrategyManagerTests
{
    [TestFixture]
    class When_creating_a_strategy
    {
        StrategyManager _sut;

        [SetUp]
        public void BeforeEach()
        {
            _sut = new StrategyManager();
        }

        [Test]
        public void The_strategy_configuration_action_is_called()
        {
            var theActionWasCalled = false;
            _sut.UpdateStrategy<ICloneable>(strategy => { theActionWasCalled = true; });
            theActionWasCalled.Should().BeTrue();
        }

        public void Strategy_updates_are_applied_progressively()
        {
            var strategies = new List<IConfigureMappingStrategy<ICloneable>>();

            for (var i = 0; i < 10; i++)
            {
                _sut.UpdateStrategy<ICloneable>(strategy => { strategies.Add(strategy); });
            }

            // 10 configurations were invoked
            strategies.Count.Should().Be(10);
            // all the configurations were invoked on the same strategy object
            strategies.Distinct().Should().HaveCount(1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Nerdle.AutoConfig.Strategy;
using NUnit.Framework;

namespace Nerdle.AutoConfig.Tests.Unit.Strategy.StrategyManagerTests
{
    [TestFixture]
    class When_creating_a_strategy
    {
        StrategyManager _sut;

        [SetUp]
        public void BeforeEach()
        {
            _sut = new StrategyManager();
        }

        [Test]
        public void The_strategy_configuration_action_is_called()
        {
            var theActionWasCalled = false;
            _sut.UpdateStrategy<ICloneable>(strategy => { theActionWasCalled = true; });
            theActionWasCalled.Should().BeTrue();
        }

        [Test]
        public void Strategy_updates_are_applied_progressively()
        {
            var strategies = new List<IConfigureMappingStrategy<ICloneable>>();

            for (var i = 0; i < 10; i++)
            {
                _sut.UpdateStrategy<ICloneable>(strategy => { strategies.Add(strategy); });
            }

            // 10 configurations were invoked
            strategies.Count.Should().Be(10);
            // all the configurations were invoked on the same strategy object
            strategies.Distinct().Should().HaveCount(1);
        }
    }
}

Add missing [Test] attribute on test method


using System.Dynamic;
using System.IO;
using System.Management.Automation;
using System.Reflection;

namespace ConfigPS
{
    public class Global : DynamicObject
    {
        readonly PowerShell ps;

        public Global()
        {
            var fileName = Path.GetFileName(Assembly.GetCallingAssembly().CodeBase);
            var configFileName = fileName + ".ps1";
            ps = PowerShell.Create();

            if (File.Exists(configFileName))
            {
                const string initScript = @"
                        function Add-ConfigItem($name, $value)
                        {
                            Set-Variable -Name $name -Value $value -Scope global
                        }
                    ";

                ps.AddScript(initScript);
                ps.Invoke();

                var profileScript = File.ReadAllText(configFileName);
                ps.AddScript(profileScript);
                ps.Invoke();
            }
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = ps.Runspace.SessionStateProxy.GetVariable(binder.Name);
            return true;
        }
    }
}

using System.Dynamic;
using System.IO;
using System.Management.Automation;
using System.Reflection;

namespace ConfigPS
{
    public class Global : DynamicObject
    {
        readonly PowerShell ps;

        public Global(string configFileName = null)
        {
            if (configFileName == null)
            {
                var fileName = Path.GetFileName(Assembly.GetCallingAssembly().CodeBase);
                configFileName = fileName + ".ps1";
            }

            ps = PowerShell.Create();

            if (File.Exists(configFileName))
            {
                const string initScript = @"
                        function Add-ConfigItem($name, $value)
                        {
                            Set-Variable -Name $name -Value $value -Scope global
                        }
                    ";

                ps.AddScript(initScript);
                ps.Invoke();

                var profileScript = File.ReadAllText(configFileName);
                ps.AddScript(profileScript);
                ps.Invoke();
            }
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = ps.Runspace.SessionStateProxy.GetVariable(binder.Name);
            return true;
        }
    }
}

Allow config file to passed in

Allow config file to passed in


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

namespace RailPhase.Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a simple web app and serve content on to URLs.
            var app = new App();

            // Define the URL patterns
            app.AddUrlPattern("^/$", (request) => new HttpResponse("
Hello World
"));
            app.AddUrlPattern("^/info$", InfoView);

            app.RunTestServer();
        }

        ///
        /// A view that generates a simple request info page
        ///
        static HttpResponse InfoView(RailPhase.HttpRequest request)
        {
            // Get the template for the info page.
            var render = Template.FromFile("InfoTemplate.html");

            // Pass the HttpRequest as the template context, because we want
            // to display information about the request. Normally, we would
            // pass some custom object here, containing the information we
            // want to display.
            var body = render(request);

            // Return a simple Http response.
            // We could also return non-HTML content or error codes here
            // by setting the parameters in the HttpResponse constructor.
            return new HttpResponse(body);
        }
    }

    public class DemoContext
    {
        public string Heading;
        public string Username;
    }
}

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

namespace RailPhase.Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a simple web app and serve content on to URLs.
            var app = new App();

            // Define the URL patterns to respond to incoming requests.
            // Any request that does not match one of these patterns will
            // be served by app.NotFoundView, which defaults to a simple
            // 404 message.

            // Easiest way to respond to a request: return a string
            app.AddUrlPattern("^/$", (request) => "Hello World");
            // More complex response, see below
            app.AddUrlPattern("^/info$", InfoView);

            // Start listening for HTTP requests. Default port is 8080.
            // This method does never return!
            app.RunTestServer();

            // Now you should be able to visit me in your browser on http://localhost:8080
        }

        /// <summary>
        /// A view that generates a simple request info page
        /// </summary>
        static HttpResponse InfoView(RailPhase.HttpRequest request)
        {
            // Get the template for the info page.
            var render = Template.FromFile("InfoTemplate.html");

            // Pass the HttpRequest as the template context, because we want
            // to display information about the request. Normally, we would
            // pass some custom object here, containing the information we
            // want to display.
            var body = render(context: request);

            // Return a simple Http response.
            // We could also return non-HTML content or error codes here
            // by setting the parameters in the HttpResponse constructor.
            return new HttpResponse(body);
        }
    }

    public class DemoContext
    {
        public string Heading;
        public string Username;
    }
}

Update demo app with more comments

Update demo app with more comments


using System;
using System.Linq;

namespace CefSharp.Example
{
    public static class CefExample
    {
        public const string DefaultUrl = "custom://cefsharp/BindingTest.html";

        // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
        private const bool debuggingSubProcess = true;

        public static void Init()
        {
            var settings = new CefSettings();
            settings.RemoteDebuggingPort = 8088;
            //settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
            //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
            settings.LogSeverity = LogSeverity.Verbose;

            if (debuggingSubProcess)
            {
                var architecture = Environment.Is64BitProcess ? "x64" : "x86";
                settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
            }

            settings.RegisterScheme(new CefCustomScheme
            {
                SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
                SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
            });

            if (!Cef.Initialize(settings))
            {
                if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
                {
                    Environment.Exit(0);
                }
                else
                {
                    return;
                }
            }
        }
    }
}

using System;
using System.Diagnostics;
using System.Linq;

namespace CefSharp.Example
{
    public static class CefExample
    {
        public const string DefaultUrl = "custom://cefsharp/BindingTest.html";

        // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
        private static readonly bool DebuggingSubProcess = Debugger.IsAttached;

        public static void Init()
        {
            var settings = new CefSettings();
            settings.RemoteDebuggingPort = 8088;
            //settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
            //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
            settings.LogSeverity = LogSeverity.Verbose;

            if (DebuggingSubProcess)
            {
                var architecture = Environment.Is64BitProcess ? "x64" : "x86";
                settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
            }

            settings.RegisterScheme(new CefCustomScheme
            {
                SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
                SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
            });

            if (!Cef.Initialize(settings))
            {
                if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
                {
                    Environment.Exit(0);
                }
                else
                {
                    return;
                }
            }
        }
    }
}

Set DebuggingSubProcess = Debugger.IsAttached rather than a hard coded value


using System;
using System.Collections.Generic;

namespace compiler.middleend.ir
{
	//TODO: redisign this class and its supporting classes
	public class BasicBlock
	{
        public string Name { get;  }
		public List<Instruction> Instructions{ get; set; }

		public Anchor AnchorBlock { get; set; }

		public BasicBlock()
		{
			Instructions = new List<Instruction>();
			AnchorBlock = new Anchor();
		}

        public BasicBlock(string pName)
        {
            Instructions = new List<Instruction>();
            Name = pName;
            AnchorBlock = new Anchor();
        }

        public void AddInstruction(Instruction ins)
		{
			Instructions.Add(ins);
			AnchorBlock.Insert(ins);
		}

		public Instruction Search(Instruction ins)
		{
			var instList = AnchorBlock.FindOpChain(ins.Op);

			foreach(var item in instList)
			{
				if (item.Equals(ins))
					return item;
			}

			return null;
		}

	}
}

using System;
using System.Collections.Generic;

namespace compiler.middleend.ir
{
	//TODO: redisign this class and its supporting classes
	public class BasicBlock
	{
        public string Name { get;  }
		public List<Instruction> Instructions{ get; set; }

		public Anchor AnchorBlock { get; set; }

		public BasicBlock()
		{
			Instructions = new List<Instruction>();
			AnchorBlock = new Anchor();
		}

        public BasicBlock(string pName)
        {
            Instructions = new List<Instruction>();
            Name = pName;
            AnchorBlock = new Anchor();
        }

        public void AddInstruction(Instruction ins)
		{
			Instructions.Add(ins);
			AnchorBlock.Insert(ins);
		}

		public Instruction Search(Instruction ins)
		{
			var instList = AnchorBlock.FindOpChain(ins.Op);

		    if (instList != null)
		    {

		        foreach (var item in instList)
		        {
		            if (item.Equals(ins))
		                return item;
		        }
		    }

		    return null;
		}

	}
}

Add check for possible null reference

Add check for possible null reference


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StackExchange.DataExplorer.Helpers;
using System.Text;

namespace StackExchange.DataExplorer.Models {
    public partial class Query {

        public string BodyWithoutComments {
            get {
                ParsedQuery pq = new ParsedQuery(this.QueryBody, null);
                return pq.ExecutionSql;
            }
        }

        public void UpdateQueryBodyComment() {
            StringBuilder buffer = new StringBuilder();

            if (Name != null) {
                buffer.Append(ToComment(Name));
                buffer.Append("\n");
            }

            if (Description != null) {
                buffer.Append(ToComment(Description));
                buffer.Append("\n");
            }

            buffer.Append("\n");
            buffer.Append(BodyWithoutComments);

            QueryBody = buffer.ToString();
        }

        private string ToComment(string text) {

            string rval = text.Replace("\r\n", "\n");
            rval = "-- " + rval;
            rval = rval.Replace("\n", "\n-- ");
            if (rval.Contains("\n--")) {
                rval = rval.Substring(0, rval.Length - 3);
            }
            return rval;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StackExchange.DataExplorer.Helpers;
using System.Text;

namespace StackExchange.DataExplorer.Models {
    public partial class Query {

        public string BodyWithoutComments {
            get {
                ParsedQuery pq = new ParsedQuery(this.QueryBody, null);
                return pq.ExecutionSql;
            }
        }

        public void UpdateQueryBodyComment() {
            StringBuilder buffer = new StringBuilder();

            if (Name != null) {
                buffer.Append(ToComment(Name));
                buffer.Append("\n");
            }

            if (Description != null) {
                buffer.Append(ToComment(Description));
                buffer.Append("\n");
            }

            buffer.Append("\n");
            buffer.Append(BodyWithoutComments);

            QueryBody = buffer.ToString();
        }

        private string ToComment(string text) {

            if (string.IsNullOrEmpty(text)) return "";
            if (text != null) text = text.Trim();

            string rval = text.Replace("\r\n", "\n");
            rval = "-- " + rval;
            rval = rval.Replace("\n", "\n-- ");

            return rval;
        }
    }
}

Clean up ToComment so it handles a few edge cases a bit better


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public struct CategoryItem
{
    public string name;
    public SoundItem[] soundItems;
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public struct CategoryItem
{
    public string name;
    public SoundItem[] soundItems;
    public GameObject audioObjectPrefab;
}

Add possibility to add custom AudioObject prefab.