Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Handle hastebin failure in the CodePaste module
using Discord.Commands; using Modix.Services.AutoCodePaste; using System.Threading.Tasks; namespace Modix.Modules { [Name("Code Paste"), Summary("Paste some code to the internet.")] public class CodePasteModule : ModuleBase { private CodePasteService _service; public CodePasteModule(CodePasteService service) { _service = service; } [Command("paste"), Summary("Paste the rest of your message to the internet, and return the URL.")] public async Task Run([Remainder] string code) { string url = await _service.UploadCode(Context.Message, code); var embed = _service.BuildEmbed(Context.User, code, url); await ReplyAsync(Context.User.Mention, false, embed); await Context.Message.DeleteAsync(); } } }
using Discord.Commands; using Modix.Services.AutoCodePaste; using System.Net; using System.Threading.Tasks; namespace Modix.Modules { [Name("Code Paste"), Summary("Paste some code to the internet.")] public class CodePasteModule : ModuleBase { private CodePasteService _service; public CodePasteModule(CodePasteService service) { _service = service; } [Command("paste"), Summary("Paste the rest of your message to the internet, and return the URL.")] public async Task Run([Remainder] string code) { string url = null; string error = null; try { url = await _service.UploadCode(Context.Message, code); } catch (WebException ex) { url = null; error = ex.Message; } if (url != null) { var embed = _service.BuildEmbed(Context.User, code, url); await ReplyAsync(Context.User.Mention, false, embed); await Context.Message.DeleteAsync(); } else { await ReplyAsync(error); } } } }
Fix failing test ... by removing it
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(), 5); Assert.AreEqual(ClassLibrary1.Class1.ReturnSix(), 6); } [TestMethod] public void ShouldFail() { Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(), ClassLibrary1.Class1.ReturnSix()); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(), 5); Assert.AreEqual(ClassLibrary1.Class1.ReturnSix(), 6); } } }
Fix to convert paragraph tag with single carriage return
using System; using System.Linq; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class P : ConverterBase { public P(Converter converter) : base(converter) { Converter.Register("p", this); } public override string Convert(HtmlNode node) { var indentation = IndentationFor(node); return $"{indentation}{TreatChildren(node).Trim()}{Environment.NewLine}{Environment.NewLine}"; } private static string IndentationFor(HtmlNode node) { var length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count(); return node.ParentNode.Name.ToLowerInvariant() == "li" && node.ParentNode.FirstChild != node ? new string(' ', length * 4) : Environment.NewLine + Environment.NewLine; } } }
using System; using System.Linq; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class P : ConverterBase { public P(Converter converter) : base(converter) { Converter.Register("p", this); } public override string Convert(HtmlNode node) { var indentation = IndentationFor(node); return $"{indentation}{TreatChildren(node).Trim()}{Environment.NewLine}"; } private static string IndentationFor(HtmlNode node) { var length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count(); return node.ParentNode.Name.ToLowerInvariant() == "li" && node.ParentNode.FirstChild != node ? new string(' ', length * 4) : Environment.NewLine; } } }
Add test to verify overwriting of values.
using System; using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.TeamFoundation.Authentication.Test { /// <summary> /// A class to test <see cref="Configuration"/>. /// </summary> [TestClass] public class ConfigurationTests { [TestMethod] public void ParseGitConfig_Simple() { const string input = @" [core] autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } private static Dictionary<string, string> TestParseGitConfig(string input) { var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); using (var sr = new StringReader(input)) { Configuration.ParseGitConfig(sr, values); } return values; } } }
using System; using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.TeamFoundation.Authentication.Test { /// <summary> /// A class to test <see cref="Configuration"/>. /// </summary> [TestClass] public class ConfigurationTests { [TestMethod] public void ParseGitConfig_Simple() { const string input = @" [core] autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } [TestMethod] public void ParseGitConfig_OverwritesValues() { // http://thedailywtf.com/articles/What_Is_Truth_0x3f_ const string input = @" [core] autocrlf = true autocrlf = FileNotFound autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } private static Dictionary<string, string> TestParseGitConfig(string input) { var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); using (var sr = new StringReader(input)) { Configuration.ParseGitConfig(sr, values); } return values; } } }
Add function to get deductions from a payrun for a specific employee
using KeyPay.DomainModels.V2.PayRun; using RestSharp; namespace KeyPay.ApiFunctions.V2 { public class PayRunDeductionFunction : BaseFunction { public PayRunDeductionFunction(ApiRequestExecutor api) : base(api) { } public DeductionsResponse List(int businessId, int payRunId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions"); } public DeductionModel Submit(int businessId, SubmitDeductionsRequest deductions) { return ApiRequest<DeductionModel, SubmitDeductionsRequest>("/business/" + businessId + "/payrun/" + deductions.PayRunId + "/deductions", deductions, Method.POST); } } }
using KeyPay.DomainModels.V2.PayRun; using RestSharp; namespace KeyPay.ApiFunctions.V2 { public class PayRunDeductionFunction : BaseFunction { public PayRunDeductionFunction(ApiRequestExecutor api) : base(api) { } public DeductionsResponse List(int businessId, int payRunId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions"); } public DeductionsResponse List(int businessId, int payRunId, int employeeId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions/" + employeeId); } public DeductionModel Submit(int businessId, SubmitDeductionsRequest deductions) { return ApiRequest<DeductionModel, SubmitDeductionsRequest>("/business/" + businessId + "/payrun/" + deductions.PayRunId + "/deductions", deductions, Method.POST); } } }
Change app to use minified files
using System.Web; using System.Web.Optimization; namespace ClubChallengeBeta { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); //blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js", "~/Scripts/blueimp-gallery.js", "~/Scripts/bootstrap-image-gallery.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/blueimp-gallery.css", "~/Content/bootstrap-image-gallery.css", "~/Content/bootstrap-social.css", "~/Content/font-awesome.css", "~/Content/ionicons.css", "~/Content/site.css")); } } }
using System.Web; using System.Web.Optimization; namespace ClubChallengeBeta { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.min.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); //blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.min.js", "~/Scripts/respond.min.js", "~/Scripts/blueimp-gallery.min.js", "~/Scripts/bootstrap-image-gallery.min.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.min.css", "~/Content/blueimp-gallery.min.css", "~/Content/bootstrap-image-gallery.min.css", "~/Content/bootstrap-social.css", "~/Content/font-awesome.css", "~/Content/ionicons.min.css", "~/Content/site.css")); } } }
Remove windows long filename prefix
using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; namespace Tgstation.Server.Host.Watchdog { /// <summary> /// See <see cref="IActiveAssemblyDeleter"/> for Windows systems /// </summary> sealed class WindowsActiveAssemblyDeleter : IActiveAssemblyDeleter { /// <summary> /// Set a file located at <paramref name="path"/> to be deleted on reboot /// </summary> /// <param name="path">The file to delete on reboot</param> [ExcludeFromCodeCoverage] static void DeleteFileOnReboot(string path) { if (!NativeMethods.MoveFileEx(path, null, NativeMethods.MoveFileFlags.DelayUntilReboot)) throw new Win32Exception(Marshal.GetLastWin32Error()); } /// <inheritdoc /> public void DeleteActiveAssembly(string assemblyPath) { if (assemblyPath == null) throw new ArgumentNullException(nameof(assemblyPath)); //Can't use Path.GetTempFileName() because it may cross drives, which won't actually rename the file //Also append the long path prefix just in case we're running on .NET framework var tmpLocation = String.Concat(@"\\?\", assemblyPath, Guid.NewGuid()); File.Move(assemblyPath, tmpLocation); DeleteFileOnReboot(tmpLocation); } } }
using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; namespace Tgstation.Server.Host.Watchdog { /// <summary> /// See <see cref="IActiveAssemblyDeleter"/> for Windows systems /// </summary> sealed class WindowsActiveAssemblyDeleter : IActiveAssemblyDeleter { /// <summary> /// Set a file located at <paramref name="path"/> to be deleted on reboot /// </summary> /// <param name="path">The file to delete on reboot</param> [ExcludeFromCodeCoverage] static void DeleteFileOnReboot(string path) { if (!NativeMethods.MoveFileEx(path, null, NativeMethods.MoveFileFlags.DelayUntilReboot)) throw new Win32Exception(Marshal.GetLastWin32Error()); } /// <inheritdoc /> public void DeleteActiveAssembly(string assemblyPath) { if (assemblyPath == null) throw new ArgumentNullException(nameof(assemblyPath)); //Can't use Path.GetTempFileName() because it may cross drives, which won't actually rename the file var tmpLocation = String.Concat(assemblyPath, Guid.NewGuid()); File.Move(assemblyPath, tmpLocation); DeleteFileOnReboot(tmpLocation); } } }
Fix namespace issue in uwp
using MarcelloDB.Collections; using MarcelloDB.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace MarcelloDB.uwp { public class Platform : IPlatform { public Storage.IStorageStreamProvider CreateStorageStreamProvider(string rootPath) { return new FileStorageStreamProvider(GetFolderForPath(rootPath)); } StorageFolder GetFolderForPath(string path) { var getFolderTask = StorageFolder.GetFolderFromPathAsync(path).AsTask(); getFolderTask.ConfigureAwait(false); getFolderTask.Wait(); return getFolderTask.Result; } } }
using MarcelloDB.Collections; using MarcelloDB.Platform; using MarcelloDB.Storage; using MarcelloDB.uwp.Storage; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace MarcelloDB.uwp { public class Platform : IPlatform { public IStorageStreamProvider CreateStorageStreamProvider(string rootPath) { return new FileStorageStreamProvider(GetFolderForPath(rootPath)); } StorageFolder GetFolderForPath(string path) { var getFolderTask = StorageFolder.GetFolderFromPathAsync(path).AsTask(); getFolderTask.ConfigureAwait(false); getFolderTask.Wait(); return getFolderTask.Result; } } }
Add new method to overwrite TransactionDetail line with a new string.
using System.Collections.Generic; namespace BankFileParsers { public class BaiDetail { public string TransactionDetail { get; private set; } public List<string> DetailContinuation { get; internal set; } public BaiDetail(string line) { TransactionDetail = line; DetailContinuation = new List<string>(); } } }
using System.Collections.Generic; namespace BankFileParsers { public class BaiDetail { public string TransactionDetail { get; private set; } public List<string> DetailContinuation { get; internal set; } public BaiDetail(string line) { TransactionDetail = line; DetailContinuation = new List<string>(); } /// <summary> /// Overwrite the TransactionDetail line with a new string /// </summary> /// <param name="line">New string to overwrite with</param> public void SetTransactionDetail(string line) { TransactionDetail = line; } } }
Replace obsolete NavMeshAgent interface fot he newer one
using UnityEngine; [CreateAssetMenu (menuName = "AI/Actions/Enemy_Patrol")] public class Action_Patrol : Action { public override void Act(StateController controller) { Act(controller as Enemy_StateController); } public void Act(Enemy_StateController controller) { Patrol(controller); } private void Patrol(Enemy_StateController controller) { controller.navMeshAgent.destination = controller.movementVariables.wayPointList [controller.movementVariables.nextWayPoint].position; controller.navMeshAgent.Resume (); if (controller.navMeshAgent.remainingDistance <= controller.navMeshAgent.stoppingDistance && !controller.navMeshAgent.pathPending) { controller.movementVariables.nextWayPoint = (controller.movementVariables.nextWayPoint + 1) % controller.movementVariables.wayPointList.Count; } } }
using UnityEngine; [CreateAssetMenu (menuName = "AI/Actions/Enemy_Patrol")] public class Action_Patrol : Action { public override void Act(StateController controller) { Act(controller as Enemy_StateController); } public void Act(Enemy_StateController controller) { Patrol(controller); } private void Patrol(Enemy_StateController controller) { controller.navMeshAgent.destination = controller.movementVariables.wayPointList [controller.movementVariables.nextWayPoint].position; controller.navMeshAgent.isStopped = false; if (controller.navMeshAgent.remainingDistance <= controller.navMeshAgent.stoppingDistance && !controller.navMeshAgent.pathPending) { controller.movementVariables.nextWayPoint = (controller.movementVariables.nextWayPoint + 1) % controller.movementVariables.wayPointList.Count; } } }
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.AggregateService")] [assembly: AssemblyDescription("")]
using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.AggregateService")]
Add HasClass extension method for IWebElement
using OpenQA.Selenium; using System; namespace Atata { // TODO: Review IWebElementExtensions class. Remove unused methods. public static class IWebElementExtensions { public static WebElementExtendedSearchContext Try(this IWebElement element) { return new WebElementExtendedSearchContext(element); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout) { return new WebElementExtendedSearchContext(element, timeout); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout, TimeSpan retryInterval) { return new WebElementExtendedSearchContext(element, timeout, retryInterval); } public static bool HasContent(this IWebElement element, string content) { return element.Text.Contains(content); } public static string GetValue(this IWebElement element) { return element.GetAttribute("value"); } public static IWebElement FillInWith(this IWebElement element, string text) { element.Clear(); if (!string.IsNullOrEmpty(text)) element.SendKeys(text); return element; } } }
using System; using System.Linq; using OpenQA.Selenium; namespace Atata { // TODO: Review IWebElementExtensions class. Remove unused methods. public static class IWebElementExtensions { public static WebElementExtendedSearchContext Try(this IWebElement element) { return new WebElementExtendedSearchContext(element); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout) { return new WebElementExtendedSearchContext(element, timeout); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout, TimeSpan retryInterval) { return new WebElementExtendedSearchContext(element, timeout, retryInterval); } public static bool HasContent(this IWebElement element, string content) { return element.Text.Contains(content); } public static bool HasClass(this IWebElement element, string className) { return element.GetAttribute("class").Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Contains(className); } public static string GetValue(this IWebElement element) { return element.GetAttribute("value"); } public static IWebElement FillInWith(this IWebElement element, string text) { element.Clear(); if (!string.IsNullOrEmpty(text)) element.SendKeys(text); return element; } } }
Use public interface in test app
using System; using Xamarin.Forms; namespace XamarinTest { public class App : Application { public App () { // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { XAlign = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" } } } }; } protected override void OnStart () { TelemetryManager.TrackEvent ("My Shared Event"); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
using System; using Xamarin.Forms; namespace XamarinTest { public class App : Application { public App () { // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { XAlign = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" } } } }; } protected override void OnStart () { TelemetryManager.TrackEvent ("My Shared Event"); ApplicationInsights.RenewSessionWithId ("MySession"); ApplicationInsights.SetUserId ("Christoph"); TelemetryManager.TrackMetric ("My custom metric", 2.2); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
Fix remote API load order
using NLog; using Sandbox; using Torch.API; using Torch.Managers; using VRage.Dedicated.RemoteAPI; namespace Torch.Server.Managers { public class RemoteAPIManager : Manager { /// <inheritdoc /> public RemoteAPIManager(ITorchBase torchInstance) : base(torchInstance) { } /// <inheritdoc /> public override void Attach() { if (MySandboxGame.ConfigDedicated.RemoteApiEnabled && !string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.RemoteSecurityKey)) { var myRemoteServer = new MyRemoteServer(MySandboxGame.ConfigDedicated.RemoteApiPort, MySandboxGame.ConfigDedicated.RemoteSecurityKey); LogManager.GetCurrentClassLogger().Info($"Remote API started on port {myRemoteServer.Port}"); } base.Attach(); } } }
using NLog; using Sandbox; using Torch.API; using Torch.Managers; using VRage.Dedicated.RemoteAPI; namespace Torch.Server.Managers { public class RemoteAPIManager : Manager { /// <inheritdoc /> public RemoteAPIManager(ITorchBase torchInstance) : base(torchInstance) { } /// <inheritdoc /> public override void Attach() { Torch.GameStateChanged += TorchOnGameStateChanged; base.Attach(); } /// <inheritdoc /> public override void Detach() { Torch.GameStateChanged -= TorchOnGameStateChanged; base.Detach(); } private void TorchOnGameStateChanged(MySandboxGame game, TorchGameState newstate) { if (newstate == TorchGameState.Loading && MySandboxGame.ConfigDedicated.RemoteApiEnabled && !string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.RemoteSecurityKey)) { var myRemoteServer = new MyRemoteServer(MySandboxGame.ConfigDedicated.RemoteApiPort, MySandboxGame.ConfigDedicated.RemoteSecurityKey); LogManager.GetCurrentClassLogger().Info($"Remote API started on port {myRemoteServer.Port}"); } } } }
Fix regex pattern in removing emotes.
using System.Text.RegularExpressions; namespace MarekMotykaBot.ExtensionsMethods { public static class StringExtensions { public static string RemoveRepeatingChars(this string inputString) { string newString = string.Empty; char[] charArray = inputString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { if (string.IsNullOrEmpty(newString)) newString += charArray[i].ToString(); else if (newString[newString.Length - 1] != charArray[i]) newString += charArray[i].ToString(); } return newString; } public static string RemoveEmojis(this string inputString) { return Regex.Replace(inputString, @"[^a-zA-Z0-9żźćńółęąśŻŹĆĄŚĘŁÓŃ\s\?\.\,\!\-\']+", "", RegexOptions.Compiled); } public static string RemoveEmotes(this string inputString) { return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled); } public static string RemoveEmojisAndEmotes(this string inputString) { return inputString.RemoveEmotes().RemoveEmojis(); } } }
using System.Text.RegularExpressions; namespace MarekMotykaBot.ExtensionsMethods { public static class StringExtensions { public static string RemoveRepeatingChars(this string inputString) { string newString = string.Empty; char[] charArray = inputString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { if (string.IsNullOrEmpty(newString)) newString += charArray[i].ToString(); else if (newString[newString.Length - 1] != charArray[i]) newString += charArray[i].ToString(); } return newString; } public static string RemoveEmojis(this string inputString) { return Regex.Replace(inputString, @"[^a-zA-Z0-9żźćńółęąśŻŹĆĄŚĘŁÓŃ\s\?\.\,\!\-]+", "", RegexOptions.Compiled); } public static string RemoveEmotes(this string inputString) { return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled); } public static string RemoveEmojisAndEmotes(this string inputString) { return inputString.RemoveEmotes().RemoveEmojis(); } } }
Add input binder to allow for comma-separated list inputs for API routes
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace api { public class CommaDelimitedArrayModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelMetadata.IsEnumerableType) { var key = bindingContext.ModelName; var value = bindingContext.ValueProvider.GetValue(key).ToString(); if (!string.IsNullOrWhiteSpace(value)) { var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Result = ModelBindingResult.Success(typedValues); } else { Console.WriteLine("string was empty"); // change this line to null if you prefer nulls to empty arrays bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0)); } return Task.CompletedTask; } Console.WriteLine("Not enumerable"); return Task.CompletedTask; } } }
using System; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace api { public class CommaDelimitedArrayModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelMetadata.IsEnumerableType) { var key = bindingContext.ModelName; var value = bindingContext.ValueProvider.GetValue(key).ToString(); if (!string.IsNullOrWhiteSpace(value)) { var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Result = ModelBindingResult.Success(typedValues); } else { Console.WriteLine("string was empty"); // change this line to null if you prefer nulls to empty arrays bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0)); } return Task.CompletedTask; } Console.WriteLine("Not enumerable"); return Task.CompletedTask; } } }
Modify WhatDoIHave to show expected result
using Core; using StructureMap; using System.Diagnostics; using Xunit; namespace Tests { public class TroubleshootingTests { [Fact] public void ShowBuildPlan() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var buildPlan = container.Model.For<IService>() .Default .DescribeBuildPlan(); var expectedBuildPlan = @"PluginType: Core.IService Lifecycle: Transient new Service() "; Assert.Equal(expectedBuildPlan, buildPlan); } [Fact] public void WhatDoIHave() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var whatDoIHave = container.WhatDoIHave(); Trace.Write(whatDoIHave); } } }
using Core; using StructureMap; using Xunit; namespace Tests { public class TroubleshootingTests { [Fact] public void ShowBuildPlan() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var buildPlan = container.Model.For<IService>() .Default .DescribeBuildPlan(); var expectedBuildPlan = @"PluginType: Core.IService Lifecycle: Transient new Service() "; Assert.Equal(expectedBuildPlan, buildPlan); } [Fact] public void WhatDoIHave() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var whatDoIHave = container.WhatDoIHave(); var expectedWhatDoIHave = @" =================================================================================================== PluginType Namespace Lifecycle Description Name --------------------------------------------------------------------------------------------------- Func<TResult> System Transient Open Generic Template for Func<> (Default) --------------------------------------------------------------------------------------------------- Func<T, TResult> System Transient Open Generic Template for Func<,> (Default) --------------------------------------------------------------------------------------------------- IContainer StructureMap Singleton Object: StructureMap.Container (Default) --------------------------------------------------------------------------------------------------- IService Core Transient Core.Service (Default) --------------------------------------------------------------------------------------------------- Lazy<T> System Transient Open Generic Template for Func<> (Default) ==================================================================================================="; Assert.Equal(expectedWhatDoIHave, whatDoIHave); } } }
Handle empty entity name in rescuer
using Rescuer.Management.Rescuers; namespace Rescuer.Management.Controller { public class RescuerController : IRescuerController { private readonly IRescuerFactory _factory; public RescuerController(IRescuerFactory factory) { _factory = factory; } public IRescuer[] IntializeRescuers(string[] monitoredEntities) { var rescuers = new IRescuer[monitoredEntities.Length]; for (int i = 0; i < rescuers.Length; i++) { rescuers[i] = _factory.Create(); rescuers[i].Connect(monitoredEntities[i]); } return rescuers; } public void DoWork(IRescuer[] rescuers) { for (int i = 0; i < rescuers.Length; i++) { rescuers[i].MonitorAndRescue(); } } } }
using System; using System.Text; using Rescuer.Management.Rescuers; namespace Rescuer.Management.Controller { public class RescuerController : IRescuerController { private readonly IRescuerFactory _factory; public RescuerController(IRescuerFactory factory) { _factory = factory; } public IRescuer[] IntializeRescuers(string[] monitoredEntities) { var rescuers = new IRescuer[monitoredEntities.Length]; for (int i = 0; i < rescuers.Length; i++) { if (String.IsNullOrWhiteSpace(monitoredEntities[i])) { var entitiesString = ToFlatString(monitoredEntities); throw new ArgumentException($"monitored entity name can't be null or empty! FailedIndex: {i} Array: [{entitiesString}]"); } rescuers[i] = _factory.Create(); rescuers[i].Connect(monitoredEntities[i]); } return rescuers; } public void DoWork(IRescuer[] rescuers) { for (int i = 0; i < rescuers.Length; i++) { rescuers[i].MonitorAndRescue(); } } private static string ToFlatString(string[] array) { var builder = new StringBuilder(); foreach (var entity in array) { builder.Append(entity); builder.Append(","); } var str = builder.ToString(); return str.Remove(str.Length - 1, 1); } } }
Fix string test for ubuntu
namespace ReamQuery.Test { using System; using Xunit; using ReamQuery.Helpers; using Microsoft.CodeAnalysis.Text; public class Helpers { [Fact] public void String_InsertTextAt() { var inp = "\r\n text\r\n"; var exp = "\r\n new text\r\n"; var output = inp.InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines_And_InsertTextAt() { var inp = "\r\n text\n"; var exp = "\r\n new text\r\n"; var output = inp.NormalizeNewlines().InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines() { var inp = "\r\n text\n"; var exp = Environment.NewLine + " text" + Environment.NewLine; var output = inp.NormalizeNewlines(); Assert.Equal(exp, output); } [Fact] public void String_ReplaceToken() { var inp = Environment.NewLine + Environment.NewLine + " token " + Environment.NewLine; var exp = Environment.NewLine + Environment.NewLine + " " + Environment.NewLine; LinePosition pos; var output = inp.ReplaceToken("token", string.Empty, out pos); Assert.Equal(new LinePosition(2, 1), pos); Assert.Equal(exp, output); } } }
namespace ReamQuery.Test { using System; using Xunit; using ReamQuery.Helpers; using Microsoft.CodeAnalysis.Text; public class Helpers { [Fact] public void String_InsertTextAt() { var inp = Environment.NewLine + " text" + Environment.NewLine; var exp = Environment.NewLine + " new text" + Environment.NewLine; var output = inp.InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines_And_InsertTextAt() { var inp = "\r\n text\n"; var exp = Environment.NewLine + " new text" + Environment.NewLine; var output = inp.NormalizeNewlines().InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines() { var inp = "\r\n text\n"; var exp = Environment.NewLine + " text" + Environment.NewLine; var output = inp.NormalizeNewlines(); Assert.Equal(exp, output); } [Fact] public void String_ReplaceToken() { var inp = Environment.NewLine + Environment.NewLine + " token " + Environment.NewLine; var exp = Environment.NewLine + Environment.NewLine + " " + Environment.NewLine; LinePosition pos; var output = inp.ReplaceToken("token", string.Empty, out pos); Assert.Equal(new LinePosition(2, 1), pos); Assert.Equal(exp, output); } } }
Disable delayed messages to see what effect it has on tests.
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Foundatio.Extensions; using Foundatio.Utility; namespace Foundatio.Messaging { public abstract class MessageBusBase : IMessagePublisher, IDisposable { private readonly CancellationTokenSource _queueDisposedCancellationTokenSource; private readonly List<DelayedMessage> _delayedMessages = new List<DelayedMessage>(); public MessageBusBase() { _queueDisposedCancellationTokenSource = new CancellationTokenSource(); TaskHelper.RunPeriodic(DoMaintenance, TimeSpan.FromMilliseconds(500), _queueDisposedCancellationTokenSource.Token, TimeSpan.FromMilliseconds(100)); } private Task DoMaintenance() { Trace.WriteLine("Doing maintenance..."); foreach (var message in _delayedMessages.Where(m => m.SendTime <= DateTime.Now).ToList()) { _delayedMessages.Remove(message); Publish(message.MessageType, message.Message); } return TaskHelper.Completed(); } public abstract void Publish(Type messageType, object message, TimeSpan? delay = null); protected void AddDelayedMessage(Type messageType, object message, TimeSpan delay) { if (message == null) throw new ArgumentNullException("message"); _delayedMessages.Add(new DelayedMessage { Message = message, MessageType = messageType, SendTime = DateTime.Now.Add(delay) }); } protected class DelayedMessage { public DateTime SendTime { get; set; } public Type MessageType { get; set; } public object Message { get; set; } } public virtual void Dispose() { _queueDisposedCancellationTokenSource.Cancel(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Foundatio.Extensions; using Foundatio.Utility; namespace Foundatio.Messaging { public abstract class MessageBusBase : IMessagePublisher, IDisposable { private readonly CancellationTokenSource _queueDisposedCancellationTokenSource; private readonly List<DelayedMessage> _delayedMessages = new List<DelayedMessage>(); public MessageBusBase() { _queueDisposedCancellationTokenSource = new CancellationTokenSource(); //TaskHelper.RunPeriodic(DoMaintenance, TimeSpan.FromMilliseconds(500), _queueDisposedCancellationTokenSource.Token, TimeSpan.FromMilliseconds(100)); } private Task DoMaintenance() { Trace.WriteLine("Doing maintenance..."); foreach (var message in _delayedMessages.Where(m => m.SendTime <= DateTime.Now).ToList()) { _delayedMessages.Remove(message); Publish(message.MessageType, message.Message); } return TaskHelper.Completed(); } public abstract void Publish(Type messageType, object message, TimeSpan? delay = null); protected void AddDelayedMessage(Type messageType, object message, TimeSpan delay) { if (message == null) throw new ArgumentNullException("message"); _delayedMessages.Add(new DelayedMessage { Message = message, MessageType = messageType, SendTime = DateTime.Now.Add(delay) }); } protected class DelayedMessage { public DateTime SendTime { get; set; } public Type MessageType { get; set; } public object Message { get; set; } } public virtual void Dispose() { _queueDisposedCancellationTokenSource.Cancel(); } } }
Revert "(GH-36) Fix broken test"
using System; using Shouldly; using Xunit; namespace Cake.Figlet.Tests { public class FigletTests { [Fact] public void Figlet_can_render() { const string expected = @" _ _ _ _ __ __ _ _ | | | | ___ | || | ___ \ \ / / ___ _ __ | | __| | | |_| | / _ \| || | / _ \ \ \ /\ / / / _ \ | '__|| | / _` | | _ || __/| || || (_) | _ \ V V / | (_) || | | || (_| | |_| |_| \___||_||_| \___/ ( ) \_/\_/ \___/ |_| |_| \__,_| |/ "; FigletAliases.Figlet(null, "Hello, World").ShouldBeWithLeadingLineBreak(expected); } } public static class ShouldlyAsciiExtensions { /// <summary> /// Helper to allow the expected ASCII art to be on it's own line when declaring /// the expected value in the source code /// </summary> /// <param name="input">The input.</param> /// <param name="expected">The expected.</param> public static void ShouldBeWithLeadingLineBreak(this string input, string expected) { (Environment.NewLine + input).ShouldBe(expected, StringCompareShould.IgnoreLineEndings); } } }
using System; using Shouldly; using Xunit; namespace Cake.Figlet.Tests { public class FigletTests { [Fact] public void Figlet_can_render() { const string expected = @" _ _ _ _ __ __ _ _ | | | | ___ | || | ___ \ \ / / ___ _ __ | | __| | | |_| | / _ \| || | / _ \ \ \ /\ / / / _ \ | '__|| | / _` | | _ || __/| || || (_) | _ \ V V / | (_) || | | || (_| | |_| |_| \___||_||_| \___/ ( ) \_/\_/ \___/ |_| |_| \__,_| |/ "; FigletAliases.Figlet(null, "Hello, World").ShouldBeWithLeadingLineBreak(expected); } } public static class ShouldlyAsciiExtensions { /// <summary> /// Helper to allow the expected ASCII art to be on it's own line when declaring /// the expected value in the source code /// </summary> /// <param name="input">The input.</param> /// <param name="expected">The expected.</param> public static void ShouldBeWithLeadingLineBreak(this string input, string expected) { (Environment.NewLine + input).ShouldBe(expected); } } }
Fix xml comment cref compiler warning
namespace System.Collections.Async { /// <summary> /// This exception is thrown when you call <see cref="AsyncEnumerable{T}.Break"/>. /// </summary> public sealed class ForEachAsyncCanceledException : OperationCanceledException { } }
namespace System.Collections.Async { /// <summary> /// This exception is thrown when you call <see cref="ForEachAsyncExtensions.Break"/>. /// </summary> public sealed class ForEachAsyncCanceledException : OperationCanceledException { } }
Remove session-commit statement that is not needed and already handled by middleware
using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System.Text; namespace MotleyFlash.AspNetCore.MessageProviders { public class SessionMessageProvider : IMessageProvider { public SessionMessageProvider(ISession session) { this.session = session; } private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; private readonly ISession session; private const string sessionKey = "motleyflash-session-message-provider"; public object Get() { byte[] value; object messages = null; if (session.TryGetValue(sessionKey, out value)) { if (value != null) { messages = JsonConvert.DeserializeObject( Encoding.UTF8.GetString(value, 0, value.Length), jsonSerializerSettings); } } return messages; } public void Set(object messages) { session.Set( sessionKey, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject( messages, jsonSerializerSettings))); session.CommitAsync(); } } }
using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System.Text; namespace MotleyFlash.AspNetCore.MessageProviders { public class SessionMessageProvider : IMessageProvider { public SessionMessageProvider(ISession session) { this.session = session; } private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; private readonly ISession session; private const string sessionKey = "motleyflash-session-message-provider"; public object Get() { byte[] value; object messages = null; if (session.TryGetValue(sessionKey, out value)) { if (value != null) { messages = JsonConvert.DeserializeObject( Encoding.UTF8.GetString(value, 0, value.Length), jsonSerializerSettings); } } return messages; } public void Set(object messages) { session.Set( sessionKey, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject( messages, jsonSerializerSettings))); } } }
Update to use property, not field. bugid: 146
using System; using Csla.Server; namespace Csla.Testing.Business.DataPortal { /// <summary> /// Basically this test class exposes protected DataPortal constructor overloads to the /// Unit Testing System, allowing for a more fine-grained Unit Tests /// </summary> public class TestableDataPortal : Csla.Server.DataPortal { public TestableDataPortal() : base(){} public TestableDataPortal(string cslaAuthorizationProviderAppSettingName): base(cslaAuthorizationProviderAppSettingName) { } public TestableDataPortal(Type authProviderType):base(authProviderType) { } public static void Setup() { _authorizer = null; } public Type AuthProviderType { get { return _authorizer.GetType(); } } public IAuthorizeDataPortal AuthProvider { get { return _authorizer; } } public bool NullAuthorizerUsed { get { return AuthProviderType == typeof (NullAuthorizer); } } } }
using System; using Csla.Server; namespace Csla.Testing.Business.DataPortal { /// <summary> /// Basically this test class exposes protected DataPortal constructor overloads to the /// Unit Testing System, allowing for a more fine-grained Unit Tests /// </summary> public class TestableDataPortal : Csla.Server.DataPortal { public TestableDataPortal() : base(){} public TestableDataPortal(string cslaAuthorizationProviderAppSettingName): base(cslaAuthorizationProviderAppSettingName) { } public TestableDataPortal(Type authProviderType):base(authProviderType) { } public static void Setup() { Authorizer = null; } public Type AuthProviderType { get { return Authorizer.GetType(); } } public IAuthorizeDataPortal AuthProvider { get { return Authorizer; } } public bool NullAuthorizerUsed { get { return AuthProviderType == typeof (NullAuthorizer); } } } }
Make the UWP page presenter us a common content control
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using ReactiveUI.Routing.Presentation; using Splat; namespace ReactiveUI.Routing.UWP { public class PagePresenter : Presenter<PagePresenterRequest> { private readonly Frame host; private readonly IViewLocator locator; public PagePresenter(Frame host, IViewLocator locator = null) { this.host = host ?? throw new ArgumentNullException(nameof(host)); this.locator = locator ?? Locator.Current.GetService<IViewLocator>(); } protected override IObservable<PresenterResponse> PresentCore(PagePresenterRequest request) { return Observable.Create<PresenterResponse>(o => { try { var view = locator.ResolveView(request.ViewModel); view.ViewModel = request.ViewModel; host.Navigate(view.GetType()); o.OnNext(new PresenterResponse(view)); o.OnCompleted(); } catch (Exception ex) { o.OnError(ex); } return new CompositeDisposable(); }); } public static IDisposable RegisterHost(Frame control) { var resolver = Locator.Current.GetService<IMutablePresenterResolver>(); return resolver.Register(new PagePresenter(control)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using ReactiveUI.Routing.Presentation; using Splat; namespace ReactiveUI.Routing.UWP { public class PagePresenter : Presenter<PagePresenterRequest> { private readonly ContentControl host; private readonly IViewLocator locator; public PagePresenter(ContentControl host, IViewLocator locator = null) { this.host = host ?? throw new ArgumentNullException(nameof(host)); this.locator = locator ?? Locator.Current.GetService<IViewLocator>(); } protected override IObservable<PresenterResponse> PresentCore(PagePresenterRequest request) { return Observable.Create<PresenterResponse>(o => { try { var view = locator.ResolveView(request.ViewModel); var disposable = view.WhenActivated(d => { o.OnNext(new PresenterResponse(view)); o.OnCompleted(); }); view.ViewModel = request.ViewModel; host.Content = view; return disposable; } catch (Exception ex) { o.OnError(ex); throw; } }); } public static IDisposable RegisterHost(ContentControl control) { var resolver = Locator.Current.GetService<IMutablePresenterResolver>(); return resolver.Register(new PagePresenter(control)); } } }
Fix compile error around exporting SecureString
using System; using System.Runtime.InteropServices; using System.Security; using LibGit2Sharp.Core; namespace LibGit2Sharp { /// <summary> /// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access. /// </summary> public sealed class SecureUsernamePasswordCredentials : Credentials { /// <summary> /// Callback to acquire a credential object. /// </summary> /// <param name="cred">The newly created credential object.</param> /// <returns>0 for success, &lt; 0 to indicate an error, &gt; 0 to indicate no credential was acquired.</returns> protected internal override int GitCredentialHandler(out IntPtr cred) { if (Username == null || Password == null) { throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password."); } IntPtr passwordPtr = IntPtr.Zero; try { passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password); return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Marshal.PtrToStringUni(passwordPtr)); } finally { Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr); } } /// <summary> /// Username for username/password authentication (as in HTTP basic auth). /// </summary> public string Username { get; set; } /// <summary> /// Password for username/password authentication (as in HTTP basic auth). /// </summary> public SecureString Password { get; set; } } }
using System; using System.Runtime.InteropServices; using System.Security; using LibGit2Sharp.Core; namespace LibGit2Sharp { /// <summary> /// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access. /// </summary> public sealed class SecureUsernamePasswordCredentials : Credentials { /// <summary> /// Callback to acquire a credential object. /// </summary> /// <param name="cred">The newly created credential object.</param> /// <returns>0 for success, &lt; 0 to indicate an error, &gt; 0 to indicate no credential was acquired.</returns> protected internal override int GitCredentialHandler(out IntPtr cred) { if (Username == null || Password == null) { throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password."); } IntPtr passwordPtr = IntPtr.Zero; try { #if NET40 passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password); #else passwordPtr = SecureStringMarshal.SecureStringToCoTaskMemUnicode(Password); #endif return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Marshal.PtrToStringUni(passwordPtr)); } finally { #if NET40 Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr); #else SecureStringMarshal.ZeroFreeCoTaskMemUnicode(passwordPtr); #endif } } /// <summary> /// Username for username/password authentication (as in HTTP basic auth). /// </summary> public string Username { get; set; } /// <summary> /// Password for username/password authentication (as in HTTP basic auth). /// </summary> public SecureString Password { get; set; } } }
Remove the build attributes because they'll be generated with a full namespace
//----------------------------------------------------------------------- // <copyright company="TheNucleus"> // Copyright (c) TheNucleus. All rights reserved. // Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using Nuclei.Build; [assembly: AssemblyCulture("")] // Resources [assembly: NeutralResourcesLanguage("en-US")] // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Indicate that the assembly is CLS compliant. [assembly: CLSCompliant(true)] // The time the assembly was build [assembly: AssemblyBuildTime(buildTime: "1900-01-01T00:00:00.0000000+00:00")] // The version from which the assembly was build [module: SuppressMessage( "Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Justification = "It's a VCS revision, not a version")] [assembly: AssemblyBuildInformation(buildNumber: 0, versionControlInformation: "1234567890123456789012345678901234567890")]
//----------------------------------------------------------------------- // <copyright company="TheNucleus"> // Copyright (c) TheNucleus. All rights reserved. // Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using Nuclei.Build; [assembly: AssemblyCulture("")] // Resources [assembly: NeutralResourcesLanguage("en-US")] // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Indicate that the assembly is CLS compliant. [assembly: CLSCompliant(true)]
Use the same folder as the JAVA implementation
using System; using System.Text.RegularExpressions; namespace Floobits.Common { public class Constants { static public string baseDir = FilenameUtils.concat(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "floobits"); static public string shareDir = FilenameUtils.concat(baseDir, "share"); static public string version = "0.11"; static public string pluginVersion = "0.01"; static public string OUTBOUND_FILTER_PROXY_HOST = "proxy.floobits.com"; static public int OUTBOUND_FILTER_PROXY_PORT = 443; static public string floobitsDomain = "floobits.com"; static public string defaultHost = "floobits.com"; static public int defaultPort = 3448; static public Regex NEW_LINE = new Regex("\\r\\n?", RegexOptions.Compiled); static public int TOO_MANY_BIG_DIRS = 50; } }
using System; using System.Text.RegularExpressions; namespace Floobits.Common { public class Constants { static public string baseDir = baseDirInit(); static public string shareDir = FilenameUtils.concat(baseDir, "share"); static public string version = "0.11"; static public string pluginVersion = "0.01"; static public string OUTBOUND_FILTER_PROXY_HOST = "proxy.floobits.com"; static public int OUTBOUND_FILTER_PROXY_PORT = 443; static public string floobitsDomain = "floobits.com"; static public string defaultHost = "floobits.com"; static public int defaultPort = 3448; static public Regex NEW_LINE = new Regex("\\r\\n?", RegexOptions.Compiled); static public int TOO_MANY_BIG_DIRS = 50; static public string baseDirInit() { return FilenameUtils.concat(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "floobits"); } } }
Use Timer based Observable to generate data
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataGenerator { class Program { static void Main(string[] args) { var gen = new Fare.Xeger(ConfigurationSettings.AppSettings["pattern"]); for (int i = 0; i < 25; i++) { Console.WriteLine(gen.Generate()); } Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; namespace DataGenerator { class Program { static void Main(string[] args) { var data = new Fare.Xeger(ConfigurationSettings.AppSettings["pattern"]); var tick = TimeSpan.Parse(ConfigurationSettings.AppSettings["timespan"]); Observable .Timer(TimeSpan.Zero, tick) .Subscribe( t => { Console.WriteLine(data.Generate()); } ); Console.ReadLine(); } } }
Update server side API for single multiple answer question
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } }
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } }
Remove setters from IObservable properties
namespace Mappy.Models { using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using Mappy.Data; using Mappy.Database; public interface IMapViewSettingsModel { IObservable<bool> GridVisible { get; } IObservable<Color> GridColor { get; } IObservable<Size> GridSize { get; } IObservable<bool> HeightmapVisible { get; } IObservable<bool> FeaturesVisible { get; } IObservable<IFeatureDatabase> FeatureRecords { get; } IObservable<IMainModel> Map { get; } IObservable<int> ViewportWidth { get; set; } IObservable<int> ViewportHeight { get; set; } void SetViewportSize(Size size); void SetViewportLocation(Point pos); void OpenFromDragDrop(string filename); void DragDropData(IDataObject data, Point loc); } }
namespace Mappy.Models { using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using Mappy.Data; using Mappy.Database; public interface IMapViewSettingsModel { IObservable<bool> GridVisible { get; } IObservable<Color> GridColor { get; } IObservable<Size> GridSize { get; } IObservable<bool> HeightmapVisible { get; } IObservable<bool> FeaturesVisible { get; } IObservable<IFeatureDatabase> FeatureRecords { get; } IObservable<IMainModel> Map { get; } IObservable<int> ViewportWidth { get; } IObservable<int> ViewportHeight { get; } void SetViewportSize(Size size); void SetViewportLocation(Point pos); void OpenFromDragDrop(string filename); void DragDropData(IDataObject data, Point loc); } }
Split responsibility of ConvertMovie() method
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpeningsMoeWpfClient { class FfmpegMovieConverter : IMovieConverter { private string ffmpegPath; public Task<string> ConvertMovie(string sourcePath, string targetPath) { var tcs = new TaskCompletionSource<string>(); var process = new Process { StartInfo = { UseShellExecute = false, FileName = ffmpegPath, Arguments = $@"-i ""{sourcePath}"" -vcodec msmpeg4v2 -acodec libmp3lame -strict -2 ""{targetPath}""", CreateNoWindow = true }, EnableRaisingEvents = true }; process.Exited += (sender, args) => { if(process.ExitCode == 0) tcs.SetResult(targetPath); else tcs.SetException(new InvalidOperationException("SOMETHING WENT WRONG")); process.Dispose(); }; process.Start(); process.PriorityClass = ProcessPriorityClass.BelowNormal; return tcs.Task; } public FfmpegMovieConverter(string ffmpegPath) { this.ffmpegPath = ffmpegPath; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpeningsMoeWpfClient { class FfmpegMovieConverter : IMovieConverter { private string ffmpegPath; private Task<int> LaunchProcess(Func<Process> factory, Action<Process> postLaunchConfiguration) { var tcs = new TaskCompletionSource<int>(); var process = factory(); process.Exited += (sender, args) => { tcs.SetResult(process.ExitCode); process.Dispose(); }; process.Start(); postLaunchConfiguration(process); return tcs.Task; } public async Task<string> ConvertMovie(string sourcePath, string targetPath) { int exitCode = await LaunchProcess(() => new Process { StartInfo = { UseShellExecute = false, FileName = ffmpegPath, Arguments = $@"-i ""{sourcePath}"" -vcodec msmpeg4v2 -acodec libmp3lame -strict -2 ""{targetPath}""", CreateNoWindow = true }, EnableRaisingEvents = true }, process => { process.PriorityClass = ProcessPriorityClass.BelowNormal; }); if(exitCode == 0) return targetPath; throw new InvalidOperationException("SOMETHING WENT WRONG"); } public FfmpegMovieConverter(string ffmpegPath) { this.ffmpegPath = ffmpegPath; } } }
Allow .par in auto in case of '(T) expr.par'
using System.Linq; using JetBrains.Annotations; using JetBrains.ReSharper.Feature.Services.Lookup; using JetBrains.ReSharper.PostfixTemplates.LookupItems; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; namespace JetBrains.ReSharper.PostfixTemplates.Templates { // todo: (Bar) foo.par - available in auto? [PostfixTemplate( templateName: "par", description: "Parenthesizes current expression", example: "(expr)")] public class ParenthesizedExpressionTemplate : IPostfixTemplate { public ILookupItem CreateItem(PostfixTemplateContext context) { if (context.IsAutoCompletion) return null; PrefixExpressionContext bestContext = null; foreach (var expressionContext in context.Expressions.Reverse()) { if (CommonUtils.IsNiceExpression(expressionContext.Expression)) { bestContext = expressionContext; break; } } return new ParenthesesItem(bestContext ?? context.OuterExpression); } private sealed class ParenthesesItem : ExpressionPostfixLookupItem<ICSharpExpression> { public ParenthesesItem([NotNull] PrefixExpressionContext context) : base("par", context) { } protected override ICSharpExpression CreateExpression(CSharpElementFactory factory, ICSharpExpression expression) { return factory.CreateExpression("($0)", expression); } } } }
using System.Linq; using JetBrains.Annotations; using JetBrains.ReSharper.Feature.Services.Lookup; using JetBrains.ReSharper.PostfixTemplates.LookupItems; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; namespace JetBrains.ReSharper.PostfixTemplates.Templates { [PostfixTemplate( templateName: "par", description: "Parenthesizes current expression", example: "(expr)")] public class ParenthesizedExpressionTemplate : IPostfixTemplate { public ILookupItem CreateItem(PostfixTemplateContext context) { PrefixExpressionContext bestContext = null; foreach (var expressionContext in context.Expressions.Reverse()) { if (CommonUtils.IsNiceExpression(expressionContext.Expression)) { bestContext = expressionContext; break; } } // available in auto over cast expressions var targetContext = bestContext ?? context.OuterExpression; var insideCastExpression = CastExpressionNavigator.GetByOp(targetContext.Expression) != null; if (!insideCastExpression && context.IsAutoCompletion) return null; return new ParenthesesItem(targetContext); } private sealed class ParenthesesItem : ExpressionPostfixLookupItem<ICSharpExpression> { public ParenthesesItem([NotNull] PrefixExpressionContext context) : base("par", context) { } protected override ICSharpExpression CreateExpression(CSharpElementFactory factory, ICSharpExpression expression) { return factory.CreateExpression("($0)", expression); } } } }
Fix AgileUploader (remove SO image resizer)
@using So.ImageResizer.Helpers @{ Style.Include("slimbox2.css"); Script.Require("jQuery").AtFoot(); Script.Include("slimbox2.js").AtFoot(); } @if (!string.IsNullOrEmpty(Model.ContentField.FileNames)) { <div class="stripGallery"> @foreach (var fileName in Model.ContentField.FileNames.Split(';')) { <a href="@fileName" rel="lightbox-gallery"> @{ var alternateText = string.IsNullOrEmpty(Model.ContentField.AlternateText) ? Path.GetFileNameWithoutExtension(fileName) : Model.ContentField.AlternateText; } <img width="100" height="80" src='@string.Format("/resizedImage?url={0}&width=100&height=80&maxWidth=100&maxheight=80&cropMode={1}&scale={2}&stretchMode={3}", fileName, ResizeSettingType.CropMode.Auto, ResizeSettingType.ScaleMode.DownscaleOnly, ResizeSettingType.StretchMode.Proportionally)' alt="@alternateText"/> </a> } </div> }
@{ Style.Include("slimbox2.css"); Script.Require("jQuery").AtFoot(); Script.Include("slimbox2.js").AtFoot(); } @if (!string.IsNullOrEmpty(Model.ContentField.FileNames)) { <div class="stripGallery"> @foreach (var fileName in Model.ContentField.FileNames.Split(';')) { <a href="@fileName" rel="lightbox-gallery"> @{ var alternateText = string.IsNullOrEmpty(Model.ContentField.AlternateText) ? Path.GetFileNameWithoutExtension(fileName) : Model.ContentField.AlternateText; } <img alt="@alternateText" src='@Display.ResizeMediaUrl(Width: 250, Path: fileName)' /> </a> } </div> }
Fix for Binding singleton to instance.
using System; namespace CmnTools.Suice { /// <summary> /// @author DisTurBinG /// </summary> public class SingletonProvider : AbstractProvider { internal object Instance; public SingletonProvider (Type providedType) : base(providedType) { } internal virtual void CreateSingletonInstance() { SetInstance(Activator.CreateInstance(ProvidedType, ConstructorDependencies)); } internal void SetInstance (object instance) { DependencyProxy dependencyProxy = Instance as DependencyProxy; if (dependencyProxy == null) { Instance = instance; } else { dependencyProxy.SetInstance(instance); } } protected override object ProvideObject() { return Instance ?? (Instance = new DependencyProxy (ProvidedType)); } } }
using System; namespace CmnTools.Suice { /// <summary> /// @author DisTurBinG /// </summary> public class SingletonProvider : AbstractProvider { internal object Instance; public SingletonProvider (Type providedType) : base(providedType) { } internal virtual void CreateSingletonInstance() { if (Instance == null) { SetInstance(Activator.CreateInstance(ProvidedType, ConstructorDependencies)); } } internal void SetInstance (object instance) { DependencyProxy dependencyProxy = Instance as DependencyProxy; if (dependencyProxy == null) { Instance = instance; } else { dependencyProxy.SetInstance(instance); } } protected override object ProvideObject() { return Instance ?? (Instance = new DependencyProxy (ProvidedType)); } } }
Fix NullReference when using T4MVC
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Xml.Linq; namespace Twilio.TwiML.Mvc { public class TwiMLResult : ActionResult { XDocument data; public TwiMLResult() { } public TwiMLResult(string twiml) { data = XDocument.Parse(twiml); } public TwiMLResult(XDocument twiml) { data = twiml; } public TwiMLResult(TwilioResponse response) { data = response.ToXDocument(); } public override void ExecuteResult(ControllerContext controllerContext) { var context = controllerContext.RequestContext.HttpContext; context.Response.ContentType = "application/xml"; if (data == null) { data = new XDocument(new XElement("Response")); } data.Save(context.Response.Output); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Xml.Linq; namespace Twilio.TwiML.Mvc { public class TwiMLResult : ActionResult { XDocument data; public TwiMLResult() { } public TwiMLResult(string twiml) { data = XDocument.Parse(twiml); } public TwiMLResult(XDocument twiml) { data = twiml; } public TwiMLResult(TwilioResponse response) { if (response != null) data = response.ToXDocument(); } public override void ExecuteResult(ControllerContext controllerContext) { var context = controllerContext.RequestContext.HttpContext; context.Response.ContentType = "application/xml"; if (data == null) { data = new XDocument(new XElement("Response")); } data.Save(context.Response.Output); } } }
Fix a bug of wrong counting characters with HTTPS URL
using System.Linq; using System.Text.RegularExpressions; namespace Inscribe.Text { public static class TweetTextCounter { public static int Count(string input) { // URL is MAX 19 Chars. int prevIndex = 0; int totalCount = 0; foreach (var m in RegularExpressions.UrlRegex.Matches(input).OfType<Match>()) { totalCount += m.Index - prevIndex; prevIndex = m.Index + m.Groups[0].Value.Length; if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength) totalCount += m.Groups[0].Value.Length; else totalCount += TwitterDefine.UrlMaxLength; } totalCount += input.Length - prevIndex; return totalCount; } } }
using System.Linq; using System.Text.RegularExpressions; namespace Inscribe.Text { public static class TweetTextCounter { public static int Count(string input) { // URL is MAX 20 Chars (if URL has HTTPS scheme, URL is MAX 21 Chars) int prevIndex = 0; int totalCount = 0; foreach (var m in RegularExpressions.UrlRegex.Matches(input).OfType<Match>()) { totalCount += m.Index - prevIndex; prevIndex = m.Index + m.Groups[0].Value.Length; bool isHasHttpsScheme = m.Groups[0].Value.Contains("https"); if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0)) totalCount += m.Groups[0].Value.Length; else totalCount += TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0); } totalCount += input.Length - prevIndex; return totalCount; } } }
Add problem function (with IsMacroType=true)
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using ExcelDna.Integration; namespace RtdArrayTest { public static class TestFunctions { public static object RtdArrayTest(string prefix) { object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, prefix); var resultString = rtdValue as string; if (resultString == null) return rtdValue; // We have a string value, parse and return as an 2x1 array var parts = resultString.Split(';'); Debug.Assert(parts.Length == 2); var result = new object[2, 1]; result[0, 0] = parts[0]; result[1, 0] = parts[1]; return result; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using ExcelDna.Integration; namespace RtdArrayTest { public static class TestFunctions { public static object RtdArrayTest(string prefix) { object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, prefix); var resultString = rtdValue as string; if (resultString == null) return rtdValue; // We have a string value, parse and return as an 2x1 array var parts = resultString.Split(';'); Debug.Assert(parts.Length == 2); var result = new object[2, 1]; result[0, 0] = parts[0]; result[1, 0] = parts[1]; return result; } // NOTE: This is that problem case discussed in https://groups.google.com/d/topic/exceldna/62cgmRMVtfQ/discussion // It seems that the DisconnectData will not be called on updates triggered by parameters from the sheet // for RTD functions that are marked IsMacroType=true. [ExcelFunction(IsMacroType=true)] public static object RtdArrayTestMT(string prefix) { object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, "X" + prefix); var resultString = rtdValue as string; if (resultString == null) return rtdValue; // We have a string value, parse and return as an 2x1 array var parts = resultString.Split(';'); Debug.Assert(parts.Length == 2); var result = new object[2, 1]; result[0, 0] = parts[0]; result[1, 0] = parts[1]; return result; } } }
Use transform.Find instead of deprecated transform.FindChild
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using System.Collections; public class PortraitFlipTest : MonoBehaviour { void Update () { Transform t = gameObject.transform.FindChild("Canvas/JohnCharacter"); if (t == null) { return; } if (t.transform.localScale.x != -1f) { IntegrationTest.Fail("Character object not flipped horizontally"); } } }
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using System.Collections; public class PortraitFlipTest : MonoBehaviour { void Update () { Transform t = gameObject.transform.Find("Canvas/JohnCharacter"); if (t == null) { return; } if (t.transform.localScale.x != -1f) { IntegrationTest.Fail("Character object not flipped horizontally"); } } }
Add test description and fix param order in Assert call
using NUnit.Framework; namespace FullSerializer.Tests.InitialInstance { public class SimpleModel { public int A; } public class InitialInstanceTests { [Test] public void TestInitialInstance() { SimpleModel model1 = new SimpleModel { A = 3 }; fsData data; var serializer = new fsSerializer(); Assert.IsTrue(serializer.TrySerialize(model1, out data).Succeeded); model1.A = 1; SimpleModel model2 = model1; Assert.IsTrue(serializer.TryDeserialize(data, ref model2).Succeeded); Assert.AreEqual(model1.A, 3); Assert.AreEqual(model2.A, 3); Assert.IsTrue(ReferenceEquals(model1, model2)); } } }
using NUnit.Framework; namespace FullSerializer.Tests.InitialInstance { public class SimpleModel { public int A; } public class InitialInstanceTests { [Test] public void TestPopulateObject() { // This test verifies that when we pass in an existing object // instance that same instance is used to deserialize into, ie, // we can do the equivalent of Json.NET's PopulateObject SimpleModel model1 = new SimpleModel { A = 3 }; fsData data; var serializer = new fsSerializer(); Assert.IsTrue(serializer.TrySerialize(model1, out data).Succeeded); model1.A = 1; SimpleModel model2 = model1; Assert.AreEqual(1, model1.A); Assert.AreEqual(1, model2.A); Assert.IsTrue(serializer.TryDeserialize(data, ref model2).Succeeded); Assert.AreEqual(3, model1.A); Assert.AreEqual(3, model2.A); Assert.IsTrue(ReferenceEquals(model1, model2)); } } }
Change assembly version from 2.0.0.0 to 2.0.*
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zermelo.API")] [assembly: AssemblyDescription("Connect to Zermelo from your .NET app")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Zermelo.API")] [assembly: AssemblyCopyright("Copyright 2016 Arthur Rump")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Make internal classes and functions available for testing [assembly: InternalsVisibleTo("Zermelo.API.Tests")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zermelo.API")] [assembly: AssemblyDescription("Connect to Zermelo from your .NET app")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Zermelo.API")] [assembly: AssemblyCopyright("Copyright 2016 Arthur Rump")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] // Make internal classes and functions available for testing [assembly: InternalsVisibleTo("Zermelo.API.Tests")]
Use empty stopwords set when the default stopwords file is missing.
using System.Collections.Generic; using System.IO; namespace JiebaNet.Analyser { public abstract class KeywordExtractor { protected static readonly List<string> DefaultStopWords = new List<string>() { "the", "of", "is", "and", "to", "in", "that", "we", "for", "an", "are", "by", "be", "as", "on", "with", "can", "if", "from", "which", "you", "it", "this", "then", "at", "have", "all", "not", "one", "has", "or", "that" }; protected virtual ISet<string> StopWords { get; set; } public void SetStopWords(string stopWordsFile) { var path = Path.GetFullPath(stopWordsFile); if (File.Exists(path)) { var lines = File.ReadAllLines(path); StopWords = new HashSet<string>(); foreach (var line in lines) { StopWords.Add(line.Trim()); } } } public abstract IEnumerable<string> ExtractTags(string text, int count = 20, IEnumerable<string> allowPos = null); public abstract IEnumerable<WordWeightPair> ExtractTagsWithWeight(string text, int count = 20, IEnumerable<string> allowPos = null); } }
using System.Collections.Generic; using System.IO; namespace JiebaNet.Analyser { public abstract class KeywordExtractor { protected static readonly List<string> DefaultStopWords = new List<string>() { "the", "of", "is", "and", "to", "in", "that", "we", "for", "an", "are", "by", "be", "as", "on", "with", "can", "if", "from", "which", "you", "it", "this", "then", "at", "have", "all", "not", "one", "has", "or", "that" }; protected virtual ISet<string> StopWords { get; set; } public void SetStopWords(string stopWordsFile) { StopWords = new HashSet<string>(); var path = Path.GetFullPath(stopWordsFile); if (File.Exists(path)) { var lines = File.ReadAllLines(path); foreach (var line in lines) { StopWords.Add(line.Trim()); } } } public abstract IEnumerable<string> ExtractTags(string text, int count = 20, IEnumerable<string> allowPos = null); public abstract IEnumerable<WordWeightPair> ExtractTagsWithWeight(string text, int count = 20, IEnumerable<string> allowPos = null); } }
Fix up InternalsVisibleTo to new name
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion(SolutionInfo.Version + ".0")] [assembly: AssemblyInformationalVersion(SolutionInfo.Version)] [assembly: AssemblyFileVersion(SolutionInfo.Version + ".0")] [assembly: ComVisible(false)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("GitHub")] [assembly: AssemblyProduct("Octokit")] [assembly: AssemblyCopyright("Copyright GitHub 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Octokit.Tests")] [assembly: InternalsVisibleTo("OctokitRT.Tests")] [assembly: CLSCompliant(false)] class SolutionInfo { public const string Version = "0.1.0"; }
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion(SolutionInfo.Version + ".0")] [assembly: AssemblyInformationalVersion(SolutionInfo.Version)] [assembly: AssemblyFileVersion(SolutionInfo.Version + ".0")] [assembly: ComVisible(false)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("GitHub")] [assembly: AssemblyProduct("Octokit")] [assembly: AssemblyCopyright("Copyright GitHub 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Octokit.Tests")] [assembly: InternalsVisibleTo("Octokit.Tests-NetCore45")] [assembly: CLSCompliant(false)] class SolutionInfo { public const string Version = "0.1.0"; }
Make foreign key converter thread-safe.
using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model.ModifiedAt = new DateTime (); model = Model.Update (model); } return model; } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } }
using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); lock (Model.SyncRoot) { var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model.ModifiedAt = new DateTime (); model = Model.Update (model); } return model; } } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } }
Implement rest call to get teams.
using System; using System.Collections.Generic; using Newtonsoft.Json; using OutlookMatters.Core.Http; using OutlookMatters.Core.Mattermost.v4.Interface; namespace OutlookMatters.Core.Mattermost.v4 { public class RestService : IRestService { private readonly IHttpClient _httpClient; public RestService(IHttpClient httpClient) { _httpClient = httpClient; } public void Login(Uri baseUri, Login login, out string token) { var loginUrl = new Uri(baseUri, "api/v4/users/login"); using (var response = _httpClient.Request(loginUrl) .WithContentType("text/json") .Post(JsonConvert.SerializeObject(login))) { token = response.GetHeaderValue("Token"); } } public IEnumerable<Team> GetTeams(Uri baseUri, string token) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using OutlookMatters.Core.Http; using OutlookMatters.Core.Mattermost.v4.Interface; namespace OutlookMatters.Core.Mattermost.v4 { public class RestService : IRestService { private readonly IHttpClient _httpClient; public RestService(IHttpClient httpClient) { _httpClient = httpClient; } public void Login(Uri baseUri, Login login, out string token) { var loginUrl = new Uri(baseUri, "api/v4/users/login"); using (var response = _httpClient.Request(loginUrl) .WithContentType("application/json") .Post(JsonConvert.SerializeObject(login))) { token = response.GetHeaderValue("Token"); } } public IEnumerable<Team> GetTeams(Uri baseUri, string token) { var teamsUrl = new Uri(baseUri, "api/v4/teams"); using (var response = _httpClient.Request(teamsUrl) .WithHeader("Authorization", "Bearer " + token) .Get()) { var payload = response.GetPayload(); return JsonConvert.DeserializeObject<IEnumerable<Team>>(payload); } } } }
Fix import error in demo.
using System; using System.Collections.Generic; using Demo.Endpoints; using Distributor; namespace Demo { internal class Program { private static void Main(string[] args) { var distributables = new List<DistributableFile> { new DistributableFile { Id = Guid.NewGuid(), ProfileName = "TestProfile", Name = "test.pdf", Contents = null } }; //Configure the distributor var distributor = new Distributor<DistributableFile>(); distributor.EndpointDeliveryServices.Add(new SharepointDeliveryService()); distributor.EndpointDeliveryServices.Add(new FileSystemDeliveryService()); //Run the Distributor distributor.Distribute(distributables); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using Demo.Endpoints.FileSystem; using Demo.Endpoints.Sharepoint; using Distributor; namespace Demo { internal class Program { private static void Main(string[] args) { var distributables = new List<DistributableFile> { new DistributableFile { Id = Guid.NewGuid(), ProfileName = "TestProfile", Name = "test.pdf", Contents = null } }; //Configure the distributor var distributor = new Distributor<DistributableFile>(); distributor.EndpointDeliveryServices.Add(new SharepointDeliveryService()); distributor.EndpointDeliveryServices.Add(new FileSystemDeliveryService()); //Run the Distributor distributor.Distribute(distributables); Console.ReadLine(); } } }
Handle IPv4 Address and IPv6 Address
namespace McIP { using System; using System.Diagnostics; using System.IO; public static class Program { public static void Main() { var si = new ProcessStartInfo("ipconfig", "/all") { RedirectStandardOutput = true, UseShellExecute = false }; var p = Process.Start(si); StreamReader reader = p.StandardOutput; string heading = string.Empty; string line; while ((line = reader.ReadLine()) != null) { if (!string.IsNullOrEmpty(line) && !line.StartsWith(" ", StringComparison.Ordinal)) { heading = line; } if (line.Contains("IP Address")) { Console.WriteLine(heading); Console.WriteLine(line); Console.WriteLine(); } } } } }
namespace McIP { using System; using System.Diagnostics; using System.IO; public static class Program { public static void Main() { var si = new ProcessStartInfo("ipconfig", "/all") { RedirectStandardOutput = true, UseShellExecute = false }; var p = Process.Start(si); StreamReader reader = p.StandardOutput; string heading = string.Empty; bool headingPrinted = false; string line; while ((line = reader.ReadLine()) != null) { if (!string.IsNullOrEmpty(line) && !line.StartsWith(" ", StringComparison.Ordinal)) { heading = line; headingPrinted = false; } if (line.ContainsAny("IP Address", "IPv4 Address", "IPv6 Address")) { if (!headingPrinted) { Console.WriteLine(); Console.WriteLine(heading); headingPrinted = true; } Console.WriteLine(line); } } } private static bool ContainsAny(this string target, params string[] values) { if (values == null) { throw new ArgumentNullException("values"); } foreach (var value in values) { if (target.Contains(value)) { return true; } } return false; } } }
Create server side API for single multiple answer question
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.ApplicationClasses; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api")] public class QuestionController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleQuestion"></param> /// <returns></returns> [Route("singlemultiplequestion")] [HttpPost] public IActionResult AddSingleMultipleAnswerQuestion([FromBody]SingleMultipleQuestion singleMultipleQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleQuestion.singleMultipleAnswerQuestion,singleMultipleQuestion.singleMultipleAnswerQuestionOption); return Ok(singleMultipleQuestion); } } }
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.ApplicationClasses; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api")] public class QuestionController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleQuestion"></param> /// <returns></returns> [Route("singlemultiplequestion")] [HttpPost] public IActionResult AddSingleMultipleAnswerQuestion([FromBody]SingleMultipleQuestion singleMultipleQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleQuestion.singleMultipleAnswerQuestion,singleMultipleQuestion.singleMultipleAnswerQuestionOption); return Ok(singleMultipleQuestion); } } }
Remove timezone specification for scheduled triggers to use server timezone
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Utilities; namespace Nuke.Common.CI.TeamCity.Configuration { public class TeamCityScheduledTrigger : TeamCityTrigger { public string BranchFilter { get; set; } public string TriggerRules { get; set; } public bool TriggerBuildAlways { get; set; } //TODO: check public bool WithPendingChangesOnly { get; set; } public bool EnableQueueOptimization { get; set; } public override void Write(CustomFileWriter writer) { using (writer.WriteBlock("schedule")) { using (writer.WriteBlock("schedulingPolicy = daily")) { writer.WriteLine("hour = 3"); writer.WriteLine("timezone = \"Europe/Berlin\""); } writer.WriteLine($"branchFilter = {BranchFilter.DoubleQuote()}"); writer.WriteLine($"triggerRules = {TriggerRules.DoubleQuote()}"); writer.WriteLine("triggerBuild = always()"); writer.WriteLine("withPendingChangesOnly = false"); writer.WriteLine($"enableQueueOptimization = {EnableQueueOptimization.ToString().ToLowerInvariant()}"); writer.WriteLine("param(\"cronExpression_min\", \"3\")"); } } } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Utilities; namespace Nuke.Common.CI.TeamCity.Configuration { public class TeamCityScheduledTrigger : TeamCityTrigger { public string BranchFilter { get; set; } public string TriggerRules { get; set; } public bool TriggerBuildAlways { get; set; } //TODO: check public bool WithPendingChangesOnly { get; set; } public bool EnableQueueOptimization { get; set; } public override void Write(CustomFileWriter writer) { using (writer.WriteBlock("schedule")) { using (writer.WriteBlock("schedulingPolicy = daily")) { writer.WriteLine("hour = 3"); } writer.WriteLine($"branchFilter = {BranchFilter.DoubleQuote()}"); writer.WriteLine($"triggerRules = {TriggerRules.DoubleQuote()}"); writer.WriteLine("triggerBuild = always()"); writer.WriteLine("withPendingChangesOnly = false"); writer.WriteLine($"enableQueueOptimization = {EnableQueueOptimization.ToString().ToLowerInvariant()}"); writer.WriteLine("param(\"cronExpression_min\", \"3\")"); } } } }
Change char to byte in gaf frame header
namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public char Unknown1; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(Stream f, ref GafFrameData e) { BinaryReader b = new BinaryReader(f); e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.Unknown1 = b.ReadChar(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public byte Unknown1; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(Stream f, ref GafFrameData e) { BinaryReader b = new BinaryReader(f); e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.Unknown1 = b.ReadByte(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
Make SplitTrimmed give empty list when given white-space-only string
using System.Collections.Generic; namespace Palaso.Extensions { public static class StringExtensions { public static List<string> SplitTrimmed(this string s, char seperator) { var x = s.Split(seperator); var r = new List<string>(); foreach (var part in x) { r.Add(part.Trim()); } return r; } } }
using System.Collections.Generic; namespace Palaso.Extensions { public static class StringExtensions { public static List<string> SplitTrimmed(this string s, char seperator) { if(s.Trim() == string.Empty) return new List<string>(); var x = s.Split(seperator); var r = new List<string>(); foreach (var part in x) { r.Add(part.Trim()); } return r; } } }
Make sure password validation works after saving
namespace Snittlistan.Test { using System.IO; using System.Text; using Models; using Raven.Imports.Newtonsoft.Json; using Xunit; public class SerializationTest : DbTest { [Fact] public void CanSerialize8x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create8x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match8x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.AwayTeam); } [Fact] public void CanSerialize4x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create4x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match4x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.HomeTeam); } } }
namespace Snittlistan.Test { using System.IO; using System.Text; using Models; using Raven.Imports.Newtonsoft.Json; using Xunit; public class SerializationTest : DbTest { [Fact] public void CanSerialize8x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create8x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match8x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.AwayTeam); } [Fact] public void CanSerialize4x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create4x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match4x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.HomeTeam); } [Fact] public void CanSerializeUser() { // Arrange var user = new User("firstName", "lastName", "e@d.com", "some-pass"); // Act using (var session = Store.OpenSession()) { session.Store(user); session.SaveChanges(); } // Assert using (var session = Store.OpenSession()) { var loadedUser = session.Load<User>(user.Id); Assert.True(loadedUser.ValidatePassword("some-pass"), "Password validation failed"); } } } }
Fix bug in the StringCollection converter when DataServicePackage.Authors is a simple string.
using System; using System.Collections.Generic; using System.Windows.Data; namespace NuPack.Dialog.PackageManagerUI { public class StringCollectionsToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType == typeof(string)) { IEnumerable<string> parts = (IEnumerable<string>)value; return String.Join(", ", parts); } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Windows.Data; namespace NuPack.Dialog.PackageManagerUI { public class StringCollectionsToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType == typeof(string)) { string stringValue = value as string; if (stringValue != null) { return stringValue; } else { IEnumerable<string> parts = (IEnumerable<string>)value; return String.Join(", ", parts); } } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34003 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Wcf 3.0.0")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Wcf 3.0.0")]
Handle null id for Cars/Details action
using CarFuel.DataAccess; using CarFuel.Models; using CarFuel.Services; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CarFuel.Controllers { public class CarsController : Controller { private ICarDb db; private CarService carService; public CarsController() { db = new CarDb(); carService = new CarService(db); } [Authorize] public ActionResult Index() { var userId = new Guid(User.Identity.GetUserId()); IEnumerable<Car> cars = carService.GetCarsByMember(userId); return View(cars); } [Authorize] public ActionResult Create() { return View(); } [HttpPost] [Authorize] public ActionResult Create(Car item) { var userId = new Guid(User.Identity.GetUserId()); try { carService.AddCar(item, userId); } catch (OverQuotaException ex) { TempData["error"] = ex.Message; } return RedirectToAction("Index"); } public ActionResult Details(Guid id) { var userId = new Guid(User.Identity.GetUserId()); var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id); return View(c); } } }
using CarFuel.DataAccess; using CarFuel.Models; using CarFuel.Services; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; namespace CarFuel.Controllers { public class CarsController : Controller { private ICarDb db; private CarService carService; public CarsController() { db = new CarDb(); carService = new CarService(db); } [Authorize] public ActionResult Index() { var userId = new Guid(User.Identity.GetUserId()); IEnumerable<Car> cars = carService.GetCarsByMember(userId); return View(cars); } [Authorize] public ActionResult Create() { return View(); } [HttpPost] [Authorize] public ActionResult Create(Car item) { var userId = new Guid(User.Identity.GetUserId()); try { carService.AddCar(item, userId); } catch (OverQuotaException ex) { TempData["error"] = ex.Message; } return RedirectToAction("Index"); } public ActionResult Details(Guid? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var userId = new Guid(User.Identity.GetUserId()); var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id); return View(c); } } }
Fix data migration code for UserRecord
using Orchard.Data.Migration; namespace Orchard.Users.DataMigrations { public class UsersDataMigration : DataMigrationImpl { public int Create() { //CREATE TABLE Orchard_Users_UserRecord (Id INTEGER not null, UserName TEXT, Email TEXT, NormalizedUserName TEXT, Password TEXT, PasswordFormat TEXT, PasswordSalt TEXT, primary key (Id)); SchemaBuilder.CreateTable("UserRecord", table => table .ContentPartRecord() .Column<string>("UserName") .Column<string>("Email") .Column<string>("NormalizedUserName") .Column<string>("Password") .Column<string>("PasswordFormat") .Column<string>("PasswordSalt") ); return 0010; } } }
using Orchard.Data.Migration; namespace Orchard.Users.DataMigrations { public class UsersDataMigration : DataMigrationImpl { public int Create() { //CREATE TABLE Orchard_Users_UserRecord (Id INTEGER not null, UserName TEXT, Email TEXT, NormalizedUserName TEXT, Password TEXT, PasswordFormat TEXT, PasswordSalt TEXT, primary key (Id)); SchemaBuilder.CreateTable("UserRecord", table => table .ContentPartRecord() .Column<string>("UserName") .Column<string>("Email") .Column<string>("NormalizedUserName") .Column<string>("Password") .Column<string>("PasswordFormat") .Column<string>("HashAlgorithm") .Column<string>("PasswordSalt") ); return 0010; } } }
Support list of hints per problem
using System; namespace CITS.Models { public class MathProblemModel : ProblemModel { public MathProblemModel(string Problem, string Solution):base(Problem,Solution){} public override Boolean IsSolutionCorrect(String candidateSolution) { return Solution.Equals(candidateSolution.Trim()); } } }
using System; using System.Collections.Generic; namespace CITS.Models { public class MathProblemModel : ProblemModel { public MathProblemModel(string problem, string solution, List<String> listOfHints):base(problem,solution, listOfHints){} public override Boolean IsSolutionCorrect(String candidateSolution) { return Solution.Equals(candidateSolution.Trim()); } } }
Update TypeCatalogParser for CoreConsoleHost removal
using System; using System.IO; using System.Linq; using NuGet.Frameworks; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.Extensions.DependencyModel.Resolution; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { // The TypeCatalogGen project takes this as input var outputPath = "../TypeCatalogGen/powershell.inc"; // Get a context for our top level project var context = ProjectContext.Create("../Microsoft.PowerShell.CoreConsoleHost", NuGetFramework.Parse("netcoreapp1.0")); System.IO.File.WriteAllLines(outputPath, // Get the target for the current runtime from t in context.LockFile.Targets where t.RuntimeIdentifier == Constants.RuntimeIdentifier // Get the packages (not projects) from x in t.Libraries where x.Type == "package" // Get the real reference assemblies from y in x.CompileTimeAssemblies where y.Path.EndsWith(".dll") // Construct the path to the assemblies select $"{context.PackagesDirectory}/{x.Name}/{x.Version}/{y.Path};"); Console.WriteLine($"List of reference assemblies written to {outputPath}"); } } }
using System; using System.IO; using System.Linq; using NuGet.Frameworks; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.Extensions.DependencyModel.Resolution; namespace TypeCatalogParser { public class Program { public static void Main(string[] args) { // The TypeCatalogGen project takes this as input var outputPath = "../TypeCatalogGen/powershell.inc"; // Get a context for our top level project var context = ProjectContext.Create("../powershell", NuGetFramework.Parse("netcoreapp1.0")); System.IO.File.WriteAllLines(outputPath, // Get the target for the current runtime from t in context.LockFile.Targets where t.RuntimeIdentifier == Constants.RuntimeIdentifier // Get the packages (not projects) from x in t.Libraries where x.Type == "package" // Get the real reference assemblies from y in x.CompileTimeAssemblies where y.Path.EndsWith(".dll") // Construct the path to the assemblies select $"{context.PackagesDirectory}/{x.Name}/{x.Version}/{y.Path};"); Console.WriteLine($"List of reference assemblies written to {outputPath}"); } } }
Disable the disable mouse script for now
 using UnityEngine; using UnityEngine.EventSystems; class DisableMouse : MonoBehaviour { // private stuff we don't want the editor to see private GameObject m_lastSelectedGameObject; // this is called by unity before start void Awake() { m_lastSelectedGameObject = new GameObject(); } // this is called by unity every frame void Update() { // check if we have an active ui if ( EventSystem.current != null ) { // check if we have a currently selected game object if ( EventSystem.current.currentSelectedGameObject == null ) { // nope - the mouse may have stolen it - give it back to the last selected game object EventSystem.current.SetSelectedGameObject( m_lastSelectedGameObject ); } else if ( EventSystem.current.currentSelectedGameObject != m_lastSelectedGameObject ) { // we changed our selection - remember it m_lastSelectedGameObject = EventSystem.current.currentSelectedGameObject; } } } }
 using UnityEngine; using UnityEngine.EventSystems; class DisableMouse : MonoBehaviour { // private stuff we don't want the editor to see private GameObject m_lastSelectedGameObject; // this is called by unity before start void Awake() { m_lastSelectedGameObject = new GameObject(); } // this is called by unity every frame void Update() { // check if we have an active ui if ( false && ( EventSystem.current != null ) ) { // check if we have a currently selected game object if ( EventSystem.current.currentSelectedGameObject == null ) { // nope - the mouse may have stolen it - give it back to the last selected game object EventSystem.current.SetSelectedGameObject( m_lastSelectedGameObject ); } else if ( EventSystem.current.currentSelectedGameObject != m_lastSelectedGameObject ) { // we changed our selection - remember it m_lastSelectedGameObject = EventSystem.current.currentSelectedGameObject; } } } }
Update interface for return type
using com.techphernalia.MyPersonalAccounts.Model.Inventory; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace com.techphernalia.MyPersonalAccounts.Model.Controller { public interface IInventoryController { #region Stock Unit List<StockUnit> GetAllStockUnits(); StockUnit GetStockUnitFromId(int unitId); int AddStockUnit(StockUnit stockUnit); bool UpdateStockUnit(StockUnit stockUnit); bool DeleteStockUnit(int unitId); #endregion #region Stock Group List<StockGroup> GetAllStockGroups(); List<StockGroup> GetStockGroupsForGroup(int stockGroupId); StockGroup GetStockGroupFromId(int stockGroupId); int AddStockGroup(StockItem stockItem); bool UpdateStockGroup(StockItem stockItem); bool DeleteStockGroup(int stockGroupId); #endregion #region Stock Item List<StockItem> GetAllStockItems(); List<StockItem> GetStockItemsForGroup(int stockGroupId); StockItem GetStockItemFromId(int stockItemId); int AddStockItem(StockGroup stockGroup); bool UpdateStockItem(StockGroup stockGroup); bool DeleteStockItemI(int stockItemId); #endregion } }
using com.techphernalia.MyPersonalAccounts.Model.Inventory; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace com.techphernalia.MyPersonalAccounts.Model.Controller { public interface IInventoryController { #region Stock Unit List<StockUnit> GetAllStockUnits(); StockUnit GetStockUnitFromId(int unitId); int AddStockUnit(StockUnit stockUnit); void UpdateStockUnit(StockUnit stockUnit); void DeleteStockUnit(int unitId); #endregion #region Stock Group List<StockGroup> GetAllStockGroups(); List<StockGroup> GetStockGroupsForGroup(int stockGroupId); StockGroup GetStockGroupFromId(int stockGroupId); int AddStockGroup(StockItem stockItem); bool UpdateStockGroup(StockItem stockItem); bool DeleteStockGroup(int stockGroupId); #endregion #region Stock Item List<StockItem> GetAllStockItems(); List<StockItem> GetStockItemsForGroup(int stockGroupId); StockItem GetStockItemFromId(int stockItemId); int AddStockItem(StockGroup stockGroup); bool UpdateStockItem(StockGroup stockGroup); bool DeleteStockItemI(int stockItemId); #endregion } }
Add documentation for episode ids.
namespace TraktApiSharp.Objects.Get.Shows.Episodes { using Basic; public class TraktEpisodeIds : TraktIds { } }
namespace TraktApiSharp.Objects.Get.Shows.Episodes { using Basic; /// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt episode.</summary> public class TraktEpisodeIds : TraktIds { } }
Fix DomainException LogError parameter order
namespace GeekLearning.Domain.AspnetCore { using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; public class DomainExceptionFilter : IActionFilter { private ILoggerFactory loggerFactory; private IOptions<DomainOptions> options; public DomainExceptionFilter(ILoggerFactory loggerFactory, IOptions<DomainOptions> domainOptions) { this.loggerFactory = loggerFactory; this.options = domainOptions; } public void OnActionExecuted(ActionExecutedContext context) { if (context.Exception != null) { var domainException = context.Exception as DomainException; var logger = this.loggerFactory.CreateLogger<DomainExceptionFilter>(); if (domainException == null) { logger.LogError(new EventId(1, "Unknown error"), context.Exception.Message, context.Exception); domainException = new Explanations.Unknown().AsException(context.Exception); } context.Result = new MaybeResult<object>(domainException.Explanation); context.ExceptionHandled = true; } } public void OnActionExecuting(ActionExecutingContext context) { } } }
namespace GeekLearning.Domain.AspnetCore { using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; public class DomainExceptionFilter : IActionFilter { private ILoggerFactory loggerFactory; private IOptions<DomainOptions> options; public DomainExceptionFilter(ILoggerFactory loggerFactory, IOptions<DomainOptions> domainOptions) { this.loggerFactory = loggerFactory; this.options = domainOptions; } public void OnActionExecuted(ActionExecutedContext context) { if (context.Exception != null) { var domainException = context.Exception as DomainException; var logger = this.loggerFactory.CreateLogger<DomainExceptionFilter>(); if (domainException == null) { logger.LogError(new EventId(1, "Unknown error"), context.Exception, context.Exception.Message); domainException = new Explanations.Unknown().AsException(context.Exception); } context.Result = new MaybeResult<object>(domainException.Explanation); context.ExceptionHandled = true; } } public void OnActionExecuting(ActionExecutingContext context) { } } }
Fix score retrieval no longer working
// 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; using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Users; using osu.Game.Rulesets.Replays; namespace osu.Game.Rulesets.Scoring { public class Score { public ScoreRank Rank { get; set; } public double TotalScore { get; set; } public double Accuracy { get; set; } public double Health { get; set; } = 1; public double? PP { get; set; } public int MaxCombo { get; set; } public int Combo { get; set; } public RulesetInfo Ruleset { get; set; } public Mod[] Mods { get; set; } = { }; public User User; public Replay Replay; public BeatmapInfo Beatmap; public long OnlineScoreID; public DateTimeOffset Date; public Dictionary<HitResult, object> Statistics = new Dictionary<HitResult, object>(); } }
// 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; using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Users; using osu.Game.Rulesets.Replays; namespace osu.Game.Rulesets.Scoring { public class Score { public ScoreRank Rank { get; set; } public double TotalScore { get; set; } public double Accuracy { get; set; } public double Health { get; set; } = 1; public double? PP { get; set; } public int MaxCombo { get; set; } public int Combo { get; set; } public RulesetInfo Ruleset { get; set; } public Mod[] Mods { get; set; } = { }; public User User; [JsonIgnore] public Replay Replay; public BeatmapInfo Beatmap; public long OnlineScoreID; public DateTimeOffset Date; public Dictionary<HitResult, object> Statistics = new Dictionary<HitResult, object>(); } }
Enable testing in emulated or actual device mode
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace xwalk { class TwoinoneTest { static void Main(string[] args) { Emulator emulator = new Emulator(); TabletMonitor monitor = new TabletMonitor(emulator); monitor.TabletModeDelegate = onTabletModeChanged; monitor.start(); Console.WriteLine("Main: " + monitor.IsTablet); bool isTabletEmulated = monitor.IsTablet; // Fudge mainloop int tick = 0; while (true) { Thread.Sleep(500); Console.Write("."); tick++; if (tick % 10 == 0) { Console.WriteLine(""); isTabletEmulated = !isTabletEmulated; emulator.IsTablet = isTabletEmulated; } } } private static void onTabletModeChanged(bool isTablet) { Console.WriteLine("onTabletModeChanged: " + isTablet); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace xwalk { class TwoinoneTest { static void Main(string[] args) { if (args.Length > 0 && args[0] == "emulator") { runEmulator(); } else { run(); } } static void run() { Emulator emulator = new Emulator(); TabletMonitor monitor = new TabletMonitor(emulator); monitor.TabletModeDelegate = onTabletModeChanged; monitor.start(); Console.WriteLine("Main: " + monitor.IsTablet); // Fudge mainloop int tick = 0; while (true) { Thread.Sleep(500); Console.Write("."); tick++; if (tick % 10 == 0) { Console.WriteLine(""); Console.WriteLine("Tablet mode " + monitor.IsTablet); } } } static void runEmulator() { Emulator emulator = new Emulator(); TabletMonitor monitor = new TabletMonitor(emulator); monitor.TabletModeDelegate = onTabletModeChanged; monitor.start(); Console.WriteLine("Main: " + monitor.IsTablet); bool isTabletEmulated = monitor.IsTablet; // Fudge mainloop int tick = 0; while (true) { Thread.Sleep(500); Console.Write("."); tick++; if (tick % 10 == 0) { Console.WriteLine(""); isTabletEmulated = !isTabletEmulated; emulator.IsTablet = isTabletEmulated; } } } private static void onTabletModeChanged(bool isTablet) { Console.WriteLine("onTabletModeChanged: " + isTablet); } } }
Add method ToString to override default display and replace by Caption
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NBi.Core.Analysis.Metadata { public class Property : IField { public string UniqueName { get; private set; } public string Caption { get; set; } public Property(string uniqueName, string caption) { UniqueName = uniqueName; Caption = caption; } public Property Clone() { return new Property(UniqueName, Caption); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NBi.Core.Analysis.Metadata { public class Property : IField { public string UniqueName { get; private set; } public string Caption { get; set; } public Property(string uniqueName, string caption) { UniqueName = uniqueName; Caption = caption; } public Property Clone() { return new Property(UniqueName, Caption); } public override string ToString() { return Caption.ToString(); } } }
Revert "Dummy commit to test PR. No real changes"
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Platform { using Microsoft.ApplicationInsights.DataContracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using Assert = Xunit.Assert; [TestClass] public class PlatformReferencesTests { [TestMethod] public void NoSystemWebReferences() { // Validate Platform assembly. foreach (var assembly in typeof(DebugOutput).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } // Validate Core assembly foreach (var assembly in typeof(EventTelemetry).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } } } }
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Platform { using Microsoft.ApplicationInsights.DataContracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using Assert = Xunit.Assert; [TestClass] public class PlatformReferencesTests { [TestMethod] public void NoSystemWebReferences() { // Validate Platform assembly foreach (var assembly in typeof(DebugOutput).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } // Validate Core assembly foreach (var assembly in typeof(EventTelemetry).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } } } }
Mark Activity and it's properties as Serializable
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Remoting.Messaging; using System.Security; namespace System.Diagnostics { public partial class Activity { /// <summary> /// Returns the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { return (Activity)CallContext.LogicalGetData(FieldKey); } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private set { CallContext.LogicalSetData(FieldKey, value); } } #region private private partial class KeyValueListNode { } private static readonly string FieldKey = $"{typeof(Activity).FullName}"; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Remoting.Messaging; using System.Security; namespace System.Diagnostics { // this code is specific to .NET 4.5 and uses CallContext to store Activity.Current which requires Activity to be Serializable. [Serializable] // DO NOT remove public partial class Activity { /// <summary> /// Returns the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { return (Activity)CallContext.LogicalGetData(FieldKey); } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private set { CallContext.LogicalSetData(FieldKey, value); } } #region private [Serializable] // DO NOT remove private partial class KeyValueListNode { } private static readonly string FieldKey = $"{typeof(Activity).FullName}"; #endregion } }
Add some tests for a bug.
using System.Linq; using Xunit; namespace Microsoft.Language.Xml.Tests { public class TestApi { [Fact] public void TestAttributeValue() { var root = Parser.ParseText("<e a=\"\"/>"); var attributeValue = root.Attributes.First().Value; Assert.Equal("", attributeValue); } [Fact] public void TestContent() { var root = Parser.ParseText("<e>Content</e>"); var value = root.Value; Assert.Equal("Content", value); } } }
using System.Linq; using Xunit; namespace Microsoft.Language.Xml.Tests { public class TestApi { [Fact] public void TestAttributeValue() { var root = Parser.ParseText("<e a=\"\"/>"); var attributeValue = root.Attributes.First().Value; Assert.Equal("", attributeValue); } [Fact] public void TestContent() { var root = Parser.ParseText("<e>Content</e>"); var value = root.Value; Assert.Equal("Content", value); } [Fact] public void TestRootLevel() { var root = Parser.ParseText("<Root></Root>"); Assert.Equal("Root", root.Name); } [Fact(Skip = "https://github.com/KirillOsenkov/XmlParser/issues/8")] public void TestRootLevelTrivia() { var root = Parser.ParseText("<!-- C --><Root></Root>"); Assert.Equal("Root", root.Name); } [Fact] public void TestRootLevelTriviaWithDeclaration() { var root = Parser.ParseText("<?xml version=\"1.0\" encoding=\"utf-8\"?><!-- C --><Root></Root>"); Assert.Equal("Root", root.Name); } } }
Set nuget package version to 2.0.0-beta1
using System.Reflection; [assembly: AssemblyCompany("Andrew Davey")] [assembly: AssemblyProduct("Cassette")] [assembly: AssemblyCopyright("Copyright © 2011 Andrew Davey")] // NOTE: When changing this version, also update Cassette.MSBuild\Cassette.targets to match. [assembly: AssemblyInformationalVersion("2.0.0")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyFileVersion("2.0.0.0")]
using System.Reflection; [assembly: AssemblyCompany("Andrew Davey")] [assembly: AssemblyProduct("Cassette")] [assembly: AssemblyCopyright("Copyright © 2011 Andrew Davey")] [assembly: AssemblyInformationalVersion("2.0.0-beta1")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyFileVersion("2.0.0.0")]
Support added for HTML comment removal
namespace DotnetThoughts.AspNet { using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using System.IO; using System.Threading.Tasks; using System.Text; using System.Text.RegularExpressions; public class HtmlMinificationMiddleware { private RequestDelegate _next; public HtmlMinificationMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { var stream = context.Response.Body; using (var buffer = new MemoryStream()) { context.Response.Body = buffer; await _next(context); var isHtml = context.Response.ContentType?.ToLower().Contains("text/html"); buffer.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(buffer)) { string responseBody = await reader.ReadToEndAsync(); if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault()) { responseBody = Regex.Replace(responseBody, @">\s+<", "><", RegexOptions.Compiled); } using (var memoryStream = new MemoryStream()) { var bytes = Encoding.UTF8.GetBytes(responseBody); memoryStream.Write(bytes, 0, bytes.Length); memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(stream, bytes.Length); } } } } } }
namespace DotnetThoughts.AspNet { using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using System.IO; using System.Threading.Tasks; using System.Text; using System.Text.RegularExpressions; public class HtmlMinificationMiddleware { private RequestDelegate _next; public HtmlMinificationMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { var stream = context.Response.Body; using (var buffer = new MemoryStream()) { context.Response.Body = buffer; await _next(context); var isHtml = context.Response.ContentType?.ToLower().Contains("text/html"); buffer.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(buffer)) { string responseBody = await reader.ReadToEndAsync(); if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault()) { responseBody = Regex.Replace(responseBody, @">\s+<", "><", RegexOptions.Compiled); responseBody = Regex.Replace(responseBody, @"<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->)(.|\n))*-->", "", RegexOptions.Compiled); } using (var memoryStream = new MemoryStream()) { var bytes = Encoding.UTF8.GetBytes(responseBody); memoryStream.Write(bytes, 0, bytes.Length); memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(stream, bytes.Length); } } } } } }
Change Always(x) so that it doesn't depend on the 'true' literal
using LogicalShift.Reason.Api; using LogicalShift.Reason.Clauses; using System; using System.Linq; namespace LogicalShift.Reason { /// <summary> /// Methods for creating an altering clauses /// </summary> public static class Clause { /// <summary> /// Creates a new negative Horn clause /// </summary> public static IClause If(params ILiteral[] literals) { if (literals == null) throw new ArgumentNullException("literals"); if (literals.Any(literal => literal == null)) throw new ArgumentException("Null literals are not allowed", "literals"); return new NegativeClause(literals); } /// <summary> /// Adds a positive literal to a negative Horn clause /// </summary> public static IClause Then(this IClause negativeHornClause, ILiteral then) { if (negativeHornClause == null) throw new ArgumentNullException("negativeHornClause"); if (negativeHornClause.Implies != null) throw new ArgumentException("Clause already has an implication", "negativeHornClause"); if (then == null) throw new ArgumentNullException("then"); return new PositiveClause(negativeHornClause, then); } /// <summary> /// Returns a clause indicating that a literal is unconditionally true /// </summary> public static IClause Always(ILiteral always) { return If(Literal.True()).Then(always); } } }
using LogicalShift.Reason.Api; using LogicalShift.Reason.Clauses; using System; using System.Linq; namespace LogicalShift.Reason { /// <summary> /// Methods for creating an altering clauses /// </summary> public static class Clause { /// <summary> /// Creates a new negative Horn clause /// </summary> public static IClause If(params ILiteral[] literals) { if (literals == null) throw new ArgumentNullException("literals"); if (literals.Any(literal => literal == null)) throw new ArgumentException("Null literals are not allowed", "literals"); return new NegativeClause(literals); } /// <summary> /// Adds a positive literal to a negative Horn clause /// </summary> public static IClause Then(this IClause negativeHornClause, ILiteral then) { if (negativeHornClause == null) throw new ArgumentNullException("negativeHornClause"); if (negativeHornClause.Implies != null) throw new ArgumentException("Clause already has an implication", "negativeHornClause"); if (then == null) throw new ArgumentNullException("then"); return new PositiveClause(negativeHornClause, then); } /// <summary> /// Returns a clause indicating that a literal is unconditionally true /// </summary> public static IClause Always(ILiteral always) { return If().Then(always); } } }
Fix initial value not propagating
// 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.Bindables; namespace osu.Framework.Statistics { public class GlobalStatistic<T> : IGlobalStatistic { public string Group { get; } public string Name { get; } public IBindable<string> DisplayValue => displayValue; private readonly Bindable<string> displayValue = new Bindable<string>(); public Bindable<T> Bindable { get; } = new Bindable<T>(); public T Value { get => Bindable.Value; set => Bindable.Value = value; } public GlobalStatistic(string group, string name) { Group = group; Name = name; Bindable.ValueChanged += val => displayValue.Value = val.NewValue.ToString(); } public virtual void Clear() => Bindable.SetDefault(); } }
// 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.Bindables; namespace osu.Framework.Statistics { public class GlobalStatistic<T> : IGlobalStatistic { public string Group { get; } public string Name { get; } public IBindable<string> DisplayValue => displayValue; private readonly Bindable<string> displayValue = new Bindable<string>(); public Bindable<T> Bindable { get; } = new Bindable<T>(); public T Value { get => Bindable.Value; set => Bindable.Value = value; } public GlobalStatistic(string group, string name) { Group = group; Name = name; Bindable.BindValueChanged(val => displayValue.Value = val.NewValue.ToString(), true); } public virtual void Clear() => Bindable.SetDefault(); } }
Remove trailing slashes from baseUrl in .NET to prevent double slashes in URL
using System; using System.Collections.Generic; using System.Text; using OpenQA.Selenium; using Selenium.Internal.SeleniumEmulation; namespace Selenium.Internal.SeleniumEmulation { /// <summary> /// Defines the command for the open keyword. /// </summary> internal class Open : SeleneseCommand { private Uri baseUrl; /// <summary> /// Initializes a new instance of the <see cref="Open"/> class. /// </summary> /// <param name="baseUrl">The base URL to open with the command.</param> public Open(Uri baseUrl) { this.baseUrl = baseUrl; } /// <summary> /// Handles the command. /// </summary> /// <param name="driver">The driver used to execute the command.</param> /// <param name="locator">The first parameter to the command.</param> /// <param name="value">The second parameter to the command.</param> /// <returns>The result of the command.</returns> protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value) { string urlToOpen = this.ConstructUrl(locator); driver.Url = urlToOpen; return null; } private string ConstructUrl(string path) { string urlToOpen = path.Contains("://") ? path : this.baseUrl.ToString() + (!path.StartsWith("/", StringComparison.Ordinal) ? "/" : string.Empty) + path; return urlToOpen; } } }
using System; using System.Collections.Generic; using System.Text; using OpenQA.Selenium; using Selenium.Internal.SeleniumEmulation; namespace Selenium.Internal.SeleniumEmulation { /// <summary> /// Defines the command for the open keyword. /// </summary> internal class Open : SeleneseCommand { private Uri baseUrl; /// <summary> /// Initializes a new instance of the <see cref="Open"/> class. /// </summary> /// <param name="baseUrl">The base URL to open with the command.</param> public Open(Uri baseUrl) { this.baseUrl = baseUrl; } /// <summary> /// Handles the command. /// </summary> /// <param name="driver">The driver used to execute the command.</param> /// <param name="locator">The first parameter to the command.</param> /// <param name="value">The second parameter to the command.</param> /// <returns>The result of the command.</returns> protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value) { string urlToOpen = this.ConstructUrl(locator); driver.Url = urlToOpen; return null; } private string ConstructUrl(string path) { string urlToOpen = path.Contains("://") ? path : this.baseUrl.ToString().TrimEnd('/') + (!path.StartsWith("/", StringComparison.Ordinal) ? "/" : string.Empty) + path; return urlToOpen; } } }
Add comment to Auth Login action describing redirect
// Copyright(c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. using System.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { // GET: Session/Login public ActionResult Login() { HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); return new HttpUnauthorizedResult(); } // ... // [END login] // [START logout] // GET: Session/Logout public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } }
// Copyright(c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. using System.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { public ActionResult Login() { // Redirect to the Google OAuth 2.0 user consent screen HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); return new HttpUnauthorizedResult(); } // ... // [END login] // [START logout] public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } }
Use separator when joining string attributes
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace SpotifyAPI.Web { public static class Util { public static string GetStringAttribute<T>(this T en, String separator) where T : struct, IConvertible { Enum e = (Enum)(object)en; IEnumerable<StringAttribute> attributes = Enum.GetValues(typeof(T)) .Cast<T>() .Where(v => e.HasFlag((Enum)(object)v)) .Select(v => typeof(T).GetField(v.ToString(CultureInfo.InvariantCulture))) .Select(f => f.GetCustomAttributes(typeof(StringAttribute), false)[0]) .Cast<StringAttribute>(); List<String> list = new List<String>(); attributes.ToList().ForEach(element => list.Add(element.Text)); return string.Join(" ", list); } } public sealed class StringAttribute : Attribute { public String Text { get; set; } public StringAttribute(String text) { Text = text; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace SpotifyAPI.Web { public static class Util { public static string GetStringAttribute<T>(this T en, String separator) where T : struct, IConvertible { Enum e = (Enum)(object)en; IEnumerable<StringAttribute> attributes = Enum.GetValues(typeof(T)) .Cast<T>() .Where(v => e.HasFlag((Enum)(object)v)) .Select(v => typeof(T).GetField(v.ToString(CultureInfo.InvariantCulture))) .Select(f => f.GetCustomAttributes(typeof(StringAttribute), false)[0]) .Cast<StringAttribute>(); List<String> list = new List<String>(); attributes.ToList().ForEach(element => list.Add(element.Text)); return string.Join(separator, list); } } public sealed class StringAttribute : Attribute { public String Text { get; set; } public StringAttribute(String text) { Text = text; } } }
Implement IPropertyDescriptorInitializer to validate properties on initializing
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HermaFx.Settings { [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Property, AllowMultiple = false)] public sealed class SettingsAttribute : Attribute { public const string DEFAULT_PREFIX_SEPARATOR = ":"; /// <summary> /// Gets or sets the key prefix. /// </summary> /// <value> /// The key prefix. /// </value> public string KeyPrefix { get; } /// <summary> /// Gets or sets the prefix separator. /// </summary> /// <value> /// The prefix separator. /// </value> public string PrefixSeparator { get; set; } public SettingsAttribute() { PrefixSeparator = DEFAULT_PREFIX_SEPARATOR; } public SettingsAttribute(string keyPrefix) : this() { KeyPrefix = keyPrefix; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Castle.Components.DictionaryAdapter; namespace HermaFx.Settings { [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Property, AllowMultiple = false)] public sealed class SettingsAttribute : Attribute, IPropertyDescriptorInitializer { public const string DEFAULT_PREFIX_SEPARATOR = ":"; /// <summary> /// Gets or sets the key prefix. /// </summary> /// <value> /// The key prefix. /// </value> public string KeyPrefix { get; } /// <summary> /// Gets or sets the prefix separator. /// </summary> /// <value> /// The prefix separator. /// </value> public string PrefixSeparator { get; set; } public SettingsAttribute() { PrefixSeparator = DEFAULT_PREFIX_SEPARATOR; } public SettingsAttribute(string keyPrefix) : this() { KeyPrefix = keyPrefix; } #region IPropertyDescriptorInitializer public int ExecutionOrder => DictionaryBehaviorAttribute.LastExecutionOrder; public void Initialize(PropertyDescriptor propertyDescriptor, object[] behaviors) { propertyDescriptor.Fetch = true; } public IDictionaryBehavior Copy() { return this; } #endregion } }
Remove duplicates from sorted array II - Linq
using System; static class Program { static int RemoveDupes(this int[] a) { int write = 1; int read = 0; bool same = false; int count = 0; for (int i = 1; i < a.Length; i++) { read = i; if (same && a[read] == a[write]) { count++; continue; } same = a[read] == a[write]; a[write++] = a[read]; } return a.Length - count; } static void Main() { int[] a = new int[] {1, 1, 1, 2, 2, 3, 3, 3}; int c = RemoveDupes(a); for (int i = 0; i < c; i++) { Console.Write("{0} ", a[i]); } Console.WriteLine(); } }
using System; using System.Linq; using System.Collections.Generic; static class Program { static int RemoveDupes(this int[] a) { int write = 1; int read = 0; bool same = false; int count = 0; for (int i = 1; i < a.Length; i++) { read = i; if (same && a[read] == a[write]) { count++; continue; } same = a[read] == a[write]; a[write++] = a[read]; } return a.Length - count; } static int[] RemoveDupes2(this int[] v) { return v.Aggregate(new List<int>(), (a, b) => { if (a.Count(x => x == b) < 2) { a.Add(b); } return a; }).ToArray(); } static void Main() { int[] a = new int[] {1, 1, 1, 2, 2, 3, 3, 3}; int c = RemoveDupes(a); for (int i = 0; i < c; i++) { Console.Write("{0} ", a[i]); } Console.WriteLine(); foreach (int x in RemoveDupes2(a)) { Console.Write("{0} ", x); } Console.WriteLine(); } }
Store max combo in ScoreProcessor.
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using osu.Framework.Configuration; using osu.Game.Modes.Objects.Drawables; namespace osu.Game.Modes { public class ScoreProcessor { public virtual Score GetScore() => new Score(); public BindableDouble TotalScore = new BindableDouble { MinValue = 0 }; public BindableDouble Accuracy = new BindableDouble { MinValue = 0, MaxValue = 1 }; public BindableInt Combo = new BindableInt(); public List<JudgementInfo> Judgements = new List<JudgementInfo>(); public virtual void AddJudgement(JudgementInfo judgement) { Judgements.Add(judgement); UpdateCalculations(); judgement.ComboAtHit = (ulong)Combo.Value; } /// <summary> /// Update any values that potentially need post-processing on a judgement change. /// </summary> protected virtual void UpdateCalculations() { } } }
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using osu.Framework.Configuration; using osu.Game.Modes.Objects.Drawables; namespace osu.Game.Modes { public class ScoreProcessor { public virtual Score GetScore() => new Score(); public BindableDouble TotalScore = new BindableDouble { MinValue = 0 }; public BindableDouble Accuracy = new BindableDouble { MinValue = 0, MaxValue = 1 }; public BindableInt Combo = new BindableInt(); public BindableInt MaximumCombo = new BindableInt(); public List<JudgementInfo> Judgements = new List<JudgementInfo>(); public virtual void AddJudgement(JudgementInfo judgement) { Judgements.Add(judgement); UpdateCalculations(); judgement.ComboAtHit = (ulong)Combo.Value; if (Combo.Value > MaximumCombo.Value) MaximumCombo.Value = Combo.Value; } /// <summary> /// Update any values that potentially need post-processing on a judgement change. /// </summary> protected virtual void UpdateCalculations() { } } }
Include top left encoded targa in benchmark
using System.IO; using BenchmarkDotNet.Attributes; using FreeImageAPI; using ImageMagick; using DS = DevILSharp; namespace Pfim.Benchmarks { public class TargaBenchmark { [Params("true-32-rle-large.tga", "true-24-large.tga", "true-24.tga", "true-32-rle.tga")] public string Payload { get; set; } private byte[] data; [GlobalSetup] public void SetupData() { data = File.ReadAllBytes(Payload); DS.Bootstrap.Init(); } [Benchmark] public IImage Pfim() => Targa.Create(new MemoryStream(data)); [Benchmark] public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data)); [Benchmark] public int ImageMagick() { var settings = new MagickReadSettings {Format = MagickFormat.Tga}; using (var image = new MagickImage(new MemoryStream(data), settings)) { return image.Width; } } [Benchmark] public int DevILSharp() { using (var image = DS.Image.Load(data, DS.ImageType.Tga)) { return image.Width; } } [Benchmark] public int TargaImage() { using (var image = new Paloma.TargaImage(new MemoryStream(data))) { return image.Stride; } } } }
using System.IO; using BenchmarkDotNet.Attributes; using FreeImageAPI; using ImageMagick; using DS = DevILSharp; namespace Pfim.Benchmarks { public class TargaBenchmark { [Params("true-32-rle-large.tga", "true-24-large.tga", "true-24.tga", "true-32-rle.tga", "rgb24_top_left")] public string Payload { get; set; } private byte[] data; [GlobalSetup] public void SetupData() { data = File.ReadAllBytes(Payload); DS.Bootstrap.Init(); } [Benchmark] public IImage Pfim() => Targa.Create(new MemoryStream(data)); [Benchmark] public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data)); [Benchmark] public int ImageMagick() { var settings = new MagickReadSettings {Format = MagickFormat.Tga}; using (var image = new MagickImage(new MemoryStream(data), settings)) { return image.Width; } } [Benchmark] public int DevILSharp() { using (var image = DS.Image.Load(data, DS.ImageType.Tga)) { return image.Width; } } [Benchmark] public int TargaImage() { using (var image = new Paloma.TargaImage(new MemoryStream(data))) { return image.Stride; } } } }
Remove LocatorId generation code from DTO since the locator id will be generated by a SQL CLR function
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PS.Mothership.Core.Common.Dto.Merchant { public class AddProspectDto { public string CompanyName { get; set; } public string LocatorId { get { var id = Convert.ToString(((CompanyName.GetHashCode() ^ DateTime.UtcNow.Ticks.GetHashCode()) & 0xffffff) | 0x1000000, 16).Substring(1); return id; } } public long MainPhoneCountryKey { get; set; } public string MainPhoneNumber { get; set; } public Guid ContactGuid { get; set; } public Guid AddressGuid { get; set; } public Guid MainPhoneGuid { get; set; } } }
using System; namespace PS.Mothership.Core.Common.Dto.Merchant { public class AddProspectDto { public string CompanyName { get; set; } public string LocatorId { get; set; } public long MainPhoneCountryKey { get; set; } public string MainPhoneNumber { get; set; } public Guid ContactGuid { get; set; } public Guid AddressGuid { get; set; } public Guid MainPhoneGuid { get; set; } } }
Fix - The -t command-line switch is optional. Use first argument if omitted.
using System; using System.Collections.Generic; using System.IO; using NDesk.Options; namespace make { public class CommandLine { public string Program { get; set; } public string OutputFile { get; set; } public string InputFile { get; set; } public string[] Arguments { get; set; } private CommandLine() { } public static CommandLine Parse(string[] args) { var commandLine = new CommandLine(); var options = new OptionSet { { "p|program=", v => commandLine.Program = v }, { "o|out=", v => commandLine.OutputFile = v }, }; try { var remaining = options.Parse(args); commandLine.ParseRemainingArguments(remaining); } catch (OptionException e) { Console.Error.WriteLine(e.Message); } return commandLine; } private void ParseRemainingArguments(List<string> remaining) { var input = ""; var options = new List<string>(); foreach (var arg in remaining) { if (arg.StartsWith("/") || arg.StartsWith("-")) options.Add(arg); else if (File.Exists(arg)) input = arg; else options.Add(arg); } InputFile = input; Arguments = options.ToArray(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using NDesk.Options; namespace make { public class CommandLine { public string Program { get; set; } public string OutputFile { get; set; } public string InputFile { get; set; } public string[] Arguments { get; set; } private CommandLine() { } public static CommandLine Parse(string[] args) { var commandLine = new CommandLine(); var options = new OptionSet { { "p|program=", v => commandLine.Program = v }, { "o|out=", v => commandLine.OutputFile = v }, }; try { var remaining = options.Parse(args); commandLine.ParseRemainingArguments(remaining); } catch (OptionException e) { Console.Error.WriteLine(e.Message); } return commandLine; } private void ParseRemainingArguments(List<string> remaining) { var input = ""; var options = new List<string>(); var arguments = remaining.AsEnumerable(); if (Program == null) { Program = remaining.FirstOrDefault(a => !a.StartsWith("/") && !a.StartsWith("/")); if (Program == null) { Console.Error.WriteLine("Wrong argument count. Please, use the -t switch to specify a valid program name."); Environment.Exit(1); } arguments = remaining.Skip(1); } foreach (var arg in arguments) { if (arg.StartsWith("/") || arg.StartsWith("-")) options.Add(arg); else if (File.Exists(arg)) input = arg; else options.Add(arg); } InputFile = input; Arguments = options.ToArray(); } } }
Stop playing the track in editor to avoid unused member warning
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Graphics; using osu.Framework.Screens; using osu.Game.Beatmaps; using osu.Game.Screens.Backgrounds; namespace osu.Game.Screens.Edit { internal class Editor : ScreenWhiteBox { //private WorkingBeatmap beatmap; public Editor(WorkingBeatmap workingBeatmap) { //beatmap = workingBeatmap; } protected override BackgroundScreen CreateBackground() => new BackgroundScreenCustom(@"Backgrounds/bg4"); protected override void OnEntering(Screen last) { base.OnEntering(last); Background.Schedule(() => Background.FadeColour(Color4.DarkGray, 500)); } protected override bool OnExiting(Screen next) { Background.Schedule(() => Background.FadeColour(Color4.White, 500)); return base.OnExiting(next); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Graphics; using osu.Framework.Screens; using osu.Game.Beatmaps; using osu.Game.Screens.Backgrounds; namespace osu.Game.Screens.Edit { internal class Editor : ScreenWhiteBox { private WorkingBeatmap beatmap; public Editor(WorkingBeatmap workingBeatmap) { beatmap = workingBeatmap; } protected override BackgroundScreen CreateBackground() => new BackgroundScreenCustom(@"Backgrounds/bg4"); protected override void OnEntering(Screen last) { base.OnEntering(last); Background.Schedule(() => Background.FadeColour(Color4.DarkGray, 500)); beatmap.Track?.Stop(); } protected override bool OnExiting(Screen next) { Background.Schedule(() => Background.FadeColour(Color4.White, 500)); beatmap.Track?.Start(); return base.OnExiting(next); } } }
Change date type of MaxDownloadingItems to byte and change to get only
using System.Collections.Generic; using TirkxDownloader.Models; namespace TirkxDownloader.Framework.Interface { public delegate void DownloadCompleteHandler(GeneralDownloadItem downloadInfo); /// <summary> /// Implementation that implement this interface should implement PropertyChanged Event for data-binding /// </summary> public interface IDownloader { bool IsDownloading { get; } long MaximumBytesPerSecond { get; set; } int MaxDownloadingItems { get; set; } string DownloaderErrorMessage { get; set; } int DownloadingItems { get; set; } void DownloadItem(IDownloadItem item); void DownloadItems(IEnumerable<IDownloadItem> items); void StopDownloadItem(IDownloadItem item); void StopDownloadItems(IEnumerable<IDownloadItem> items); } }
using System.Collections.Generic; using TirkxDownloader.Models; namespace TirkxDownloader.Framework.Interface { public delegate void DownloadCompleteHandler(GeneralDownloadItem downloadInfo); /// <summary> /// Implementation that implement this interface should implement PropertyChanged Event for data-binding /// </summary> public interface IDownloader { bool IsDownloading { get; } long MaximumBytesPerSecond { get; } byte MaxDownloadingItems { get; } string DownloaderErrorMessage { get; set; } int DownloadingItems { get; set; } void DownloadItem(IDownloadItem item); void DownloadItems(IEnumerable<IDownloadItem> items); void StopDownloadItem(IDownloadItem item); void StopDownloadItems(IEnumerable<IDownloadItem> items); } }
Read connection string from configuration
using System; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.Extensions.Configuration; namespace QueueGettingStarted { public class Program { public static void Main(string[] args) { // configuration var builder = new ConfigurationBuilder() .AddJsonFile("./appsettings.json") .AddUserSecrets() .AddEnvironmentVariables(); Configuration = builder.Build(); // options ConfigurationBinder.Bind(Configuration.GetSection("Azure:Storage"), Options); Console.WriteLine("Queue encryption sample"); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(""); CloudQueueClient client = storageAccount.CreateCloudQueueClient(); if(client != null){ Console.WriteLine("Client created"); } else { Console.WriteLine("Error creating client"); } Console.ReadKey(); } static IConfiguration Configuration { get; set; } static AzureStorageOptions Options {get; set; } = new AzureStorageOptions(); } class AzureStorageOptions { public string ConnectionString { get; set; } } }
using System; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.Extensions.Configuration; namespace QueueGettingStarted { public class Program { public static void Main(string[] args) { // configuration var builder = new ConfigurationBuilder() .AddJsonFile("./appsettings.json") .AddUserSecrets() .AddEnvironmentVariables(); Configuration = builder.Build(); // options ConfigurationBinder.Bind(Configuration.GetSection("Azure:Storage"), Options); Console.WriteLine("Queue encryption sample"); Console.WriteLine($"Configuration for ConnectionString: {Options.ConnectionString}"); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Options.ConnectionString); CloudQueueClient client = storageAccount.CreateCloudQueueClient(); if (client != null) { Console.WriteLine("Client created"); } else { Console.WriteLine("Error creating client"); } Console.ReadKey(); } static IConfiguration Configuration { get; set; } static AzureStorageOptions Options { get; set; } = new AzureStorageOptions(); } class AzureStorageOptions { public string ConnectionString { get; set; } } }
Add UserName to LogEntries When Authenticated
using LogBook.Services; using LogBook.Services.Models; using Portal.CMS.Web.Architecture.ViewEngines; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Razor; using System.Web.Routing; using System.Web.WebPages; namespace Portal.CMS.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); ViewEngines.Engines.Add(new CSSViewEngine()); RazorCodeLanguage.Languages.Add("cscss", new CSharpRazorCodeLanguage()); WebPageHttpHandler.RegisterExtension("cscss"); MvcHandler.DisableMvcResponseHeader = true; } protected void Application_Error() { var logHandler = new LogHandler(); var exception = Server.GetLastError(); logHandler.WriteLog(LogType.Error, "PortalCMS", exception, "An Exception has occured while Running PortalCMS", string.Empty); if (System.Configuration.ConfigurationManager.AppSettings["CustomErrorPage"] == "true") { Response.Redirect("~/Home/Error"); } } } }
using LogBook.Services; using LogBook.Services.Models; using Portal.CMS.Web.Architecture.Helpers; using Portal.CMS.Web.Architecture.ViewEngines; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Razor; using System.Web.Routing; using System.Web.WebPages; namespace Portal.CMS.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); ViewEngines.Engines.Add(new CSSViewEngine()); RazorCodeLanguage.Languages.Add("cscss", new CSharpRazorCodeLanguage()); WebPageHttpHandler.RegisterExtension("cscss"); MvcHandler.DisableMvcResponseHeader = true; } protected void Application_Error() { var logHandler = new LogHandler(); var exception = Server.GetLastError(); var userAccount = UserHelper.UserId; logHandler.WriteLog(LogType.Error, "PortalCMS", exception, "An Exception has occured while Running PortalCMS", userAccount.ToString()); if (System.Configuration.ConfigurationManager.AppSettings["CustomErrorPage"] == "true") { Response.Redirect("~/Home/Error"); } } } }
Fix potential crash in old .NET versions
namespace SnappyMap.IO { using System; using System.Collections.Generic; using System.Linq; using SnappyMap.Data; [Serializable] public struct SectionMapping { public SectionMapping(SectionType type, params string[] sections) : this() { this.Type = type; this.Sections = sections.ToList(); } public SectionType Type { get; set; } public List<string> Sections { get; set; } } [Serializable] public class SectionConfig { public SectionConfig() { this.SectionMappings = new List<SectionMapping>(); } public int SeaLevel { get; set; } public List<SectionMapping> SectionMappings { get; private set; } } }
namespace SnappyMap.IO { using System; using System.Collections.Generic; using System.Linq; using SnappyMap.Data; [Serializable] public struct SectionMapping { public SectionMapping(SectionType type, params string[] sections) : this() { this.Type = type; this.Sections = sections.ToList(); } public SectionType Type { get; set; } public List<string> Sections { get; set; } } [Serializable] public class SectionConfig { public SectionConfig() { this.SectionMappings = new List<SectionMapping>(); } public int SeaLevel { get; set; } public List<SectionMapping> SectionMappings { get; set; } } }
Split out divider update in timer
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace elbgb.gameboy { class Timer { public static class Registers { public const ushort DIV = 0xFF04; public const ushort TIMA = 0xFF05; public const ushort TMA = 0xFF06; public const ushort TAC = 0xFF07; } private GameBoy _gb; private ulong _lastUpdate; private ushort _div; public Timer(GameBoy gameBoy) { _gb = gameBoy; } public byte ReadByte(ushort address) { switch (address) { case Registers.DIV: return (byte)(_div >> 8); default: throw new NotImplementedException(); } } public void WriteByte(ushort address, byte value) { switch (address) { // a write always clears the upper 8 bits of DIV, regardless of value case Registers.DIV: _div &= 0x00FF; break; default: throw new NotImplementedException(); } } public void Update() { ulong cyclesToUpdate = _gb.Timestamp - _lastUpdate; _lastUpdate = _gb.Timestamp; // update divider _div += (ushort)cyclesToUpdate; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace elbgb.gameboy { class Timer { public static class Registers { public const ushort DIV = 0xFF04; public const ushort TIMA = 0xFF05; public const ushort TMA = 0xFF06; public const ushort TAC = 0xFF07; } private GameBoy _gb; private ulong _lastUpdate; private ushort _div; public Timer(GameBoy gameBoy) { _gb = gameBoy; } public byte ReadByte(ushort address) { switch (address) { case Registers.DIV: return (byte)(_div >> 8); default: throw new NotImplementedException(); } } public void WriteByte(ushort address, byte value) { switch (address) { // a write always clears the upper 8 bits of DIV, regardless of value case Registers.DIV: _div &= 0x00FF; break; default: throw new NotImplementedException(); } } public void Update() { ulong cyclesToUpdate = _gb.Timestamp - _lastUpdate; _lastUpdate = _gb.Timestamp; UpdateDivider(cyclesToUpdate); } private void UpdateDivider(ulong cyclesToUpdate) { _div += (ushort)cyclesToUpdate; } } }
Add image link to movie
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MeDaUmFilme { public class Movie { public string Title { get; set; } public string Year { get; set; } } public class OmdbResult { public List<Movie> Search { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MeDaUmFilme { public class Movie { public string Title { get; set; } public string Year { get; set; } public string Poster { get; set; } public string Type { get; set; } } public class OmdbResult { public List<Movie> Search { get; set; } } }
Format file, remove outcommented code.
using Microsoft.EntityFrameworkCore; using Mitternacht.Services.Database; namespace Mitternacht.Services { public class DbService { private readonly DbContextOptions _options; public DbService(IBotCredentials creds) { var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseSqlite(creds.DbConnectionString); _options = optionsBuilder.Options; //switch (_creds.Db.Type.ToUpperInvariant()) //{ // case "SQLITE": // dbType = typeof(NadekoSqliteContext); // break; // //case "SQLSERVER": // // dbType = typeof(NadekoSqlServerContext); // // break; // default: // break; //} } public NadekoContext GetDbContext() { var context = new NadekoContext(_options); context.Database.SetCommandTimeout(60); context.Database.Migrate(); context.EnsureSeedData(); //set important sqlite stuffs var conn = context.Database.GetDbConnection(); conn.Open(); context.Database.ExecuteSqlRaw("PRAGMA journal_mode=WAL"); using (var com = conn.CreateCommand()) { com.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=OFF"; com.ExecuteNonQuery(); } return context; } public IUnitOfWork UnitOfWork => new UnitOfWork(GetDbContext()); } }
using Microsoft.EntityFrameworkCore; using Mitternacht.Services.Database; namespace Mitternacht.Services { public class DbService { private readonly DbContextOptions _options; public DbService(IBotCredentials creds) { var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseSqlite(creds.DbConnectionString); _options = optionsBuilder.Options; } public NadekoContext GetDbContext() { var context = new NadekoContext(_options); context.Database.SetCommandTimeout(60); context.Database.Migrate(); context.EnsureSeedData(); //set important sqlite stuffs var conn = context.Database.GetDbConnection(); conn.Open(); context.Database.ExecuteSqlRaw("PRAGMA journal_mode=WAL"); using(var com = conn.CreateCommand()) { com.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=OFF"; com.ExecuteNonQuery(); } return context; } public IUnitOfWork UnitOfWork => new UnitOfWork(GetDbContext()); } }
Fix Log4Net path for loading config file
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Log4NetIntegration.Logging { using System.IO; using MassTransit.Logging; using log4net; using log4net.Config; public class Log4NetLogger : ILogger { public MassTransit.Logging.ILog Get(string name) { return new Log4NetLog(LogManager.GetLogger(name)); } public static void Use() { Logger.UseLogger(new Log4NetLogger()); } public static void Use(string file) { Logger.UseLogger(new Log4NetLogger()); var configFile = new FileInfo(file); XmlConfigurator.Configure(configFile); } } }
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Log4NetIntegration.Logging { using System; using System.IO; using MassTransit.Logging; using log4net; using log4net.Config; public class Log4NetLogger : ILogger { public MassTransit.Logging.ILog Get(string name) { return new Log4NetLog(LogManager.GetLogger(name)); } public static void Use() { Logger.UseLogger(new Log4NetLogger()); } public static void Use(string file) { Logger.UseLogger(new Log4NetLogger()); file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file); var configFile = new FileInfo(file); XmlConfigurator.Configure(configFile); } } }
Update file version of DLL to match NuGet package.
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DiffPlex")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("DiffPlex")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.*")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DiffPlex")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("DiffPlex")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Assembly version should consist of just major and minor versions. // We omit revision and build numbers so that folks who compile against // 1.2.0 can also run against 1.2.1 without a recompile or a binding redirect. [assembly: AssemblyVersion("1.2.0.0")] // File version can include the revision and build numbers so // file properties can reveal the true version of this build. [assembly: AssemblyFileVersion("1.2.1.0")]
Introduce a retry machanism with the Blockchain API
using MultiMiner.Blockchain.Data; using MultiMiner.ExchangeApi; using MultiMiner.ExchangeApi.Data; using MultiMiner.Utility.Net; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net; using System.Text; namespace MultiMiner.Blockchain { public class ApiContext : IApiContext { public IEnumerable<ExchangeInformation> GetExchangeInformation() { WebClient webClient = new ApiWebClient(); webClient.Encoding = Encoding.UTF8; string response = webClient.DownloadString(new Uri(GetApiUrl())); Dictionary<string, TickerEntry> tickerEntries = JsonConvert.DeserializeObject<Dictionary<string, TickerEntry>>(response); List<ExchangeInformation> results = new List<ExchangeInformation>(); foreach (KeyValuePair<string, TickerEntry> keyValuePair in tickerEntries) { results.Add(new ExchangeInformation() { SourceCurrency = "BTC", TargetCurrency = keyValuePair.Key, TargetSymbol = keyValuePair.Value.Symbol, ExchangeRate = keyValuePair.Value.Last }); } return results; } public string GetInfoUrl() { return "https://blockchain.info"; } public string GetApiUrl() { //use HTTP as HTTPS is down at times and returns: //The request was aborted: Could not create SSL/TLS secure channel. return "http://blockchain.info/ticker"; } public string GetApiName() { return "Blockchain"; } } }
using MultiMiner.Blockchain.Data; using MultiMiner.ExchangeApi; using MultiMiner.ExchangeApi.Data; using MultiMiner.Utility.Net; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace MultiMiner.Blockchain { public class ApiContext : IApiContext { public IEnumerable<ExchangeInformation> GetExchangeInformation() { ApiWebClient webClient = new ApiWebClient(); webClient.Encoding = Encoding.UTF8; string response = webClient.DownloadFlakyString(new Uri(GetApiUrl())); Dictionary<string, TickerEntry> tickerEntries = JsonConvert.DeserializeObject<Dictionary<string, TickerEntry>>(response); List<ExchangeInformation> results = new List<ExchangeInformation>(); foreach (KeyValuePair<string, TickerEntry> keyValuePair in tickerEntries) { results.Add(new ExchangeInformation() { SourceCurrency = "BTC", TargetCurrency = keyValuePair.Key, TargetSymbol = keyValuePair.Value.Symbol, ExchangeRate = keyValuePair.Value.Last }); } return results; } public string GetInfoUrl() { return "https://blockchain.info"; } public string GetApiUrl() { //use HTTP as HTTPS is down at times and returns: //The request was aborted: Could not create SSL/TLS secure channel. return "https://blockchain.info/ticker"; } public string GetApiName() { return "Blockchain"; } } }
Fix the URL to point at the Noda Time blog because msmvps.com 503.
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; namespace NodaTime.Annotations { /// <summary> /// Indicates that a value-type field which would otherwise by <c>readonly</c> /// is read/write so that invoking members on the field avoids taking a copy of /// the field value. /// </summary> /// <remarks> /// See http://msmvps.com/blogs/jon_skeet/archive/2014/07/16/micro-optimization-the-surprising-inefficiency-of-readonly-fields.aspx /// for details of why we're doing this at all. /// </remarks> [AttributeUsage(AttributeTargets.Field)] internal sealed class ReadWriteForEfficiencyAttribute : Attribute { } }
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; namespace NodaTime.Annotations { /// <summary> /// Indicates that a value-type field which would otherwise by <c>readonly</c> /// is read/write so that invoking members on the field avoids taking a copy of /// the field value. /// </summary> /// <remarks> /// See http://noda-time.blogspot.com/2014/07/micro-optimization-surprising.html /// for details of why we're doing this at all. /// </remarks> [AttributeUsage(AttributeTargets.Field)] internal sealed class ReadWriteForEfficiencyAttribute : Attribute { } }
Update Console Program with a Condition - Add unit test for Guest role
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Training.CSharpWorkshop.Tests { [TestClass] public class ProgramTests { [Ignore] [TestMethod] public void IgnoreTest() { Assert.Fail(); } [TestMethod()] public void GetRoleMessageForAdminTest() { // Arrange var userName = "Andrew"; var expected = "Role: Admin."; // Act var actual = Program.GetRoleMessage(userName); // Assert Assert.AreEqual(expected, actual); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Training.CSharpWorkshop.Tests { [TestClass] public class ProgramTests { [Ignore] [TestMethod] public void IgnoreTest() { Assert.Fail(); } [TestMethod()] public void GetRoleMessageForAdminTest() { // Arrange var userName = "Andrew"; var expected = "Role: Admin."; // Act var actual = Program.GetRoleMessage(userName); // Assert Assert.AreEqual(expected, actual); } [TestMethod()] public void GetRoleMessageForGuestTest() { // Arrange var userName = "Dave"; var expected = "Role: Guest."; // Act var actual = Program.GetRoleMessage(userName); // Assert Assert.AreEqual(expected, actual); } } }
Fix showing only minutes of the hour insteal of total minutes in virtual table.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Data; namespace TramlineFive.Converters { public class TimingConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { string[] timings = (string[])value; StringBuilder builder = new StringBuilder(); foreach (string singleTiming in timings) { TimeSpan timing; if (TimeSpan.TryParse((string)singleTiming, out timing)) { TimeSpan timeLeft = timing - DateTime.Now.TimeOfDay; builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft.Minutes < 0 ? 0 : timeLeft.Minutes); } } builder.Remove(builder.Length - 2, 2); return builder.ToString(); } 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.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Data; namespace TramlineFive.Converters { public class TimingConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { string[] timings = (string[])value; StringBuilder builder = new StringBuilder(); foreach (string singleTiming in timings) { TimeSpan timing; if (TimeSpan.TryParse((string)singleTiming, out timing)) { int timeLeft = (int)(timing - DateTime.Now.TimeOfDay).TotalMinutes; builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft < 0 ? 0 : timeLeft); } } builder.Remove(builder.Length - 2, 2); return builder.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } }
Fix broken migration for v11
using System.Linq; using MongoDB.Bson; using MongoDB.Driver; namespace Hangfire.Mongo.Migration.Steps.Version11 { /// <summary> /// Create signal capped collection /// </summary> internal class UseObjectIdForJob : IMongoMigrationStep { public MongoSchema TargetSchema => MongoSchema.Version11; public long Sequence => 0; public bool Execute(IMongoDatabase database, MongoStorageOptions storageOptions, IMongoMigrationBag migrationBag) { var jobsCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".job"); SetFieldAsObjectId(jobsCollection, "_id"); var jobQueueCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".jobQueue"); SetFieldAsObjectId(jobQueueCollection, "JobId"); return true; } private static void SetFieldAsObjectId(IMongoCollection<BsonDocument> collection, string fieldName) { var documents = collection.Find(new BsonDocument()).ToList(); if(!documents.Any()) return; foreach (var doc in documents) { var jobIdString = doc[fieldName].ToString(); doc[fieldName] = ObjectId.Parse(jobIdString); } collection.DeleteMany(new BsonDocument()); collection.InsertMany(documents); } } }
using System.Linq; using MongoDB.Bson; using MongoDB.Driver; namespace Hangfire.Mongo.Migration.Steps.Version11 { /// <summary> /// Create signal capped collection /// </summary> internal class UseObjectIdForJob : IMongoMigrationStep { public MongoSchema TargetSchema => MongoSchema.Version11; public long Sequence => 0; public bool Execute(IMongoDatabase database, MongoStorageOptions storageOptions, IMongoMigrationBag migrationBag) { var jobsCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".job"); SetFieldAsObjectId(jobsCollection, "_id"); var jobQueueCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".jobQueue"); SetFieldAsObjectId(jobQueueCollection, "JobId"); return true; } private static void SetFieldAsObjectId(IMongoCollection<BsonDocument> collection, string fieldName) { var filter = Builders<BsonDocument>.Filter.Exists(fieldName); var documents = collection.Find(filter).ToList(); if (!documents.Any()) return; foreach (var doc in documents) { var jobIdString = doc[fieldName].ToString(); doc[fieldName] = ObjectId.Parse(jobIdString); } collection.DeleteMany(new BsonDocument()); collection.InsertMany(documents); } } }
Update sample to use Save() and Load()
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Hjson; namespace HjsonSample { class Program { static void Main(string[] args) { var data=HjsonValue.Load("test.hjson").Qo(); Console.WriteLine(data.Qs("hello")); Console.WriteLine("Saving as json..."); HjsonValue.Save(data, "test.json"); Console.WriteLine("Saving as hjson..."); HjsonValue.Save(data, "test2.hjson"); // edit (preserve whitespace and comments) var wdata=(WscJsonObject)HjsonValue.LoadWsc(new StreamReader("test.hjson")).Qo(); // edit like you normally would wdata["hugo"]="value"; // optionally set order and comments: wdata.Order.Insert(2, "hugo"); wdata.Comments["hugo"]="just another test"; var sw=new StringWriter(); HjsonValue.SaveWsc(wdata, sw); Console.WriteLine(sw.ToString()); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Hjson; namespace HjsonSample { class Program { static void Main(string[] args) { var data=HjsonValue.Load("test.hjson").Qo(); Console.WriteLine(data.Qs("hello")); Console.WriteLine("Saving as json..."); HjsonValue.Save(data, "test.json"); Console.WriteLine("Saving as hjson..."); HjsonValue.Save(data, "test2.hjson"); // edit (preserve whitespace and comments) var wdata=(WscJsonObject)HjsonValue.Load(new StreamReader("test.hjson"), preserveComments:true).Qo(); // edit like you normally would wdata["hugo"]="value"; // optionally set order and comments: wdata.Order.Insert(2, "hugo"); wdata.Comments["hugo"]="just another test"; var sw=new StringWriter(); HjsonValue.Save(wdata, sw, new HjsonOptions() { KeepWsc = true }); Console.WriteLine(sw.ToString()); } } }
Add extension method to add a disposable to a composite disposable
using System; using System.Collections.Generic; using System.Reactive.Disposables; using System.Text; namespace SolidworksAddinFramework { public static class DisposableExtensions { public static IDisposable ToCompositeDisposable(this IEnumerable<IDisposable> d) { return new CompositeDisposable(d); } } }
using System; using System.Collections.Generic; using System.Reactive.Disposables; using System.Text; namespace SolidworksAddinFramework { public static class DisposableExtensions { public static IDisposable ToCompositeDisposable(this IEnumerable<IDisposable> d) { return new CompositeDisposable(d); } public static void DisposeWith(this IDisposable disposable, CompositeDisposable container) { container.Add(disposable); } } }
Use TabNavigation.Continue for top-level menu.
// ----------------------------------------------------------------------- // <copyright file="MenuStyle.cs" company="Steven Kirk"> // Copyright 2015 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Perspex.Themes.Default { using Perspex.Controls; using Perspex.Controls.Presenters; using Perspex.Styling; using System.Linq; public class MenuStyle : Styles { public MenuStyle() { this.AddRange(new[] { new Style(x => x.OfType<Menu>()) { Setters = new[] { new Setter(Menu.TemplateProperty, ControlTemplate.Create<Menu>(this.Template)), }, }, }); } private Control Template(Menu control) { return new Border { [~Border.BackgroundProperty] = control[~Menu.BackgroundProperty], [~Border.BorderBrushProperty] = control[~Menu.BorderBrushProperty], [~Border.BorderThicknessProperty] = control[~Menu.BorderThicknessProperty], [~Border.PaddingProperty] = control[~Menu.PaddingProperty], Content = new ItemsPresenter { Name = "itemsPresenter", [~ItemsPresenter.ItemsProperty] = control[~Menu.ItemsProperty], [~ItemsPresenter.ItemsPanelProperty] = control[~Menu.ItemsPanelProperty], } }; } } }
// ----------------------------------------------------------------------- // <copyright file="MenuStyle.cs" company="Steven Kirk"> // Copyright 2015 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Perspex.Themes.Default { using System.Linq; using Perspex.Controls; using Perspex.Controls.Presenters; using Perspex.Input; using Perspex.Styling; public class MenuStyle : Styles { public MenuStyle() { this.AddRange(new[] { new Style(x => x.OfType<Menu>()) { Setters = new[] { new Setter(Menu.TemplateProperty, ControlTemplate.Create<Menu>(this.Template)), }, }, }); } private Control Template(Menu control) { return new Border { [~Border.BackgroundProperty] = control[~Menu.BackgroundProperty], [~Border.BorderBrushProperty] = control[~Menu.BorderBrushProperty], [~Border.BorderThicknessProperty] = control[~Menu.BorderThicknessProperty], [~Border.PaddingProperty] = control[~Menu.PaddingProperty], Content = new ItemsPresenter { Name = "itemsPresenter", [~ItemsPresenter.ItemsProperty] = control[~Menu.ItemsProperty], [~ItemsPresenter.ItemsPanelProperty] = control[~Menu.ItemsPanelProperty], [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Continue, } }; } } }
Use Wait() instead of Result in void overload
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace Bugsnag.Common { public class BugsnagClient : IClient { static Uri _uri = new Uri("http://notify.bugsnag.com"); static Uri _sslUri = new Uri("https://notify.bugsnag.com"); static JsonSerializerSettings _settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; static HttpClient _HttpClient { get; } = new HttpClient(); public void Send(INotice notice) => Send(notice, true); public void Send(INotice notice, bool useSSL) { var _ = SendAsync(notice, useSSL).Result; } public Task<HttpResponseMessage> SendAsync(INotice notice) => SendAsync(notice, true); public Task<HttpResponseMessage> SendAsync(INotice notice, bool useSSL) { var uri = useSSL ? _sslUri : _uri; var json = JsonConvert.SerializeObject(notice, _settings); var content = new StringContent(json, Encoding.UTF8, "application/json"); return _HttpClient.PostAsync(uri, content); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace Bugsnag.Common { public class BugsnagClient : IClient { static Uri _uri = new Uri("http://notify.bugsnag.com"); static Uri _sslUri = new Uri("https://notify.bugsnag.com"); static JsonSerializerSettings _settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; static HttpClient _HttpClient { get; } = new HttpClient(); public void Send(INotice notice) => Send(notice, true); public void Send(INotice notice, bool useSSL) => SendAsync(notice, useSSL).Wait(); public Task<HttpResponseMessage> SendAsync(INotice notice) => SendAsync(notice, true); public Task<HttpResponseMessage> SendAsync(INotice notice, bool useSSL) { var uri = useSSL ? _sslUri : _uri; var json = JsonConvert.SerializeObject(notice, _settings); var content = new StringContent(json, Encoding.UTF8, "application/json"); return _HttpClient.PostAsync(uri, content); } } }