Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Update Container Host to only count running containers
using System; using System.Threading; using System.Threading.Tasks; using Docker.DotNet; using Docker.DotNet.Models; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Metrics; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace SharpLab.Container.Manager.Azure { public class ContainerCountMetricReporter : BackgroundService { private static readonly MetricIdentifier ContainerCountMetric = new("Custom Metrics", "Container Count"); private readonly DockerClient _dockerClient; private readonly TelemetryClient _telemetryClient; private readonly ILogger<ContainerCountMetricReporter> _logger; public ContainerCountMetricReporter( DockerClient dockerClient, TelemetryClient telemetryClient, ILogger<ContainerCountMetricReporter> logger ) { _dockerClient = dockerClient; _telemetryClient = telemetryClient; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { var containers = await _dockerClient.Containers.ListContainersAsync(new ContainersListParameters { All = true }); _telemetryClient.GetMetric(ContainerCountMetric).TrackValue(containers.Count); } catch (Exception ex) { _logger.LogError(ex, "Failed to report container count"); await Task.Delay(TimeSpan.FromMinutes(4), stoppingToken); } await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); } } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Docker.DotNet; using Docker.DotNet.Models; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Metrics; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace SharpLab.Container.Manager.Azure { public class ContainerCountMetricReporter : BackgroundService { private static readonly MetricIdentifier ContainerCountMetric = new("Custom Metrics", "Container Count"); private static readonly ContainersListParameters RunningOnlyListParameters = new() { Filters = new Dictionary<string, IDictionary<string, bool>> { { "status", new Dictionary<string, bool> { { "running", true } } } } }; private readonly DockerClient _dockerClient; private readonly TelemetryClient _telemetryClient; private readonly ILogger<ContainerCountMetricReporter> _logger; public ContainerCountMetricReporter( DockerClient dockerClient, TelemetryClient telemetryClient, ILogger<ContainerCountMetricReporter> logger ) { _dockerClient = dockerClient; _telemetryClient = telemetryClient; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { var containers = await _dockerClient.Containers.ListContainersAsync(RunningOnlyListParameters); _telemetryClient.GetMetric(ContainerCountMetric).TrackValue(containers.Count); } catch (Exception ex) { _logger.LogError(ex, "Failed to report container count"); await Task.Delay(TimeSpan.FromMinutes(4), stoppingToken); } await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); } } } }
Add TODO reminder about ruleset reference transfer quirk
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Database; #nullable enable namespace osu.Game.Rulesets { /// <summary> /// A representation of a ruleset's metadata. /// </summary> public interface IRulesetInfo : IHasOnlineID { /// <summary> /// The user-exposed name of this ruleset. /// </summary> string Name { get; } /// <summary> /// An acronym defined by the ruleset that can be used as a permanent identifier. /// </summary> string ShortName { get; } /// <summary> /// A string representation of this ruleset, to be used with reflection to instantiate the ruleset represented by this metadata. /// </summary> string InstantiationInfo { get; } public Ruleset? CreateInstance() { var type = Type.GetType(InstantiationInfo); if (type == null) return null; var ruleset = Activator.CreateInstance(type) as Ruleset; // overwrite the pre-populated RulesetInfo with a potentially database attached copy. // ruleset.RulesetInfo = this; return ruleset; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Database; #nullable enable namespace osu.Game.Rulesets { /// <summary> /// A representation of a ruleset's metadata. /// </summary> public interface IRulesetInfo : IHasOnlineID { /// <summary> /// The user-exposed name of this ruleset. /// </summary> string Name { get; } /// <summary> /// An acronym defined by the ruleset that can be used as a permanent identifier. /// </summary> string ShortName { get; } /// <summary> /// A string representation of this ruleset, to be used with reflection to instantiate the ruleset represented by this metadata. /// </summary> string InstantiationInfo { get; } public Ruleset? CreateInstance() { var type = Type.GetType(InstantiationInfo); if (type == null) return null; var ruleset = Activator.CreateInstance(type) as Ruleset; // overwrite the pre-populated RulesetInfo with a potentially database attached copy. // TODO: figure if we still want/need this after switching to realm. // ruleset.RulesetInfo = this; return ruleset; } } }
Change GetService calls to GetRequiredService
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Reflection; using Microsoft.Framework.DependencyInjection; namespace Microsoft.AspNet.Builder { public static class UseMiddlewareExtensions { public static IApplicationBuilder UseMiddleware<T>(this IApplicationBuilder builder, params object[] args) { return builder.UseMiddleware(typeof(T), args); } public static IApplicationBuilder UseMiddleware(this IApplicationBuilder builder, Type middleware, params object[] args) { return builder.Use(next => { var typeActivator = builder.ApplicationServices.GetService<ITypeActivator>(); var instance = typeActivator.CreateInstance(builder.ApplicationServices, middleware, new[] { next }.Concat(args).ToArray()); var methodinfo = middleware.GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public); return (RequestDelegate)methodinfo.CreateDelegate(typeof(RequestDelegate), instance); }); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Reflection; using Microsoft.Framework.DependencyInjection; namespace Microsoft.AspNet.Builder { public static class UseMiddlewareExtensions { public static IApplicationBuilder UseMiddleware<T>(this IApplicationBuilder builder, params object[] args) { return builder.UseMiddleware(typeof(T), args); } public static IApplicationBuilder UseMiddleware(this IApplicationBuilder builder, Type middleware, params object[] args) { return builder.Use(next => { var typeActivator = builder.ApplicationServices.GetRequiredService<ITypeActivator>(); var instance = typeActivator.CreateInstance(builder.ApplicationServices, middleware, new[] { next }.Concat(args).ToArray()); var methodinfo = middleware.GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public); return (RequestDelegate)methodinfo.CreateDelegate(typeof(RequestDelegate), instance); }); } } }
Include common options in test
using System; using System.Collections.Generic; using System.IO; using AppHarbor.Commands; using Xunit; namespace AppHarbor.Tests.Commands { public class HelpCommandTest { private static Type FooCommandType = typeof(FooCommand); private static Type FooBarCommandType = typeof(FooBarCommand); private static Type BazQuxCommandType = typeof(BazQuxCommand); [CommandHelp("Lorem Ipsum motherfucker", "[bar]")] class FooCommand { } [CommandHelp("Lorem Ipsum motherfucker", "[bar]")] class FooBarCommand { } [CommandHelp("Ipsum lol", "[Quz]", "quux")] class BazQuxCommand { } [Fact] public void ShouldOutputHelpInformation() { var types = new List<Type> { FooCommandType, BazQuxCommandType, FooBarCommandType }; var writer = new StringWriter(); var helpCommand = new HelpCommand(types, writer); helpCommand.Execute(new string[0]); Assert.Equal("Usage: appharbor COMMAND [command-options]\r\n\r\nAvailable commands:\r\n\r\n bar foo [bar] # Lorem Ipsum motherfucker\r\n foo [bar] # Lorem Ipsum motherfucker\r\n qux baz [quz] # Ipsum lol (\"quux\")\r\n", writer.ToString()); } } }
using System; using System.Collections.Generic; using System.IO; using AppHarbor.Commands; using Xunit; namespace AppHarbor.Tests.Commands { public class HelpCommandTest { private static Type FooCommandType = typeof(FooCommand); private static Type FooBarCommandType = typeof(FooBarCommand); private static Type BazQuxCommandType = typeof(BazQuxCommand); [CommandHelp("Lorem Ipsum motherfucker", "[bar]")] class FooCommand { } [CommandHelp("Lorem Ipsum motherfucker", "[bar]")] class FooBarCommand { } [CommandHelp("Ipsum lol", "[Quz]", "quux")] class BazQuxCommand { } [Fact] public void ShouldOutputHelpInformation() { var types = new List<Type> { FooCommandType, BazQuxCommandType, FooBarCommandType }; var writer = new StringWriter(); var helpCommand = new HelpCommand(types, writer); helpCommand.Execute(new string[0]); Assert.Equal("Usage: appharbor COMMAND [command-options]\r\n\r\nAvailable commands:\r\n\r\n bar foo [bar] # Lorem Ipsum motherfucker\r\n foo [bar] # Lorem Ipsum motherfucker\r\n qux baz [quz] # Ipsum lol (\"quux\")\r\n\r\nCommon options:\r\n -h, --help Show command help\r\n", writer.ToString()); } } }
Allow the json parser to deserialize non string values.
using System; using System.Collections; using System.Collections.Generic; namespace Mindscape.Raygun4Net.Parsers { public class RaygunRequestDataJsonParser : IRaygunRequestDataParser { public IDictionary ToDictionary(string data) { try { return SimpleJson.DeserializeObject<Dictionary<string, string>>(data) as IDictionary; } catch { return null; } } } }
using System; using System.Collections; using System.Collections.Generic; namespace Mindscape.Raygun4Net.Parsers { public class RaygunRequestDataJsonParser : IRaygunRequestDataParser { public IDictionary ToDictionary(string data) { try { return SimpleJson.DeserializeObject<Dictionary<string, object>>(data) as IDictionary; } catch { return null; } } } }
Improve N1QL identifier escaping performance
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Couchbase.Linq.QueryGeneration { /// <summary> /// Helpers for N1QL query generation /// </summary> public static class N1QlHelpers { /// <summary> /// Escapes a N1QL identifier using tick (`) characters /// </summary> /// <param name="identifier">The identifier to format</param> /// <returns>An escaped identifier</returns> public static string EscapeIdentifier(string identifier) { if (identifier == null) { throw new ArgumentNullException("identifier"); } if (identifier.IndexOf('`') >= 0) { // This should not occur, and is primarily in place to prevent N1QL injection attacks // So it isn't performance critical to perform this replace in the StringBuilder identifier = identifier.Replace("`", "``"); } var sb = new StringBuilder(identifier.Length + 2); sb.Append('`'); sb.Append(identifier); sb.Append('`'); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Couchbase.Linq.QueryGeneration { /// <summary> /// Helpers for N1QL query generation /// </summary> public static class N1QlHelpers { /// <summary> /// Escapes a N1QL identifier using tick (`) characters /// </summary> /// <param name="identifier">The identifier to format</param> /// <returns>An escaped identifier</returns> public static string EscapeIdentifier(string identifier) { if (identifier == null) { throw new ArgumentNullException("identifier"); } if (identifier.IndexOf('`') >= 0) { // This should not occur, and is primarily in place to prevent N1QL injection attacks // So it isn't performance critical to perform this replace in a StringBuilder with the concatenation identifier = identifier.Replace("`", "``"); } return string.Concat("`", identifier, "`"); } } }
Change import of jquery files.
using System.Web; using System.Web.Optimization; namespace TwitterWebApplication { 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-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); bundles.Add(new StyleBundle("~/Structure/css").Include( "~/Content/Structure/*.css")); bundles.Add(new StyleBundle("~/Presentation/css").Include( "~/Content/Presentation/*.css")); bundles.Add(new StyleBundle("~/MediaQueries/css").Include( "~/Content/MediaQueries/*.css")); } } }
using System.Web; using System.Web.Optimization; namespace TwitterWebApplication { 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-1.10.2.min.js", "~/Scripts/jquery-1.10.2.intellisense.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-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); bundles.Add(new StyleBundle("~/Structure/css").Include( "~/Content/Structure/*.css")); bundles.Add(new StyleBundle("~/Presentation/css").Include( "~/Content/Presentation/*.css")); bundles.Add(new StyleBundle("~/MediaQueries/css").Include( "~/Content/MediaQueries/*.css")); } } }
Allow missing members without throwing exceptions
using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Modules.JsonNet { /// <summary> /// IFormatter implementation based on Newtonsoft.Json serialization. /// Requires the Serializable attribute and optionally the ISerializable interface. /// Reads/writes fields, including inherited and compiler generated. /// Reconstructs an identical object graph on deserialization. /// </summary> public class JsonNetFormatter : IFormatter { private readonly JsonSerializer _serializer; public SerializationBinder Binder{ get; set; } public StreamingContext Context { get; set; } public ISurrogateSelector SurrogateSelector { get; set; } public JsonNetFormatter() { var settings = new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver { IgnoreSerializableAttribute = false, SerializeCompilerGeneratedMembers = true }, PreserveReferencesHandling = PreserveReferencesHandling.All, TypeNameHandling = TypeNameHandling.All, TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple }; _serializer = JsonSerializer.Create(settings); } public object Deserialize(Stream serializationStream) { var reader = new JsonTextReader(new StreamReader(serializationStream)); return _serializer.Deserialize(reader); } public void Serialize(Stream serializationStream, object graph) { var writer = new JsonTextWriter(new StreamWriter(serializationStream)); _serializer.Serialize(writer, graph); writer.Flush(); } } }
using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Modules.JsonNet { /// <summary> /// IFormatter implementation based on Newtonsoft.Json serialization. /// Requires the Serializable attribute and optionally the ISerializable interface. /// Reads/writes fields, including inherited and compiler generated. /// Reconstructs an identical object graph on deserialization. /// </summary> public class JsonNetFormatter : IFormatter { private readonly JsonSerializer _serializer; public SerializationBinder Binder{ get; set; } public StreamingContext Context { get; set; } public ISurrogateSelector SurrogateSelector { get; set; } public JsonNetFormatter() { var settings = new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver { IgnoreSerializableAttribute = false, SerializeCompilerGeneratedMembers = true }, PreserveReferencesHandling = PreserveReferencesHandling.All, TypeNameHandling = TypeNameHandling.All, TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, MissingMemberHandling = MissingMemberHandling.Ignore }; _serializer = JsonSerializer.Create(settings); } public object Deserialize(Stream serializationStream) { var reader = new JsonTextReader(new StreamReader(serializationStream)); return _serializer.Deserialize(reader); } public void Serialize(Stream serializationStream, object graph) { var writer = new JsonTextWriter(new StreamWriter(serializationStream)); _serializer.Serialize(writer, graph); writer.Flush(); } } }
Disable test to temp pass build
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.WindowsAzure.Commands.ScenarioTest; using Xunit; namespace Commands.Network.Test.ScenarioTests { public class TestDnsAvailabilityTest { [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestDnsAvailability() { NetworkResourcesController.NewInstance.RunPsTest("Test-DnsAvailability"); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.WindowsAzure.Commands.ScenarioTest; using Xunit; namespace Commands.Network.Test.ScenarioTests { public class TestDnsAvailabilityTest { [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestDnsAvailability() { // NetworkResourcesController.NewInstance.RunPsTest("Test-DnsAvailability"); } } }
Remove directives to expose assembly internals to now removed test projects
using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using TweetDuck; // 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("TweetDeck Client for Windows")] [assembly: AssemblyDescription("TweetDeck Client for Windows")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct(Program.BrandName)] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7f09373d-8beb-416f-a48d-45d8aaeb8caf")] [assembly: NeutralResourcesLanguage("en")] [assembly: CLSCompliant(true)] #if DEBUG [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("TweetTest.System")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("TweetTest.Unit")] #endif
using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using TweetDuck; // 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("TweetDeck Client for Windows")] [assembly: AssemblyDescription("TweetDeck Client for Windows")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct(Program.BrandName)] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7f09373d-8beb-416f-a48d-45d8aaeb8caf")] [assembly: NeutralResourcesLanguage("en")] [assembly: CLSCompliant(true)]
Fix Cannot access a disposed object crash in LruCache.SizeOf method
using System; using FFImageLoading.Drawables; namespace FFImageLoading.Cache { public class LRUCache : Android.Util.LruCache { public LRUCache(int maxSize) : base(maxSize) { } public event EventHandler<EntryRemovedEventArgs<Java.Lang.Object>> OnEntryRemoved; protected override int SizeOf(Java.Lang.Object key, Java.Lang.Object value) { var drawable = value as ISelfDisposingBitmapDrawable; if (drawable != null) return drawable.SizeInBytes; return 0; } protected override void EntryRemoved(bool evicted, Java.Lang.Object key, Java.Lang.Object oldValue, Java.Lang.Object newValue) { base.EntryRemoved(evicted, key, oldValue, newValue); OnEntryRemoved?.Invoke(this, new EntryRemovedEventArgs<Java.Lang.Object>(key.ToString(), oldValue, evicted)); } } public class EntryRemovedEventArgs<TValue> : EventArgs { public EntryRemovedEventArgs(string key, TValue value, bool evicted) { Key = key; Value = value; Evicted = evicted; } public bool Evicted; public string Key; public TValue Value; } public class EntryAddedEventArgs<TValue> : EventArgs { public EntryAddedEventArgs(string key, TValue value) { Key = key; Value = value; } public string Key; public TValue Value; } }
using System; using FFImageLoading.Drawables; namespace FFImageLoading.Cache { public class LRUCache : Android.Util.LruCache { public LRUCache(int maxSize) : base(maxSize) { } public event EventHandler<EntryRemovedEventArgs<Java.Lang.Object>> OnEntryRemoved; protected override int SizeOf(Java.Lang.Object key, Java.Lang.Object value) { var drawable = value as ISelfDisposingBitmapDrawable; if (drawable != null && drawable.Handle.ToInt32() != 0) return drawable.SizeInBytes; return 0; } protected override void EntryRemoved(bool evicted, Java.Lang.Object key, Java.Lang.Object oldValue, Java.Lang.Object newValue) { base.EntryRemoved(evicted, key, oldValue, newValue); OnEntryRemoved?.Invoke(this, new EntryRemovedEventArgs<Java.Lang.Object>(key.ToString(), oldValue, evicted)); } } public class EntryRemovedEventArgs<TValue> : EventArgs { public EntryRemovedEventArgs(string key, TValue value, bool evicted) { Key = key; Value = value; Evicted = evicted; } public bool Evicted; public string Key; public TValue Value; } public class EntryAddedEventArgs<TValue> : EventArgs { public EntryAddedEventArgs(string key, TValue value) { Key = key; Value = value; } public string Key; public TValue Value; } }
Change player count with both left shift or right shift + num key
using UnityEngine; using System.Collections; public class Menus : MonoBehaviour { public enum MenuState { Starting = 0, Playing = 1, GameOver = 2 } public GameLoopManager gameLoopManager; public SpriteRenderer titleSprite; public SpriteRenderer gameOverSprite; public MenuState menuState = MenuState.Starting; // Use this for initialization void Start () { } // Update is called once per frame void Update () { titleSprite.enabled = false; gameOverSprite.enabled = false; switch(menuState) { case MenuState.Starting: titleSprite.enabled = true; if (Input.GetButton("Confirm")) { gameLoopManager.StartGame(); menuState = MenuState.Playing; } else { if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.Alpha1)) gameLoopManager.InitializeGame(1); if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.Alpha2)) gameLoopManager.InitializeGame(2); if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.Alpha3)) gameLoopManager.InitializeGame(3); if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.Alpha4)) gameLoopManager.InitializeGame(4); } break; case MenuState.GameOver: gameOverSprite.enabled = true; break; } } }
using UnityEngine; using System.Collections; public class Menus : MonoBehaviour { public enum MenuState { Starting = 0, Playing = 1, GameOver = 2 } public GameLoopManager gameLoopManager; public SpriteRenderer titleSprite; public SpriteRenderer gameOverSprite; public MenuState menuState = MenuState.Starting; // Use this for initialization void Start () { } // Update is called once per frame void Update () { titleSprite.enabled = false; gameOverSprite.enabled = false; switch(menuState) { case MenuState.Starting: titleSprite.enabled = true; if (Input.GetButton("Confirm")) { gameLoopManager.StartGame(); menuState = MenuState.Playing; } else { if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.Alpha1)) gameLoopManager.InitializeGame(1); if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.Alpha2)) gameLoopManager.InitializeGame(2); if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.Alpha3)) gameLoopManager.InitializeGame(3); if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.Alpha4)) gameLoopManager.InitializeGame(4); } break; case MenuState.GameOver: gameOverSprite.enabled = true; break; } } }
Update with LinkTarget.ArmV7s and frameworks.
using System; using MonoTouch.ObjCRuntime; [assembly: LinkWith ("libTTTAttributedLabel.a", LinkTarget.Simulator | LinkTarget.ArmV7, ForceLoad = true)]
using System; using MonoTouch.ObjCRuntime; [assembly: LinkWith ("libTTTAttributedLabel.a", LinkTarget.Simulator | LinkTarget.ArmV7 | LinkTarget.ArmV7s, Frameworks = "CoreGraphics CoreText QuartzCore", ForceLoad = true)]
Clarify that your unit test runner will never speak with you again
using System; using System.Diagnostics; using System.Linq; using System.Threading; using System.Windows; namespace Mahapps.Metro.Tests { /// <summary> /// This class is the ultimate hack to work around that we can't /// create more than one application in the same AppDomain /// /// It is once initialized at the start and never properly cleaned up, /// this means the AppDomain will throw an exception when xUnit unloads it. /// </summary> public class TestHost { private TestApp app; private readonly Thread appThread; private readonly AutoResetEvent gate = new AutoResetEvent(false); private static TestHost testHost; public static void Initialize() { if (testHost == null) { testHost = new TestHost(); } } private TestHost() { appThread = new Thread(StartDispatcher); appThread.SetApartmentState(ApartmentState.STA); appThread.Start(); gate.WaitOne(); } private void StartDispatcher() { app = new TestApp { ShutdownMode = ShutdownMode.OnExplicitShutdown }; app.Startup += (sender, args) => gate.Set(); app.Run(); } /// <summary> /// Await this method in every test that should run on the UI thread. /// </summary> public static SwitchContextToUiThreadAwaiter SwitchToAppThread() { return new SwitchContextToUiThreadAwaiter(testHost.app.Dispatcher); } } }
using System; using System.Diagnostics; using System.Linq; using System.Threading; using System.Windows; namespace Mahapps.Metro.Tests { /// <summary> /// This class is the ultimate hack to work around that we can't /// create more than one application in the same AppDomain /// /// It is initialized once at startup and is never properly cleaned up, /// this means the AppDomain will throw an exception when xUnit unloads it. /// /// Your test runner will inevitably hate you and hang endlessly. /// /// Better than no unit tests. /// </summary> public class TestHost { private TestApp app; private readonly Thread appThread; private readonly AutoResetEvent gate = new AutoResetEvent(false); private static TestHost testHost; public static void Initialize() { if (testHost == null) { testHost = new TestHost(); } } private TestHost() { appThread = new Thread(StartDispatcher); appThread.SetApartmentState(ApartmentState.STA); appThread.Start(); gate.WaitOne(); } private void StartDispatcher() { app = new TestApp { ShutdownMode = ShutdownMode.OnExplicitShutdown }; app.Startup += (sender, args) => gate.Set(); app.Run(); } /// <summary> /// Await this method in every test that should run on the UI thread. /// </summary> public static SwitchContextToUiThreadAwaiter SwitchToAppThread() { return new SwitchContextToUiThreadAwaiter(testHost.app.Dispatcher); } } }
Remove TransfersMatching flag and use the new one at action level
using System.Threading.Tasks; using System.Web.Mvc; using SFA.DAS.Authorization.Mvc.Attributes; using SFA.DAS.EmployerFinance.Web.Orchestrators; namespace SFA.DAS.EmployerFinance.Web.Controllers { [DasAuthorize("EmployerFeature.TransfersMatching")] [RoutePrefix("accounts/{HashedAccountId}")] public class TransfersController : Controller { private readonly TransfersOrchestrator _transfersOrchestrator; public TransfersController(TransfersOrchestrator transfersOrchestrator) { _transfersOrchestrator = transfersOrchestrator; } [HttpGet] [Route("transfers")] public async Task<ActionResult> Index(string hashedAccountId) { var viewModel = await _transfersOrchestrator.GetIndexViewModel(hashedAccountId); return View(viewModel); } [HttpGet] [Route("transfers/financial-breakdown")] public ActionResult FinancialBreakdown(string hashedAccountId) { return View(); } } }
using System.Threading.Tasks; using System.Web.Mvc; using SFA.DAS.Authorization.Mvc.Attributes; using SFA.DAS.EmployerFinance.Web.Orchestrators; namespace SFA.DAS.EmployerFinance.Web.Controllers { [RoutePrefix("accounts/{HashedAccountId}")] public class TransfersController : Controller { private readonly TransfersOrchestrator _transfersOrchestrator; public TransfersController(TransfersOrchestrator transfersOrchestrator) { _transfersOrchestrator = transfersOrchestrator; } [HttpGet] [Route("transfers")] public async Task<ActionResult> Index(string hashedAccountId) { var viewModel = await _transfersOrchestrator.GetIndexViewModel(hashedAccountId); return View(viewModel); } [DasAuthorize("EmployerFeature.FinanceDetails")] [HttpGet] [Route("transfers/financial-breakdown")] public ActionResult FinancialBreakdown(string hashedAccountId) { return View(); } } }
Fix the social sample port.
using System; using System.IO; using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.FileProviders; namespace SocialSample { public static class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel(options => { if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT"))) { // ANCM is not hosting the process options.Listen(IPAddress.Loopback, 5000, listenOptions => { // Configure SSL var serverCertificate = LoadCertificate(); listenOptions.UseHttps(serverCertificate); }); } }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } private static X509Certificate2 LoadCertificate() { var socialSampleAssembly = typeof(Startup).GetTypeInfo().Assembly; var embeddedFileProvider = new EmbeddedFileProvider(socialSampleAssembly, "SocialSample"); var certificateFileInfo = embeddedFileProvider.GetFileInfo("compiler/resources/cert.pfx"); using (var certificateStream = certificateFileInfo.CreateReadStream()) { byte[] certificatePayload; using (var memoryStream = new MemoryStream()) { certificateStream.CopyTo(memoryStream); certificatePayload = memoryStream.ToArray(); } return new X509Certificate2(certificatePayload, "testPassword"); } } } }
using System; using System.IO; using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.FileProviders; namespace SocialSample { public static class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel(options => { if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT"))) { // ANCM is not hosting the process options.Listen(IPAddress.Loopback, 44318, listenOptions => { // Configure SSL var serverCertificate = LoadCertificate(); listenOptions.UseHttps(serverCertificate); }); } }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } private static X509Certificate2 LoadCertificate() { var socialSampleAssembly = typeof(Startup).GetTypeInfo().Assembly; var embeddedFileProvider = new EmbeddedFileProvider(socialSampleAssembly, "SocialSample"); var certificateFileInfo = embeddedFileProvider.GetFileInfo("compiler/resources/cert.pfx"); using (var certificateStream = certificateFileInfo.CreateReadStream()) { byte[] certificatePayload; using (var memoryStream = new MemoryStream()) { certificateStream.CopyTo(memoryStream); certificatePayload = memoryStream.ToArray(); } return new X509Certificate2(certificatePayload, "testPassword"); } } } }
Call Draw on the output of Build
using System; using System.IO; namespace Hangman { public class Hangman { public static void Main(string[] args) { var game = new Game("HANG THE MAN"); string titleText = File.ReadAllText("title.txt"); object[] titleCell = {titleText, Cell.CentreAlign}; object[] titleRow = {titleCell}; while (true) { string shownWord = game.ShownWord(); object[] wordCell = {shownWord, Cell.CentreAlign}; object[] wordRow = {wordCell}; object[] lettersCell = {"Incorrect letters:\n A B I U", Cell.LeftAlign}; object[] livesCell = {"Lives remaining:\n 11/15", Cell.RightAlign}; object[] statsRow = {lettersCell, livesCell}; object[] statusCell = {"Press any letter to guess!", Cell.CentreAlign}; object[] statusRow = {statusCell}; object[] tableConfig = { titleRow, wordRow, statsRow, statusRow }; // var table = new Table( // Broken // Math.Min(81, Console.WindowWidth), // 2, // rows // ); var table = TableFactory.Build(tableConfig); // var tableOutput = table.Draw(); // Console.WriteLine(tableOutput); Console.WriteLine("Still Alive"); char key = Console.ReadKey(true).KeyChar; bool wasCorrect = game.GuessLetter(Char.ToUpper(key)); Console.Clear(); } } } }
using System; using System.IO; namespace Hangman { public class Hangman { public static void Main(string[] args) { var game = new Game("HANG THE MAN"); string titleText = File.ReadAllText("title.txt"); object[] titleCell = {titleText, Cell.CentreAlign}; object[] titleRow = {titleCell}; while (true) { string shownWord = game.ShownWord(); object[] wordCell = {shownWord, Cell.CentreAlign}; object[] wordRow = {wordCell}; object[] lettersCell = {"Incorrect letters:\n A B I U", Cell.LeftAlign}; object[] livesCell = {"Lives remaining:\n 11/15", Cell.RightAlign}; object[] statsRow = {lettersCell, livesCell}; object[] statusCell = {"Press any letter to guess!", Cell.CentreAlign}; object[] statusRow = {statusCell}; object[] tableConfig = { titleRow, wordRow, statsRow, statusRow }; var table = TableFactory.Build(tableConfig); var tableOutput = table.Draw(); Console.WriteLine(tableOutput); Console.WriteLine("Still Alive"); char key = Console.ReadKey(true).KeyChar; bool wasCorrect = game.GuessLetter(Char.ToUpper(key)); Console.Clear(); } } } }
Move settings update to first line
using System; using System.Windows.Forms; using VigilantCupcake.OperatingSystemUtilities; namespace VigilantCupcake { internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static void Main() { if (!SingleInstance.Start()) { SingleInstance.ShowFirstInstance(); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (Properties.Settings.Default.UpgradeRequired) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.UpgradeRequired = false; Properties.Settings.Default.Save(); } try { MainForm mainForm = new MainForm(); Application.Run(mainForm); } catch (Exception e) { MessageBox.Show(e.Message); } SingleInstance.Stop(); } } }
using System; using System.Windows.Forms; using VigilantCupcake.OperatingSystemUtilities; namespace VigilantCupcake { internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static void Main() { if (Properties.Settings.Default.UpgradeRequired) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.UpgradeRequired = false; Properties.Settings.Default.Save(); } if (!SingleInstance.Start()) { SingleInstance.ShowFirstInstance(); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { MainForm mainForm = new MainForm(); Application.Run(mainForm); } catch (Exception e) { MessageBox.Show(e.Message); } SingleInstance.Stop(); } } }
Check regex for only 1 match
using Albatross.Expression; using System; namespace RollGen.Domain { public class RandomDice : Dice { private readonly Random random; public RandomDice(Random random) { this.random = random; } public override PartialRoll Roll(int quantity = 1) { return new RandomPartialRoll(quantity, random); } public override object Compute(string rolled) { var unrolledDieRolls = rollRegex.Matches(rolled); if (unrolledDieRolls.Count > 0) { var message = string.Format("Cannot compute unrolled die roll {0}", unrolledDieRolls[0]); throw new ArgumentException(message); } return Parser.GetParser().Compile(rolled).EvalValue(null); } } }
using Albatross.Expression; using System; namespace RollGen.Domain { public class RandomDice : Dice { private readonly Random random; public RandomDice(Random random) { this.random = random; } public override PartialRoll Roll(int quantity = 1) { return new RandomPartialRoll(quantity, random); } public override object Compute(string rolled) { if (rollRegex.IsMatch(rolled)) { var match = rollRegex.Match(rolled); var message = string.Format("Cannot compute unrolled die roll {0}", match.Value); throw new ArgumentException(message); } return Parser.GetParser().Compile(rolled).EvalValue(null); } } }
Fix exception with invalid mesh
using SRPCommon.Util; using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using System.Diagnostics.CodeAnalysis; namespace SRPCommon.Scene { public class MeshInstancePrimitive : Primitive { public override PrimitiveType Type => PrimitiveType.MeshInstance; public SceneMesh Mesh { get; private set; } public override bool IsValid => Mesh != null; [JsonProperty("mesh")] [SuppressMessage("Language", "CSE0002:Use getter-only auto properties", Justification = "Needed for serialisation")] private string MeshName { get; set; } internal override void PostLoad(Scene scene) { base.PostLoad(scene); if (MeshName != null) { // Look up mesh in the scene's collection. SceneMesh mesh; if (scene.Meshes.TryGetValue(MeshName, out mesh)) { Mesh = mesh; } else { OutputLogger.Instance.LogLine(LogCategory.Log, "Mesh not found: " + MeshName); } } } } }
using SRPCommon.Util; using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using System.Diagnostics.CodeAnalysis; namespace SRPCommon.Scene { public class MeshInstancePrimitive : Primitive { public override PrimitiveType Type => PrimitiveType.MeshInstance; public SceneMesh Mesh { get; private set; } public override bool IsValid => Mesh != null && Mesh.IsValid; [JsonProperty("mesh")] [SuppressMessage("Language", "CSE0002:Use getter-only auto properties", Justification = "Needed for serialisation")] private string MeshName { get; set; } internal override void PostLoad(Scene scene) { base.PostLoad(scene); if (MeshName != null) { // Look up mesh in the scene's collection. SceneMesh mesh; if (scene.Meshes.TryGetValue(MeshName, out mesh)) { Mesh = mesh; } else { OutputLogger.Instance.LogLine(LogCategory.Log, "Mesh not found: " + MeshName); } } } } }
Add version and environment to completed/failed work item
using System; namespace CertiPay.Common.WorkQueue { public class CompletedWorkItem<T> { public T WorkItem { get; set; } public String Server { get; set; } public DateTime CompletedAt { get; set; } // TODO Version? public CompletedWorkItem() { this.Server = System.Environment.MachineName; this.CompletedAt = DateTime.UtcNow; } } }
using System; namespace CertiPay.Common.WorkQueue { public class CompletedWorkItem<T> { public T WorkItem { get; set; } public String Server { get; set; } public DateTime CompletedAt { get; set; } public String Version { get; set; } public EnvUtil.Environment Environment { get; set; } public CompletedWorkItem() { this.Server = System.Environment.MachineName; this.CompletedAt = DateTime.UtcNow; this.Version = Utilities.Version; this.Environment = EnvUtil.Current; } } }
Fix Denver theme to point CSS to configured skin location
@using CkanDotNet.Web.Models.Helpers @using System.Configuration <!--v Denvergov:1of3(head) v--> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link rel="Stylesheet" type="text/css" href="http://dgqa.denvergov.org/dgskin1/Scripts/Denvergov.style.skin.css" /> <link rel="shortcut icon" href="@Url.Content("~/Content/Theme/" + SettingsHelper.GetCatalogTheme() + "/favicon.ico")"/> <script type="text/javascript" src="@Url.Content(ConfigurationManager.AppSettings["Catalog.SkinLocation"] + "/dgskin1/Scripts/Denvergov.skin.js")"></script> <!--^ Denvergov:1of3(head) ^--> <link rel="Stylesheet" type="text/css" href="@Url.Content(ConfigurationManager.AppSettings["Catalog.SkinLocation"] + "/Portals/_default/Skins/DenverGov/skin.css")" /> <link href="@Url.Content("~/Content/Theme/" + SettingsHelper.GetCatalogTheme() + "/Styles.css")" rel="stylesheet" type="text/css" />
@using CkanDotNet.Web.Models.Helpers @using System.Configuration <!--v Denvergov:1of3(head) v--> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link rel="Stylesheet" type="text/css" href="@Url.Content(ConfigurationManager.AppSettings["Catalog.SkinLocation"] + "/dgskin1/Scripts/Denvergov.style.skin.css")" /> <link rel="shortcut icon" href="@Url.Content("~/Content/Theme/" + SettingsHelper.GetCatalogTheme() + "/favicon.ico")"/> <script type="text/javascript" src="@Url.Content(ConfigurationManager.AppSettings["Catalog.SkinLocation"] + "/dgskin1/Scripts/Denvergov.skin.js")"></script> <!--^ Denvergov:1of3(head) ^--> <link rel="Stylesheet" type="text/css" href="@Url.Content(ConfigurationManager.AppSettings["Catalog.SkinLocation"] + "/Portals/_default/Skins/DenverGov/skin.css")" /> <link href="@Url.Content("~/Content/Theme/" + SettingsHelper.GetCatalogTheme() + "/Styles.css")" rel="stylesheet" type="text/css" />
Add Authorize attributes to verify sample
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using UsageSampleMvc.AspNetCore.Models; namespace UsageSampleMvc.AspNetCore.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
using System.Diagnostics; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using UsageSampleMvc.AspNetCore.Models; namespace UsageSampleMvc.AspNetCore.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } [Authorize] public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } [Authorize] public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
Put unhandled exception logging in to custom handler class.
using System.Net; using System.Net.Http; using System.Web.Http.ExceptionHandling; using FluentValidation; using NLog; using SFA.DAS.Commitments.Application.Exceptions; namespace SFA.DAS.Commitments.Api { public class CustomExceptionHandler : ExceptionHandler { private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); public override void Handle(ExceptionHandlerContext context) { if (context.Exception is ValidationException) { var response = new HttpResponseMessage(HttpStatusCode.BadRequest); var message = ((ValidationException)context.Exception).Message; response.Content = new StringContent(message); context.Result = new CustomErrorResult(context.Request, response); Logger.Warn(context.Exception, "Validation error"); return; } if (context.Exception is UnauthorizedException) { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized); var message = ((UnauthorizedException)context.Exception).Message; response.Content = new StringContent(message); context.Result = new CustomErrorResult(context.Request, response); Logger.Warn(context.Exception, "Authorisation error"); return; } base.Handle(context); } } }
using System.Net; using System.Net.Http; using System.Web.Http.ExceptionHandling; using FluentValidation; using NLog; using SFA.DAS.Commitments.Application.Exceptions; namespace SFA.DAS.Commitments.Api { public class CustomExceptionHandler : ExceptionHandler { private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); public override void Handle(ExceptionHandlerContext context) { if (context.Exception is ValidationException) { var response = new HttpResponseMessage(HttpStatusCode.BadRequest); var message = ((ValidationException)context.Exception).Message; response.Content = new StringContent(message); context.Result = new CustomErrorResult(context.Request, response); _logger.Warn(context.Exception, "Validation error"); return; } if (context.Exception is UnauthorizedException) { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized); var message = ((UnauthorizedException)context.Exception).Message; response.Content = new StringContent(message); context.Result = new CustomErrorResult(context.Request, response); _logger.Warn(context.Exception, "Authorisation error"); return; } _logger.Error(context.Exception, "Unhandled exception"); base.Handle(context); } } }
Adjust column width on url part on the create household page
@model Vaskelista.Models.Household @{ ViewBag.Title = "Create"; } <h2>Velkommen til vaskelista</h2> <p>Her kan du velge hva vaskelisten din skal hete:</p> <div class="form-horizontal"> <div class="form-group"> <div class="col-md-2"><label>@Request.Url.ToString()</label></div> <div class="col-md-4"> <ul class="form-option-list"> @foreach (string randomUrl in ViewBag.RandomUrls) { <li> @using (Html.BeginForm("Create", "Household", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Token, new { Value = randomUrl }) <input type="submit" value="@randomUrl" class="btn btn-default" /> } </li> } </ul> </div> </div> </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
@model Vaskelista.Models.Household @{ ViewBag.Title = "Create"; } <h2>Velkommen til vaskelista</h2> <p>Her kan du velge hva vaskelisten din skal hete:</p> <div class="form-horizontal"> <div class="form-group"> <div class="col-md-4"><label>@Request.Url.ToString()</label></div> <div class="col-md-4"> <ul class="form-option-list"> @foreach (string randomUrl in ViewBag.RandomUrls) { <li> @using (Html.BeginForm("Create", "Household", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Token, new { Value = randomUrl }) <input type="submit" value="@randomUrl" class="btn btn-default" /> } </li> } </ul> </div> </div> </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Mark internal query builder non-browsable
namespace NRules.Fluent.Dsl { /// <summary> /// Root of the query method chain. /// </summary> public interface IQuery { /// <summary> /// Internal query builder. /// This method is intended for framework use only. /// </summary> IQueryBuilder Builder { get; } } /// <summary> /// Intermediate query chain element. /// </summary> /// <typeparam name="TSource">Type of the element the query operates on.</typeparam> public interface IQuery<out TSource> { /// <summary> /// Internal query builder. /// This method is intended for framework use only. /// </summary> IQueryBuilder Builder { get; } } }
using System.ComponentModel; namespace NRules.Fluent.Dsl { /// <summary> /// Root of the query method chain. /// </summary> public interface IQuery { /// <summary> /// Internal query builder. /// This method is intended for framework use only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] IQueryBuilder Builder { get; } } /// <summary> /// Intermediate query chain element. /// </summary> /// <typeparam name="TSource">Type of the element the query operates on.</typeparam> public interface IQuery<out TSource> { /// <summary> /// Internal query builder. /// This method is intended for framework use only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] IQueryBuilder Builder { get; } } }
Check for a valid image handle when loading resources in the editor.
using System; using Flood.GUI.Controls; using Flood.GUI.Renderers; using Flood.GUI.Skins; namespace Flood.Editor.Client.Gui { public abstract class GuiWindow : IDisposable { /// <summary> /// Native GUI window. /// </summary> public Window NativeWindow { get; set; } /// <summary> /// Renderer of the GUI. /// </summary> public Renderer Renderer { get; private set; } /// <summary> /// Skin of the GUI. /// </summary> public Skin Skin { get; private set; } public Canvas Canvas { get; private set; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposing) return; Canvas.Dispose(); Skin.Dispose(); Renderer.Dispose(); } public void Init(Renderer renderer, string textureName, Flood.GUI.Font defaultFont) { Renderer = renderer; var resMan = FloodEngine.GetEngine().ResourceManager; var options = new ResourceLoadOptions {Name = textureName, AsynchronousLoad = false}; var imageHandle = resMan.LoadResource<Image>(options); Skin = new TexturedSkin(renderer, imageHandle, defaultFont); Canvas = new Canvas(Skin); Init(); } protected abstract void Init(); public void Render() { Canvas.RenderCanvas(); } } }
using System; using Flood.GUI.Controls; using Flood.GUI.Renderers; using Flood.GUI.Skins; namespace Flood.Editor.Client.Gui { public abstract class GuiWindow : IDisposable { /// <summary> /// Native GUI window. /// </summary> public Window NativeWindow { get; set; } /// <summary> /// Renderer of the GUI. /// </summary> public Renderer Renderer { get; private set; } /// <summary> /// Skin of the GUI. /// </summary> public Skin Skin { get; private set; } public Canvas Canvas { get; private set; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposing) return; Canvas.Dispose(); Skin.Dispose(); Renderer.Dispose(); } public void Init(Renderer renderer, string textureName, Flood.GUI.Font defaultFont) { Renderer = renderer; var resMan = FloodEngine.GetEngine().ResourceManager; var options = new ResourceLoadOptions {Name = textureName, AsynchronousLoad = false}; var imageHandle = resMan.LoadResource<Image>(options); if (imageHandle.Id == 0) return; Skin = new TexturedSkin(renderer, imageHandle, defaultFont); Canvas = new Canvas(Skin); Init(); } protected abstract void Init(); public void Render() { Canvas.RenderCanvas(); } } }
Build fix? (not sure why travis doesn't see this file)
namespace FlatBuffers { public static class FieldTypeMetaData { public const string Index = "id"; public const string Required = "required"; } }
namespace FlatBuffers { public static class FieldTypeMetaData { public const string Index = "id"; public const string Required = "required"; } }
Add base action property ordering
using System; using System.ComponentModel; using System.Windows; using DesktopWidgets.Classes; namespace DesktopWidgets.Actions { public abstract class ActionBase { [DisplayName("Delay")] public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0); [DisplayName("Show Errors")] public bool ShowErrors { get; set; } = false; public void Execute() { DelayedAction.RunAction((int) Delay.TotalMilliseconds, () => { try { ExecuteAction(); } catch (Exception ex) { if (ShowErrors) Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}", image: MessageBoxImage.Error); } }); } public virtual void ExecuteAction() { } } }
using System; using System.ComponentModel; using System.Windows; using DesktopWidgets.Classes; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Actions { public abstract class ActionBase { [PropertyOrder(0)] [DisplayName("Delay")] public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0); [PropertyOrder(1)] [DisplayName("Show Errors")] public bool ShowErrors { get; set; } = false; public void Execute() { DelayedAction.RunAction((int) Delay.TotalMilliseconds, () => { try { ExecuteAction(); } catch (Exception ex) { if (ShowErrors) Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}", image: MessageBoxImage.Error); } }); } public virtual void ExecuteAction() { } } }
Remove some methods to try get element, as if an element is not found, Direct2D only returns a zero pointer with a S_Ok hresult
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SharpDX.Direct2D1 { public partial class SvgDocument { /// <summary> /// Finds an svg element by id /// </summary> /// <param name="id">Id to lookup for</param> /// <returns>SvgElement</returns> public SvgElement FindElementById(string id) { SharpDX.Result __result__; SvgElement svgElement; __result__ = TryFindElementById_(id, out svgElement); __result__.CheckError(); return svgElement; } /// <summary> /// Try to find an element by id /// </summary> /// <param name="id">id to search for</param> /// <param name="svgElement">When this method completes, contains the relevant element (if applicable)</param> /// <returns>true if element has been found, false otherwise</returns> public bool TryFindElementById(string id, out SvgElement svgElement) { SharpDX.Result __result__; __result__ = TryFindElementById_(id, out svgElement); return __result__.Code >= 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SharpDX.Direct2D1 { public partial class SvgDocument { /// <summary> /// Finds an svg element by id /// </summary> /// <param name="id">Id to lookup for</param> /// <returns>SvgElement if found, null otherwise</returns> public SvgElement FindElementById(string id) { SharpDX.Result __result__; SvgElement svgElement; __result__ = TryFindElementById_(id, out svgElement); __result__.CheckError(); return svgElement; } } }
Add ChessGame parameter to IsValidDestination
namespace ChessDotNet { public abstract class ChessPiece { public abstract Player Owner { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj == null || GetType() != obj.GetType()) return false; ChessPiece piece1 = this; ChessPiece piece2 = (ChessPiece)obj; return piece1.Owner == piece2.Owner; } public override int GetHashCode() { return new { Piece = GetFenCharacter(), Owner }.GetHashCode(); } public static bool operator ==(ChessPiece piece1, ChessPiece piece2) { if (ReferenceEquals(piece1, piece2)) return true; if ((object)piece1 == null || (object)piece2 == null) return false; return piece1.Equals(piece2); } public static bool operator !=(ChessPiece piece1, ChessPiece piece2) { if (ReferenceEquals(piece1, piece2)) return false; if ((object)piece1 == null || (object)piece2 == null) return true; return !piece1.Equals(piece2); } public abstract string GetFenCharacter(); public abstract bool IsValidDestination(Position from, Position to); } }
namespace ChessDotNet { public abstract class ChessPiece { public abstract Player Owner { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj == null || GetType() != obj.GetType()) return false; ChessPiece piece1 = this; ChessPiece piece2 = (ChessPiece)obj; return piece1.Owner == piece2.Owner; } public override int GetHashCode() { return new { Piece = GetFenCharacter(), Owner }.GetHashCode(); } public static bool operator ==(ChessPiece piece1, ChessPiece piece2) { if (ReferenceEquals(piece1, piece2)) return true; if ((object)piece1 == null || (object)piece2 == null) return false; return piece1.Equals(piece2); } public static bool operator !=(ChessPiece piece1, ChessPiece piece2) { if (ReferenceEquals(piece1, piece2)) return false; if ((object)piece1 == null || (object)piece2 == null) return true; return !piece1.Equals(piece2); } public abstract string GetFenCharacter(); public abstract bool IsValidDestination(Position from, Position to, ChessGame game); } }
Check for header before removing it
using System; using System.IO; using System.Linq; namespace AutoHeader.Options { public class RemoveHeaderOption : Option { public override void Execute() { Console.WriteLine("Execute \'RemoveHeaderOption\': {0}", Arg); if (!Directory.Exists(Arg)) { throw new ExecutionException(string.Format("Directory does not exist: {0}", Arg)); } RemoveHeaderFromFilesInDirectory(Arg); } private void RemoveHeaderFromFilesInDirectory(string directory) { foreach (var filePath in Directory.GetFiles(directory).Where(f => f.EndsWith(".cs"))) { RemoveHeaderFromFile(filePath); } foreach (var subDir in Directory.GetDirectories(directory)) { RemoveHeaderFromFilesInDirectory(subDir); } } private void RemoveHeaderFromFile(string filePath) { var tempFilePath = GetTempFileName(filePath); File.Move(filePath, tempFilePath); string header; using (var streamReader = new StreamReader("HeaderTemplate.txt")) { header = streamReader.ReadToEnd(); } string fileContent; using (var streamReader = new StreamReader(tempFilePath)) { fileContent = streamReader.ReadToEnd(); } fileContent = fileContent.Substring(header.Length); using (var stream = new StreamWriter(filePath, false)) { stream.Write(fileContent); } File.Delete(tempFilePath); } private static string GetTempFileName(string filePath) { var fileName = Path.GetFileName(filePath); var path = Path.GetDirectoryName(filePath) ?? string.Empty; var tempFilePath = Path.Combine(path, string.Format("~{0}", fileName)); return tempFilePath; } } }
using System; using System.IO; using System.Linq; namespace AutoHeader.Options { public class RemoveHeaderOption : Option { public override void Execute() { Console.WriteLine("Execute \'RemoveHeaderOption\': {0}", Arg); if (!Directory.Exists(Arg)) { throw new ExecutionException(string.Format("Directory does not exist: {0}", Arg)); } RemoveHeaderFromFilesInDirectory(Arg); } private void RemoveHeaderFromFilesInDirectory(string directory) { foreach (var filePath in Directory.GetFiles(directory).Where(f => f.EndsWith(".cs"))) { RemoveHeaderFromFile(filePath); } foreach (var subDir in Directory.GetDirectories(directory)) { RemoveHeaderFromFilesInDirectory(subDir); } } private void RemoveHeaderFromFile(string filePath) { string header; using (var streamReader = new StreamReader("HeaderTemplate.txt")) { header = streamReader.ReadToEnd(); } string fileContent; using (var streamReader = new StreamReader(filePath)) { fileContent = streamReader.ReadToEnd(); } if (fileContent.Length >= header.Length) { var fileHeader = fileContent.Substring(0, header.Length); if (fileHeader == header) { fileContent = fileContent.Substring(header.Length); using (var stream = new StreamWriter(filePath, false)) { stream.Write(fileContent); } } } } } }
Change color to be more visible
using System.Drawing; using MonoHaven.Graphics; using MonoHaven.Graphics.Text; namespace MonoHaven.UI.Widgets { public class Progress : Widget { private readonly TextLine textLine; private int value; public Progress(Widget parent) : base(parent) { textLine = new TextLine(Fonts.LabelText); textLine.TextColor = Color.DeepPink; textLine.TextAlign = TextAlign.Center; textLine.SetWidth(75); Resize(textLine.Width, 20); } public int Value { get { return value; } set { this.value = value; textLine.Clear(); textLine.Append(string.Format("{0}%", value)); } } protected override void OnDraw(DrawingContext dc) { dc.Draw(textLine, 0, 0); } protected override void OnDispose() { if (textLine != null) textLine.Dispose(); } } }
using System.Drawing; using MonoHaven.Graphics; using MonoHaven.Graphics.Text; namespace MonoHaven.UI.Widgets { public class Progress : Widget { private readonly TextLine textLine; private int value; public Progress(Widget parent) : base(parent) { textLine = new TextLine(Fonts.LabelText); textLine.TextColor = Color.Yellow; textLine.TextAlign = TextAlign.Center; textLine.SetWidth(75); Resize(textLine.Width, 20); } public int Value { get { return value; } set { this.value = value; textLine.Clear(); textLine.Append(string.Format("{0}%", value)); } } protected override void OnDraw(DrawingContext dc) { dc.Draw(textLine, 0, 0); } protected override void OnDispose() { if (textLine != null) textLine.Dispose(); } } }
Make sure Expiration field is also indexed in the db
using System; using SQLite; namespace Amica.vNext.SimpleCache { class CacheElement { [PrimaryKey] public string Key { get; set; } [Indexed] public string TypeName { get; set; } public byte[] Value { get; set; } public DateTime? Expiration { get; set; } public DateTimeOffset CreatedAt { get; set; } } }
using System; using SQLite; namespace Amica.vNext.SimpleCache { class CacheElement { [PrimaryKey] public string Key { get; set; } [Indexed] public string TypeName { get; set; } public byte[] Value { get; set; } [Indexed] public DateTime? Expiration { get; set; } public DateTimeOffset CreatedAt { get; set; } } }
Add App Package location sample code
using Xamarin.UITest; namespace Xtc101.UITest { public class AppInitializer { public static IApp StartApp(Platform platform) { if (platform == Platform.Android) { return ConfigureApp .Android .PreferIdeSettings() .StartApp(); } return ConfigureApp .iOS .PreferIdeSettings() .StartApp(); } } }
using Xamarin.UITest; namespace Xtc101.UITest { public class AppInitializer { public static IApp StartApp(Platform platform) { if (platform == Platform.Android) { return ConfigureApp .Android // Run Release Android project on Simulator and then uncomment line bellow (you can run the tests under the debug config) //.ApkFile("../../../Xtc101/bin/Release/com.companyname.xtc101.apk") .PreferIdeSettings() .StartApp(); } return ConfigureApp .iOS .PreferIdeSettings() .StartApp(); } } }
Add ids from service endpoint
using System.Net; using LtiLibrary.Core.Outcomes.v2; namespace LtiLibrary.AspNet.Outcomes.v2 { public class PutResultContext { public PutResultContext(LisResult result) { Result = result; StatusCode = HttpStatusCode.OK; } public LisResult Result { get; private set; } public HttpStatusCode StatusCode { get; set; } } }
using System.Net; using LtiLibrary.Core.Outcomes.v2; namespace LtiLibrary.AspNet.Outcomes.v2 { public class PutResultContext { public PutResultContext(string contextId, string lineItemId, string id, LisResult result) { ContextId = contextId; LineItemId = lineItemId; Id = id; Result = result; StatusCode = HttpStatusCode.OK; } public string ContextId { get; set; } public string LineItemId { get; set; } public string Id { get; set; } public LisResult Result { get; private set; } public HttpStatusCode StatusCode { get; set; } } }
Stop wrapping exceptions we don't know about and let them throw at the point of error.
using System; using SevenDigital.Api.Wrapper.Exceptions; namespace SevenDigital.Api.Wrapper.Utility.Serialization { public class ApiXmlDeSerializer<T> : IDeSerializer<T> where T : class { private readonly IDeSerializer<T> _deSerializer; private readonly IXmlErrorHandler _xmlErrorHandler; public ApiXmlDeSerializer(IDeSerializer<T> deSerializer, IXmlErrorHandler xmlErrorHandler) { _deSerializer = deSerializer; _xmlErrorHandler = xmlErrorHandler; } public T DeSerialize(string response) { try { var responseNode = _xmlErrorHandler.GetResponseAsXml(response); _xmlErrorHandler.AssertError(responseNode); var resourceNode = responseNode.FirstNode.ToString(); return _deSerializer.DeSerialize(resourceNode); } catch (Exception e) { if (e is ApiXmlException) throw; throw new ApplicationException("Internal error while deserializing response " + response, e); } } } }
namespace SevenDigital.Api.Wrapper.Utility.Serialization { public class ApiXmlDeSerializer<T> : IDeSerializer<T> where T : class { private readonly IDeSerializer<T> _deSerializer; private readonly IXmlErrorHandler _xmlErrorHandler; public ApiXmlDeSerializer(IDeSerializer<T> deSerializer, IXmlErrorHandler xmlErrorHandler) { _deSerializer = deSerializer; _xmlErrorHandler = xmlErrorHandler; } public T DeSerialize(string response) { var responseNode = _xmlErrorHandler.GetResponseAsXml(response); _xmlErrorHandler.AssertError(responseNode); var resourceNode = responseNode.FirstNode.ToString(); return _deSerializer.DeSerialize(resourceNode); } } }
Make avatars use a delayed load wrapper
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Users { /// <summary> /// An avatar which can update to a new user when needed. /// </summary> public class UpdateableAvatar : Container { private Container displayedAvatar; private User user; public User User { get { return user; } set { if (user?.Id == value?.Id) return; user = value; if (IsLoaded) updateAvatar(); } } protected override void LoadComplete() { base.LoadComplete(); updateAvatar(); } private void updateAvatar() { displayedAvatar?.FadeOut(300); displayedAvatar?.Expire(); Add(displayedAvatar = new AsyncLoadWrapper(new Avatar(user) { RelativeSizeAxes = Axes.Both, OnLoadComplete = d => d.FadeInFromZero(200), })); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Users { /// <summary> /// An avatar which can update to a new user when needed. /// </summary> public class UpdateableAvatar : Container { private Container displayedAvatar; private User user; public User User { get { return user; } set { if (user?.Id == value?.Id) return; user = value; if (IsLoaded) updateAvatar(); } } protected override void LoadComplete() { base.LoadComplete(); updateAvatar(); } private void updateAvatar() { displayedAvatar?.FadeOut(300); displayedAvatar?.Expire(); Add(displayedAvatar = new DelayedLoadWrapper(new Avatar(user) { RelativeSizeAxes = Axes.Both, OnLoadComplete = d => d.FadeInFromZero(200), })); } } }
Make attribute search more to the point
using System.Linq; using UnityEngine; using UnityEditor; namespace EasyButtons { /// <summary> /// Custom inspector for Object including derived classes. /// </summary> [CanEditMultipleObjects] [CustomEditor(typeof(Object), true)] public class ObjectEditor : Editor { public override void OnInspectorGUI() { // Loop through all methods with the Button attribute and no arguments foreach (var method in target.GetType().GetMethods() .Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0) .Where(m => m.GetParameters().Length == 0)) { // Draw a button which invokes the method if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name))) { foreach (var target in targets) { method.Invoke(target, null); } } } // Draw the rest of the inspector as usual DrawDefaultInspector(); } } }
using System.Linq; using UnityEngine; using UnityEditor; namespace EasyButtons { /// <summary> /// Custom inspector for Object including derived classes. /// </summary> [CanEditMultipleObjects] [CustomEditor(typeof(Object), true)] public class ObjectEditor : Editor { public override void OnInspectorGUI() { // Loop through all methods with the Button attribute and no arguments foreach (var method in target.GetType().GetMethods() .Where(m => System.Attribute.IsDefined(m, typeof(ButtonAttribute), true)) .Where(m => m.GetParameters().Length == 0)) { // Draw a button which invokes the method if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name))) { foreach (var target in targets) { method.Invoke(target, null); } } } // Draw the rest of the inspector as usual DrawDefaultInspector(); } } }
Use DeveloperExceptionPage only in DEV Enviroment
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Shariff.Backend { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseDeveloperExceptionPage(); app.UseMvc(); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Shariff.Backend { public class Startup { public Startup( IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices( IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.UseMvc(); } } }
Fix to support virtual directories/folders in IIS.
using Glimpse.Core.Extensibility; namespace Glimpse.Knockout { public sealed class ClientScript : IStaticClientScript { public ScriptOrder Order { get { return ScriptOrder.IncludeAfterClientInterfaceScript; } } public string GetUri(string version) { return "/Scripts/glimpse-knockout.js"; } } }
using Glimpse.Core.Extensibility; namespace Glimpse.Knockout { public sealed class ClientScript : IStaticClientScript { public ScriptOrder Order { get { return ScriptOrder.IncludeAfterClientInterfaceScript; } } public string GetUri(string version) { return System.Web.VirtualPathUtility.ToAbsolute("~/Scripts/glimpse-knockout.js"); } } }
Check when list is null and campaign details doesn't exist
namespace Microsoft.eShopOnContainers.WebMVC.Controllers { using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.WebMVC.Services; using Microsoft.eShopOnContainers.WebMVC.ViewModels; using System; using System.Collections.Generic; using System.Threading.Tasks; [Authorize] public class CampaignsController : Controller { private ICampaignService _campaignService; public CampaignsController(ICampaignService campaignService) => _campaignService = campaignService; public async Task<IActionResult> Index() { var campaignList = await _campaignService.GetCampaigns(); return View(campaignList); } public async Task<IActionResult> Details(int id) { var campaignDto = await _campaignService.GetCampaignById(id); var campaign = new Campaign { Id = campaignDto.Id, Name = campaignDto.Name, Description = campaignDto.Description, From = campaignDto.From, To = campaignDto.To, PictureUri = campaignDto.PictureUri }; return View(campaign); } } }
namespace Microsoft.eShopOnContainers.WebMVC.Controllers { using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.WebMVC.Models; using Microsoft.eShopOnContainers.WebMVC.Services; using Microsoft.eShopOnContainers.WebMVC.ViewModels; using System.Collections.Generic; using System.Threading.Tasks; [Authorize] public class CampaignsController : Controller { private ICampaignService _campaignService; public CampaignsController(ICampaignService campaignService) => _campaignService = campaignService; public async Task<IActionResult> Index() { var campaignDtoList = await _campaignService.GetCampaigns(); if(campaignDtoList is null) { return View(); } var campaignList = MapCampaignModelListToDtoList(campaignDtoList); return View(campaignList); } public async Task<IActionResult> Details(int id) { var campaignDto = await _campaignService.GetCampaignById(id); if (campaignDto is null) { return NotFound(); } var campaign = new Campaign { Id = campaignDto.Id, Name = campaignDto.Name, Description = campaignDto.Description, From = campaignDto.From, To = campaignDto.To, PictureUri = campaignDto.PictureUri }; return View(campaign); } private List<Campaign> MapCampaignModelListToDtoList(IEnumerable<CampaignDTO> campaignDtoList) { var campaignList = new List<Campaign>(); foreach(var campaignDto in campaignDtoList) { campaignList.Add(MapCampaignDtoToModel(campaignDto)); } return campaignList; } private Campaign MapCampaignDtoToModel(CampaignDTO campaign) { return new Campaign { Id = campaign.Id, Name = campaign.Name, Description = campaign.Description, From = campaign.From, To = campaign.To, PictureUri = campaign.PictureUri }; } } }
Add support for APP_IN_USE dependency change
using Mycroft.App; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mycroft.Cmd.App { class AppCommand : Command { /// <summary> /// Parses JSON into App command objects /// </summary> /// <param name="messageType">The message type that determines the command to create</param> /// <param name="json">The JSON body of the message</param> /// <returns>Returns a command object for the parsed message</returns> public static Command Parse(String type, String json, AppInstance instance) { switch (type) { case "APP_UP": return new DependencyChange(instance, Status.up); case "APP_DOWN": return new DependencyChange(instance, Status.down); case "APP_MANIFEST": return Manifest.Parse(json, instance); default: //data is incorrect - can't do anything with it // TODO notify that is wrong break; } return null ; } } }
using Mycroft.App; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mycroft.Cmd.App { class AppCommand : Command { /// <summary> /// Parses JSON into App command objects /// </summary> /// <param name="messageType">The message type that determines the command to create</param> /// <param name="json">The JSON body of the message</param> /// <returns>Returns a command object for the parsed message</returns> public static Command Parse(String type, String json, AppInstance instance) { switch (type) { case "APP_UP": return new DependencyChange(instance, Status.up); case "APP_DOWN": return new DependencyChange(instance, Status.down); case "APP_IN_USE": return new DependencyChange(instance, Status.in_use); case "APP_MANIFEST": return Manifest.Parse(json, instance); default: //data is incorrect - can't do anything with it // TODO notify that is wrong break; } return null ; } } }
Fix reference plane rotation bug.
using UnityEngine; using System; namespace Starstrider42.CustomAsteroids { /// <summary>Standard implementation of <see cref="ReferencePlane"/>.</summary> internal class SimplePlane : ReferencePlane { public string name { get; private set; } /// <summary>Rotation used to implement toDefaultFrame.</summary> private readonly Quaternion xform; /// <summary> /// Creates a new ReferencePlane with the given name and rotation. /// </summary> /// <param name="id">A unique identifier for this object. Initialises the <see cref="name"/> property.</param> /// <param name="thisToDefault">A rotation that transforms vectors from this reference frame /// to the KSP default reference frame.</param> internal SimplePlane(string id, Quaternion thisToDefault) { this.name = id; this.xform = thisToDefault; } public Vector3d toDefaultFrame(Vector3d inFrame) { Quaternion frameCorrection = Planetarium.Rotation; return frameCorrection * xform * Quaternion.Inverse(frameCorrection) * inFrame; } } }
using UnityEngine; namespace Starstrider42.CustomAsteroids { /// <summary>Standard implementation of <see cref="ReferencePlane"/>.</summary> internal class SimplePlane : ReferencePlane { public string name { get; private set; } /// <summary>Rotation used to implement toDefaultFrame.</summary> private readonly Quaternion xform; /// <summary> /// Creates a new ReferencePlane with the given name and rotation. /// </summary> /// <param name="id">A unique identifier for this object. Initialises the <see cref="name"/> property.</param> /// <param name="thisToDefault">A rotation that transforms vectors from this reference frame /// to the KSP default reference frame.</param> internal SimplePlane(string id, Quaternion thisToDefault) { this.name = id; this.xform = thisToDefault; } public Vector3d toDefaultFrame(Vector3d inFrame) { Quaternion frameCorrection = Planetarium.Zup.Rotation; return Quaternion.Inverse(frameCorrection) * xform * frameCorrection * inFrame; } } }
Fix to ensure HTMLElement uses the Caption when loading up the actual HTML page.
using Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Webkit; using Uri = Android.Net.Uri; namespace MonoDroid.Dialog { public class HtmlElement : StringElement { // public string Value; public HtmlElement(string caption, string url) : base(caption) { Url = Uri.Parse(url); } public HtmlElement(string caption, Uri uri) : base(caption) { Url = uri; } public Uri Url { get; set; } void OpenUrl(Context context) { Intent intent = new Intent(context, typeof(HtmlActivity)); intent.PutExtra("URL",this.Url.ToString()); intent.AddFlags(ActivityFlags.NewTask); context.StartActivity(intent); } public override View GetView(Context context, View convertView, ViewGroup parent) { View view = base.GetView (context, convertView, parent); this.Click = (o, e) => OpenUrl(context); return view; } } [Activity] public class HtmlActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Intent i = this.Intent; string url = i.GetStringExtra("URL"); WebView webview = new WebView(this); webview.Settings.JavaScriptEnabled = true; SetContentView(webview); webview.LoadUrl(url); } } }
using Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Webkit; using Uri = Android.Net.Uri; namespace MonoDroid.Dialog { public class HtmlElement : StringElement { // public string Value; public HtmlElement(string caption, string url) : base(caption) { Url = Uri.Parse(url); } public HtmlElement(string caption, Uri uri) : base(caption) { Url = uri; } public Uri Url { get; set; } void OpenUrl(Context context) { Intent intent = new Intent(context, typeof(HtmlActivity)); intent.PutExtra("URL",this.Url.ToString()); intent.PutExtra("Title",Caption); intent.AddFlags(ActivityFlags.NewTask); context.StartActivity(intent); } public override View GetView(Context context, View convertView, ViewGroup parent) { View view = base.GetView (context, convertView, parent); this.Click = (o, e) => OpenUrl(context); return view; } } [Activity] public class HtmlActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Intent i = this.Intent; string url = i.GetStringExtra("URL"); this.Title = i.GetStringExtra("Title"); WebView webview = new WebView(this); webview.Settings.JavaScriptEnabled = true; SetContentView(webview); webview.LoadUrl(url); } } }
Fix a image naming bug.
using System; using System.IO; using System.Timers; using Shell.Execute; namespace PiDashcam { public class StillCam { Timer timer; int imgcounter; string folder; public StillCam(string imageFolder) { folder = imageFolder; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } foreach (var file in Directory.EnumerateFiles(folder)) { int count = Int32.Parse(file.Remove(file.IndexOf('.')).Substring(file.LastIndexOf('/') + 1)); if (imgcounter <= count) { imgcounter = count + 1; } } timer = new Timer(6000); timer.Elapsed += Timer_Elapsed; timer.Start(); imgcounter = 1; } public void Stop() { timer.Stop(); } void Timer_Elapsed(object sender, ElapsedEventArgs e) { ProgramLauncher.Execute("raspistill", String.Format("-h 1080 -w 1920 -n -o {0}/{1}.jpg", folder, imgcounter.ToString("D8"))); imgcounter++; } } }
using System; using System.IO; using System.Timers; using Shell.Execute; namespace PiDashcam { public class StillCam { Timer timer; int imgcounter; string folder; public StillCam(string imageFolder) { imgcounter = 1; folder = imageFolder; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } foreach (var file in Directory.EnumerateFiles(folder)) { int count = Int32.Parse(file.Remove(file.IndexOf('.')).Substring(file.LastIndexOf('/') + 1)); if (imgcounter <= count) { imgcounter = count + 1; } } timer = new Timer(6000); timer.Elapsed += Timer_Elapsed; timer.Start(); } public void Stop() { timer.Stop(); } void Timer_Elapsed(object sender, ElapsedEventArgs e) { ProgramLauncher.Execute("raspistill", String.Format("-h 1080 -w 1920 -n -o {0}/{1}.jpg", folder, imgcounter.ToString("D8"))); imgcounter++; } } }
Change serialize/deserialize functions to abstract
using LiteNetLib.Utils; namespace LiteNetLibHighLevel { public abstract class LiteNetLibMessageBase { public virtual void Deserialize(NetDataReader reader) { } public virtual void Serialize(NetDataWriter writer) { } } }
using LiteNetLib.Utils; namespace LiteNetLibHighLevel { public abstract class LiteNetLibMessageBase { public abstract void Deserialize(NetDataReader reader); public abstract void Serialize(NetDataWriter writer); } }
Add dbus-sharp-glib to friend assemblies
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("dbus-monitor")] [assembly: InternalsVisibleTo ("dbus-daemon")]
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("dbus-sharp-glib")] [assembly: InternalsVisibleTo ("dbus-monitor")] [assembly: InternalsVisibleTo ("dbus-daemon")]
Add client_iden field to push requests
using System.Runtime.Serialization; namespace PushbulletSharp.Models.Requests { [DataContract] public abstract class PushRequestBase { /// <summary> /// Gets or sets the device iden. /// </summary> /// <value> /// The device iden. /// </value> [DataMember(Name = "device_iden")] public string DeviceIden { get; set; } /// <summary> /// Gets or sets the email. /// </summary> /// <value> /// The email. /// </value> [DataMember(Name = "email")] public string Email { get; set; } /// <summary> /// Gets or sets the type. /// </summary> /// <value> /// The type. /// </value> [DataMember(Name = "type")] public string Type { get; protected set; } /// <summary> /// Gets or sets the source_device_iden. /// </summary> /// <value> /// The source_device_iden. /// </value> [DataMember(Name = "source_device_iden")] public string SourceDeviceIden { get; set; } /// <summary> /// Gets or sets the channel tag /// </summary> /// <value> /// The channel_tag. /// </value> [DataMember(Name = "channel_tag")] public string ChannelTag { get; set; } } }
using System.Runtime.Serialization; namespace PushbulletSharp.Models.Requests { [DataContract] public abstract class PushRequestBase { /// <summary> /// Gets or sets the device iden. /// </summary> /// <value> /// The device iden. /// </value> [DataMember(Name = "device_iden")] public string DeviceIden { get; set; } /// <summary> /// Gets or sets the email. /// </summary> /// <value> /// The email. /// </value> [DataMember(Name = "email")] public string Email { get; set; } /// <summary> /// Gets or sets the type. /// </summary> /// <value> /// The type. /// </value> [DataMember(Name = "type")] public string Type { get; protected set; } /// <summary> /// Gets or sets the source_device_iden. /// </summary> /// <value> /// The source_device_iden. /// </value> [DataMember(Name = "source_device_iden")] public string SourceDeviceIden { get; set; } /// <summary> /// Gets or sets the client_iden /// </summary> /// <value> /// The client_iden. /// </value> [DataMember(Name = "client_iden")] public string ClientIden { get; set; } /// <summary> /// Gets or sets the channel tag /// </summary> /// <value> /// The channel_tag. /// </value> [DataMember(Name = "channel_tag")] public string ChannelTag { get; set; } } }
Fix drawable mania judgement scene looking broken
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Mania.Scoring; using osu.Game.Rulesets.Mania.UI; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Tests.Skinning { public class TestSceneDrawableJudgement : ManiaSkinnableTestScene { public TestSceneDrawableJudgement() { var hitWindows = new ManiaHitWindows(); foreach (HitResult result in Enum.GetValues(typeof(HitResult)).OfType<HitResult>().Skip(1)) { if (hitWindows.IsHitResultAllowed(result)) { AddStep("Show " + result.GetDescription(), () => SetContents(_ => new DrawableManiaJudgement(new JudgementResult(new HitObject { StartTime = Time.Current }, new Judgement()) { Type = result }, null) { Anchor = Anchor.Centre, Origin = Anchor.Centre, })); } } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Mania.Scoring; using osu.Game.Rulesets.Mania.Skinning.Legacy; using osu.Game.Rulesets.Mania.UI; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Tests.Skinning { public class TestSceneDrawableJudgement : ManiaSkinnableTestScene { public TestSceneDrawableJudgement() { var hitWindows = new ManiaHitWindows(); foreach (HitResult result in Enum.GetValues(typeof(HitResult)).OfType<HitResult>().Skip(1)) { if (hitWindows.IsHitResultAllowed(result)) { AddStep("Show " + result.GetDescription(), () => { SetContents(_ => new DrawableManiaJudgement(new JudgementResult(new HitObject { StartTime = Time.Current }, new Judgement()) { Type = result }, null) { Anchor = Anchor.Centre, Origin = Anchor.Centre, }); // for test purposes, undo the Y adjustment related to the `ScorePosition` legacy positioning config value // (see `LegacyManiaJudgementPiece.load()`). // this prevents the judgements showing somewhere below or above the bounding box of the judgement. foreach (var legacyPiece in this.ChildrenOfType<LegacyManiaJudgementPiece>()) legacyPiece.Y = 0; }); } } } } }
Bump version to v1.2.1, breaking change for Data.HashFunction.CRC only.
using System; using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Data.HashFunction Developers")] [assembly: AssemblyCopyright("Copyright 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] [assembly: AssemblyVersion("1.1.1")]
using System; using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Data.HashFunction Developers")] [assembly: AssemblyCopyright("Copyright 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] [assembly: AssemblyVersion("1.2.1")]
Add helper methods to http descriptor. This provides a more fluent interface between setting name and description with actions.
using System; using System.Linq.Expressions; using RimDev.Descriptor.Generic; namespace RimDev.Descriptor { public class HttpDescriptor<TClass> : Descriptor<TClass> where TClass : class, new() { public HttpDescriptor<TClass> Action<TModel>( Expression<Func<TClass, Func<TModel, object>>> method, string description = null, string rel = null, string uri = null, Action<HttpMethodDescriptorContainer<TModel>> model = null) { var methodInfo = ExtractMemberInfoFromExpression<TModel>(method); var methodName = methodInfo.Name; var methodContainer = HydrateMethodDescriptionContainer<HttpMethodDescriptorContainer<TModel>, TModel>( methodName, description, Convert<HttpMethodDescriptorContainer<TModel>>(model)); methodContainer.Rel = methodContainer.Rel ?? rel ?? "n/a"; methodContainer.Uri = methodContainer.Uri ?? uri ?? "n/a"; Methods.Add(methodContainer); return this; } } }
using System; using System.Linq.Expressions; using RimDev.Descriptor.Generic; namespace RimDev.Descriptor { public class HttpDescriptor<TClass> : Descriptor<TClass> where TClass : class, new() { public HttpDescriptor( string name = null, string description = null, string type = null) :base(name, description, type) { } public HttpDescriptor<TClass> Action<TModel>( Expression<Func<TClass, Func<TModel, object>>> method, string description = null, string rel = null, string uri = null, Action<HttpMethodDescriptorContainer<TModel>> model = null) { var methodInfo = ExtractMemberInfoFromExpression<TModel>(method); var methodName = methodInfo.Name; var methodContainer = HydrateMethodDescriptionContainer<HttpMethodDescriptorContainer<TModel>, TModel>( methodName, description, Convert<HttpMethodDescriptorContainer<TModel>>(model)); methodContainer.Rel = methodContainer.Rel ?? rel ?? "n/a"; methodContainer.Uri = methodContainer.Uri ?? uri ?? "n/a"; Methods.Add(methodContainer); return this; } public new HttpDescriptor<TClass> SetDescription(string description) { base.SetDescription(description); return this; } public new HttpDescriptor<TClass> SetName(string name) { base.SetName(name); return this; } public new HttpDescriptor<TClass> SetType(string type) { base.SetType(type); return this; } } }
Fix "Popup" action "Text", "Title" default values
using System.ComponentModel; using System.Windows; namespace DesktopWidgets.Actions { internal class PopupAction : ActionBase { [DisplayName("Text")] public string Text { get; set; } [DisplayName("Title")] public string Title { get; set; } [DisplayName("Image")] public MessageBoxImage Image { get; set; } public override void ExecuteAction() { base.ExecuteAction(); MessageBox.Show(Text, Title, MessageBoxButton.OK, Image); } } }
using System.ComponentModel; using System.Windows; namespace DesktopWidgets.Actions { internal class PopupAction : ActionBase { [DisplayName("Text")] public string Text { get; set; } = ""; [DisplayName("Title")] public string Title { get; set; } = ""; [DisplayName("Image")] public MessageBoxImage Image { get; set; } public override void ExecuteAction() { base.ExecuteAction(); MessageBox.Show(Text, Title, MessageBoxButton.OK, Image); } } }
Improve error if github can't be reached.
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Security.Cryptography; using GistClient.FileSystem; using RestSharp; using RestSharp.Deserializers; namespace GistClient.Client { public static class GistClient { private static readonly RestClient Client; static GistClient(){ Client = new RestClient("https://api.github.com"); } public static Dictionary<String,String> SendRequest(RestRequest request){ var response = Client.Execute(request); HandleResponse(response); var jsonResponse = TrySerializeResponse(response); return jsonResponse; } public static void SetAuthentication(String username, String password){ Client.Authenticator = new HttpBasicAuthenticator(username,password.Decrypt()); } public static void HandleResponse(IRestResponse response){ var statusHeader = response.Headers.FirstOrDefault(x => x.Name == "Status"); var statusValue = statusHeader.Value.ToString(); if (!statusValue.Contains("201")){ String message = TrySerializeResponse(response)["message"]; throw new Exception(statusValue + ", "+message); } } private static Dictionary<string, string> TrySerializeResponse(IRestResponse response) { var deserializer = new JsonDeserializer(); var jsonResponse = deserializer.Deserialize<Dictionary<String, String>>(response); return jsonResponse; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Security.Cryptography; using GistClient.FileSystem; using RestSharp; using RestSharp.Deserializers; namespace GistClient.Client { public static class GistClient { private static readonly RestClient Client; static GistClient(){ Client = new RestClient("https://api.github.com"); } public static Dictionary<String,String> SendRequest(RestRequest request){ var response = Client.Execute(request); HandleResponse(response); var jsonResponse = TrySerializeResponse(response); return jsonResponse; } public static void SetAuthentication(String username, String password){ Client.Authenticator = new HttpBasicAuthenticator(username,password.Decrypt()); } public static void HandleResponse(IRestResponse response){ var statusHeader = response.Headers.FirstOrDefault(x => x.Name == "Status"); if (statusHeader != null){ var statusValue = statusHeader.Value.ToString(); if (!statusValue.Contains("201")){ String message = TrySerializeResponse(response)["message"]; throw new Exception(statusValue + ", " + message); } } else{ throw new Exception("Github could not be reached. Verify your connection."); } } private static Dictionary<string, string> TrySerializeResponse(IRestResponse response) { var deserializer = new JsonDeserializer(); var jsonResponse = deserializer.Deserialize<Dictionary<String, String>>(response); return jsonResponse; } } }
Support high DPI (96DPI, 120DPI tested)
/* * 由SharpDevelop创建。 * 用户: imknown * 日期: 2015/12/3 周四 * 时间: 上午 11:22 * * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件 */ using System; using System.Windows.Forms; namespace KeyFingerprintLooker { /// <summary> /// Class with program entry point. /// </summary> internal sealed class Program { /// <summary> /// Program entry point. /// </summary> [STAThread] private static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
/* * 由SharpDevelop创建。 * 用户: imknown * 日期: 2015/12/3 周四 * 时间: 上午 11:22 * * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件 */ using System; using System.Windows.Forms; namespace KeyFingerprintLooker { /// <summary> /// Class with program entry point. /// </summary> internal sealed class Program { /// <summary> /// Program entry point. /// </summary> [STAThread] private static void Main(string[] args) { if (Environment.OSVersion.Version.Major >= 6) { SetProcessDPIAware(); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool SetProcessDPIAware(); } }
Fix stylecop issues in debugging project
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeGeneration.Debugging { class Program { static void Main(string[] args) { // This app is a dummy. But when it is debugged within VS, it builds the Tests // allowing VS to debug into the build/code generation process. } } }
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace CodeGeneration.Debugging { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; internal class Program { private static void Main(string[] args) { // This app is a dummy. But when it is debugged within VS, it builds the Tests // allowing VS to debug into the build/code generation process. } } }
Test even and odd tab settings.
using ColorProvider; using Common; namespace BoxBuilder { public sealed class BoxBuilderFactory { internal static IBoxPointGenerator GetBoxPointGenerator(ILogger Logger) { IPiecePointGenerator piecePointGen = new PiecePointGenerator(); IBoxPointGenerator pointGen = new BoxPointGenerator(piecePointGen, Logger); return pointGen; } public static IBoxBuilderSVG GetBoxHandler(ILogger Logger) { IColorProvider colorProvider = new ColorProviderAllDifferent(); IBoxPointRendererSVG pointRender = new BoxPointRendererSVG(colorProvider); IBoxPointGenerator pointGen = GetBoxPointGenerator(Logger); IBoxBuilderSVG handler = new BoxBuilderSVG(pointGen, pointRender, Logger); return handler; } } }
using ColorProvider; using Common; namespace BoxBuilder { public sealed class BoxBuilderFactory { internal static IBoxPointGenerator GetBoxPointGenerator(ILogger Logger) { IPiecePointGenerator piecePointGen = new PiecePointGenerator(); IBoxPointGenerator pointGen = new BoxPointGenerator(piecePointGen, Logger); return pointGen; } public static IBoxBuilderSVG GetBoxHandler(ILogger Logger) { IColorProvider colorProvider = new ColorProviderAllDifferent(); IBoxPointRendererSVG pointRender = new BoxPointRendererSVG(colorProvider, true); IBoxPointGenerator pointGen = GetBoxPointGenerator(Logger); IBoxBuilderSVG handler = new BoxBuilderSVG(pointGen, pointRender, Logger); return handler; } } }
Add "now im in the cloud"
 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> Hello people! </div> </body> </html>
 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> Hello people!<br /> Now I'm in the CLOUDDDD </div> </body> </html>
Add links to photo details and question details views.
@model QuestionIndexViewModel @{ ViewBag.Title = "Question Index"; } <h2>Question Index</h2> @if (Model.Questions.SafeAny()) { <table class="index"> <thead> <tr> <th>ID</th> <th>Photo ID</th> <th>Question</th> <th>Sentence Starters</th> <th></th> </tr> </thead> <tbody> @foreach (var question in Model.Questions) { <tr> <td>@question.ID</td> <td>@question.PhotoID</td> <td>@question.Text</td> <td>@question.SentenceStarters</td> <td> @if (Model.DisplayAdminLinks) { <span> @Html.ActionLink("Details", MVC.Questions.QuestionDetails(question.ID)) | @Html.ActionLink("Edit", MVC.Questions.QuestionEdit(question.ID)) | @Html.ActionLink("Delete", MVC.Questions.QuestionDelete(question.ID)) </span> } </td> </tr> } </tbody> </table> } else { @:No questions found. }
@model QuestionIndexViewModel @{ ViewBag.Title = "Question Index"; } <h2>Question Index</h2> @if (Model.Questions.SafeAny()) { <table class="index"> <thead> <tr> <th>ID</th> <th>Photo ID</th> <th>Question</th> <th>Sentence Starters</th> <th></th> </tr> </thead> <tbody> @foreach (var question in Model.Questions) { <tr> <td>@question.ID</td> <td>@Html.ActionLink(question.PhotoID.ToString(), MVC.Photos.PhotoDetails(question.PhotoID))</td> <td>@Html.ActionLink(question.Text, MVC.Questions.QuestionDetails(question.ID))</td> <td>@question.SentenceStarters</td> <td> @if (Model.DisplayAdminLinks) { <span> @Html.ActionLink("Details", MVC.Questions.QuestionDetails(question.ID)) | @Html.ActionLink("Edit", MVC.Questions.QuestionEdit(question.ID)) | @Html.ActionLink("Delete", MVC.Questions.QuestionDelete(question.ID)) </span> } </td> </tr> } </tbody> </table> } else { @:No questions found. }
Comment is no longer reqired
using System.Data; namespace NHibernate.Engine.Transaction { /// <summary> /// Represents work that needs to be performed in a manner /// which isolates it from any current application unit of /// work transaction. /// </summary> public interface IIsolatedWork { /// <summary> /// Perform the actual work to be done. /// </summary> /// <param name="connection">The ADP connection to use.</param> void DoWork(IDbConnection connection, IDbTransaction transaction); // 2009-05-04 Another time we need a TransactionManager to manage isolated // work for a given connection. } }
using System.Data; namespace NHibernate.Engine.Transaction { /// <summary> /// Represents work that needs to be performed in a manner /// which isolates it from any current application unit of /// work transaction. /// </summary> public interface IIsolatedWork { /// <summary> /// Perform the actual work to be done. /// </summary> /// <param name="connection">The ADP connection to use.</param> void DoWork(IDbConnection connection, IDbTransaction transaction); } }
Add CFNetwork to list of Xamarin iOS dependencies, should fix Xamarin/iOS linking issues
using System.Reflection; using System.Runtime.CompilerServices; using ObjCRuntime; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("CartoMobileSDK.iOS")] [assembly: AssemblyDescription ("Carto Mobile SDK for iOS")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("CartoDB")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("(c) CartoDB 2016, All rights reserved")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] [assembly: LinkWith("libcarto_mobile_sdk.a", LinkTarget.ArmV7|LinkTarget.ArmV7s|LinkTarget.Arm64|LinkTarget.Simulator|LinkTarget.Simulator64, ForceLoad=true, IsCxx=true, Frameworks="OpenGLES GLKit UIKit CoreGraphics CoreText Foundation")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; using System.Runtime.CompilerServices; using ObjCRuntime; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("CartoMobileSDK.iOS")] [assembly: AssemblyDescription ("Carto Mobile SDK for iOS")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("CartoDB")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("(c) CartoDB 2016, All rights reserved")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] [assembly: LinkWith("libcarto_mobile_sdk.a", LinkTarget.ArmV7|LinkTarget.ArmV7s|LinkTarget.Arm64|LinkTarget.Simulator|LinkTarget.Simulator64, ForceLoad=true, IsCxx=true, Frameworks="OpenGLES GLKit UIKit CoreGraphics CoreText CFNetwork Foundation")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
Create arango exception which consists only of message.
using System; using System.Net; namespace Arango.Client { public class ArangoException : Exception { /// <summary> /// HTTP status code which caused the exception. /// </summary> public HttpStatusCode HttpStatusCode { get; set; } /// <summary> /// Exception message of the web request object. /// </summary> public string WebExceptionMessage { get; set; } public ArangoException() { } public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage) : base(message) { HttpStatusCode = httpStatusCode; WebExceptionMessage = webExceptionMessage; } public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage, Exception inner) : base(message, inner) { HttpStatusCode = httpStatusCode; WebExceptionMessage = webExceptionMessage; } } }
using System; using System.Net; namespace Arango.Client { public class ArangoException : Exception { /// <summary> /// HTTP status code which caused the exception. /// </summary> public HttpStatusCode HttpStatusCode { get; set; } /// <summary> /// Exception message of the web request object. /// </summary> public string WebExceptionMessage { get; set; } public ArangoException() { } public ArangoException(string message) : base(message) { } public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage) : base(message) { HttpStatusCode = httpStatusCode; WebExceptionMessage = webExceptionMessage; } public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage, Exception inner) : base(message, inner) { HttpStatusCode = httpStatusCode; WebExceptionMessage = webExceptionMessage; } } }
Add correct defaults to domain subscriber
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Aggregates.Contracts; using Aggregates.Extensions; using EventStore.ClientAPI; using Newtonsoft.Json; using NServiceBus; using NServiceBus.Features; using NServiceBus.Logging; using NServiceBus.MessageInterfaces; using NServiceBus.ObjectBuilder; using NServiceBus.Settings; using Aggregates.Internal; namespace Aggregates.GetEventStore { public class Feature : NServiceBus.Features.Feature { public Feature() { RegisterStartupTask<ConsumerRunner>(); Defaults(s => { s.SetDefault("SetEventStoreMaxDegreeOfParallelism", Environment.ProcessorCount); s.SetDefault("SetEventStoreCapacity", 10000); }); } protected override void Setup(FeatureConfigurationContext context) { context.Container.ConfigureComponent<StoreEvents>(DependencyLifecycle.InstancePerCall); context.Container.ConfigureComponent<StoreSnapshots>(DependencyLifecycle.InstancePerCall); context.Container.ConfigureComponent<NServiceBusDispatcher>(DependencyLifecycle.SingleInstance); context.Container.ConfigureComponent<DomainSubscriber>(DependencyLifecycle.SingleInstance); context.Container.ConfigureComponent(y => { return new JsonSerializerSettings { Binder = new EventSerializationBinder(y.Build<IMessageMapper>()), ContractResolver = new EventContractResolver(y.Build<IMessageMapper>(), y.Build<IMessageCreator>()) }; }, DependencyLifecycle.SingleInstance); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Aggregates.Contracts; using Aggregates.Extensions; using EventStore.ClientAPI; using Newtonsoft.Json; using NServiceBus; using NServiceBus.Features; using NServiceBus.Logging; using NServiceBus.MessageInterfaces; using NServiceBus.ObjectBuilder; using NServiceBus.Settings; using Aggregates.Internal; namespace Aggregates.GetEventStore { public class Feature : NServiceBus.Features.Feature { public Feature() { RegisterStartupTask<ConsumerRunner>(); Defaults(s => { s.SetDefault("SetEventStoreMaxDegreeOfParallelism", Environment.ProcessorCount); s.SetDefault("ParallelHandlers", true); s.SetDefault("ReadSize", 500); }); } protected override void Setup(FeatureConfigurationContext context) { context.Container.ConfigureComponent<StoreEvents>(DependencyLifecycle.InstancePerCall); context.Container.ConfigureComponent<StoreSnapshots>(DependencyLifecycle.InstancePerCall); context.Container.ConfigureComponent<NServiceBusDispatcher>(DependencyLifecycle.SingleInstance); context.Container.ConfigureComponent<DomainSubscriber>(DependencyLifecycle.SingleInstance); context.Container.ConfigureComponent(y => { return new JsonSerializerSettings { Binder = new EventSerializationBinder(y.Build<IMessageMapper>()), ContractResolver = new EventContractResolver(y.Build<IMessageMapper>(), y.Build<IMessageCreator>()) }; }, DependencyLifecycle.SingleInstance); } } }
Remove property from ProductTestObjetBuilder that is left over from move of building with constructor feature to TestObjectBuilder class.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TestObjectBuilder; namespace TestObjectBuilderTests { public class ProductTestObjectBuilder : TestObjBuilder<Product> { public ProductTestObjectBuilder() { this.FirstDependency = new DummyDependency1(); this.SecondDependency = new DummyDependency2(); this.ConstructorArgumentPropertyNames = new List<string>() { "FirstDependency" }; } public List<string> ConstructorArgumentPropertyNames { get; set; } public IDependency1 FirstDependency { get; set; } public IDependency2 SecondDependency { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TestObjectBuilder; namespace TestObjectBuilderTests { public class ProductTestObjectBuilder : TestObjBuilder<Product> { public ProductTestObjectBuilder() { this.FirstDependency = new DummyDependency1(); this.SecondDependency = new DummyDependency2(); this.PropertiesUsedByProductConstructor = new List<string>() { "FirstDependency" }; } public IDependency1 FirstDependency { get; set; } public IDependency2 SecondDependency { get; set; } } }
Fix system web detection logic.
using System; using System.Collections.Generic; using Owin; namespace JabbR.Infrastructure { public static class AppBuilderExtensions { private static readonly string SystemWebHostName = "System.Web 4.5, Microsoft.Owin.Host.SystemWeb 1.0.0.0"; public static bool IsRunningUnderSystemWeb(this IAppBuilder app) { var capabilities = (IDictionary<string, object>)app.Properties["server.Capabilities"]; // Not hosing on system web host? Bail out. object serverName; if (capabilities.TryGetValue("server.Name", out serverName) && !SystemWebHostName.Equals((string)serverName, StringComparison.Ordinal)) { return false; } return true; } } }
using System; using System.Collections.Generic; using Owin; namespace JabbR.Infrastructure { public static class AppBuilderExtensions { private static readonly string SystemWebHostName = "System.Web 4.5, Microsoft.Owin.Host.SystemWeb 1.0.0.0"; public static bool IsRunningUnderSystemWeb(this IAppBuilder app) { var capabilities = (IDictionary<string, object>)app.Properties["server.Capabilities"]; // Not hosing on system web host? Bail out. object serverName; if (capabilities.TryGetValue("server.Name", out serverName) && SystemWebHostName.Equals((string)serverName, StringComparison.Ordinal)) { return true; } return false; } } }
Make sure we test across more than two lines.
using System; using System.IO; using NUnit.Framework; namespace Mango.Server.Tests { [TestFixture()] public class HttpHeadersTest { [Test()] public void TestMultilineParse () { // // multiline values are acceptable if the next // line starts with spaces // string header = @"HeaderName: Some multiline value"; HttpHeaders headers = new HttpHeaders (); headers.Parse (new StringReader (header)); Assert.AreEqual ("some multiline value", headers ["HeaderName"], "a1"); } } }
using System; using System.IO; using NUnit.Framework; namespace Mango.Server.Tests { [TestFixture()] public class HttpHeadersTest { [Test()] public void TestMultilineParse () { // // multiline values are acceptable if the next // line starts with spaces // string header = @"HeaderName: Some multiline value"; HttpHeaders headers = new HttpHeaders (); headers.Parse (new StringReader (header)); Assert.AreEqual ("some multiline value", headers ["HeaderName"], "a1"); header = @"HeaderName: Some multiline value that spans a bunch of lines"; headers = new HttpHeaders (); headers.Parse (new StringReader (header)); Assert.AreEqual ("Some multiline value that spans a bunch of lines", headers ["HeaderName"], "a2"); } } }
Change URL of initialization in integration tests
namespace CypherTwo.Tests { using System; using System.Net.Http; using CypherTwo.Core; using NUnit.Framework; [TestFixture] public class IntegrationTests { private INeoClient neoClient; private ISendRestCommandsToNeo neoApi; private IJsonHttpClientWrapper httpClientWrapper; [SetUp] public void SetupBeforeEachTest() { this.httpClientWrapper = new JsonHttpClientWrapper(new HttpClient()); this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:7474/"); this.neoClient = new NeoClient(this.neoApi); this.neoClient.Initialise(); } [Test] public void InitialiseThrowsExecptionWithInvalidUrl() { this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:1111/"); this.neoClient = new NeoClient(this.neoApi); Assert.Throws<InvalidOperationException>(() => this.neoClient.Initialise()); } [Test] public async void CreateAndSelectNode() { var reader = await this.neoClient.QueryAsync("CREATE (n:Person { name : 'Andres', title : 'Developer' }) RETURN Id(n)"); Assert.That(reader.Read(), Is.EqualTo(true)); Assert.That(reader.Get<int>(0), Is.EqualTo(1)); } } }
namespace CypherTwo.Tests { using System; using System.Net.Http; using CypherTwo.Core; using NUnit.Framework; [TestFixture] public class IntegrationTests { private INeoClient neoClient; private ISendRestCommandsToNeo neoApi; private IJsonHttpClientWrapper httpClientWrapper; [SetUp] public void SetupBeforeEachTest() { this.httpClientWrapper = new JsonHttpClientWrapper(new HttpClient()); this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:7474/db/data"); this.neoClient = new NeoClient(this.neoApi); this.neoClient.Initialise(); } [Test] public void InitialiseThrowsExecptionWithInvalidUrl() { this.neoApi = new NeoRestApiClient(this.httpClientWrapper, "http://localhost:1111/"); this.neoClient = new NeoClient(this.neoApi); Assert.Throws<InvalidOperationException>(() => this.neoClient.Initialise()); } [Test] public async void CreateAndSelectNode() { var reader = await this.neoClient.QueryAsync("CREATE (n:Person { name : 'Andres', title : 'Developer' }) RETURN Id(n)"); Assert.That(reader.Read(), Is.EqualTo(true)); Assert.That(reader.Get<int>(0), Is.EqualTo(1)); } } }
Fix Object reference not set to an instance of an object.
using System.Threading.Tasks; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; namespace Template10.Samples.SearchSample { sealed partial class App : Template10.Common.BootStrapper { public App() { InitializeComponent(); } public override Task OnInitializeAsync(IActivatedEventArgs args) { var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include, null); Window.Current.Content = new Views.Shell(nav); return Task.CompletedTask; } public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); return Task.CompletedTask; } } }
using System.Threading.Tasks; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; namespace Template10.Samples.SearchSample { sealed partial class App : Template10.Common.BootStrapper { public App() { InitializeComponent(); } public override Task OnInitializeAsync(IActivatedEventArgs args) { var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include); Window.Current.Content = new Views.Shell(nav); return Task.CompletedTask; } public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); return Task.CompletedTask; } } }
Switch over agent to using Agent bus
using Glimpse.Web; using System; namespace Glimpse.Agent.Web { public class AgentRuntime : IRequestRuntime { private readonly IMessagePublisher _messagePublisher; public AgentRuntime(IMessagePublisher messagePublisher) { _messagePublisher = messagePublisher; } public void Begin(IContext newContext) { var message = new BeginRequestMessage(); // TODO: Full out message more _messagePublisher.PublishMessage(message); } public void End(IContext newContext) { var message = new EndRequestMessage(); // TODO: Full out message more _messagePublisher.PublishMessage(message); } } }
using Glimpse.Web; using System; namespace Glimpse.Agent.Web { public class AgentRuntime : IRequestRuntime { private readonly IMessageAgentBus _messageBus; public AgentRuntime(IMessageAgentBus messageBus) { _messageBus = messageBus; } public void Begin(IContext newContext) { var message = new BeginRequestMessage(); // TODO: Full out message more _messageBus.SendMessage(message); } public void End(IContext newContext) { var message = new EndRequestMessage(); // TODO: Full out message more _messageBus.SendMessage(message); } } }
Use positive statement and let it return as soon as possible
using System; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; using Wangkanai.Detection.Models; using Wangkanai.Detection.Services; namespace Microsoft.AspNetCore.Mvc.TagHelpers { [HtmlTargetElement(ElementName, Attributes = OnlyAttributeName, TagStructure = TagStructure.NormalOrSelfClosing)] public class PreferenceTagHelper : TagHelper { private const string ElementName = "preference"; private const string OnlyAttributeName = "only"; protected IHtmlGenerator Generator { get; } private readonly IResponsiveService _responsive; private readonly IDeviceService _device; [HtmlAttributeName(OnlyAttributeName)] public string? Only { get; set; } public PreferenceTagHelper(IHtmlGenerator generator, IResponsiveService responsive, IDeviceService device) { Generator = generator ?? throw new ArgumentNullException(nameof(generator)); _responsive = responsive ?? throw new ArgumentNullException(nameof(responsive)); _device = device ?? throw new ArgumentNullException(nameof(device)); } public override void Process(TagHelperContext context, TagHelperOutput output) { if (context == null) throw new ArgumentNullException(nameof(context)); if (output == null) throw new ArgumentNullException(nameof(output)); output.TagName = null; if (string.IsNullOrWhiteSpace(Only)) return; if (!_responsive.HasPreferred() && !DisplayOnlyDevice) output.SuppressOutput(); } private bool DisplayOnlyDevice => _device.Type == OnlyDevice; private Device OnlyDevice => Enum.Parse<Device>(Only, true); } }
using System; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; using Wangkanai.Detection.Models; using Wangkanai.Detection.Services; namespace Microsoft.AspNetCore.Mvc.TagHelpers { [HtmlTargetElement(ElementName, Attributes = OnlyAttributeName, TagStructure = TagStructure.NormalOrSelfClosing)] public class PreferenceTagHelper : TagHelper { private const string ElementName = "preference"; private const string OnlyAttributeName = "only"; protected IHtmlGenerator Generator { get; } private readonly IResponsiveService _responsive; private readonly IDeviceService _device; [HtmlAttributeName(OnlyAttributeName)] public string? Only { get; set; } public PreferenceTagHelper(IHtmlGenerator generator, IResponsiveService responsive, IDeviceService device) { Generator = generator ?? throw new ArgumentNullException(nameof(generator)); _responsive = responsive ?? throw new ArgumentNullException(nameof(responsive)); _device = device ?? throw new ArgumentNullException(nameof(device)); } public override void Process(TagHelperContext context, TagHelperOutput output) { if (context == null) throw new ArgumentNullException(nameof(context)); if (output == null) throw new ArgumentNullException(nameof(output)); output.TagName = null; if (string.IsNullOrWhiteSpace(Only)) return; if (_responsive.HasPreferred()) return; if (DisplayOnlyDevice) return; output.SuppressOutput(); } private bool DisplayOnlyDevice => _device.Type == OnlyDevice; private Device OnlyDevice => Enum.Parse<Device>(Only, true); } }
Put auto focus on search too
@{ ViewBag.Title = "Search"; } <div class="col"> <form asp-controller="Lab" asp-action="Search"> <div> <div class="form-group"> <label class="control-label">Search By Id, Request Num, or Share Identifier</label> <div> <input id="term" class="form-control" name="term" /> </div> </div> <button type="submit" class="btn btn-danger"><i class="fa fa-search" aria-hidden="true"></i> Search</button> </div> </form> </div>
@{ ViewBag.Title = "Search"; } <div class="col"> <form asp-controller="Lab" asp-action="Search"> <div> <div class="form-group"> <label class="control-label">Search By Id, Request Num, or Share Identifier</label> <div> <input id="term" class="form-control" name="term" autofocus /> </div> </div> <button type="submit" class="btn btn-danger"><i class="fa fa-search" aria-hidden="true"></i> Search</button> </div> </form> </div>
Add unit test for reading a project definition.
using System; using Xunit; using SolutionEdit; namespace SolutionParserTest { public class ProjectTest { [Fact] public void CreateNewDirectoryProject() { // Arrange. var directoryName = "Test"; // Act. var directoryProject = Project.NewDirectoryProject(directoryName); // Assert. Assert.Equal(directoryName, directoryProject.Name); Assert.Equal(directoryName, directoryProject.Location); Assert.Equal(ProjectType.Directory, directoryProject.Type); } } }
using System; using Xunit; using SolutionEdit; using System.IO; namespace SolutionParserTest { public class ProjectTest { [Fact] public void CreateNewDirectoryProject() { // Arrange. var directoryName = "Test"; // Act. var directoryProject = Project.NewDirectoryProject(directoryName); // Assert. Assert.Equal(directoryName, directoryProject.Name); Assert.Equal(directoryName, directoryProject.Location); Assert.Equal(ProjectType.Directory, directoryProject.Type); } [Fact] public void ReadProjectFromStream() { // Project is of the form: //Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SolutionParser", "SolutionParser\SolutionParser.csproj", "{AE17D442-B29B-4F55-9801-7151BCD0D9CA}" //EndProject // Arrange. var guid = new Guid("1DC4FA2D-16D1-459D-9C35-D49208F753C5"); var projectName = "TestProject"; var projectLocation = @"This\is\a\test\TestProject.csproj"; var projectDefinition = $"Project(\"{{9A19103F-16F7-4668-BE54-9A1E7A4F7556}}\") = \"{projectName}\", \"{projectLocation}\", \"{guid.ToString("B").ToUpper()}\"\nEndProject"; using (TextReader inStream = new StringReader(projectDefinition)) { // Act. var project = new Project(inStream); // Assert. Assert.Equal(projectName, project.Name); Assert.Equal(projectLocation, project.Location); Assert.Equal(ProjectType.Project, project.Type); } } } }
Update product name in Assembly
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("TinCan")] [assembly: AssemblyDescription("Library for implementing Tin Can API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rustici Software")] [assembly: AssemblyProduct("TinCan")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6b7c12d3-32ea-4cb2-9399-3004963d2340")] // 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("0.0.1.0")] [assembly: AssemblyFileVersion("0.0.1.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("TinCan")] [assembly: AssemblyDescription("Library for implementing Tin Can API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rustici Software")] [assembly: AssemblyProduct("TinCan.NET")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6b7c12d3-32ea-4cb2-9399-3004963d2340")] // 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("0.0.1.0")] [assembly: AssemblyFileVersion("0.0.1.0")]
Change the feature define to be more uniform.
using Flood.RPC.Server; using Flood.RPC.Transport; namespace Flood.Server { public abstract class Server { public IDatabaseManager Database { get; set; } public TSimpleServer RPCServer { get; set; } public TServerSocket Socket { get; set; } protected Server() { #if RAVENDBSET Database = new RavenDatabaseManager(); #else Database = new NullDatabaseManager(); #endif } public void Shutdown() { } public void Update() { } } }
using Flood.RPC.Server; using Flood.RPC.Transport; namespace Flood.Server { public abstract class Server { public IDatabaseManager Database { get; set; } public TSimpleServer RPCServer { get; set; } public TServerSocket Socket { get; set; } protected Server() { #if USE_RAVENDB Database = new RavenDatabaseManager(); #else Database = new NullDatabaseManager(); #endif } public void Shutdown() { } public void Update() { } } }
Add test URL to libvideo.debug
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using YoutubeExtractor; namespace VideoLibrary.Debug { class Program { static void Main(string[] args) { string[] queries = { // test queries, borrowed from // github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/youtube.py // "http://www.youtube.com/watch?v=6kLq3WMV1nU", // "http://www.youtube.com/watch?v=6kLq3WMV1nU", "https://www.youtube.com/watch?v=IB3lcPjvWLA", "https://www.youtube.com/watch?v=BgpXMA_M98o" }; using (var cli = Client.For(YouTube.Default)) { for (int i = 0; i < queries.Length; i++) { string query = queries[i]; var video = cli.GetVideo(query); string uri = video.Uri; string otherUri = DownloadUrlResolver .GetDownloadUrls(query).First() .DownloadUrl; } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using YoutubeExtractor; namespace VideoLibrary.Debug { class Program { static void Main(string[] args) { string[] queries = { // test queries, borrowed from // github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/youtube.py // "http://www.youtube.com/watch?v=6kLq3WMV1nU", // "http://www.youtube.com/watch?v=6kLq3WMV1nU", "https://www.youtube.com/watch?v=IB3lcPjvWLA", "https://www.youtube.com/watch?v=BgpXMA_M98o", "https://www.youtube.com/watch?v=nfWlot6h_JM" }; using (var cli = Client.For(YouTube.Default)) { for (int i = 0; i < queries.Length; i++) { string query = queries[i]; var video = cli.GetVideo(query); string uri = video.Uri; string otherUri = DownloadUrlResolver .GetDownloadUrls(query).First() .DownloadUrl; } } } } }
Add test ensuring that user id is copied from request if present
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Security.Principal; using System.ServiceModel; namespace Microsoft.ApplicationInsights.Wcf.Tests { [TestClass] public class UserTelemetryInitializerTests { [TestMethod] public void AnonymousDoesNotIncludeUserId() { var context = new MockOperationContext(); context.EndpointUri = new Uri("http://localhost/Service1.svc"); context.OperationName = "GetData"; var authContext = new SimpleAuthorizationContext(); context.SecurityContext = new ServiceSecurityContext(authContext); var initializer = new UserTelemetryInitializer(); var telemetry = new RequestTelemetry(); initializer.Initialize(telemetry, context); Assert.IsNull(telemetry.Context.User.Id); } [TestMethod] public void AuthenticatedRequestFillsUserIdWithUserName() { var context = new MockOperationContext(); context.EndpointUri = new Uri("http://localhost/Service1.svc"); context.OperationName = "GetData"; var authContext = new SimpleAuthorizationContext(); authContext.AddIdentity(new GenericIdentity("myuser")); context.SecurityContext = new ServiceSecurityContext(authContext); var initializer = new UserTelemetryInitializer(); var telemetry = new RequestTelemetry(); initializer.Initialize(telemetry, context); Assert.AreEqual("myuser", telemetry.Context.User.Id); } } }
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Security.Principal; using System.ServiceModel; namespace Microsoft.ApplicationInsights.Wcf.Tests { [TestClass] public class UserTelemetryInitializerTests { [TestMethod] public void AnonymousDoesNotIncludeUserId() { var context = new MockOperationContext(); context.EndpointUri = new Uri("http://localhost/Service1.svc"); context.OperationName = "GetData"; var authContext = new SimpleAuthorizationContext(); context.SecurityContext = new ServiceSecurityContext(authContext); var initializer = new UserTelemetryInitializer(); var telemetry = new RequestTelemetry(); initializer.Initialize(telemetry, context); Assert.IsNull(telemetry.Context.User.Id); } [TestMethod] public void AuthenticatedRequestFillsUserIdWithUserName() { var context = new MockOperationContext(); context.EndpointUri = new Uri("http://localhost/Service1.svc"); context.OperationName = "GetData"; var authContext = new SimpleAuthorizationContext(); authContext.AddIdentity(new GenericIdentity("myuser")); context.SecurityContext = new ServiceSecurityContext(authContext); var initializer = new UserTelemetryInitializer(); var telemetry = new RequestTelemetry(); initializer.Initialize(telemetry, context); Assert.AreEqual("myuser", telemetry.Context.User.Id); } [TestMethod] public void UserIdCopiedFromRequestIfPresent() { const String userName = "MyUserName"; var context = new MockOperationContext(); context.EndpointUri = new Uri("http://localhost/Service1.svc"); context.OperationName = "GetData"; context.Request.Context.User.Id = userName; var initializer = new UserTelemetryInitializer(); var telemetry = new EventTelemetry(); initializer.Initialize(telemetry, context); Assert.AreEqual(userName, telemetry.Context.User.Id); } } }
Increase default count to 500
using Azure.Test.PerfStress; using CommandLine; namespace Azure.Storage.Blobs.PerfStress.Core { public class CountOptions : PerfStressOptions { [Option('c', "count", Default = 100, HelpText = "Number of blobs")] public int Count { get; set; } } }
using Azure.Test.PerfStress; using CommandLine; namespace Azure.Storage.Blobs.PerfStress.Core { public class CountOptions : PerfStressOptions { [Option('c', "count", Default = 500, HelpText = "Number of blobs")] public int Count { get; set; } } }
Use proper case for text showing the current VM operation
namespace AzureBot.Forms { using System; using System.Collections.Generic; using System.Linq; using Azure.Management.Models; [Serializable] public class VirtualMachineFormState { public VirtualMachineFormState(IEnumerable<VirtualMachine> availableVMs, Operations operation) { this.AvailableVMs = availableVMs; this.Operation = operation; } public string VirtualMachine { get; set; } public IEnumerable<VirtualMachine> AvailableVMs { get; private set; } public Operations Operation { get; private set; } public VirtualMachine SelectedVM { get { return this.AvailableVMs.Where(p => p.Name == this.VirtualMachine).SingleOrDefault(); } } } }
namespace AzureBot.Forms { using System; using System.Collections.Generic; using System.Linq; using Azure.Management.Models; [Serializable] public class VirtualMachineFormState { public VirtualMachineFormState(IEnumerable<VirtualMachine> availableVMs, Operations operation) { this.AvailableVMs = availableVMs; this.Operation = operation.ToString().ToLower(); } public string VirtualMachine { get; set; } public IEnumerable<VirtualMachine> AvailableVMs { get; private set; } public string Operation { get; private set; } public VirtualMachine SelectedVM { get { return this.AvailableVMs.Where(p => p.Name == this.VirtualMachine).SingleOrDefault(); } } } }
Fix overkill and use `switch` statement
// 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.Platform; using osu.Framework.Platform.Linux; using osu.Framework.Platform.MacOS; using osu.Framework.Platform.Windows; using System; namespace osu.Framework { public static class Host { [Obsolete("Use GetSuitableHost(HostConfig) instead.")] public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.macOS: return new MacOSGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Windows: return new WindowsGameHost(gameName, bindIPC, portableInstallation); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)})."); } } public static DesktopGameHost GetSuitableHost(HostConfig hostConfig) { return RuntimeInfo.OS switch { RuntimeInfo.Platform.Windows => new WindowsGameHost(hostConfig), RuntimeInfo.Platform.Linux => new LinuxGameHost(hostConfig), RuntimeInfo.Platform.macOS => new MacOSGameHost(hostConfig), _ => throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)})."), }; } } }
// 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.Platform; using osu.Framework.Platform.Linux; using osu.Framework.Platform.MacOS; using osu.Framework.Platform.Windows; using System; namespace osu.Framework { public static class Host { [Obsolete("Use GetSuitableHost(HostConfig) instead.")] public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.macOS: return new MacOSGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(gameName, bindIPC, portableInstallation); case RuntimeInfo.Platform.Windows: return new WindowsGameHost(gameName, bindIPC, portableInstallation); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({RuntimeInfo.OS})."); } } public static DesktopGameHost GetSuitableHost(HostConfig hostConfig) { switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.Windows: return new WindowsGameHost(hostConfig); case RuntimeInfo.Platform.Linux: return new LinuxGameHost(hostConfig); case RuntimeInfo.Platform.macOS: return new MacOSGameHost(hostConfig); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({RuntimeInfo.OS})."); }; } } }
Fix bug which was making the app crash when clicking outside of the spoiler form
using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Navigation; using Abc.NCrafts.App.ViewModels; namespace Abc.NCrafts.App.Views { /// <summary> /// Interaction logic for GameView.xaml /// </summary> public partial class Performance2018GameView : UserControl { public Performance2018GameView() { InitializeComponent(); } private void OnLoaded(object sender, RoutedEventArgs e) { Focusable = true; Keyboard.Focus(this); } private void OnWebBrowserLoaded(object sender, NavigationEventArgs e) { var script = "document.body.style.overflow ='hidden'"; var wb = (WebBrowser)sender; wb.InvokeScript("execScript", script, "JavaScript"); } private void HtmlHelpClick(object sender, MouseButtonEventArgs e) { var pagePage = (PerformanceGamePage)DataContext; pagePage.IsHelpVisible = false; } private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if (DataContext == null) return; var htmlHelpContent = ((Performance2018GamePage)DataContext).HtmlHelpContent; _webBrowser.NavigateToString(htmlHelpContent); } } }
using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Navigation; using Abc.NCrafts.App.ViewModels; namespace Abc.NCrafts.App.Views { /// <summary> /// Interaction logic for GameView.xaml /// </summary> public partial class Performance2018GameView : UserControl { public Performance2018GameView() { InitializeComponent(); } private void OnLoaded(object sender, RoutedEventArgs e) { Focusable = true; Keyboard.Focus(this); } private void OnWebBrowserLoaded(object sender, NavigationEventArgs e) { var script = "document.body.style.overflow ='hidden'"; var wb = (WebBrowser)sender; wb.InvokeScript("execScript", script, "JavaScript"); } private void HtmlHelpClick(object sender, MouseButtonEventArgs e) { var pagePage = (Performance2018GamePage)DataContext; pagePage.IsHelpVisible = false; } private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if (DataContext == null) return; var htmlHelpContent = ((Performance2018GamePage)DataContext).HtmlHelpContent; _webBrowser.NavigateToString(htmlHelpContent); } } }
Check digit: recognize infrastructural code and domain logic
namespace CheckDigit { class Program { static int GetControllDigit(long number) { int sum = 0; bool isOddPos = true; while (number > 0) { int digit = (int)(number % 10); if (isOddPos) { sum += 3 * digit; } else { sum += digit; number /= 10; isOddPos = !isOddPos; } } int modulo = sum % 7; return modulo; } static void Main(string[] args) { int digit = GetControllDigit(12345); } } }
namespace CheckDigit { class Program { static int GetControllDigit(long number) { int sum = 0; bool isOddPos = true; while (number > 0) // infrastructure { int digit = (int)(number % 10); // infrastructure if (isOddPos) // domain { sum += 3 * digit; // 3 = parameter } else { sum += digit; number /= 10; // infrastructure isOddPos = !isOddPos; // domain } } int modulo = sum % 7; // 7 = parameter return modulo; // % = domain } static void Main(string[] args) { int digit = GetControllDigit(12345); } } }
Use imperative in help messages.
using System; using CommandLine; using CommandLine.Text; namespace Mugo { /// <summary> /// Command line options of the game. /// </summary> public class CommandLineOptions { [Option ('m', "noBackgroundMusic", DefaultValue = false, HelpText = "Disables background music. It can still be enabled via the m hotkey.")] public bool NoBackgroundMusic { get; set; } [Option ('s', "seed", HelpText = "Sets the seed value of the random number generator.")] public int? Seed { get; set; } [HelpOption ('h', "help")] public string GetUsage () { return HelpText.AutoBuild (this, (HelpText current) => HelpText.DefaultParsingErrorsHandler (this, current)); } } }
using System; using CommandLine; using CommandLine.Text; namespace Mugo { /// <summary> /// Command line options of the game. /// </summary> public class CommandLineOptions { [Option ('m', "noBackgroundMusic", DefaultValue = false, HelpText = "Disable background music. It can still be enabled via the m hotkey.")] public bool NoBackgroundMusic { get; set; } [Option ('s', "seed", HelpText = "Set the seed value of the random number generator.")] public int? Seed { get; set; } [HelpOption ('h', "help")] public string GetUsage () { return HelpText.AutoBuild (this, (HelpText current) => HelpText.DefaultParsingErrorsHandler (this, current)); } } }
Fix unhandled error causing crash
#region using System.Windows; using SteamAccountSwitcher.Properties; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnExit(ExitEventArgs e) { base.OnExit(e); Settings.Default.Save(); ClickOnceHelper.RunOnStartup(Settings.Default.AlwaysOn); } } }
#region using System.Windows; using SteamAccountSwitcher.Properties; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public App() { Dispatcher.UnhandledException += OnDispatcherUnhandledException; } protected override void OnExit(ExitEventArgs e) { base.OnExit(e); Settings.Default.Save(); ClickOnceHelper.RunOnStartup(Settings.Default.AlwaysOn); } private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { var errorMessage = $"An unhandled exception occurred:\n\n{e.Exception.Message}"; MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error); e.Handled = true; } } }
Use the .After() method in NUnit instead of Thread.Sleep
using System; using System.Threading; using NUnit.Framework; using SharpBrake; using SharpBrake.Serialization; namespace Tests { [TestFixture] public class AirbrakeClientTests { #region Setup/Teardown [SetUp] public void SetUp() { this.client = new AirbrakeClient(); } #endregion private AirbrakeClient client; [Test] public void Send_EndRequestEventIsInvoked_And_ResponseOnlyContainsApiError() { bool requestEndInvoked = false; AirbrakeResponseError[] errors = null; int i = 0; this.client.RequestEnd += (sender, e) => { requestEndInvoked = true; errors = e.Response.Errors; }; var configuration = new AirbrakeConfiguration { ApiKey = Guid.NewGuid().ToString("N"), EnvironmentName = "test", }; var builder = new AirbrakeNoticeBuilder(configuration); AirbrakeNotice notice = builder.Notice(new Exception("Test")); notice.Request = new AirbrakeRequest("http://example.com", "Test") { Params = new[] { new AirbrakeVar("TestKey", "TestValue") } }; this.client.Send(notice); while (!requestEndInvoked) { // Sleep for maximum 5 seconds to wait for the request to end. Can probably be done more elegantly. if (i++ == 50) break; Thread.Sleep(100); } Assert.That(requestEndInvoked, Is.True); Assert.That(errors, Is.Not.Null); Assert.That(errors, Has.Length.EqualTo(1)); } } }
using System; using NUnit.Framework; using SharpBrake; using SharpBrake.Serialization; namespace Tests { [TestFixture] public class AirbrakeClientTests { #region Setup/Teardown [SetUp] public void SetUp() { this.client = new AirbrakeClient(); } #endregion private AirbrakeClient client; [Test] public void Send_EndRequestEventIsInvoked_And_ResponseOnlyContainsApiError() { bool requestEndInvoked = false; AirbrakeResponseError[] errors = null; int i = 0; this.client.RequestEnd += (sender, e) => { requestEndInvoked = true; errors = e.Response.Errors; }; var configuration = new AirbrakeConfiguration { ApiKey = Guid.NewGuid().ToString("N"), EnvironmentName = "test", }; var builder = new AirbrakeNoticeBuilder(configuration); AirbrakeNotice notice = builder.Notice(new Exception("Test")); notice.Request = new AirbrakeRequest("http://example.com", "Test") { Params = new[] { new AirbrakeVar("TestKey", "TestValue") } }; this.client.Send(notice); Assert.That(requestEndInvoked, Is.True.After(5000)); Assert.That(errors, Is.Not.Null); Assert.That(errors, Has.Length.EqualTo(1)); } } }
Use strongly typed ReaderProgress instead of object[]
using System; namespace SharpCompress.Common { public class ReaderExtractionEventArgs<T> : EventArgs { internal ReaderExtractionEventArgs(T entry, params object[] paramList) { Item = entry; ParamList = paramList; } public T Item { get; private set; } public object[] ParamList { get; private set; } } }
using System; using SharpCompress.Readers; namespace SharpCompress.Common { public class ReaderExtractionEventArgs<T> : EventArgs { internal ReaderExtractionEventArgs(T entry, ReaderProgress readerProgress = null) { Item = entry; ReaderProgress = readerProgress; } public T Item { get; private set; } public ReaderProgress ReaderProgress { get; private set; } } }
Fix IPV6 issue with BindTest
using System.Net; using System.Net.Sockets; namespace Tgstation.Server.Host.Extensions { /// <summary> /// Extension methods for the <see cref="Socket"/> <see langword="class"/>. /// </summary> static class SocketExtensions { /// <summary> /// Attempt to exclusively bind to a given <paramref name="port"/>. /// </summary> /// <param name="port">The port number to bind to.</param> /// <param name="includeIPv6">If IPV6 should be tested as well.</param> public static void BindTest(ushort port, bool includeIPv6) { using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); if (includeIPv6) socket.DualMode = true; socket.Bind( new IPEndPoint( includeIPv6 ? IPAddress.IPv6Any : IPAddress.Any, port)); } } }
using System.Net; using System.Net.Sockets; namespace Tgstation.Server.Host.Extensions { /// <summary> /// Extension methods for the <see cref="Socket"/> <see langword="class"/>. /// </summary> static class SocketExtensions { /// <summary> /// Attempt to exclusively bind to a given <paramref name="port"/>. /// </summary> /// <param name="port">The port number to bind to.</param> /// <param name="includeIPv6">If IPV6 should be tested as well.</param> public static void BindTest(ushort port, bool includeIPv6) { using var socket = new Socket( includeIPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); if (includeIPv6) socket.DualMode = true; socket.Bind( new IPEndPoint( includeIPv6 ? IPAddress.IPv6Any : IPAddress.Any, port)); } } }
Improve performance counter test stability
using System.Diagnostics; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class PerformanceCounterTest { [Fact] public void Performance_counter_without_instance_name() { var performanceCounter = new PerformanceCounter("Memory", "Available Bytes"); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Memory", "Available Bytes")); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 100000, "Because memory usage can change between the two values"); } [Fact] public void Performance_counter_with_instance_name() { var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 100000, "Because memory usage can change between the two values"); } } }
using System.Diagnostics; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class PerformanceCounterTest { [Fact] public void Performance_counter_without_instance_name() { var performanceCounter = new PerformanceCounter("Memory", "Available Bytes"); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Memory", "Available Bytes")); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 500000, "Because memory usage can change between the two values"); } [Fact] public void Performance_counter_with_instance_name() { var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 500000, "Because memory usage can change between the two values"); } } }
Fix error when deserializing response with BodySize set to null (tested with HAR file exported with Firefox).
using System.Collections.Generic; namespace HarSharp { /// <summary> /// A base class for HTTP messages. /// </summary> public abstract class MessageBase : EntityBase { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="MessageBase"/> class. /// </summary> protected MessageBase() { Cookies = new List<Cookie>(); Headers = new List<Header>(); } #endregion #region Properties /// <summary> /// Gets or sets the HTTP Version. /// </summary> public string HttpVersion { get; set; } /// <summary> /// Gets the list of cookie objects. /// </summary> public IList<Cookie> Cookies { get; private set; } /// <summary> /// Gets the list of header objects. /// </summary> public IList<Header> Headers { get; private set; } /// <summary> /// Gets or sets the total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body. /// </summary> public int HeadersSize { get; set; } /// <summary> /// Gets or sets the size of the request body (POST data payload) in bytes. /// </summary> public int BodySize { get; set; } #endregion } }
using System.Collections.Generic; namespace HarSharp { /// <summary> /// A base class for HTTP messages. /// </summary> public abstract class MessageBase : EntityBase { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="MessageBase"/> class. /// </summary> protected MessageBase() { Cookies = new List<Cookie>(); Headers = new List<Header>(); } #endregion #region Properties /// <summary> /// Gets or sets the HTTP Version. /// </summary> public string HttpVersion { get; set; } /// <summary> /// Gets the list of cookie objects. /// </summary> public IList<Cookie> Cookies { get; private set; } /// <summary> /// Gets the list of header objects. /// </summary> public IList<Header> Headers { get; private set; } /// <summary> /// Gets or sets the total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body. /// </summary> public int HeadersSize { get; set; } /// <summary> /// Gets or sets the size of the request body (POST data payload) in bytes. /// </summary> public int? BodySize { get; set; } #endregion } }
Add note about supported Visual Studio versions
Order: 30 Title: Visual Studio Description: Extensions and supported features for Visual Studio RedirectFrom: docs/editors/visualstudio --- <p> The <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio </a> brings the following features to Visual Studio: <ul> <li>Language support for Cake build scripts</li> <li><a href="/docs/integrations/editors/visualstudio/templates">Templates</a></li> <li><a href="/docs/integrations/editors/visualstudio/commands">Commands</a> for working with Cake files</li> <li><a href="/docs/integrations/editors/visualstudio/snippets">Snippets</a></li> <li><a href="/docs/integrations/editors/visualstudio/task-runner">Integration with Task Runner Explorer</a></li> </ul> </p> <h1>Installation & configuration</h1> See <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio</a> for instructions how to install and configure the extension. <h1>Child pages</h1> @Html.Partial("_ChildPages")
Order: 30 Title: Visual Studio Description: Extensions and supported features for Visual Studio RedirectFrom: docs/editors/visualstudio --- <p> The <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio </a> brings the following features to Visual Studio: <ul> <li>Language support for Cake build scripts</li> <li><a href="/docs/integrations/editors/visualstudio/templates">Templates</a></li> <li><a href="/docs/integrations/editors/visualstudio/commands">Commands</a> for working with Cake files</li> <li><a href="/docs/integrations/editors/visualstudio/snippets">Snippets</a></li> <li><a href="/docs/integrations/editors/visualstudio/task-runner">Integration with Task Runner Explorer</a></li> </ul> </p> <h1>Installation & configuration</h1> <p> See <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio</a> for instructions how to install and configure the extension. </p> <div class="alert alert-info"> <p> The <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio</a> supports Visual Studio 2017 and newer. </p> </div> <h1>Child pages</h1> @Html.Partial("_ChildPages")
Adjust to new model. Provide change callback for task.
// SqliteNote.cs created with MonoDevelop // User: calvin at 10:56 AM 2/12/2008 // // To change standard headers go to Edit->Preferences->Coding->Standard Headers // namespace Tasque.Backends.Sqlite { public class SqliteNote : TaskNote { private int id; private string text; public SqliteNote (int id, string text) { this.id = id; this.text = text; } public string Text { get { return this.text; } set { this.text = value; } } public int ID { get { return this.id; } } } }
// SqliteNote.cs created with MonoDevelop // User: calvin at 10:56 AM 2/12/2008 // // To change standard headers go to Edit->Preferences->Coding->Standard Headers // using System; namespace Tasque.Backends.Sqlite { public class SqliteNote : TaskNote { public SqliteNote (int id, string text) : base (text) { Id = id; } public int Id { get; private set; } protected override void OnTextChanged () { if (OnTextChangedAction != null) OnTextChangedAction (); base.OnTextChanged (); } internal Action OnTextChangedAction { get; set; } } }
Normalize path so NuGet.Core's GetFiles(path) works correctly.
using System.Collections.Generic; using System.IO; using System.Runtime.Versioning; namespace NuGet.Lucene { public class FastZipPackageFile : IPackageFile { private readonly IFastZipPackage fastZipPackage; private readonly FrameworkName targetFramework; internal FastZipPackageFile(IFastZipPackage fastZipPackage, string path) { this.fastZipPackage = fastZipPackage; Path = path; string effectivePath; targetFramework = VersionUtility.ParseFrameworkNameFromFilePath(Normalize(path), out effectivePath); EffectivePath = effectivePath; } private string Normalize(string path) { return path .Replace('/', System.IO.Path.DirectorySeparatorChar) .TrimStart(System.IO.Path.DirectorySeparatorChar); } public string Path { get; private set; } public string EffectivePath { get; private set; } public FrameworkName TargetFramework { get { return targetFramework; } } IEnumerable<FrameworkName> IFrameworkTargetable.SupportedFrameworks { get { if (TargetFramework != null) { yield return TargetFramework; } } } public Stream GetStream() { return fastZipPackage.GetZipEntryStream(Path); } public override string ToString() { return Path; } } }
using System.Collections.Generic; using System.IO; using System.Runtime.Versioning; namespace NuGet.Lucene { public class FastZipPackageFile : IPackageFile { private readonly IFastZipPackage fastZipPackage; private readonly FrameworkName targetFramework; internal FastZipPackageFile(IFastZipPackage fastZipPackage, string path) { this.fastZipPackage = fastZipPackage; Path = Normalize(path); string effectivePath; targetFramework = VersionUtility.ParseFrameworkNameFromFilePath(Path, out effectivePath); EffectivePath = effectivePath; } private string Normalize(string path) { return path .Replace('/', System.IO.Path.DirectorySeparatorChar) .TrimStart(System.IO.Path.DirectorySeparatorChar); } public string Path { get; private set; } public string EffectivePath { get; private set; } public FrameworkName TargetFramework { get { return targetFramework; } } IEnumerable<FrameworkName> IFrameworkTargetable.SupportedFrameworks { get { if (TargetFramework != null) { yield return TargetFramework; } } } public Stream GetStream() { return fastZipPackage.GetZipEntryStream(Path); } public override string ToString() { return Path; } } }
Remove requirement on master branch existing
namespace GitVersion { using System.IO; using System.Linq; using GitVersion.VersionCalculation; using LibGit2Sharp; public class GitVersionFinder { public SemanticVersion FindVersion(GitVersionContext context) { Logger.WriteInfo(string.Format("Running against branch: {0} ({1})", context.CurrentBranch.Name, context.CurrentCommit.Sha)); EnsureMainTopologyConstraints(context); var filePath = Path.Combine(context.Repository.GetRepositoryDirectory(), "NextVersion.txt"); if (File.Exists(filePath)) { throw new WarningException("NextVersion.txt has been depreciated. See http://gitversion.readthedocs.org/en/latest/configuration/ for replacement"); } return new NextVersionCalculator().FindVersion(context); } void EnsureMainTopologyConstraints(GitVersionContext context) { EnsureLocalBranchExists(context.Repository, "master"); EnsureHeadIsNotDetached(context); } void EnsureHeadIsNotDetached(GitVersionContext context) { if (!context.CurrentBranch.IsDetachedHead()) { return; } var message = string.Format( "It looks like the branch being examined is a detached Head pointing to commit '{0}'. " + "Without a proper branch name GitVersion cannot determine the build version.", context.CurrentCommit.Id.ToString(7)); throw new WarningException(message); } void EnsureLocalBranchExists(IRepository repository, string branchName) { if (repository.FindBranch(branchName) != null) { return; } var existingBranches = string.Format("'{0}'", string.Join("', '", repository.Branches.Select(x => x.CanonicalName))); throw new WarningException(string.Format("This repository doesn't contain a branch named '{0}'. Please create one. Existing branches: {1}", branchName, existingBranches)); } } }
namespace GitVersion { using System.IO; using System.Linq; using GitVersion.VersionCalculation; using LibGit2Sharp; public class GitVersionFinder { public SemanticVersion FindVersion(GitVersionContext context) { Logger.WriteInfo(string.Format("Running against branch: {0} ({1})", context.CurrentBranch.Name, context.CurrentCommit.Sha)); EnsureMainTopologyConstraints(context); var filePath = Path.Combine(context.Repository.GetRepositoryDirectory(), "NextVersion.txt"); if (File.Exists(filePath)) { throw new WarningException("NextVersion.txt has been depreciated. See http://gitversion.readthedocs.org/en/latest/configuration/ for replacement"); } return new NextVersionCalculator().FindVersion(context); } void EnsureMainTopologyConstraints(GitVersionContext context) { EnsureHeadIsNotDetached(context); } void EnsureHeadIsNotDetached(GitVersionContext context) { if (!context.CurrentBranch.IsDetachedHead()) { return; } var message = string.Format( "It looks like the branch being examined is a detached Head pointing to commit '{0}'. " + "Without a proper branch name GitVersion cannot determine the build version.", context.CurrentCommit.Id.ToString(7)); throw new WarningException(message); } } }
Write arbitrary content to the repl
namespace Mages.Repl.Functions { using System; sealed class ReplObject { public String Read() { return Console.ReadLine(); } public void Write(String str) { Console.Write(str); } public void WriteLine(String str) { Console.WriteLine(str); } } }
namespace Mages.Repl.Functions { using Mages.Core.Runtime; using System; sealed class ReplObject { public String Read() { return Console.ReadLine(); } public void Write(Object value) { var str = Stringify.This(value); Console.Write(str); } public void WriteLine(Object value) { var str = Stringify.This(value); Console.WriteLine(str); } } }
Change assemblyinfo for quartz 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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Abp.Quartz")] [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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f90b1606-f375-4c84-9118-ab0c1ddeb0df")]
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("Abp.Quartz")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Volosoft")] [assembly: AssemblyProduct("Abp.Quartz")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f90b1606-f375-4c84-9118-ab0c1ddeb0df")]
Fix for link sdk assemblies only on iOS
using System.ComponentModel; using RoundedBoxView.Forms.Plugin.iOSUnified; using RoundedBoxView.Forms.Plugin.iOSUnified.ExtensionMethods; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof (RoundedBoxView.Forms.Plugin.Abstractions.RoundedBoxView), typeof (RoundedBoxViewRenderer))] namespace RoundedBoxView.Forms.Plugin.iOSUnified { /// <summary> /// Source From : https://gist.github.com/rudyryk/8cbe067a1363b45351f6 /// </summary> public class RoundedBoxViewRenderer : BoxRenderer { /// <summary> /// Used for registration with dependency service /// </summary> public static void Init() { } private Abstractions.RoundedBoxView _formControl { get { return Element as Abstractions.RoundedBoxView; } } protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e) { base.OnElementChanged(e); this.InitializeFrom(_formControl); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); this.UpdateFrom(_formControl, e.PropertyName); } } }
using System.ComponentModel; using RoundedBoxView.Forms.Plugin.iOSUnified; using RoundedBoxView.Forms.Plugin.iOSUnified.ExtensionMethods; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using Foundation; using System; [assembly: ExportRenderer(typeof (RoundedBoxView.Forms.Plugin.Abstractions.RoundedBoxView), typeof (RoundedBoxViewRenderer))] namespace RoundedBoxView.Forms.Plugin.iOSUnified { /// <summary> /// Source From : https://gist.github.com/rudyryk/8cbe067a1363b45351f6 /// </summary> [Preserve(AllMembers = true)] public class RoundedBoxViewRenderer : BoxRenderer { /// <summary> /// Used for registration with dependency service /// </summary> public static void Init() { var temp = DateTime.Now; } private Abstractions.RoundedBoxView _formControl { get { return Element as Abstractions.RoundedBoxView; } } protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e) { base.OnElementChanged(e); this.InitializeFrom(_formControl); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); this.UpdateFrom(_formControl, e.PropertyName); } } }
Replace a string.Remove with slicing.
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; namespace osu.Framework.IO.Stores { public class NamespacedResourceStore<T> : ResourceStore<T> where T : class { public string Namespace; /// <summary> /// Initializes a resource store with a single store. /// </summary> /// <param name="store">The store.</param> /// <param name="ns">The namespace to add.</param> public NamespacedResourceStore(IResourceStore<T> store, string ns) : base(store) { Namespace = ns; } protected override IEnumerable<string> GetFilenames(string name) => base.GetFilenames($@"{Namespace}/{name}"); public override IEnumerable<string> GetAvailableResources() => base.GetAvailableResources() .Where(x => x.StartsWith($"{Namespace}/")) .Select(x => x.Remove(0, $"{Namespace}/".Length)); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; namespace osu.Framework.IO.Stores { public class NamespacedResourceStore<T> : ResourceStore<T> where T : class { public string Namespace; /// <summary> /// Initializes a resource store with a single store. /// </summary> /// <param name="store">The store.</param> /// <param name="ns">The namespace to add.</param> public NamespacedResourceStore(IResourceStore<T> store, string ns) : base(store) { Namespace = ns; } protected override IEnumerable<string> GetFilenames(string name) => base.GetFilenames($@"{Namespace}/{name}"); public override IEnumerable<string> GetAvailableResources() => base.GetAvailableResources() .Where(x => x.StartsWith($"{Namespace}/")) .Select(x => x[(Namespace.Length + 1)..]); } }
Fix potential infinite loop in SkipWhitespace
using System; using System.Text; using DbUp.Support; namespace DbUp.MySql { /// <summary> /// Reads MySQL commands from an underlying text stream. Supports DELIMITED .. statement /// </summary> public class MySqlCommandReader : SqlCommandReader { const string DelimiterKeyword = "DELIMITER"; /// <summary> /// Creates an instance of MySqlCommandReader /// </summary> public MySqlCommandReader(string sqlText) : base(sqlText, ";", delimiterRequiresWhitespace: false) { } /// <summary> /// Hook to support custom statements /// </summary> protected override bool IsCustomStatement => TryPeek(DelimiterKeyword.Length - 1, out var statement) && string.Equals(DelimiterKeyword, CurrentChar + statement, StringComparison.OrdinalIgnoreCase); /// <summary> /// Read a custom statement /// </summary> protected override void ReadCustomStatement() { // Move past Delimiter keyword var count = DelimiterKeyword.Length + 1; Read(new char[count], 0, count); SkipWhitespace(); // Read until we hit the end of line. var delimiter = new StringBuilder(); do { delimiter.Append(CurrentChar); if (Read() == FailedRead) { break; } } while (!IsEndOfLine && !IsWhiteSpace); Delimiter = delimiter.ToString(); } void SkipWhitespace() { while (char.IsWhiteSpace(CurrentChar)) { Read(); } } } }
using System; using System.Text; using DbUp.Support; namespace DbUp.MySql { /// <summary> /// Reads MySQL commands from an underlying text stream. Supports DELIMITED .. statement /// </summary> public class MySqlCommandReader : SqlCommandReader { const string DelimiterKeyword = "DELIMITER"; /// <summary> /// Creates an instance of MySqlCommandReader /// </summary> public MySqlCommandReader(string sqlText) : base(sqlText, ";", delimiterRequiresWhitespace: false) { } /// <summary> /// Hook to support custom statements /// </summary> protected override bool IsCustomStatement => TryPeek(DelimiterKeyword.Length - 1, out var statement) && string.Equals(DelimiterKeyword, CurrentChar + statement, StringComparison.OrdinalIgnoreCase); /// <summary> /// Read a custom statement /// </summary> protected override void ReadCustomStatement() { // Move past Delimiter keyword var count = DelimiterKeyword.Length + 1; Read(new char[count], 0, count); SkipWhitespace(); // Read until we hit the end of line. var delimiter = new StringBuilder(); do { delimiter.Append(CurrentChar); if (Read() == FailedRead) { break; } } while (!IsEndOfLine && !IsWhiteSpace); Delimiter = delimiter.ToString(); } void SkipWhitespace() { int result; do { result = Read(); } while (result != FailedRead && char.IsWhiteSpace(CurrentChar)); } } }
Implement fake tag parser to test integration
using System; namespace FTF.Core.Notes { public class CreateNote { private readonly Func<int> _generateId; private readonly Func<DateTime> _getCurrentDate; private readonly Action<Note> _saveNote; private readonly Action _saveChanges; public CreateNote(Func<int> generateId, Func<DateTime> getCurrentDate, Action<Note> saveNote, Action saveChanges) { _generateId = generateId; _getCurrentDate = getCurrentDate; _saveNote = saveNote; _saveChanges = saveChanges; } public void Create(int id, string text) { _saveNote(new Note { Id = _generateId(), Text = text, CreationDate = _getCurrentDate() }); _saveChanges(); } } }
using System; using System.Collections.Generic; namespace FTF.Core.Notes { public class CreateNote { private readonly Func<int> _generateId; private readonly Func<DateTime> _getCurrentDate; private readonly Action<Note> _saveNote; private readonly Action _saveChanges; public CreateNote(Func<int> generateId, Func<DateTime> getCurrentDate, Action<Note> saveNote, Action saveChanges) { _generateId = generateId; _getCurrentDate = getCurrentDate; _saveNote = saveNote; _saveChanges = saveChanges; } public void Create(int id, string text) { _saveNote(new Note { Id = _generateId(), Text = text, CreationDate = _getCurrentDate(), Tags = ParseTags(text) }); _saveChanges(); } private ICollection<Tag> ParseTags(string text) => new List<Tag> { new Tag { Name = "Buy"} }; } }
Disable display test that is failing in CI build.
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using AgateLib; using AgateLib.Drivers; using AgateLib.DisplayLib; namespace AgateLib.UnitTests.DisplayTest { [TestClass] public class DisplayTest { [TestMethod] public void InitializeDisplay() { using (AgateSetup setup = new AgateSetup()) { setup.PreferredDisplay = (DisplayTypeID) 1000; setup.InitializeDisplay((DisplayTypeID)1000); Assert.IsFalse(setup.WasCanceled); DisplayWindow wind = DisplayWindow.CreateWindowed("Title", 400, 400); } } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using AgateLib; using AgateLib.Drivers; using AgateLib.DisplayLib; namespace AgateLib.UnitTests.DisplayTest { [TestClass] public class DisplayTest { /* [TestMethod] public void InitializeDisplay() { using (AgateSetup setup = new AgateSetup()) { setup.PreferredDisplay = (DisplayTypeID) 1000; setup.InitializeDisplay((DisplayTypeID)1000); Assert.IsFalse(setup.WasCanceled); DisplayWindow wind = DisplayWindow.CreateWindowed("Title", 400, 400); } } * */ } }
Add a comment for exported DefaultProperties.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using UELib; using UELib.Core; namespace UELib.Core { public partial class UTextBuffer : UObject { public override string Decompile() { if( _bDeserializeOnDemand ) { BeginDeserializing(); } if( ScriptText.Length != 0 ) { if( Outer is UStruct ) { try { return ScriptText + ((UClass)Outer).FormatDefaultProperties(); } catch { return ScriptText + "\r\n// Failed to decompile defaultproperties for this object."; } } return ScriptText; } return "TextBuffer is empty!"; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using UELib; using UELib.Core; namespace UELib.Core { public partial class UTextBuffer : UObject { public override string Decompile() { if( _bDeserializeOnDemand ) { BeginDeserializing(); } if( ScriptText.Length != 0 ) { if( Outer is UStruct ) { try { return ScriptText + (((UClass)Outer).Properties != null && ((UClass)Outer).Properties.Count > 0 ? "// Decompiled with UE Explorer." : "// No DefaultProperties.") + ((UClass)Outer).FormatDefaultProperties(); } catch { return ScriptText + "\r\n// Failed to decompile defaultproperties for this object."; } } return ScriptText; } return "TextBuffer is empty!"; } } }