Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix exception when including this in a project without TriggerAction
using UnityEngine; using System.Collections; public abstract class ConsoleAction : ActionBase { public abstract void Activate(); }
using UnityEngine; using System.Collections; public abstract class ConsoleAction : MonoBehaviour { public abstract void Activate(); }
Use the correct strong name for dbus-sharp-glib friend assembly
// 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")]
// 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 ("NDesk.DBus.GLib")] [assembly: InternalsVisibleTo ("dbus-monitor")] [assembly: InternalsVisibleTo ("dbus-daemon")]
Add a builder for the base environ, so it's easier to work with
using System; using System.Collections.Generic; namespace NValidate { public class BaseEnviron : Environ { readonly Dictionary<Type, Func<Environ, object>> _modelExtractors; readonly Dictionary<Type, object> _models; public BaseEnviron(Dictionary<Type, Func<Environ, object>> modelExtractors, Dictionary<Type, object> models) { _modelExtractors = modelExtractors; _models = models; } public override Environ Add(object model) { return new LinkedEnviron(model, this); } public override object GetByType(Type type, Environ topEnviron = null) { object result = null; _models.TryGetValue(type, out result); if (result != null) { return result; } else if (_modelExtractors != null) { Func<Environ, object> extractor = null; if (!_modelExtractors.TryGetValue(type, out extractor)) return null; return extractor(topEnviron ?? this); } else { return null; } } } }
using System; using System.Collections.Generic; namespace NValidate { public class BaseEnviron : Environ { readonly Dictionary<Type, Func<Environ, object>> _modelExtractors; readonly Dictionary<Type, object> _models; public BaseEnviron(Dictionary<Type, Func<Environ, object>> modelExtractors, Dictionary<Type, object> models) { _modelExtractors = modelExtractors; _models = models; } public override Environ Add(object model) { return new LinkedEnviron(model, this); } public override object GetByType(Type type, Environ topEnviron = null) { object result = null; _models.TryGetValue(type, out result); if (result != null) { return result; } else if (_modelExtractors != null) { Func<Environ, object> extractor = null; if (!_modelExtractors.TryGetValue(type, out extractor)) return null; return extractor(topEnviron ?? this); } else { return null; } } } public class BaseEnvironBuilder { readonly Dictionary<Type, Func<Environ, object>> _modelExtractors; readonly Dictionary<Type, object> _models; public BaseEnvironBuilder() { _modelExtractors = new Dictionary<Type, Func<Environ, object>>(); _models = new Dictionary<Type, object>(); } public BaseEnvironBuilder AddModel(object model) { _models[model.GetType()] = model; return this; } public BaseEnvironBuilder AddModelExtractor<T>(Func<Environ, object> modelExtractor) { _models[typeof(T)] = modelExtractor; return this; } public BaseEnviron Build() { return new BaseEnviron(_modelExtractors, _models); } } }
Fix problem with parsing server url.
// Copyright 2015 Apcera Inc. All rights reserved. using System; namespace NATS.Client { // Tracks individual backend servers. internal class Srv { internal Uri url = null; internal bool didConnect = false; internal int reconnects = 0; internal DateTime lastAttempt = DateTime.Now; internal bool isImplicit = false; // never create a srv object without a url. private Srv() { } internal Srv(string urlString) { // allow for host:port, without the prefix. if (urlString.ToLower().StartsWith("nats") == false) urlString = "nats://" + urlString; url = new Uri(urlString); } internal Srv(string urlString, bool isUrlImplicit) : this(urlString) { isImplicit = isUrlImplicit; } internal void updateLastAttempt() { lastAttempt = DateTime.Now; } internal TimeSpan TimeSinceLastAttempt { get { return (DateTime.Now - lastAttempt); } } } }
// Copyright 2015 Apcera Inc. All rights reserved. using System; namespace NATS.Client { // Tracks individual backend servers. internal class Srv { internal Uri url = null; internal bool didConnect = false; internal int reconnects = 0; internal DateTime lastAttempt = DateTime.Now; internal bool isImplicit = false; // never create a srv object without a url. private Srv() { } internal Srv(string urlString) { // allow for host:port, without the prefix. if (urlString.ToLower().StartsWith("nats://") == false) urlString = "nats://" + urlString; url = new Uri(urlString); } internal Srv(string urlString, bool isUrlImplicit) : this(urlString) { isImplicit = isUrlImplicit; } internal void updateLastAttempt() { lastAttempt = DateTime.Now; } internal TimeSpan TimeSinceLastAttempt { get { return (DateTime.Now - lastAttempt); } } } }
Update Step 3 - Remove integration test category.
using NSubstitute; using NUnit.Framework; namespace DependencyKata.Tests { [TestFixture] public class DoItAllTests { [Test, Category("Integration")] public void DoItAll_Does_ItAll() { var expected = "The passwords don't match"; var io = Substitute.For<IOutputInputAdapter>(); var logging = Substitute.For<ILogging>(); var doItAll = new DoItAll(io, logging); var result = doItAll.Do(); Assert.AreEqual(expected, result); } [Test, Category("Integration")] public void DoItAll_Does_ItAll_MatchingPasswords() { var expected = "Database.SaveToLog Exception:"; var io = Substitute.For<IOutputInputAdapter>(); io.GetInput().Returns("something"); var logging = new DatabaseLogging(); var doItAll = new DoItAll(io, logging); var result = doItAll.Do(); StringAssert.Contains(expected, result); } [Test, Category("Integration")] public void DoItAll_Does_ItAll_MockLogging() { var expected = string.Empty; var io = Substitute.For<IOutputInputAdapter>(); io.GetInput().Returns("something"); var logging = Substitute.For<ILogging>(); var doItAll = new DoItAll(io, logging); var result = doItAll.Do(); StringAssert.Contains(expected, result); } } }
using NSubstitute; using NUnit.Framework; namespace DependencyKata.Tests { [TestFixture] public class DoItAllTests { [Test, Category("Integration")] public void DoItAll_Does_ItAll() { var expected = "The passwords don't match"; var io = Substitute.For<IOutputInputAdapter>(); var logging = Substitute.For<ILogging>(); var doItAll = new DoItAll(io, logging); var result = doItAll.Do(); Assert.AreEqual(expected, result); } [Test, Category("Integration")] public void DoItAll_Does_ItAll_MatchingPasswords() { var expected = "Database.SaveToLog Exception:"; var io = Substitute.For<IOutputInputAdapter>(); io.GetInput().Returns("something"); var logging = new DatabaseLogging(); var doItAll = new DoItAll(io, logging); var result = doItAll.Do(); StringAssert.Contains(expected, result); } [Test] public void DoItAll_Does_ItAll_MockLogging() { var expected = string.Empty; var io = Substitute.For<IOutputInputAdapter>(); io.GetInput().Returns("something"); var logging = Substitute.For<ILogging>(); var doItAll = new DoItAll(io, logging); var result = doItAll.Do(); StringAssert.Contains(expected, result); } } }
Extend TriggerHelp for querying help
using System.Collections.Generic; using MeidoCommon; namespace MeidoBot { public static class PluginExtensions { public static string Name(this IMeidoHook plugin) { string name = plugin.Name.Trim(); switch (name) { case "": case null: name = "Unknown"; break; // Reserved names. case "Main": case "Meido": case "Triggers": case "Auth": name = "_" + name; break; } return name; } public static Dictionary<string, string> Help(this IMeidoHook plugin) { if (plugin.Help != null) return plugin.Help; return new Dictionary<string, string>(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using MeidoCommon; namespace MeidoBot { public static class PluginExtensions { public static string Name(this IMeidoHook plugin) { string name = plugin.Name.Trim(); switch (name) { case "": case null: name = "Unknown"; break; // Reserved names. case "Main": case "Meido": case "Triggers": case "Auth": name = "_" + name; break; } return name; } public static Dictionary<string, string> Help(this IMeidoHook plugin) { if (plugin.Help != null) return plugin.Help; return new Dictionary<string, string>(); } public static bool Query(this TriggerHelp root, string[] fullCommand, out CommandHelp help) { help = null; var cmdHelpNodes = root.Commands; foreach (string cmdPart in fullCommand) { if (TryGetHelp(cmdPart, cmdHelpNodes, out help)) cmdHelpNodes = help.Subcommands; else { help = null; break; } } return help != null; } static bool TryGetHelp( string command, ReadOnlyCollection<CommandHelp> searchSpace, out CommandHelp help) { foreach (var cmdHelp in searchSpace) { if (cmdHelp.Command.Equals(command, StringComparison.Ordinal)) { help = cmdHelp; return true; } } help = null; return false; } } }
Add user32 function in winutilities
using Sloth.Interfaces.Core; using System; namespace Sloth.Core { public class WinUtilities : IWinUtilities { public IntPtr FindControlHandle(IntPtr windowsHandle, string controlName) { throw new NotImplementedException(); } public IntPtr FindWindowsHandle(string className,string windowsName) { throw new NotImplementedException(); } public string GetClassName(IntPtr windowsHandle) { throw new NotImplementedException(); } public string GetWindowText(IntPtr windowsHandle) { throw new NotImplementedException(); } public void SendMessage(IntPtr windowsHandle, IntPtr controlHandle, ISlothEvent slothEvent) { throw new NotImplementedException(); } } }
using Sloth.Interfaces.Core; using System; using System.Runtime.InteropServices; using System.Text; namespace Sloth.Core { public class WinUtilities : IWinUtilities { public IntPtr FindControlHandle(IntPtr windowsHandle, string controlName) { throw new NotImplementedException(); } public IntPtr FindWindowsHandle(string className,string windowsName) { throw new NotImplementedException(); } public string GetClassName(IntPtr windowsHandle) { throw new NotImplementedException(); } public string GetWindowText(IntPtr windowsHandle) { throw new NotImplementedException(); } public void SendMessage(IntPtr windowsHandle, IntPtr controlHandle, ISlothEvent slothEvent) { throw new NotImplementedException(); } [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); [DllImport("user32.dll")] static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); } }
Create project and editor explicitly
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dependencies; namespace Core2D.Sample { class Program { static void Main(string[] args) { CreateSampleProject(); } static EditorContext CreateContext() { var context = new EditorContext() { View = null, Renderers = null, ProjectFactory = new ProjectFactory(), TextClipboard = null, Serializer = new NewtonsoftSerializer(), PdfWriter = null, DxfWriter = null, CsvReader = null, CsvWriter = null }; context.InitializeEditor(); context.InitializeCommands(); context.New(); return context; } static void CreateSampleProject() { try { var context = CreateContext(); var factory = new ShapeFactory(context); factory.Line(30, 30, 60, 30); factory.Text(30, 30, 60, 60, "Sample"); context.Save("sample.project"); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Console.ReadKey(true); } } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dependencies; namespace Core2D.Sample { class Program { static void Main(string[] args) { CreateSampleProject(); } static EditorContext CreateContext() { var context = new EditorContext() { View = null, Renderers = null, ProjectFactory = new ProjectFactory(), TextClipboard = null, Serializer = new NewtonsoftSerializer(), PdfWriter = null, DxfWriter = null, CsvReader = null, CsvWriter = null }; var project = context.ProjectFactory.GetProject(); context.Editor = Editor.Create(project); context.New(); return context; } static void CreateSampleProject() { try { var context = CreateContext(); var factory = new ShapeFactory(context); factory.Line(30, 30, 60, 30); factory.Text(30, 30, 60, 60, "Sample"); context.Save("sample.project"); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Console.ReadKey(true); } } } }
Change messages attribute to type "object"
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class BatchShipment : ShippoId { [JsonProperty (PropertyName = "object_status")] public string ObjectStatus; [JsonProperty (PropertyName = "carrier_account")] public string CarrierAccount; [JsonProperty (PropertyName = "servicelevel_token")] public string ServicelevelToken; [JsonProperty (PropertyName = "shipment")] public Object Shipment; [JsonProperty (PropertyName = "transaction")] public string Transaction; [JsonProperty (PropertyName = "messages")] public List<String> Messages; [JsonProperty (PropertyName = "metadata")] public string Metadata; public override string ToString () { return string.Format ("[BatchShipment: ObjectStatus={0}, CarrierAccount={1}, ServicelevelToken={2}, " + "Shipment={3}, Transaction={4}, Messages={5}, Metadata={6}]", ObjectStatus, CarrierAccount, ServicelevelToken, Shipment, Transaction, Messages, Metadata); } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class BatchShipment : ShippoId { [JsonProperty (PropertyName = "object_status")] public string ObjectStatus; [JsonProperty (PropertyName = "carrier_account")] public string CarrierAccount; [JsonProperty (PropertyName = "servicelevel_token")] public string ServicelevelToken; [JsonProperty (PropertyName = "shipment")] public Object Shipment; [JsonProperty (PropertyName = "transaction")] public string Transaction; [JsonProperty (PropertyName = "messages")] public object Messages; [JsonProperty (PropertyName = "metadata")] public string Metadata; public override string ToString () { return string.Format ("[BatchShipment: ObjectStatus={0}, CarrierAccount={1}, ServicelevelToken={2}, " + "Shipment={3}, Transaction={4}, Messages={5}, Metadata={6}]", ObjectStatus, CarrierAccount, ServicelevelToken, Shipment, Transaction, Messages, Metadata); } } }
Adjust timing ratio to prevent occasional failing
using System; using System.Threading; using System.Windows.Threading; using Throttle; using Xunit; using TomsToolbox.Desktop; public class ThrottleSample { int throttledCalls; [Fact] public void Run() { var dispatcher = Dispatcher.CurrentDispatcher; dispatcher.BeginInvoke(() => { ThrottledMethod(); Delay(5); ThrottledMethod(); Delay(5); ThrottledMethod(); Delay(5); ThrottledMethod(); Delay(5); ThrottledMethod(); Delay(5); Assert.Equal(0, throttledCalls); Delay(20); Assert.Equal(1, throttledCalls); dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle); }); Dispatcher.Run(); } static void Delay(int timeSpan) { var frame = new DispatcherFrame(); var timer = new DispatcherTimer(TimeSpan.FromMilliseconds(timeSpan), DispatcherPriority.Normal, (sender, args) => frame.Continue = false, Dispatcher.CurrentDispatcher); timer.Start(); Dispatcher.PushFrame(frame); } [Throttled(typeof(TomsToolbox.Desktop.Throttle), 10)] void ThrottledMethod() { Interlocked.Increment(ref throttledCalls); } }
using System; using System.Threading; using System.Windows.Threading; using Throttle; using Xunit; using TomsToolbox.Desktop; public class ThrottleSample { int throttledCalls; [Fact] public void Run() { var dispatcher = Dispatcher.CurrentDispatcher; dispatcher.BeginInvoke(() => { ThrottledMethod(); Delay(5); ThrottledMethod(); Delay(5); ThrottledMethod(); Delay(5); ThrottledMethod(); Delay(5); ThrottledMethod(); Delay(5); Assert.Equal(0, throttledCalls); Delay(200); Assert.Equal(1, throttledCalls); dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle); }); Dispatcher.Run(); } static void Delay(int timeSpan) { var frame = new DispatcherFrame(); var timer = new DispatcherTimer(TimeSpan.FromMilliseconds(timeSpan), DispatcherPriority.Normal, (sender, args) => frame.Continue = false, Dispatcher.CurrentDispatcher); timer.Start(); Dispatcher.PushFrame(frame); } [Throttled(typeof(TomsToolbox.Desktop.Throttle), 100)] void ThrottledMethod() { Interlocked.Increment(ref throttledCalls); } }
Remove random SoftPwm test code
using System; using Treehopper; using System.Threading.Tasks; using System.Diagnostics; using System.Collections.Generic; using System.Threading; namespace Blink { /// <summary> /// This demo blinks the built-in LED using async programming. /// </summary> class Program { static TreehopperUsb Board; static void Main(string[] args) { // We can't do async calls from the Console's Main() function, so we run all our code in a separate async method. RunBlink().Wait(); } static async Task RunBlink() { while (true) { Console.Write("Waiting for board..."); // Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected. Board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Found board: " + Board); Console.WriteLine("Version: " + Board.Version); // You must explicitly connect to a board before communicating with it await Board.ConnectAsync(); Board.Pins[0].SoftPwm.Enabled = true; Board.Pins[0].SoftPwm.DutyCycle = 0.5; Console.WriteLine("Start blinking. Press any key to stop."); while (Board.IsConnected && !Console.KeyAvailable) { // toggle the LED. Board.Led = !Board.Led; await Task.Delay(100); } } } } }
using System; using Treehopper; using System.Threading.Tasks; using System.Diagnostics; using System.Collections.Generic; using System.Threading; namespace Blink { /// <summary> /// This demo blinks the built-in LED using async programming. /// </summary> class Program { static TreehopperUsb Board; static void Main(string[] args) { // We can't do async calls from the Console's Main() function, so we run all our code in a separate async method. RunBlink().Wait(); } static async Task RunBlink() { while (true) { Console.Write("Waiting for board..."); // Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected. Board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Found board: " + Board); Console.WriteLine("Version: " + Board.Version); // You must explicitly connect to a board before communicating with it await Board.ConnectAsync(); Console.WriteLine("Start blinking. Press any key to stop."); while (Board.IsConnected && !Console.KeyAvailable) { // toggle the LED. Board.Led = !Board.Led; await Task.Delay(100); } } } } }
Fix Navigation link on acl
@model biz.dfch.CS.Appclusive.UI.Models.Core.Acl @using biz.dfch.CS.Appclusive.UI.App_LocalResources @if (Model != null && !string.IsNullOrEmpty(Model.Name)) { if (biz.dfch.CS.Appclusive.UI.Navigation.PermissionDecisions.Current.HasPermission(Model.GetType(), "CanRead")) { string id = (string)ViewContext.Controller.ControllerContext.RouteData.Values["id"]; string action = (string)ViewContext.Controller.ControllerContext.RouteData.Values["action"]; string controller = (string)ViewContext.Controller.ControllerContext.RouteData.Values["controller"]; @Html.ActionLink(Model.Name, "ItemDetails", "Acls", new { id = Model.Id, rId = id, rAction = action, rController = controller }, null) } else { @Html.DisplayFor(model => model.Name) } }
@model biz.dfch.CS.Appclusive.UI.Models.Core.Acl @using biz.dfch.CS.Appclusive.UI.App_LocalResources @if (Model != null && !string.IsNullOrEmpty(Model.Name)) { if (biz.dfch.CS.Appclusive.UI.Navigation.PermissionDecisions.Current.HasPermission(Model.GetType(), "CanRead")) { string id = (string)ViewContext.Controller.ControllerContext.RouteData.Values["id"]; string action = (string)ViewContext.Controller.ControllerContext.RouteData.Values["action"]; string controller = (string)ViewContext.Controller.ControllerContext.RouteData.Values["controller"]; @Html.ActionLink(Model.Name, "Details", "Acls", new { id = Model.Id, rId = id, rAction = action, rController = controller }, null) } else { @Html.DisplayFor(model => model.Name) } }
Remove drop menus from main menu
<header class="main-header"> <div class="row"> <div class="column"> <ul class="menu"> <li class="mobile-expand" id="mobile-expand"> <a href="#"> <i class="fa fa-align-justify"></i> </a> </li> <li class="branding">@Html.ActionLink("Michael's Music", "Index", "Home")</li> <li class="has-submenu"> <a href="#">Guitars</a> <ul class="submenu" data-submenu> <li><a href="/guitars/">All Guitars</a></li> <li><a href="#">Guitars by Brand</a></li> </ul> </li> <li class="has-submenu"> <a href="#">Amps</a> <ul class="submenu" data-submenu> <li><a href="#">All Amps</a></li> <li><a href="#">Amps by Brand</a></li> </ul> </li> <li class="has-submenu"> <a href="#">Pedals</a> <ul class="submenu" data-submenu> <li><a href="#">All Pedals</a></li> <li><a href="#">Pedals by Brand</a></li> </ul> </li> <li> @Html.ActionLink("About", "About", "Home") </li> </ul> </div> </div> </header>
<header class="main-header"> <div class="row"> <div class="column"> <ul class="menu"> <li class="mobile-expand" id="mobile-expand"> <a href="#"> <i class="fa fa-align-justify"></i> </a> </li> <li class="branding">@Html.ActionLink("Michael's Music", "Index", "Home")</li> <li> <a href="/guitars/">Guitars</a> </li> <li> <a href="#">Amps</a> </li> <li> <a href="#">Pedals</a> </li> <li> @Html.ActionLink("About", "About", "Home") </li> </ul> </div> </div> </header>
Make sure playerComp is in the node lookup list
using System.Collections.Generic; using Hacknet; using HarmonyLib; using Pathfinder.Event; using Pathfinder.Event.Loading; using Pathfinder.Util; namespace Pathfinder.BaseGameFixes.Performance { [HarmonyPatch] internal static class NodeLookup { [HarmonyPostfix] [HarmonyPatch(typeof(List<Computer>), nameof(List<Computer>.Add))] internal static void AddComputerReference(List<Computer> __instance, Computer item) { if (object.ReferenceEquals(__instance, OS.currentInstance?.netMap?.nodes)) { ComputerLookup.PopulateLookups(item); } } [HarmonyPrefix] [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))] internal static bool ModifyComputerLoaderLookup(out Computer __result, string target) { __result = ComputerLookup.FindById(target); return false; } [HarmonyPrefix] [HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))] internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name) { __result = ComputerLookup.Find(ip_Or_ID_or_Name); return false; } [HarmonyPostfix] [HarmonyPatch(typeof(OS), nameof(OS.quitGame))] internal static void ClearOnQuitGame() { ComputerLookup.ClearLookups(); } } }
using System.Collections.Generic; using Hacknet; using HarmonyLib; using Pathfinder.Event; using Pathfinder.Event.Loading; using Pathfinder.Util; namespace Pathfinder.BaseGameFixes.Performance { [HarmonyPatch] internal static class NodeLookup { [HarmonyPostfix] [HarmonyPatch(typeof(List<Computer>), nameof(List<Computer>.Add))] [HarmonyPatch(typeof(List<Computer>), nameof(List<Computer>.Insert))] internal static void AddComputerReference(List<Computer> __instance, Computer item) { if (object.ReferenceEquals(__instance, OS.currentInstance?.netMap?.nodes)) { ComputerLookup.PopulateLookups(item); } } [HarmonyPrefix] [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))] internal static bool ModifyComputerLoaderLookup(out Computer __result, string target) { __result = ComputerLookup.FindById(target); return false; } [HarmonyPrefix] [HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))] internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name) { __result = ComputerLookup.Find(ip_Or_ID_or_Name); return false; } [HarmonyPostfix] [HarmonyPatch(typeof(OS), nameof(OS.quitGame))] internal static void ClearOnQuitGame() { ComputerLookup.ClearLookups(); } } }
Add GetEndpointData manual test to ConsoleAppTester
using System; using System.Linq; namespace SSLLWrapper.ConsoleAppTester { class Program { private const string apiUrl = "https://api.dev.ssllabs.com/api/fa78d5a4"; static void Main(string[] args) { AnalyzeTester(); } static void AnalyzeTester() { var apiService = new ApiService(apiUrl); var analyze = apiService.Analyze("http://www.ashleypoole.co.uk"); Console.WriteLine("Has Error Occoured: {0}", analyze.HasErrorOccurred); Console.WriteLine("Status Code: {0}", analyze.Headers.statusCode); Console.WriteLine("Status: {0}", analyze.status); Console.ReadLine(); } } }
using System; using System.Linq; namespace SSLLWrapper.ConsoleAppTester { class Program { private const string ApiUrl = "https://api.dev.ssllabs.com/api/fa78d5a4"; static readonly ApiService ApiService = new ApiService(ApiUrl); static void Main(string[] args) { //AnalyzeTester(); //InfoTester(); GetEndpointData(); } static void InfoTester() { var info = ApiService.Info(); Console.WriteLine("Has Error Occoured: {0}", info.HasErrorOccurred); Console.WriteLine("Status Code: {0}", info.Headers.statusCode); Console.WriteLine("Engine Version: {0}", info.engineVersion); Console.WriteLine("Online: {0}", info.Online); Console.ReadLine(); } static void AnalyzeTester() { var analyze = ApiService.Analyze("http://www.ashleypoole.co.uk"); Console.WriteLine("Has Error Occoured: {0}", analyze.HasErrorOccurred); Console.WriteLine("Status Code: {0}", analyze.Headers.statusCode); Console.WriteLine("Status: {0}", analyze.status); Console.ReadLine(); } static void GetEndpointData() { var endpointDataModel = ApiService.GetEndpointData("http://www.ashleypoole.co.uk", "104.28.6.2"); Console.WriteLine("Has Error Occoured: {0}", endpointDataModel.HasErrorOccurred); Console.WriteLine("Status Code: {0}", endpointDataModel.Headers.statusCode); Console.WriteLine("IP Adress: {0}", endpointDataModel.ipAddress); Console.WriteLine("Grade: {0}", endpointDataModel.grade); Console.WriteLine("Status Message: {0}", endpointDataModel.statusMessage); Console.ReadLine(); } } }
Use element type name for variable names
using Mono.Cecil; using Mono.Cecil.Cil; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace MonoMod.DebugIL { public static class DebugILGeneratorExt { public readonly static Type t_MetadataType = typeof(MetadataType); public static ScopeDebugInformation GetOrAddScope(this MethodDebugInformation mdi) { if (mdi.Scope != null) return mdi.Scope; return mdi.Scope = new ScopeDebugInformation( mdi.Method.Body.Instructions[0], mdi.Method.Body.Instructions[mdi.Method.Body.Instructions.Count - 1] ); } public static string GenerateVariableName(this VariableDefinition @var, MethodDefinition method = null, int i = -1) { TypeReference type = @var.VariableType; string name = type.Name; if (type.MetadataType == MetadataType.Boolean) name = "flag"; else if (type.IsPrimitive) name = Enum.GetName(t_MetadataType, type.MetadataType); name = name.Substring(0, 1).ToLowerInvariant() + name.Substring(1); if (method == null) return i < 0 ? name : (name + i); // Check for usage as loop counter or similar? return i < 0 ? name : (name + i); } } }
using Mono.Cecil; using Mono.Cecil.Cil; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace MonoMod.DebugIL { public static class DebugILGeneratorExt { public readonly static Type t_MetadataType = typeof(MetadataType); public static ScopeDebugInformation GetOrAddScope(this MethodDebugInformation mdi) { if (mdi.Scope != null) return mdi.Scope; return mdi.Scope = new ScopeDebugInformation( mdi.Method.Body.Instructions[0], mdi.Method.Body.Instructions[mdi.Method.Body.Instructions.Count - 1] ); } public static string GenerateVariableName(this VariableDefinition @var, MethodDefinition method = null, int i = -1) { TypeReference type = @var.VariableType; while (type is TypeSpecification) type = ((TypeSpecification) type).ElementType; string name = type.Name; if (type.MetadataType == MetadataType.Boolean) name = "flag"; else if (type.IsPrimitive) name = Enum.GetName(t_MetadataType, type.MetadataType); name = name.Substring(0, 1).ToLowerInvariant() + name.Substring(1); if (method == null) return i < 0 ? name : (name + i); // Check for usage as loop counter or similar? return i < 0 ? name : (name + i); } } }
Fix GetStocks by reading the response in the proper format.
using System.Threading.Tasks; using Stockfighter.Helpers; namespace Stockfighter { public class Venue { public string Symbol { get; private set; } public Venue(string symbol) { Symbol = symbol; } public async Task<bool> IsUp() { using (var client = new Client()) { try { var response = await client.Get<Heartbeat>($"venues/{Symbol}/heartbeat"); return response.ok; } catch { return false; } } } public async Task<Stock[]> GetStocks() { using (var client = new Client()) { var stocks = await client.Get<Stock[]>($"venues/{Symbol}/stocks"); foreach (var stock in stocks) stock.Venue = Symbol; return stocks; } } private class Heartbeat { public bool ok { get; set; } public string venue { get; set; } } } }
using System.Threading.Tasks; using Stockfighter.Helpers; namespace Stockfighter { public class Venue { public string Symbol { get; private set; } public Venue(string symbol) { Symbol = symbol; } public async Task<bool> IsUp() { using (var client = new Client()) { try { var response = await client.Get<Heartbeat>($"venues/{Symbol}/heartbeat"); return response.ok; } catch { return false; } } } public async Task<Stock[]> GetStocks() { using (var client = new Client()) { var response = await client.Get<StocksResponse>($"venues/{Symbol}/stocks"); foreach (var stock in response.symbols) stock.Venue = Symbol; return response.symbols; } } private class Heartbeat { public bool ok { get; set; } public string venue { get; set; } } private class StocksResponse { public bool ok { get; set; } public Stock[] symbols { get; set; } } } }
Fix compiler error introduced by merge conflict
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; namespace RepoTasks.ProjectModel { internal class ProjectInfo { public ProjectInfo(string fullPath, IReadOnlyList<ProjectFrameworkInfo> frameworks, IReadOnlyList<DotNetCliReferenceInfo> tools, bool isPackable, string packageId, string packageVersion) { if (!Path.IsPathRooted(fullPath)) { throw new ArgumentException("Path must be absolute", nameof(fullPath)); } Frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks)); Tools = tools ?? throw new ArgumentNullException(nameof(tools)); FullPath = fullPath; FileName = Path.GetFileName(fullPath); Directory = Path.GetDirectoryName(FullPath); IsPackable = isPackable; PackageId = packageId; PackageVersion = packageVersion; } public string FullPath { get; } public string FileName { get; } public string Directory { get; } public string PackageId { get; } public string PackageVersion { get; } public bool IsPackable { get; } public SolutionInfo SolutionInfo { get; set; } public IReadOnlyList<ProjectFrameworkInfo> Frameworks { get; } public IReadOnlyList<DotNetCliReferenceInfo> Tools { get; } public SolutionInfo SolutionInfo { get; internal set; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; namespace RepoTasks.ProjectModel { internal class ProjectInfo { public ProjectInfo(string fullPath, IReadOnlyList<ProjectFrameworkInfo> frameworks, IReadOnlyList<DotNetCliReferenceInfo> tools, bool isPackable, string packageId, string packageVersion) { if (!Path.IsPathRooted(fullPath)) { throw new ArgumentException("Path must be absolute", nameof(fullPath)); } Frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks)); Tools = tools ?? throw new ArgumentNullException(nameof(tools)); FullPath = fullPath; FileName = Path.GetFileName(fullPath); Directory = Path.GetDirectoryName(FullPath); IsPackable = isPackable; PackageId = packageId; PackageVersion = packageVersion; } public string FullPath { get; } public string FileName { get; } public string Directory { get; } public string PackageId { get; } public string PackageVersion { get; } public bool IsPackable { get; } public SolutionInfo SolutionInfo { get; set; } public IReadOnlyList<ProjectFrameworkInfo> Frameworks { get; } public IReadOnlyList<DotNetCliReferenceInfo> Tools { get; } } }
Use FormatMessageHandler instead of eagerly formatting.
using System; using System.Threading.Tasks; using System.Web; using System.Web.UI; using Common.Logging; namespace NuGet.Lucene.Web { public static class UnhandledExceptionLogger { internal static readonly ILog Log = LogManager.GetLogger(typeof(UnhandledExceptionLogger)); public static void LogException(Exception exception) { LogException(exception, string.Format("Unhandled exception: {0}: {1}", exception.GetType(), exception.Message)); } public static void LogException(Exception exception, string message) { var log = GetLogSeverityDelegate(exception); log(m => m(message), exception.StackTrace != null ? exception : null); } private static Action<Action<FormatMessageHandler>, Exception> GetLogSeverityDelegate(Exception exception) { if (exception is HttpRequestValidationException || exception is ViewStateException) { return Log.Warn; } if (exception is TaskCanceledException || exception is OperationCanceledException) { return Log.Info; } var httpError = exception as HttpException; if (httpError != null && (httpError.ErrorCode == unchecked((int)0x80070057) || httpError.ErrorCode == unchecked((int)0x800704CD))) { // "The remote host closed the connection." return Log.Debug; } if (httpError != null && (httpError.GetHttpCode() < 500)) { return Log.Info; } return Log.Error; } } }
using System; using System.Threading.Tasks; using System.Web; using System.Web.UI; using Common.Logging; namespace NuGet.Lucene.Web { public static class UnhandledExceptionLogger { internal static readonly ILog Log = LogManager.GetLogger(typeof(UnhandledExceptionLogger)); public static void LogException(Exception exception) { LogException(exception, m => m("Unhandled exception: {0}: {1}", exception.GetType(), exception.Message)); } public static void LogException(Exception exception, Action<FormatMessageHandler> formatMessageCallback) { var log = GetLogSeverityDelegate(exception); log(formatMessageCallback, exception.StackTrace != null ? exception : null); } private static Action<Action<FormatMessageHandler>, Exception> GetLogSeverityDelegate(Exception exception) { if (exception is HttpRequestValidationException || exception is ViewStateException) { return Log.Warn; } if (exception is TaskCanceledException || exception is OperationCanceledException) { return Log.Info; } var httpError = exception as HttpException; if (httpError != null && (httpError.ErrorCode == unchecked((int)0x80070057) || httpError.ErrorCode == unchecked((int)0x800704CD))) { // "The remote host closed the connection." return Log.Debug; } if (httpError != null && (httpError.GetHttpCode() < 500)) { return Log.Info; } return Log.Error; } } }
Update message converter to access context
using Newtonsoft.Json; using System; using System.Globalization; using System.IO; using System.Text; namespace Glimpse { public class DefaultMessageConverter : IMessageConverter { private readonly JsonSerializer _jsonSerializer; public DefaultMessageConverter(JsonSerializer jsonSerializer) { _jsonSerializer = jsonSerializer; } public IMessageEnvelope ConvertMessage(IMessage message) { var newMessage = new MessageEnvelope(); newMessage.Type = message.GetType().FullName; newMessage.Payload = Serialize(message); return newMessage; } protected string Serialize(object data) { // Brought across from - https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConvert.cs#L635 var stringBuilder = new StringBuilder(256); using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture)) using (var jsonWriter = new JsonTextWriter(stringWriter)) { _jsonSerializer.Serialize(jsonWriter, data, data.GetType()); return stringWriter.ToString(); } } } }
using Newtonsoft.Json; using System; using System.Globalization; using System.IO; using System.Text; namespace Glimpse { public class DefaultMessageConverter : IMessageConverter { private readonly JsonSerializer _jsonSerializer; private readonly IServiceProvider _serviceProvider; public DefaultMessageConverter(JsonSerializer jsonSerializer, IServiceProvider serviceProvider) { _jsonSerializer = jsonSerializer; _serviceProvider = serviceProvider; } public IMessageEnvelope ConvertMessage(IMessage message) { //var context = (MessageContext)_serviceProvider.GetService(typeof(MessageContext)); var newMessage = new MessageEnvelope(); newMessage.Type = message.GetType().FullName; newMessage.Payload = Serialize(message); //newMessage.Context = context; return newMessage; } protected string Serialize(object data) { // Brought across from - https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConvert.cs#L635 var stringBuilder = new StringBuilder(256); using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture)) using (var jsonWriter = new JsonTextWriter(stringWriter)) { _jsonSerializer.Serialize(jsonWriter, data, data.GetType()); return stringWriter.ToString(); } } } }
Add ToString override to Process File
using System.ComponentModel; using System.Diagnostics; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("Process File")] public class ProcessFile : FilePath { public ProcessFile(string path) : base(path) { Path = path; } public ProcessFile() { } [PropertyOrder(2)] [DisplayName("Arguments")] public string Arguments { get; set; } = ""; [PropertyOrder(1)] [DisplayName("Start in Folder")] public string StartInFolder { get; set; } = ""; [PropertyOrder(3)] [DisplayName("Window Style")] public ProcessWindowStyle WindowStyle { get; set; } = ProcessWindowStyle.Normal; } }
using System.ComponentModel; using System.Diagnostics; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("Process File")] public class ProcessFile : FilePath { public ProcessFile(string path) : base(path) { Path = path; } public ProcessFile() { } [PropertyOrder(2)] [DisplayName("Arguments")] public string Arguments { get; set; } = ""; [PropertyOrder(1)] [DisplayName("Start in Folder")] public string StartInFolder { get; set; } = ""; [PropertyOrder(3)] [DisplayName("Window Style")] public ProcessWindowStyle WindowStyle { get; set; } = ProcessWindowStyle.Normal; public override string ToString() { return string.Join(" ", Path, Arguments); } } }
Add Start Manually option to IMEI prefab
using System; using UnityEngine; namespace com.adjust.sdk.imei { public class AdjustImei : MonoBehaviour { private const string errorMsgEditor = "[AdjustImei]: Adjust IMEI plugin can not be used in Editor."; private const string errorMsgPlatform = "[AdjustImei]: Adjust IMEI plugin can only be used in Android apps."; public bool readImei = false; void Awake() { if (IsEditor()) { return; } DontDestroyOnLoad(transform.gameObject); if (this.readImei) { AdjustImei.ReadImei(); } else { AdjustImei.DoNotReadImei(); } } public static void ReadImei() { if (IsEditor()) { return; } #if UNITY_ANDROID AdjustImeiAndroid.ReadImei(); #else Debug.Log(errorMsgPlatform); #endif } public static void DoNotReadImei() { if (IsEditor()) { return; } #if UNITY_ANDROID AdjustImeiAndroid.DoNotReadImei(); #else Debug.Log(errorMsgPlatform); #endif } private static bool IsEditor() { #if UNITY_EDITOR Debug.Log(errorMsgEditor); return true; #else return false; #endif } } }
using System; using UnityEngine; namespace com.adjust.sdk.imei { public class AdjustImei : MonoBehaviour { private const string errorMsgEditor = "[AdjustImei]: Adjust IMEI plugin can not be used in Editor."; private const string errorMsgPlatform = "[AdjustImei]: Adjust IMEI plugin can only be used in Android apps."; public bool startManually = true; public bool readImei = false; void Awake() { if (IsEditor()) { return; } DontDestroyOnLoad(transform.gameObject); if (!this.startManually) { if (this.readImei) { AdjustImei.ReadImei(); } else { AdjustImei.DoNotReadImei(); } } } public static void ReadImei() { if (IsEditor()) { return; } #if UNITY_ANDROID AdjustImeiAndroid.ReadImei(); #else Debug.Log(errorMsgPlatform); #endif } public static void DoNotReadImei() { if (IsEditor()) { return; } #if UNITY_ANDROID AdjustImeiAndroid.DoNotReadImei(); #else Debug.Log(errorMsgPlatform); #endif } private static bool IsEditor() { #if UNITY_EDITOR Debug.Log(errorMsgEditor); return true; #else return false; #endif } } }
Fix Trigger2D wrong method names
using UnityEngine; namespace Devdayo { [DisallowMultipleComponent] public class TriggerEnter2D : FsmEvent<Collider2D> { void OnTrigger2DEnter(Collider2D other) { Notify(other); } } [DisallowMultipleComponent] public class TriggerStay2D : FsmEvent<Collider2D> { void OnTrigger2DStay(Collider2D other) { Notify(other); } } [DisallowMultipleComponent] public class TriggerExit2D : FsmEvent<Collider2D> { void OnTrigger2DExit(Collider2D other) { Notify(other); } } }
using UnityEngine; namespace Devdayo { [DisallowMultipleComponent] public class TriggerEnter2D : FsmEvent<Collider2D> { void OnTriggerEnter2D(Collider2D other) { Notify(other); } } [DisallowMultipleComponent] public class TriggerStay2D : FsmEvent<Collider2D> { void OnTriggerStay2D(Collider2D other) { Notify(other); } } [DisallowMultipleComponent] public class TriggerExit2D : FsmEvent<Collider2D> { void OnTriggerExit2D(Collider2D other) { Notify(other); } } }
Make this interface disposable so taht code analysis should hopefully remind users to call .Dispose on it.
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Specialized; namespace CefSharp { public interface IRequest { string Url { get; set; } string Method { get; } string Body { get; } NameValueCollection Headers { get; set; } /// <summary> /// Get the transition type for this request. /// Applies to requests that represent a main frame or sub-frame navigation. /// </summary> TransitionType TransitionType { get; } } }
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Collections.Specialized; namespace CefSharp { public interface IRequest : IDisposable { string Url { get; set; } string Method { get; } string Body { get; } NameValueCollection Headers { get; set; } /// <summary> /// Get the transition type for this request. /// Applies to requests that represent a main frame or sub-frame navigation. /// </summary> TransitionType TransitionType { get; } } }
Add auth to Learners endpoint
using System; using System.Net; using System.Threading.Tasks; using MediatR; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using SFA.DAS.CommitmentsV2.Api.Types.Responses; using SFA.DAS.CommitmentsV2.Application.Queries.GetAllLearners; namespace SFA.DAS.CommitmentsV2.Api.Controllers { [ApiController] [Route("api/learners")] public class LearnerController : ControllerBase { private readonly IMediator _mediator; public LearnerController(IMediator mediator) { _mediator = mediator; } [HttpGet] public async Task<IActionResult> GetAllLearners(DateTime? sinceTime = null, int batch_number = 1, int batch_size = 1000) { var result = await _mediator.Send(new GetAllLearnersQuery(sinceTime, batch_number, batch_size)); var settings = new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd'T'HH:mm:ss" }; var jsonResult = new JsonResult(new GetAllLearnersResponse() { Learners = result.Learners, BatchNumber = result.BatchNumber, BatchSize = result.BatchSize, TotalNumberOfBatches = result.TotalNumberOfBatches }, settings); jsonResult.StatusCode = (int)HttpStatusCode.OK; jsonResult.ContentType = "application/json"; return jsonResult; } } }
using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using SFA.DAS.CommitmentsV2.Api.Types.Responses; using SFA.DAS.CommitmentsV2.Application.Queries.GetAllLearners; using System; using System.Net; using System.Threading.Tasks; namespace SFA.DAS.CommitmentsV2.Api.Controllers { [ApiController] [Authorize] [Route("api/learners")] public class LearnerController : ControllerBase { private readonly IMediator _mediator; public LearnerController(IMediator mediator) { _mediator = mediator; } [HttpGet] public async Task<IActionResult> GetAllLearners(DateTime? sinceTime = null, int batch_number = 1, int batch_size = 1000) { var result = await _mediator.Send(new GetAllLearnersQuery(sinceTime, batch_number, batch_size)); var settings = new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd'T'HH:mm:ss" }; var jsonResult = new JsonResult(new GetAllLearnersResponse() { Learners = result.Learners, BatchNumber = result.BatchNumber, BatchSize = result.BatchSize, TotalNumberOfBatches = result.TotalNumberOfBatches }, settings); jsonResult.StatusCode = (int)HttpStatusCode.OK; jsonResult.ContentType = "application/json"; return jsonResult; } } }
Check for AD credentials, check if local account
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Andromeda { public static class CredentialManager { public static string GetUser() { return "null"; } public static string GetPass() { return "null"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.DirectoryServices.AccountManagement; namespace Andromeda { public static class CredentialManager { public static string UserName { get; set; } public static string GetDomain() { return Environment.UserDomainName; } public static string GetUser() { return "null"; } public static string GetPass() { return "null"; } public static bool DoesUserExistInActiveDirectory(string userName) { try { using (var domainContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName)) { using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName)) { return foundUser != null; } } } catch (Exception ex) { return false; } } public static bool IsUserLocal(string userName) { bool exists = false; using (var domainContext = new PrincipalContext(ContextType.Machine)) { using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName)) { return true; } } return false; } } }
Replace the BELL character before writing to the console.
namespace ForwarderConsole { using System; using System.Text; public static class Print { public static void Error(string error) { InternalPrint("--- ERROR --", error, ConsoleColor.Red); } public static void Request(byte[] bytes) { string request = Encoding.ASCII.GetString(bytes); InternalPrint("--- REQUEST ---", request, ConsoleColor.White); } public static void Response(byte[] bytes) { string response = Encoding.ASCII.GetString(bytes); InternalPrint("--- RESPONSE ---", response, ConsoleColor.Yellow); } public static void Color(string message, ConsoleColor color) { Console.ForegroundColor = color; Console.WriteLine(message); } private static void InternalPrint(string header, string message, ConsoleColor color) { string txt = Line(header) + Line() + Line(message) + Line("=================================================="); Print.Color(txt, color); } private static string Line(string txt = "") { return txt + Environment.NewLine; } } }
namespace ForwarderConsole { using System; using System.Text; public static class Print { public static void Error(string error) { InternalPrint("--- ERROR --", error, ConsoleColor.Red); } public static void Request(byte[] bytes) { string request = Encoding.ASCII.GetString(bytes); InternalPrint("--- REQUEST ---", request, ConsoleColor.White); } public static void Response(byte[] bytes) { string response = Encoding.ASCII.GetString(bytes); InternalPrint("--- RESPONSE ---", response, ConsoleColor.Yellow); } public static void Color(string message, ConsoleColor color) { Console.ForegroundColor = color; // Replace the BELL character. message = message.Replace('\a', 'B'); Console.WriteLine(message); } private static void InternalPrint(string header, string message, ConsoleColor color) { string txt = Line(header) + Line() + Line(message) + Line("=================================================="); Print.Color(txt, color); } private static string Line(string txt = "") { return txt + Environment.NewLine; } } }
Add Bigsby Trovalds was here
using System; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!"); Console.WriteLine("Bigsby Gates was here!"); } } }
using System; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!"); Console.WriteLine("Bigsby Gates was here!"); Console.WriteLine("Bigsby Trovalds was here!"); } } }
Use the AppData instead of the CommonAppData folder to save the profile and settings, to avoid the UAC.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mime; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CloudNotes.DesktopClient { public static class Directories { private const string CloudNotesDataFolder = "CloudNotes"; public static string GetFullName(string fileOrDir) { #if DEBUG return Path.Combine(Application.StartupPath, fileOrDir); #else var path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), CloudNotesDataFolder); return Path.Combine(path, fileOrDir); #endif } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mime; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CloudNotes.DesktopClient { public static class Directories { private const string CloudNotesDataFolder = "CloudNotes"; public static string GetFullName(string fileOrDir) { #if DEBUG return Path.Combine(Application.StartupPath, fileOrDir); #else var path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), CloudNotesDataFolder); return Path.Combine(path, fileOrDir); #endif } } }
Clean up old BoundObject code
using CefSharp.Wpf; using System.Windows.Controls; namespace Cactbot { public partial class BrowserControl : UserControl { public BrowserControl() { DataContext = this; InitializeComponent(); CreationHandlers = delegate {}; } public delegate void OnBrowserCreation(object sender, IWpfWebBrowser browser); public OnBrowserCreation CreationHandlers { get; set; } public class BoundObject { public string MyProperty { get; set; } } private IWpfWebBrowser webBrowser; public IWpfWebBrowser WebBrowser { get { return webBrowser; } set { if (value != null) value.RegisterJsObject("bound", new BoundObject()); if (webBrowser == value) return; webBrowser = value; if (webBrowser != null) CreationHandlers(this, webBrowser); } } } }
using CefSharp.Wpf; using System.Windows.Controls; namespace Cactbot { public partial class BrowserControl : UserControl { public BrowserControl() { DataContext = this; InitializeComponent(); CreationHandlers = delegate {}; } public delegate void OnBrowserCreation(object sender, IWpfWebBrowser browser); public OnBrowserCreation CreationHandlers { get; set; } private IWpfWebBrowser webBrowser; public IWpfWebBrowser WebBrowser { get { return webBrowser; } set { if (webBrowser == value) return; webBrowser = value; if (webBrowser != null) CreationHandlers(this, webBrowser); } } } }
Use Id instead of fixed value
using System; namespace Business.Core { public partial class Individual { public IDatabase Database { get; private set; } public Individual(IDatabase database, UInt64? id = null) { Database = database; if(id != null) Load((UInt64)id); } private void Load(UInt64 id) { // Overwrite this object with Individual id Empty(); Id = id; // Default to person for now Person = true; if (Database != null) { Database.Connect(); Database.Connection.Open(); Database.Command.CommandText = GetIndividualSQL; Database.Command.Parameters.Add(new Parameter() { Name= "@id", Value = 3 }); var reader = Database.Command.ExecuteReader(); if (reader.HasRows) { if (reader.Read()) { try { FullName = reader.GetString(0); GoesBy = reader.GetString(1); } catch (Exception ex) { // Some sort of type or data issue Database.Profile.Log?.Error($"reading Individual: {ex.Message}"); } } } } } private const string GetIndividualSQL = @" SELECT fullname, goesBy FROM People WHERE individual = @id "; } }
using System; namespace Business.Core { public partial class Individual { public IDatabase Database { get; private set; } public Individual(IDatabase database, UInt64? id = null) { Database = database; if(id != null) Load((UInt64)id); } private void Load(UInt64 id) { // Overwrite this object with Individual id Empty(); Id = id; // Default to person for now Person = true; if (Database != null) { Database.Connect(); Database.Connection.Open(); Database.Command.CommandText = GetIndividualSQL; Database.Command.Parameters.Add(new Parameter() { Name= "@id", Value = id }); var reader = Database.Command.ExecuteReader(); if (reader.HasRows) { if (reader.Read()) { try { FullName = reader.GetString(0); GoesBy = reader.GetString(1); } catch (Exception ex) { // Some sort of type or data issue Database.Profile.Log?.Error($"reading Individual: {ex.Message}"); } } } } } private const string GetIndividualSQL = @" SELECT fullname, goesBY FROM ( SELECT fullname, goesBy FROM People WHERE individual = @id UNION SELECT name AS fullname, goesBy FROM Entities WHERE individual = @id ) AS Individual LIMIT 1 "; } }
Fix ctor to take arbitrary object type as model.
// ViewUserControl.cs // Copyright (c) Nikhil Kothari, 2008. All Rights Reserved. // http://www.nikhilk.net // // Silverlight.FX is an application framework for building RIAs with Silverlight. // This project is licensed under the BSD license. See the accompanying License.txt // file for more information. // For updated project information please visit http://projects.nikhilk.net/SilverlightFX. // using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; namespace SilverlightFX.UserInterface { /// <summary> /// Represents a user control within the application's user interface. /// </summary> public class ViewUserControl : View { /// <summary> /// Initializes an instance of a ViewUserControl. /// </summary> public ViewUserControl() { } /// <summary> /// Initializes an instance of a ViewUserControl with an associated view model. /// The view model is set as the DataContext of the Form. /// </summary> /// <param name="viewModel">The associated view model object.</param> public ViewUserControl(Model viewModel) : base(viewModel) { } } }
// ViewUserControl.cs // Copyright (c) Nikhil Kothari, 2008. All Rights Reserved. // http://www.nikhilk.net // // Silverlight.FX is an application framework for building RIAs with Silverlight. // This project is licensed under the BSD license. See the accompanying License.txt // file for more information. // For updated project information please visit http://projects.nikhilk.net/SilverlightFX. // using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; namespace SilverlightFX.UserInterface { /// <summary> /// Represents a user control within the application's user interface. /// </summary> public class ViewUserControl : View { /// <summary> /// Initializes an instance of a ViewUserControl. /// </summary> public ViewUserControl() { } /// <summary> /// Initializes an instance of a ViewUserControl with an associated view model. /// The view model is set as the DataContext of the Form. /// </summary> /// <param name="viewModel">The associated view model object.</param> public ViewUserControl(object viewModel) : base(viewModel) { } } }
Remove duplicate addresses before converting to dictionary
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; namespace Nowin { public class IpIsLocalChecker : IIpIsLocalChecker { readonly Dictionary<IPAddress, bool> _dict; public IpIsLocalChecker() { var host = Dns.GetHostEntry(Dns.GetHostName()); _dict = host.AddressList.Where( a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6). ToDictionary(p => p, p => true); _dict[IPAddress.Loopback] = true; _dict[IPAddress.IPv6Loopback] = true; } public bool IsLocal(IPAddress address) { return _dict.ContainsKey(address); } } }
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; namespace Nowin { public class IpIsLocalChecker : IIpIsLocalChecker { readonly Dictionary<IPAddress, bool> _dict; public IpIsLocalChecker() { var host = Dns.GetHostEntry(Dns.GetHostName()); _dict = host.AddressList.Where( a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6) .Distinct() .ToDictionary(p => p, p => true); _dict[IPAddress.Loopback] = true; _dict[IPAddress.IPv6Loopback] = true; } public bool IsLocal(IPAddress address) { return _dict.ContainsKey(address); } } }
Change default attributeStyle to lower for search
using System; using System.Net.Http; using System.Web.Http.Controllers; using System.Web.Http.ModelBinding; using WebAPI.Domain.InputOptions; namespace WebAPI.API.ModelBindings { public class SearchOptionsModelBinding : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var keyValueModel = actionContext.Request.RequestUri.ParseQueryString(); string pointJson = keyValueModel["geometry"], spatialReference = keyValueModel["spatialReference"], predicate = keyValueModel["predicate"], attribute = keyValueModel["attributeStyle"], bufferAmount = keyValueModel["buffer"]; int wkid; var attributeType = AttributeStyle.Camel; int.TryParse(string.IsNullOrEmpty(spatialReference) ? "26912" : spatialReference, out wkid); try { attributeType = (AttributeStyle) Enum.Parse(typeof(AttributeStyle), string.IsNullOrEmpty(attribute) ? "Camel" : attribute, true); } catch (Exception) { /*ie sometimes sends display value in text box.*/ } double buffer; double.TryParse(string.IsNullOrEmpty(bufferAmount) ? "0" : bufferAmount, out buffer); bindingContext.Model = new SearchOptions { Geometry = pointJson, Predicate = predicate, WkId = wkid, Buffer = buffer, AttributeStyle = attributeType }; return true; } } }
using System; using System.Net.Http; using System.Web.Http.Controllers; using System.Web.Http.ModelBinding; using WebAPI.Domain.InputOptions; namespace WebAPI.API.ModelBindings { public class SearchOptionsModelBinding : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var keyValueModel = actionContext.Request.RequestUri.ParseQueryString(); string pointJson = keyValueModel["geometry"], spatialReference = keyValueModel["spatialReference"], predicate = keyValueModel["predicate"], attribute = keyValueModel["attributeStyle"], bufferAmount = keyValueModel["buffer"]; int wkid; var attributeType = AttributeStyle.Camel; int.TryParse(string.IsNullOrEmpty(spatialReference) ? "26912" : spatialReference, out wkid); try { attributeType = (AttributeStyle) Enum.Parse(typeof(AttributeStyle), string.IsNullOrEmpty(attribute) ? "Lower" : attribute, true); } catch (Exception) { /*ie sometimes sends display value in text box.*/ } double buffer; double.TryParse(string.IsNullOrEmpty(bufferAmount) ? "0" : bufferAmount, out buffer); bindingContext.Model = new SearchOptions { Geometry = pointJson, Predicate = predicate, WkId = wkid, Buffer = buffer, AttributeStyle = attributeType }; return true; } } }
Fix incorrect file path in benchmarks
using System.IO; using BenchmarkDotNet.Attributes; using FreeImageAPI; using ImageMagick; using DS = DevILSharp; namespace Pfim.Benchmarks { public class TargaBenchmark { [Params("true-32-rle-large.tga", "true-24-large.tga", "true-24.tga", "true-32-rle.tga", "rgb24_top_left")] public string Payload { get; set; } private byte[] data; [GlobalSetup] public void SetupData() { data = File.ReadAllBytes(Payload); DS.Bootstrap.Init(); } [Benchmark] public IImage Pfim() => Targa.Create(new MemoryStream(data)); [Benchmark] public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data)); [Benchmark] public int ImageMagick() { var settings = new MagickReadSettings {Format = MagickFormat.Tga}; using (var image = new MagickImage(new MemoryStream(data), settings)) { return image.Width; } } [Benchmark] public int DevILSharp() { using (var image = DS.Image.Load(data, DS.ImageType.Tga)) { return image.Width; } } [Benchmark] public int TargaImage() { using (var image = new Paloma.TargaImage(new MemoryStream(data))) { return image.Stride; } } } }
using System.IO; using BenchmarkDotNet.Attributes; using FreeImageAPI; using ImageMagick; using DS = DevILSharp; namespace Pfim.Benchmarks { public class TargaBenchmark { [Params("true-32-rle-large.tga", "true-24-large.tga", "true-24.tga", "true-32-rle.tga", "rgb24_top_left.tga")] public string Payload { get; set; } private byte[] data; [GlobalSetup] public void SetupData() { data = File.ReadAllBytes(Payload); DS.Bootstrap.Init(); } [Benchmark] public IImage Pfim() => Targa.Create(new MemoryStream(data)); [Benchmark] public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data)); [Benchmark] public int ImageMagick() { var settings = new MagickReadSettings {Format = MagickFormat.Tga}; using (var image = new MagickImage(new MemoryStream(data), settings)) { return image.Width; } } [Benchmark] public int DevILSharp() { using (var image = DS.Image.Load(data, DS.ImageType.Tga)) { return image.Width; } } [Benchmark] public int TargaImage() { using (var image = new Paloma.TargaImage(new MemoryStream(data))) { return image.Stride; } } } }
Use <Title in about page.
@page "/about" @inject Navigator Navigator <h1>Money</h1> <h4>Neptuo</h4> <p class="gray"> v@(typeof(About).Assembly.GetName().Version.ToString(3)) </p> <p> <a target="_blank" href="@Navigator.UrlMoneyProject()">Documentation</a> </p> <p> <a target="_blank" href="@Navigator.UrlMoneyProjectIssueNew()">Report an issue</a> </p>
@page "/about" @inject Navigator Navigator <Title Main="Money" Sub="Nepuo" /> <p class="gray"> v@(typeof(About).Assembly.GetName().Version.ToString(3)) </p> <p> <a target="_blank" href="@Navigator.UrlMoneyProject()">Documentation</a> </p> <p> <a target="_blank" href="@Navigator.UrlMoneyProjectIssueNew()">Report an issue</a> </p>
Set port to -1 if port is 80
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNet.SignalR.Owin; namespace JabbR.Middleware { using AppFunc = Func<IDictionary<string, object>, Task>; public class RequireHttpsHandler { private readonly AppFunc _next; public RequireHttpsHandler(AppFunc next) { _next = next; } public Task Invoke(IDictionary<string, object> env) { var request = new ServerRequest(env); var response = new Gate.Response(env); if (!request.Url.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) { var builder = new UriBuilder(request.Url); builder.Scheme = "https"; response.SetHeader("Location", builder.ToString()); response.StatusCode = 302; return TaskAsyncHelper.Empty; } else { return _next(env); } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNet.SignalR.Owin; namespace JabbR.Middleware { using AppFunc = Func<IDictionary<string, object>, Task>; public class RequireHttpsHandler { private readonly AppFunc _next; public RequireHttpsHandler(AppFunc next) { _next = next; } public Task Invoke(IDictionary<string, object> env) { var request = new ServerRequest(env); var response = new Gate.Response(env); if (!request.Url.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) { var builder = new UriBuilder(request.Url); builder.Scheme = "https"; if (builder.Port == 80) { builder.Port = -1; } response.SetHeader("Location", builder.ToString()); response.StatusCode = 302; return TaskAsyncHelper.Empty; } else { return _next(env); } } } }
Add GetExtent to viewport extensions
using Mapsui.Utilities; using System; using System.Collections.Generic; using System.Text; namespace Mapsui.Extensions { public static class ViewportExtensions { /// <summary> /// True if Width and Height are not zero /// </summary> public static bool HasSize(this IReadOnlyViewport viewport) => !viewport.Width.IsNanOrInfOrZero() && !viewport.Height.IsNanOrInfOrZero(); /// <summary> /// IsRotated is true, when viewport displays map rotated /// </summary> public static bool IsRotated(this IReadOnlyViewport viewport) => !double.IsNaN(viewport.Rotation) && viewport.Rotation > Constants.Epsilon && viewport.Rotation < 360 - Constants.Epsilon; } }
using Mapsui.Utilities; using System; using System.Collections.Generic; using System.Text; namespace Mapsui.Extensions { public static class ViewportExtensions { /// <summary> /// True if Width and Height are not zero /// </summary> public static bool HasSize(this IReadOnlyViewport viewport) => !viewport.Width.IsNanOrInfOrZero() && !viewport.Height.IsNanOrInfOrZero(); /// <summary> /// IsRotated is true, when viewport displays map rotated /// </summary> public static bool IsRotated(this IReadOnlyViewport viewport) => !double.IsNaN(viewport.Rotation) && viewport.Rotation > Constants.Epsilon && viewport.Rotation < 360 - Constants.Epsilon; /// <summary> /// Calculates extent from the viewport /// </summary> /// <remarks> /// This MRect is horizontally and vertically aligned, even if the viewport /// is rotated. So this MRect perhaps contain parts, that are not visible. /// </remarks> public static MRect GetExtent(this IReadOnlyViewport viewport) { // calculate the window extent var halfSpanX = viewport.Width * viewport.Resolution * 0.5; var halfSpanY = viewport.Height * viewport.Resolution * 0.5; var minX = viewport.CenterX - halfSpanX; var minY = viewport.CenterY - halfSpanY; var maxX = viewport.CenterX + halfSpanX; var maxY = viewport.CenterY + halfSpanY; if (!viewport.IsRotated()) { return new MRect(minX, minY, maxX, maxY); } else { var windowExtent = new MQuad { BottomLeft = new MPoint(minX, minY), TopLeft = new MPoint(minX, maxY), TopRight = new MPoint(maxX, maxY), BottomRight = new MPoint(maxX, minY) }; // Calculate the extent that will encompass a rotated viewport (slightly larger - used for tiles). // Perform rotations on corner offsets and then add them to the Center point. return windowExtent.Rotate(-viewport.Rotation, viewport.CenterX, viewport.CenterY).ToBoundingBox(); } } } }
Change guild permissions to have ReadGuildConfig when ViewAuditLog is true.
using Discord; using System; namespace MitternachtWeb.Models { [Flags] public enum BotLevelPermission { None = 0b_0000, ReadBotConfig = 0b_0001, WriteBotConfig = 0b_0011, ReadAllGuildConfigs = 0b_0100, WriteAllGuildConfigs = 0b_1100, All = 0b_1111, } [Flags] public enum GuildLevelPermission { None = 0b_0000_0000, ReadGuildConfig = 0b_0000_0001, WriteGuildConfig = 0b_0000_0011, } public static class PagePermissionExtensions { public static GuildLevelPermission GetGuildPagePermissions(this GuildPermissions guildPerms) { var perms = GuildLevelPermission.None; if(guildPerms.KickMembers) { perms |= GuildLevelPermission.ReadGuildConfig; } if(guildPerms.Administrator) { perms |= GuildLevelPermission.WriteGuildConfig; } return perms; } } }
using Discord; using System; namespace MitternachtWeb.Models { [Flags] public enum BotLevelPermission { None = 0b_0000, ReadBotConfig = 0b_0001, WriteBotConfig = 0b_0011, ReadAllGuildConfigs = 0b_0100, WriteAllGuildConfigs = 0b_1100, All = 0b_1111, } [Flags] public enum GuildLevelPermission { None = 0b_0000_0000, ReadGuildConfig = 0b_0000_0001, WriteGuildConfig = 0b_0000_0011, } public static class PagePermissionExtensions { public static GuildLevelPermission GetGuildPagePermissions(this GuildPermissions guildPerms) { var perms = GuildLevelPermission.None; if(guildPerms.ViewAuditLog) { perms |= GuildLevelPermission.ReadGuildConfig; } if(guildPerms.Administrator) { perms |= GuildLevelPermission.WriteGuildConfig; } return perms; } } }
Use ParallelEnumerable in puzzle 10
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle010 : Puzzle { /// <inheritdoc /> public override string Question => "Find the sum of all the primes below the specified value."; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int max; if (!TryParseInt32(args[0], out max) || max < 2) { Console.Error.WriteLine("The specified number is invalid."); return -1; } Answer = Enumerable.Range(2, max - 2) .AsParallel() .Where((p) => Maths.IsPrime(p)) .Select((p) => (long)p) .Sum(); return 0; } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle010 : Puzzle { /// <inheritdoc /> public override string Question => "Find the sum of all the primes below the specified value."; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int max; if (!TryParseInt32(args[0], out max) || max < 2) { Console.Error.WriteLine("The specified number is invalid."); return -1; } Answer = ParallelEnumerable.Range(2, max - 2) .Where((p) => Maths.IsPrime(p)) .Select((p) => (long)p) .Sum(); return 0; } } }
Remove unused variable compiler warning when building release build.
using CommonUtil.Disk; namespace Common { public static class SourceDirectoryFinder { private static string crayonSourceDirectoryCached = null; public static string CrayonSourceDirectory { // Presumably running from source. Walk up to the root directory and find the Libraries directory. // From there use the list of folders. // TODO: mark this as DEBUG only get { #if DEBUG if (crayonSourceDirectoryCached == null) { string currentDirectory = Path.GetCurrentDirectory(); while (!string.IsNullOrEmpty(currentDirectory)) { string librariesPath = FileUtil.JoinPath(currentDirectory, "Libraries"); if (FileUtil.DirectoryExists(librariesPath) && FileUtil.FileExists(FileUtil.JoinPath(currentDirectory, "Compiler", "CrayonWindows.sln"))) // quick sanity check { crayonSourceDirectoryCached = currentDirectory; break; } currentDirectory = FileUtil.GetParentDirectory(currentDirectory); } } return crayonSourceDirectoryCached; #else return null; #endif } } } }
using CommonUtil.Disk; namespace Common { public static class SourceDirectoryFinder { private static string crayonSourceDirectoryCached = null; public static string CrayonSourceDirectory { // Presumably running from source. Walk up to the root directory and find the Libraries directory. // From there use the list of folders. // TODO: mark this as DEBUG only get { #if DEBUG if (crayonSourceDirectoryCached == null) { string currentDirectory = Path.GetCurrentDirectory(); while (!string.IsNullOrEmpty(currentDirectory)) { string librariesPath = FileUtil.JoinPath(currentDirectory, "Libraries"); if (FileUtil.DirectoryExists(librariesPath) && FileUtil.FileExists(FileUtil.JoinPath(currentDirectory, "Compiler", "CrayonWindows.sln"))) // quick sanity check { crayonSourceDirectoryCached = currentDirectory; break; } currentDirectory = FileUtil.GetParentDirectory(currentDirectory); } } #endif return crayonSourceDirectoryCached; } } } }
Remove unhelpful line of code.
using System; using Microsoft.AspNet.SignalR; using Microsoft.Owin; using Microsoft.Owin.Cors; using Owin; [assembly: OwinStartup(typeof(SignInCheckIn.Startup))] [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] namespace SignInCheckIn { public class Startup { public void Configuration(IAppBuilder app) { GlobalHost.Configuration.TransportConnectTimeout = TimeSpan.FromSeconds(15); // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888 // Branch the pipeline here for requests that start with /signalr app.Map("/signalr", map => { // Setup the CORS middleware to run before SignalR. // By default this will allow all origins. You can // configure the set of origins and/or http verbs by // providing a cors options with a different policy. map.UseCors(CorsOptions.AllowAll); // Run the SignalR pipeline. We're not using MapSignalR // since this branch already runs under the /signalr // path. map.RunSignalR(); }); } } }
using System; using Microsoft.AspNet.SignalR; using Microsoft.Owin; using Microsoft.Owin.Cors; using Owin; [assembly: OwinStartup(typeof(SignInCheckIn.Startup))] [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] namespace SignInCheckIn { public class Startup { public void Configuration(IAppBuilder app) { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888 // Branch the pipeline here for requests that start with /signalr app.Map("/signalr", map => { // Setup the CORS middleware to run before SignalR. // By default this will allow all origins. You can // configure the set of origins and/or http verbs by // providing a cors options with a different policy. map.UseCors(CorsOptions.AllowAll); // Run the SignalR pipeline. We're not using MapSignalR // since this branch already runs under the /signalr // path. map.RunSignalR(); }); } } }
Remove test fire schedule for eval due
using FluentScheduler; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; using System; namespace BatteryCommander.Web.Jobs { internal static class JobHandler { public static void UseJobScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory) { var logger = loggerFactory.CreateLogger(typeof(JobHandler)); JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name); JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration); JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name); JobManager.UseUtcTime(); JobManager.JobFactory = new JobFactory(app.ApplicationServices); var registry = new Registry(); registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().At(hours: 11, minutes: 0); registry.Schedule<EvaluationDueReminderJob>().ToRunNow(); // registry.Schedule<EvaluationDueReminderJob>().ToRunEvery(1).Weeks().On(DayOfWeek.Friday).At(hours: 12, minutes: 0); JobManager.Initialize(registry); } private class JobFactory : IJobFactory { private readonly IServiceProvider serviceProvider; public JobFactory(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } public IJob GetJobInstance<T>() where T : IJob { return serviceProvider.GetService(typeof(T)) as IJob; } } } }
using FluentScheduler; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; using System; namespace BatteryCommander.Web.Jobs { internal static class JobHandler { public static void UseJobScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory) { var logger = loggerFactory.CreateLogger(typeof(JobHandler)); JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name); JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration); JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name); JobManager.UseUtcTime(); JobManager.JobFactory = new JobFactory(app.ApplicationServices); var registry = new Registry(); registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().At(hours: 11, minutes: 0); registry.Schedule<EvaluationDueReminderJob>().ToRunEvery(1).Weeks().On(DayOfWeek.Friday).At(hours: 12, minutes: 0); JobManager.Initialize(registry); } private class JobFactory : IJobFactory { private readonly IServiceProvider serviceProvider; public JobFactory(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } public IJob GetJobInstance<T>() where T : IJob { return serviceProvider.GetService(typeof(T)) as IJob; } } } }
Update assembly info - copyright date
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalAssemblyInfo.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Helix Toolkit")] [assembly: AssemblyCompany("Helix Toolkit")] [assembly: AssemblyCopyright("Copyright (C) Helix Toolkit 2018.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The version numbers are patched by GitVersion, see the `before_build` step in appveyor.yml [assembly: AssemblyVersion("0.0.0.1")] [assembly: AssemblyFileVersion("0.0.0.1")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalAssemblyInfo.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Helix Toolkit")] [assembly: AssemblyCompany("Helix Toolkit")] [assembly: AssemblyCopyright("Copyright (C) Helix Toolkit 2019.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The version numbers are patched by GitVersion, see the `before_build` step in appveyor.yml [assembly: AssemblyVersion("0.0.0.1")] [assembly: AssemblyFileVersion("0.0.0.1")]
Fix Razor tag helpers and usings
@using Dangl.WebDocumentation @using Dangl.WebDocumentation.Models @using Dangl.WebDocumentation.ViewModels.Account @using Dangl.WebDocumentation.ViewModels.Manage @using Microsoft.AspNet.Identity @addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" @inject Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration TelemetryConfiguration
@using Dangl.WebDocumentation @using Dangl.WebDocumentation.Models @using Dangl.WebDocumentation.ViewModels.Account @using Dangl.WebDocumentation.ViewModels.Manage @using Microsoft.AspNetCore.Identity @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Update ViewComponentContext to respond to changed type
 namespace Glimpse.Agent.Internal.Inspectors.Mvc.Proxies { public interface IViewComponentContext { IViewComponentDescriptor ViewComponentDescriptor { get; } object[] Arguments { get; } } }
 using System.Collections.Generic; namespace Glimpse.Agent.Internal.Inspectors.Mvc.Proxies { public interface IViewComponentContext { IViewComponentDescriptor ViewComponentDescriptor { get; } IDictionary<string, object> Arguments { get; } } }
Convert to minutes in the duration display
@model Dashboard.Models.JobSummary @{ ViewBag.Title = $"{Model.Name} Summary"; var summaryValues = string.Join( ";", Model.JobDaySummaryList.Select(x => $"{x.Date.ToLocalTime().ToString("yyyy-MM-dd")},{x.Succeeded},{x.Failed},{x.Aborted}")); var durationDates = string.Join( ";", Model.JobDaySummaryList.Select(x => x.Date.ToLocalTime().ToString("yyyy-MM-dd")).ToArray()); var durationTimes = string.Join( ";", Model.JobDaySummaryList.Select(x => x.AverageDuration.TotalSeconds).ToArray()); } <h2>@Model.Name</h2> <div>Average Duration: @Model.AverageDuration</div> <div id="daily_summary_chart" style="width: 900px; height: 500px" data-values="@summaryValues"></div> <div id="daily_duration_chart" style="width: 900px; height: 500px" data-dates="@durationDates" data-times="@durationTimes"></div> @section scripts { <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript" src="@Url.Content("/Scripts/job-build-data.js")" ></script> }
@model Dashboard.Models.JobSummary @{ ViewBag.Title = $"{Model.Name} Summary"; var jobs = Model.JobDaySummaryList.OrderBy(x => x.Date); var summaryValues = string.Join( ";", jobs.Select(x => $"{x.Date.ToLocalTime().ToString("yyyy-MM-dd")},{x.Succeeded},{x.Failed},{x.Aborted}")); var durationDates = string.Join( ";", jobs.Select(x => x.Date.ToLocalTime().ToString("yyyy-MM-dd")).ToArray()); var durationTimes = string.Join( ";", jobs.Select(x => x.AverageDuration.TotalMinutes).ToArray()); } <h2>@Model.Name</h2> <div>Average Duration: @Model.AverageDuration</div> <div id="daily_summary_chart" style="width: 900px; height: 500px" data-values="@summaryValues"></div> <div id="daily_duration_chart" style="width: 900px; height: 500px" data-dates="@durationDates" data-times="@durationTimes"></div> @section scripts { <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript" src="@Url.Content("/Scripts/job-build-data.js")" ></script> }
Allow progress dialog ready API call to proceed without sync (BL-11484)
using System; using System.IO; using System.Net; using System.Windows.Forms; using Bloom.Api; using Bloom.Book; using Bloom.MiscUI; using Bloom.Publish; using Bloom.Utils; using SIL.IO; namespace Bloom.web.controllers { public class ProgressDialogApi { private static Action _cancelHandler; public static void SetCancelHandler(Action cancelHandler) { _cancelHandler = cancelHandler; } public void RegisterWithApiHandler(BloomApiHandler apiHandler) { apiHandler.RegisterEndpointLegacy("progress/cancel", Cancel, false, false); apiHandler.RegisterEndpointHandler("progress/closed", BrowserProgressDialog.HandleProgressDialogClosed, false); apiHandler.RegisterEndpointHandler("progress/ready", BrowserProgressDialog.HandleProgressReady, false); } private void Cancel(ApiRequest request) { // if it's null, and that causes a throw, well... that *is* an error situation _cancelHandler(); request.PostSucceeded(); } } }
using System; using System.IO; using System.Net; using System.Windows.Forms; using Bloom.Api; using Bloom.Book; using Bloom.MiscUI; using Bloom.Publish; using Bloom.Utils; using SIL.IO; namespace Bloom.web.controllers { public class ProgressDialogApi { private static Action _cancelHandler; public static void SetCancelHandler(Action cancelHandler) { _cancelHandler = cancelHandler; } public void RegisterWithApiHandler(BloomApiHandler apiHandler) { apiHandler.RegisterEndpointLegacy("progress/cancel", Cancel, false, false); apiHandler.RegisterEndpointHandler("progress/closed", BrowserProgressDialog.HandleProgressDialogClosed, false); // Doesn't need sync because all it does is set a flag, which nothing else modifies. // Mustn't need sync because we may be processing another request (e.g., creating a TC) when we launch the dialog // that we want to know is ready to receive messages. apiHandler.RegisterEndpointHandler("progress/ready", BrowserProgressDialog.HandleProgressReady, false, false); } private void Cancel(ApiRequest request) { // if it's null, and that causes a throw, well... that *is* an error situation _cancelHandler(); request.PostSucceeded(); } } }
Add (temporary) event handler delegate.
using System; using Microsoft.SPOT; namespace IntervalTimer { public class IntervalTimer { public TimeSpan ShortDuration { get; set; } public TimeSpan LongDuration { get; set; } public IntervalTimer(TimeSpan shortDuration, TimeSpan longDuration) { ShortDuration = shortDuration; LongDuration = longDuration; } public IntervalTimer(int shortSeconds, int longSeconds) { ShortDuration = new TimeSpan(0, 0, shortSeconds); LongDuration = new TimeSpan(0, 0, longSeconds); } } }
using System; using Microsoft.SPOT; namespace IntervalTimer { public delegate void IntervalEventHandler(object sender, EventArgs e); public class IntervalTimer { public TimeSpan ShortDuration { get; set; } public TimeSpan LongDuration { get; set; } public IntervalTimer(TimeSpan shortDuration, TimeSpan longDuration) { ShortDuration = shortDuration; LongDuration = longDuration; } public IntervalTimer(int shortSeconds, int longSeconds) { ShortDuration = new TimeSpan(0, 0, shortSeconds); LongDuration = new TimeSpan(0, 0, longSeconds); } } }
Add double click to copy functionality
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace clipman.Views { /// <summary> /// Interaction logic for ClipList.xaml /// </summary> public partial class ClipList : UserControl { public ClipList() { InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace clipman.Views { /// <summary> /// Interaction logic for ClipList.xaml /// </summary> public partial class ClipList : UserControl { public ClipList() { InitializeComponent(); } private void Copy(object sender, MouseButtonEventArgs e) { Console.WriteLine("Trying to copy"); var clip = (Models.Clip)(sender as ListBoxItem).DataContext; var parentWindow = Window.GetWindow(this) as MainWindow; if (parentWindow != null) { parentWindow.HasJustCopied = true; } clip.Copy(); } } }
Change invalid character enum to make more send (None becomes Error)
 /// <summary> /// Action to take if the message text contains an invalid character /// Valid characters are defined in the GSM 03.38 character set /// </summary> public enum InvalidCharacterAction { /// <summary> /// Use the default setting from your account /// </summary> AccountDefault = 0, /// <summary> /// Take no action /// </summary> None = 1, /// <summary> /// Remove any Non-GSM character /// </summary> Remove = 2, /// <summary> /// Replace Non-GSM characters where possible /// remove any others /// </summary> Replace = 3 }
 /// <summary> /// Action to take if the message text contains an invalid character /// Valid characters are defined in the GSM 03.38 character set /// </summary> public enum InvalidCharacterAction { /// <summary> /// Use the default setting from your account /// </summary> AccountDefault = 0, /// <summary> /// Return an error if a Non-GSM character is found /// </summary> Error = 1, /// <summary> /// Remove any Non-GSM character /// </summary> Remove = 2, /// <summary> /// Replace Non-GSM characters where possible /// remove any others /// </summary> Replace = 3 }
Update version number to 0.3.0.0.
using System.Reflection; 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("TrayLeds")] [assembly: AssemblyDescription("Tray Notification Leds")] [assembly: AssemblyProduct("TrayLeds")] [assembly: AssemblyCopyright("Copyright © Carlos Alberto Costa Beppler 2017")] // 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("eecfb156-872b-498d-9a01-42d37066d3d4")] // 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.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")]
using System.Reflection; 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("TrayLeds")] [assembly: AssemblyDescription("Tray Notification Leds")] [assembly: AssemblyProduct("TrayLeds")] [assembly: AssemblyCopyright("Copyright © Carlos Alberto Costa Beppler 2017")] // 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("eecfb156-872b-498d-9a01-42d37066d3d4")] // 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.3.0.0")] [assembly: AssemblyFileVersion("0.3.0.0")]
Set title for console window.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DangerousPanel_Server { class Program { static void Main(string[] args) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DangerousPanel_Server { class Program { static void Log(string text, ConsoleColor color) { ConsoleColor oldColor = Console.ForegroundColor; Console.ForegroundColor = color; Console.WriteLine(text); Console.ForegroundColor = oldColor; } static void Main(string[] args) { Console.Title = "Dangerous Panel Server"; Log("Dangerous Panel Server (by Mitchfizz05)", ConsoleColor.Cyan); Console.ReadKey(); } } }
Rewrite request path to serve up index instead of sending it without content type
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.StaticFiles; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Logging; namespace DocNuget { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.MinimumLevel = LogLevel.Debug; loggerFactory.AddConsole(LogLevel.Debug); app .UseErrorPage() .UseDefaultFiles() .UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true, }) .UseMvc() .UseSendFileFallback() .Use(async (context, next) => { await context.Response.SendFileAsync("wwwroot/index.html"); }); } } }
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.StaticFiles; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Logging; namespace DocNuget { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.MinimumLevel = LogLevel.Debug; loggerFactory.AddConsole(LogLevel.Debug); app .UseErrorPage() .UseDefaultFiles() .UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true, }) .UseMvc() .Use((context, next) => { context.Request.Path = new PathString("/index.html"); return next(); }) .UseStaticFiles(); } } }
Add a GetRootNode method, to match the interface of the sdk.
using System; using System.Collections.Generic; namespace FbxSharp { public class Scene : Document { public Scene(string name="") { RootNode = new Node(); Nodes.Add(RootNode); } public List<Node> Nodes = new List<Node>(); public Node RootNode { get; protected set; } } }
using System; using System.Collections.Generic; namespace FbxSharp { public class Scene : Document { public Scene(string name="") { RootNode = new Node(); Nodes.Add(RootNode); } public List<Node> Nodes = new List<Node>(); public Node RootNode { get; protected set; } public Node GetRootNode() { return RootNode; } } }
Fix typo: ouath -> oauth
using System; using System.Collections.Generic; #if NET_45 using System.Collections.ObjectModel; #endif namespace Octokit { /// <summary> /// Extra information returned as part of each api response. /// </summary> public class ApiInfo { public ApiInfo(IDictionary<string, Uri> links, IList<string> oauthScopes, IList<string> acceptedOauthScopes, string etag, RateLimit rateLimit) { Ensure.ArgumentNotNull(links, "links"); Ensure.ArgumentNotNull(oauthScopes, "ouathScopes"); Links = new ReadOnlyDictionary<string, Uri>(links); OauthScopes = new ReadOnlyCollection<string>(oauthScopes); AcceptedOauthScopes = new ReadOnlyCollection<string>(acceptedOauthScopes); Etag = etag; RateLimit = rateLimit; } /// <summary> /// Oauth scopes that were included in the token used to make the request. /// </summary> public IReadOnlyList<string> OauthScopes { get; private set; } /// <summary> /// Oauth scopes accepted for this particular call. /// </summary> public IReadOnlyList<string> AcceptedOauthScopes { get; private set; } /// <summary> /// Etag /// </summary> public string Etag { get; private set; } /// <summary> /// Links to things like next/previous pages /// </summary> public IReadOnlyDictionary<string, Uri> Links { get; private set; } /// <summary> /// Information about the API rate limit /// </summary> public RateLimit RateLimit { get; private set; } } }
using System; using System.Collections.Generic; #if NET_45 using System.Collections.ObjectModel; #endif namespace Octokit { /// <summary> /// Extra information returned as part of each api response. /// </summary> public class ApiInfo { public ApiInfo(IDictionary<string, Uri> links, IList<string> oauthScopes, IList<string> acceptedOauthScopes, string etag, RateLimit rateLimit) { Ensure.ArgumentNotNull(links, "links"); Ensure.ArgumentNotNull(oauthScopes, "oauthScopes"); Links = new ReadOnlyDictionary<string, Uri>(links); OauthScopes = new ReadOnlyCollection<string>(oauthScopes); AcceptedOauthScopes = new ReadOnlyCollection<string>(acceptedOauthScopes); Etag = etag; RateLimit = rateLimit; } /// <summary> /// Oauth scopes that were included in the token used to make the request. /// </summary> public IReadOnlyList<string> OauthScopes { get; private set; } /// <summary> /// Oauth scopes accepted for this particular call. /// </summary> public IReadOnlyList<string> AcceptedOauthScopes { get; private set; } /// <summary> /// Etag /// </summary> public string Etag { get; private set; } /// <summary> /// Links to things like next/previous pages /// </summary> public IReadOnlyDictionary<string, Uri> Links { get; private set; } /// <summary> /// Information about the API rate limit /// </summary> public RateLimit RateLimit { get; private set; } } }
Use linq expression to create dictionary
using System; using System.Linq; using System.Collections.Generic; namespace Octokit { internal static class CollectionExtensions { public static TValue SafeGet<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key) { Ensure.ArgumentNotNull(dictionary, "dictionary"); TValue value; return dictionary.TryGetValue(key, out value) ? value : default(TValue); } public static IList<string> Clone(this IReadOnlyList<string> input) { List<string> output = null; if (input == null) return output; output = new List<string>(); foreach (var item in input) { output.Add(new String(item.ToCharArray())); } return output; } public static IDictionary<string, Uri> Clone(this IReadOnlyDictionary<string, Uri> input) { Dictionary<string, Uri> output = null; if (input == null) return output; output = new Dictionary<string, Uri>(); foreach (var item in input) { output.Add(new String(item.Key.ToCharArray()), new Uri(item.Value.ToString())); } return output; } } }
using System; using System.Linq; using System.Collections.Generic; namespace Octokit { internal static class CollectionExtensions { public static TValue SafeGet<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key) { Ensure.ArgumentNotNull(dictionary, "dictionary"); TValue value; return dictionary.TryGetValue(key, out value) ? value : default(TValue); } public static IList<string> Clone(this IReadOnlyList<string> input) { if (input == null) return null; return input.Select(item => new String(item.ToCharArray())).ToList(); } public static IDictionary<string, Uri> Clone(this IReadOnlyDictionary<string, Uri> input) { if (input == null) return null; return input.ToDictionary(item => new String(item.Key.ToCharArray()), item => new Uri(item.Value.ToString())); } } }
Make internals visible to test assembly
using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Basics Algorithms")] [assembly: AssemblyCulture("")]
using System.Reflection; using System.Runtime.CompilerServices; // 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("Basics Algorithms")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Basics.Algorithms.Tests")]
Use prepared http client to build odata client.
using Autofac; using Bit.ViewModel.Contracts; using Simple.OData.Client; using System; using System.Net.Http; namespace Prism.Ioc { public static class ContainerBuilderExtensions { public static ContainerBuilder RegisterODataClient(this ContainerBuilder containerBuilder) { if (containerBuilder == null) throw new ArgumentNullException(nameof(containerBuilder)); Simple.OData.Client.V4Adapter.Reference(); containerBuilder.Register(c => { HttpMessageHandler authenticatedHttpMessageHandler = c.ResolveNamed<HttpMessageHandler>(ContractKeys.AuthenticatedHttpMessageHandler); IClientAppProfile clientAppProfile = c.Resolve<IClientAppProfile>(); IODataClient odataClient = new ODataClient(new ODataClientSettings(new Uri(clientAppProfile.HostUri, clientAppProfile.ODataRoute)) { RenewHttpConnection = false, OnCreateMessageHandler = () => authenticatedHttpMessageHandler }); return odataClient; }).PreserveExistingDefaults(); containerBuilder .Register(c => new ODataBatch(c.Resolve<IODataClient>(), reuseSession: true)) .PreserveExistingDefaults(); return containerBuilder; } } }
using Autofac; using Bit.ViewModel.Contracts; using Simple.OData.Client; using System; using System.Net.Http; namespace Prism.Ioc { public static class ContainerBuilderExtensions { public static ContainerBuilder RegisterODataClient(this ContainerBuilder containerBuilder) { if (containerBuilder == null) throw new ArgumentNullException(nameof(containerBuilder)); Simple.OData.Client.V4Adapter.Reference(); containerBuilder.Register(c => { IClientAppProfile clientAppProfile = c.Resolve<IClientAppProfile>(); IODataClient odataClient = new ODataClient(new ODataClientSettings(httpClient: c.Resolve<HttpClient>(), new Uri(clientAppProfile.ODataRoute, uriKind: UriKind.Relative)) { RenewHttpConnection = false }); return odataClient; }).PreserveExistingDefaults(); containerBuilder .Register(c => new ODataBatch(c.Resolve<IODataClient>(), reuseSession: true)) .PreserveExistingDefaults(); return containerBuilder; } } }
Set status code for not found servlet
 namespace WebServer { public class Default404Servlet : HTMLServlet { protected override void OnService() { Write( DocType("html"), Tag("html", lang => "en", another => "blah")( Tag("head")( Tag("title")("Error 404") ), Tag("body")( Tag("p")( "The URL you requested could not be found", Ln, Tag("code")(Request.RawUrl) ) ) ) ); } } }
 namespace WebServer { public class Default404Servlet : HTMLServlet { protected override void OnService() { Response.StatusCode = 404; Write( DocType("html"), Tag("html", lang => "en", another => "blah")( Tag("head")( Tag("title")("Error 404") ), Tag("body")( Tag("p")( "The URL you requested could not be found", Ln, Tag("code")(Request.RawUrl) ) ) ) ); } } }
Check if initialize string is available before setting it
using System.Collections.Generic; using AgGateway.ADAPT.ApplicationDataModel; using AgGateway.ADAPT.PluginManager; namespace AgGateway.ADAPT.Visualizer { public class DataProvider { private PluginFactory _pluginFactory; public void Initialize(string pluginsPath) { _pluginFactory = new PluginFactory(pluginsPath); } public List<string> AvailablePlugins { get { return PluginFactory.AvailablePlugins; } } public PluginFactory PluginFactory { get { return _pluginFactory; } } public ApplicationDataModel.ApplicationDataModel Import(string datacardPath, string initializeString) { foreach (var availablePlugin in AvailablePlugins) { var plugin = GetPlugin(availablePlugin); plugin.Initialize(initializeString); if (plugin.IsDataCardSupported(datacardPath)) { return plugin.Import(datacardPath); } } return null; } public IPlugin GetPlugin(string pluginName) { return _pluginFactory.GetPlugin(pluginName); } public static void Export(IPlugin plugin, ApplicationDataModel.ApplicationDataModel applicationDataModel, string initializeString, string exportPath) { if (string.IsNullOrEmpty(initializeString)) { plugin.Initialize(initializeString); } plugin.Export(applicationDataModel, exportPath); } } }
using System.Collections.Generic; using AgGateway.ADAPT.ApplicationDataModel; using AgGateway.ADAPT.PluginManager; namespace AgGateway.ADAPT.Visualizer { public class DataProvider { private PluginFactory _pluginFactory; public void Initialize(string pluginsPath) { _pluginFactory = new PluginFactory(pluginsPath); } public List<string> AvailablePlugins { get { return PluginFactory.AvailablePlugins; } } public PluginFactory PluginFactory { get { return _pluginFactory; } } public ApplicationDataModel.ApplicationDataModel Import(string datacardPath, string initializeString) { foreach (var availablePlugin in AvailablePlugins) { var plugin = GetPlugin(availablePlugin); InitializePlugin(plugin, initializeString); if (plugin.IsDataCardSupported(datacardPath)) { return plugin.Import(datacardPath); } } return null; } public IPlugin GetPlugin(string pluginName) { return _pluginFactory.GetPlugin(pluginName); } public static void Export(IPlugin plugin, ApplicationDataModel.ApplicationDataModel applicationDataModel, string initializeString, string exportPath) { InitializePlugin(plugin, initializeString); plugin.Export(applicationDataModel, exportPath); } private static void InitializePlugin(IPlugin plugin, string initializeString) { if (string.IsNullOrEmpty(initializeString)) { plugin.Initialize(initializeString); } } } }
Attach dev tools only in debug builds
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; namespace Core2D.Avalonia { public class MainWindow : Window { public MainWindow() { this.InitializeComponent(); this.AttachDevTools(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; namespace Core2D.Avalonia { public class MainWindow : Window { public MainWindow() { this.InitializeComponent(); #if DEBUG this.AttachDevTools(); #endif } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
Set improved ThreadPool values for nancy
using System; using System.Collections.Generic; using System.Web; using Nancy; using Nancy.ErrorHandling; namespace NancyBenchmark { public class Global : HttpApplication { protected void Application_Start() { } } }
using System; using System.Collections.Generic; using System.Web; using Nancy; using Nancy.ErrorHandling; using System.Threading; namespace NancyBenchmark { public class Global : HttpApplication { protected void Application_Start() { var threads = 40 * Environment.ProcessorCount; ThreadPool.SetMaxThreads(threads, threads); ThreadPool.SetMinThreads(threads, threads); } } }
Rename TimeStamp to EventTimeStamp to avoid confusion with native Azure Table Storage "Timestamp" column
using System; using System.Collections; using System.Globalization; using System.Text; using Microsoft.WindowsAzure.Storage.Table; using log4net.Core; namespace log4net.Appender { internal sealed class AzureLoggingEventEntity : TableEntity { public AzureLoggingEventEntity(LoggingEvent e) { Domain = e.Domain; Identity = e.Identity; Level = e.Level; LoggerName = e.LoggerName; var sb = new StringBuilder(e.Properties.Count); foreach (DictionaryEntry entry in e.Properties) { sb.AppendFormat("{0}:{1}", entry.Key, entry.Value); sb.AppendLine(); } Properties = sb.ToString(); Message = e.RenderedMessage; ThreadName = e.ThreadName; TimeStamp = e.TimeStamp; UserName = e.UserName; PartitionKey = e.LoggerName; RowKey = MakeRowKey(e); } private static string MakeRowKey(LoggingEvent loggingEvent) { return string.Format("{0}.{1}", loggingEvent.TimeStamp.ToString("yyyy_MM_dd_HH_mm_ss_fffffff", DateTimeFormatInfo.InvariantInfo), Guid.NewGuid().ToString().ToLower()); } public string UserName { get; set; } public DateTime TimeStamp { get; set; } public string ThreadName { get; set; } public string Message { get; set; } public string Properties { get; set; } public string LoggerName { get; set; } public Level Level { get; set; } public string Identity { get; set; } public string Domain { get; set; } } }
using System; using System.Collections; using System.Globalization; using System.Text; using Microsoft.WindowsAzure.Storage.Table; using log4net.Core; namespace log4net.Appender { internal sealed class AzureLoggingEventEntity : TableEntity { public AzureLoggingEventEntity(LoggingEvent e) { Domain = e.Domain; Identity = e.Identity; Level = e.Level; LoggerName = e.LoggerName; var sb = new StringBuilder(e.Properties.Count); foreach (DictionaryEntry entry in e.Properties) { sb.AppendFormat("{0}:{1}", entry.Key, entry.Value); sb.AppendLine(); } Properties = sb.ToString(); Message = e.RenderedMessage; ThreadName = e.ThreadName; EventTimeStamp = e.TimeStamp; UserName = e.UserName; PartitionKey = e.LoggerName; RowKey = MakeRowKey(e); } private static string MakeRowKey(LoggingEvent loggingEvent) { return string.Format("{0}.{1}", loggingEvent.TimeStamp.ToString("yyyy_MM_dd_HH_mm_ss_fffffff", DateTimeFormatInfo.InvariantInfo), Guid.NewGuid().ToString().ToLower()); } public string UserName { get; set; } public DateTime EventTimeStamp { get; set; } public string ThreadName { get; set; } public string Message { get; set; } public string Properties { get; set; } public string LoggerName { get; set; } public Level Level { get; set; } public string Identity { get; set; } public string Domain { get; set; } } }
Add support for vscode install via snap
using System; using System.Collections.Generic; using System.Linq; namespace Assent.Reporters.DiffPrograms { public class VsCodeDiffProgram : DiffProgramBase { static VsCodeDiffProgram() { var paths = new List<string>(); if (DiffReporter.IsWindows) { paths.AddRange(WindowsProgramFilePaths .Select(p => $@"{p}\Microsoft VS Code\Code.exe") .ToArray()); } else { paths.Add("/usr/local/bin/code"); } DefaultSearchPaths = paths; } public static readonly IReadOnlyList<string> DefaultSearchPaths; public VsCodeDiffProgram() : base(DefaultSearchPaths) { } public VsCodeDiffProgram(IReadOnlyList<string> searchPaths) : base(searchPaths) { } protected override string CreateProcessStartArgs(string receivedFile, string approvedFile) { return $"--diff --wait --new-window \"{receivedFile}\" \"{approvedFile}\""; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Assent.Reporters.DiffPrograms { public class VsCodeDiffProgram : DiffProgramBase { static VsCodeDiffProgram() { var paths = new List<string>(); if (DiffReporter.IsWindows) { paths.AddRange(WindowsProgramFilePaths .Select(p => $@"{p}\Microsoft VS Code\Code.exe") .ToArray()); } else { paths.Add("/usr/local/bin/code"); paths.Add("/snap/bin/code"); } DefaultSearchPaths = paths; } public static readonly IReadOnlyList<string> DefaultSearchPaths; public VsCodeDiffProgram() : base(DefaultSearchPaths) { } public VsCodeDiffProgram(IReadOnlyList<string> searchPaths) : base(searchPaths) { } protected override string CreateProcessStartArgs(string receivedFile, string approvedFile) { return $"--diff --wait --new-window \"{receivedFile}\" \"{approvedFile}\""; } } }
Add the extension method ToSJIS()
using System.Linq; using System.Text; namespace ReimuPlugins.Common { public static class StringExtensions { public static string ToCStr(this string str) { return str.Contains('\0') ? str : str + '\0'; } public static string Convert(this string str, Encoding src, Encoding dst) { return dst.GetString(Encoding.Convert(src, dst, src.GetBytes(str))); } } }
using System.Linq; using System.Text; namespace ReimuPlugins.Common { public static class StringExtensions { public static string ToCStr(this string str) { return str.Contains('\0') ? str : str + '\0'; } public static string Convert(this string str, Encoding src, Encoding dst) { return dst.GetString(Encoding.Convert(src, dst, src.GetBytes(str))); } public static string ToSJIS(this string str) { return str.Convert(Enc.UTF8, Enc.SJIS); } } }
Fix typo in build. We should add tests.
using System; namespace Equifax { /// <summary> /// Creates globally secure Equifax-style GUIDs. /// </summary> public static class Guid { /// <summary> /// Creates a new Equifax secure GUID using the current UTC time. /// UTC ensures global consistency and uniqueness. /// </summary> public static System.Guid NewGuid() => NewGuid(DateTime.UtcNow); /// <summary> /// Creates a new Equifax secure GUID from the provided time stamp, /// assumed to already have been secured for uniqueness. /// </summary> public static System.Guid NewGuid(DateTime secureTimestamp) => new System.Guid( "00000000-0000-0000-0000-00" + $"{secureTimestamp.Month:00}" + $"{secureTimestamp.Day:00}" + $"{secureTimestamp.Year % 100:00}" + $"{secureTimestamp.Hour:00}" + $"{secureTimestamp.Minute:00}");\ } }
using System; namespace Equifax { /// <summary> /// Creates globally secure Equifax-style GUIDs. /// </summary> public static class Guid { /// <summary> /// Creates a new Equifax secure GUID using the current UTC time. /// UTC ensures global consistency and uniqueness. /// </summary> public static System.Guid NewGuid() => NewGuid(DateTime.UtcNow); /// <summary> /// Creates a new Equifax secure GUID from the provided time stamp, /// assumed to already have been secured for uniqueness. /// </summary> public static System.Guid NewGuid(DateTime secureTimestamp) => new System.Guid( "00000000-0000-0000-0000-00" + $"{secureTimestamp.Month:00}" + $"{secureTimestamp.Day:00}" + $"{secureTimestamp.Year % 100:00}" + $"{secureTimestamp.Hour:00}" + $"{secureTimestamp.Minute:00}"); } }
Stop the loop when there are no subscribers
using System; using System.Diagnostics; using System.Threading; namespace Avalonia.Rendering { public class SleepLoopRenderTimer : IRenderTimer { public event Action<TimeSpan> Tick; public SleepLoopRenderTimer(int fps) { var timeBetweenTicks = TimeSpan.FromSeconds(1d / fps); new Thread(() => { var st = Stopwatch.StartNew(); var now = st.Elapsed; var lastTick = now; while (true) { var timeTillNextTick = lastTick + timeBetweenTicks - now; if (timeTillNextTick.TotalMilliseconds > 1) Thread.Sleep(timeTillNextTick); Tick?.Invoke(now); now = st.Elapsed; } }) { IsBackground = true }.Start(); } } }
using System; using System.Diagnostics; using System.Threading; namespace Avalonia.Rendering { public class SleepLoopRenderTimer : IRenderTimer { private Action<TimeSpan> _tick; private int _count; private readonly object _lock = new object(); private bool _running; private readonly Stopwatch _st = Stopwatch.StartNew(); private readonly TimeSpan _timeBetweenTicks; public SleepLoopRenderTimer(int fps) { _timeBetweenTicks = TimeSpan.FromSeconds(1d / fps); } public event Action<TimeSpan> Tick { add { lock (_lock) { _tick += value; _count++; if (_running) return; _running = true; new Thread(LoopProc) { IsBackground = true }.Start(); } } remove { lock (_lock) { _tick -= value; _count--; } } } void LoopProc() { var now = _st.Elapsed; var lastTick = now; while (true) { var timeTillNextTick = lastTick + _timeBetweenTicks - now; if (timeTillNextTick.TotalMilliseconds > 1) Thread.Sleep(timeTillNextTick); lock (_lock) { if (_count == 0) { _running = false; return; } } _tick?.Invoke(now); now = _st.Elapsed; } } } }
Use th esupplied access mappign instead of looking it up a second time.
#if TFS2015u2 using System; using System.Diagnostics.CodeAnalysis; using Microsoft.TeamFoundation.Framework.Server; using Microsoft.VisualStudio.Services.Location; using Microsoft.VisualStudio.Services.Location.Server; namespace Aggregator.Core.Extensions { public static class LocationServiceExtensions { [SuppressMessage("Maintainability", "S1172:Unused method parameters should be removed", Justification = "Required by original interface", Scope = "member", Target = "~M:Aggregator.Core.Extensions.LocationServiceExtensions.GetSelfReferenceUri(Microsoft.VisualStudio.Services.Location.Server.ILocationService,Microsoft.TeamFoundation.Framework.Server.IVssRequestContext,Microsoft.VisualStudio.Services.Location.AccessMapping)~System.Uri")] public static Uri GetSelfReferenceUri(this ILocationService self, IVssRequestContext context, AccessMapping mapping) { string url = self.GetSelfReferenceUrl(context, self.GetDefaultAccessMapping(context)); return new Uri(url, UriKind.Absolute); } } } #endif
#if TFS2015u2 using System; using System.Diagnostics.CodeAnalysis; using Microsoft.TeamFoundation.Framework.Server; using Microsoft.VisualStudio.Services.Location; using Microsoft.VisualStudio.Services.Location.Server; namespace Aggregator.Core.Extensions { public static class LocationServiceExtensions { public static Uri GetSelfReferenceUri(this ILocationService self, IVssRequestContext context, AccessMapping mapping) { string url = self.GetSelfReferenceUrl(context, mapping); return new Uri(url, UriKind.Absolute); } } } #endif
Fix NH-2927 - Oracle Dialect does not handle the correct resolution for timestamp version columns
using System.Data; using NHibernate.SqlCommand; using NHibernate.SqlTypes; namespace NHibernate.Dialect { public class Oracle9iDialect : Oracle8iDialect { public override string CurrentTimestampSelectString { get { return "select systimestamp from dual"; } } public override string CurrentTimestampSQLFunctionName { get { // the standard SQL function name is current_timestamp... return "current_timestamp"; } } protected override void RegisterDateTimeTypeMappings() { RegisterColumnType(DbType.Date, "DATE"); RegisterColumnType(DbType.DateTime, "TIMESTAMP(4)"); RegisterColumnType(DbType.Time, "TIMESTAMP(4)"); } public override string GetSelectClauseNullString(SqlType sqlType) { return GetBasicSelectClauseNullString(sqlType); } public override CaseFragment CreateCaseFragment() { // Oracle did add support for ANSI CASE statements in 9i return new ANSICaseFragment(this); } } }
using System.Data; using NHibernate.SqlCommand; using NHibernate.SqlTypes; namespace NHibernate.Dialect { public class Oracle9iDialect : Oracle8iDialect { public override string CurrentTimestampSelectString { get { return "select systimestamp from dual"; } } public override string CurrentTimestampSQLFunctionName { get { // the standard SQL function name is current_timestamp... return "current_timestamp"; } } protected override void RegisterDateTimeTypeMappings() { RegisterColumnType(DbType.Date, "DATE"); RegisterColumnType(DbType.DateTime, "TIMESTAMP(4)"); RegisterColumnType(DbType.Time, "TIMESTAMP(4)"); } public override long TimestampResolutionInTicks { // matches precision of TIMESTAMP(4) get { return 1000L; } } public override string GetSelectClauseNullString(SqlType sqlType) { return GetBasicSelectClauseNullString(sqlType); } public override CaseFragment CreateCaseFragment() { // Oracle did add support for ANSI CASE statements in 9i return new ANSICaseFragment(this); } } }
Integrate cell resources with player resources code
using UnityEngine; using System.Collections; public class NurseryResource : CellFeature { public override int Amount { set { // add _amount - value to the player's resource store _amount = value; Debug.Log("child thingy"); } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using UnityEngine; using System.Collections; public class NurseryResource : CellFeature { public override int Amount { set { _amount = value; FindObjectOfType<Resources>().addPlacementResource(_amount - value); } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
Fix casing of jQuery validation fallback test
<environment names="Development"> <script src="~/lib/jquery-validation/jquery.validate.js"></script> <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script> </environment> <environment names="Staging,Production"> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js" asp-fallback-src="~/lib/jquery-validation/jquery.validate.js" asp-fallback-test="window.jquery && window.jquery.validator"> </script> <script src="https://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js" asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js" asp-fallback-test="window.jquery && window.jquery.validator && window.jquery.validator.unobtrusive"> </script> </environment>
<environment names="Development"> <script src="~/lib/jquery-validation/jquery.validate.js"></script> <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script> </environment> <environment names="Staging,Production"> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js" asp-fallback-src="~/lib/jquery-validation/jquery.validate.js" asp-fallback-test="window.jQuery && window.jQuery.validator"> </script> <script src="https://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js" asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js" asp-fallback-test="window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive"> </script> </environment>
Implement IComparable interface for sorting
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TfsHelperLib { public class TfsChangeset { public int ChangesetId { get; set; } public string Owner { get; set; } public DateTime CreationDate { get; set; } public string Comment { get; set; } public string Changes_0_ServerItem { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TfsHelperLib { public class TfsChangeset : IComparable { public int ChangesetId { get; set; } public string Owner { get; set; } public DateTime CreationDate { get; set; } public string Comment { get; set; } public string Changes_0_ServerItem { get; set; } public int CompareTo(object obj) { return ChangesetId.CompareTo(((TfsChangeset)obj).ChangesetId); } } }
Change IGuild parameter to ulong
using System.Threading.Tasks; using Discord; using Discord.Commands; using NoAdsHere.Common; using NoAdsHere.Common.Preconditions; namespace NoAdsHere.Commands.Master { public class MasterModule : ModuleBase { [Command("Reset Guild")] [RequirePermission(AccessLevel.Master)] public async Task Reset(IGuild guild) { await Task.CompletedTask; } } }
using System.Threading.Tasks; using Discord; using Discord.Commands; using NoAdsHere.Common; using NoAdsHere.Common.Preconditions; namespace NoAdsHere.Commands.Master { public class MasterModule : ModuleBase { [Command("Reset Guild")] [RequirePermission(AccessLevel.Master)] public async Task Reset(ulong guildId) { await Task.CompletedTask; } } }
Change model reference with old namespace to new
@model IEnumerable<Zk.Models.Crop> @{ ViewBag.Title = "Gewassen"; } <div id="top"></div> <div id="yearCalendar"> <h1>Dit zijn de gewassen in onze database:</h1> <table class="table table-striped"> <tr> <th>Naam</th><th>Ras</th><th>Categorie</th><th>Opp. per 1</th> <th>Opp. per zak</th><th>Prijs per zakje</th><th>Zaaimaanden</th><th>Oogstmaanden</th> </tr> <tbody> @foreach (var crop in Model) { <tr> <td>@crop.Name</td><td>@crop.Race</td><td>@crop.Category</td><td>@crop.AreaPerCrop</td> <td>@crop.AreaPerBag</td><td>@crop.PricePerBag</td> <td>@crop.SowingMonths</td><td>@crop.HarvestingMonths</td> </tr> } </tbody> </table> </div> @Html.ActionLink("Terug naar Zaaien en oogsten", "Index", "Home", null, null)
@model IEnumerable<Oogstplanner.Models.Crop> @{ ViewBag.Title = "Gewassen"; } <div id="top"></div> <div id="yearCalendar"> <h1>Dit zijn de gewassen in onze database:</h1> <table class="table table-striped"> <tr> <th>Naam</th><th>Ras</th><th>Categorie</th><th>Opp. per 1</th> <th>Opp. per zak</th><th>Prijs per zakje</th><th>Zaaimaanden</th><th>Oogstmaanden</th> </tr> <tbody> @foreach (var crop in Model) { <tr> <td>@crop.Name</td><td>@crop.Race</td><td>@crop.Category</td><td>@crop.AreaPerCrop</td> <td>@crop.AreaPerBag</td><td>@crop.PricePerBag</td> <td>@crop.SowingMonths</td><td>@crop.HarvestingMonths</td> </tr> } </tbody> </table> </div> @Html.ActionLink("Terug naar Zaaien en oogsten", "Index", "Home", null, null)
Remove studio repo Create call used for testing
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using ISTS.Domain.Studios; namespace ISTS.Application.Studios { public class StudioService : IStudioService { private readonly IStudioRepository _studioRepository; private readonly IMapper _mapper; public StudioService( IStudioRepository studioRepository, IMapper mapper) { _studioRepository = studioRepository; _mapper = mapper; } public StudioDto Create(string name, string friendlyUrl) { var entity = _studioRepository.Create(name, friendlyUrl); var result = _mapper.Map<StudioDto>(entity); return result; } public List<StudioDto> GetAll() { var entities = _studioRepository.Get().ToList(); var result = _mapper.Map<List<StudioDto>>(entities); return result; } public StudioDto Get(Guid id) { // var entity = _studioRepository.Get(id); var entity = _studioRepository.Create("My Studio", "mystudio"); var result = _mapper.Map<StudioDto>(entity); return result; } public StudioRoomDto CreateRoom(Guid studioId, string name) { var studio = _studioRepository.Get(studioId); var model = studio.CreateRoom(name); var result = _studioRepository.CreateRoom(model.StudioId, model.Name); var studioRoomDto = _mapper.Map<StudioRoomDto>(result); return studioRoomDto; } } }
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using ISTS.Domain.Studios; namespace ISTS.Application.Studios { public class StudioService : IStudioService { private readonly IStudioRepository _studioRepository; private readonly IMapper _mapper; public StudioService( IStudioRepository studioRepository, IMapper mapper) { _studioRepository = studioRepository; _mapper = mapper; } public StudioDto Create(string name, string friendlyUrl) { var entity = _studioRepository.Create(name, friendlyUrl); var result = _mapper.Map<StudioDto>(entity); return result; } public List<StudioDto> GetAll() { var entities = _studioRepository.Get().ToList(); var result = _mapper.Map<List<StudioDto>>(entities); return result; } public StudioDto Get(Guid id) { var entity = _studioRepository.Get(id); var result = _mapper.Map<StudioDto>(entity); return result; } public StudioRoomDto CreateRoom(Guid studioId, string name) { var studio = _studioRepository.Get(studioId); var model = studio.CreateRoom(name); var result = _studioRepository.CreateRoom(model.StudioId, model.Name); var studioRoomDto = _mapper.Map<StudioRoomDto>(result); return studioRoomDto; } } }
Fix build, this is not allwoed on the method itself
// // Urho's Object C# sugar // // Authors: // Miguel de Icaza (miguel@xamarin.com) // // Copyrigh 2015 Xamarin INc // using System; using System.Runtime.InteropServices; namespace Urho { public partial class UrhoObject : RefCounted { // Invoked by the subscribe methods [UnmanagedFunctionPointer(CallingConvention.Cdecl)] static void ObjectCallback (IntPtr data, int stringHash, IntPtr variantMap) { GCHandle gch = GCHandle.FromIntPtr(data); Action<IntPtr> a = (Action<IntPtr>) gch.Target; a (variantMap); } } }
// // Urho's Object C# sugar // // Authors: // Miguel de Icaza (miguel@xamarin.com) // // Copyrigh 2015 Xamarin INc // using System; using System.Runtime.InteropServices; namespace Urho { public partial class UrhoObject : RefCounted { // Invoked by the subscribe methods static void ObjectCallback (IntPtr data, int stringHash, IntPtr variantMap) { GCHandle gch = GCHandle.FromIntPtr(data); Action<IntPtr> a = (Action<IntPtr>) gch.Target; a (variantMap); } } }
Use the new reflection API on .NET 4.5 and .NET Core
// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information. using System; using System.Collections.Generic; using System.Linq; #if PLATFORM_DOTNET using System.Reflection; #endif namespace CommandLine.Core { sealed class Verb { private readonly string name; private readonly string helpText; public Verb(string name, string helpText) { if (name == null) throw new ArgumentNullException("name"); if (helpText == null) throw new ArgumentNullException("helpText"); this.name = name; this.helpText = helpText; } public string Name { get { return name; } } public string HelpText { get { return helpText; } } public static Verb FromAttribute(VerbAttribute attribute) { return new Verb( attribute.Name, attribute.HelpText ); } public static IEnumerable<Tuple<Verb, Type>> SelectFromTypes(IEnumerable<Type> types) { return from type in types let attrs = type.GetTypeInfo().GetCustomAttributes(typeof(VerbAttribute), true).ToArray() where attrs.Length == 1 select Tuple.Create( FromAttribute((VerbAttribute)attrs.Single()), type); } } }
// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information. using System; using System.Collections.Generic; using System.Linq; #if !NET40 using System.Reflection; #endif namespace CommandLine.Core { sealed class Verb { private readonly string name; private readonly string helpText; public Verb(string name, string helpText) { if (name == null) throw new ArgumentNullException("name"); if (helpText == null) throw new ArgumentNullException("helpText"); this.name = name; this.helpText = helpText; } public string Name { get { return name; } } public string HelpText { get { return helpText; } } public static Verb FromAttribute(VerbAttribute attribute) { return new Verb( attribute.Name, attribute.HelpText ); } public static IEnumerable<Tuple<Verb, Type>> SelectFromTypes(IEnumerable<Type> types) { return from type in types let attrs = type.GetTypeInfo().GetCustomAttributes(typeof(VerbAttribute), true).ToArray() where attrs.Length == 1 select Tuple.Create( FromAttribute((VerbAttribute)attrs.Single()), type); } } }
Add skeleton code to main program
using CurrencyRates.Entity; using System; namespace CurrencyRates { class Program { static void Main(string[] args) { } } }
using System; namespace CurrencyRates { class Program { enum Actions { Fetch, Show }; static void Main(string[] args) { try { var action = Actions.Fetch; if (args.Length > 0) { action = (Actions)Enum.Parse(typeof(Actions), args[0], true); } switch (action) { case Actions.Fetch: //@todo implement Fetch action break; case Actions.Show: //@todo implement Show action break; default: break; } } catch (Exception e) { Console.WriteLine("An error occured: " + e.Message); } } } }
Update top navigation dropdown menu
@(Html.X().Panel() .Header(false) .Region(Region.North) .Border(false) .Height(70) .Content( @<text> <header class="site-header" role="banner"> <nav class="top-navigation"> <div class="logo-container"> <img src="../../resources/images/extdotnet-logo.svg" /> </div> <div class="navigation-bar"> <div class="platform-selector-container"> @(Html.X().Button() .Cls("platform-selector") .Width(450) .Text("MVC Examples Explorer (4.1)") .Height(70) .ArrowVisible(false) .Menu(Html.X().Menu() .Cls("platform-selector-dropdown") .Plain(true) .Items( Html.X().MenuItem() .Text("Web Forms Examples Explorer (4.1)") .Href("http://examples.ext.net/") .Height(70) .Width(448) .Padding(12) ) ) ) </div> <input type="checkbox" id="menu-button-checkbox" /> <label id="menu-button" for="menu-button-checkbox"> <span></span> </label> </div> </nav> </header> </text> ) )
@(Html.X().Panel() .Header(false) .Region(Region.North) .Border(false) .Height(70) .Content( @<text> <header class="site-header" role="banner"> <nav class="top-navigation"> <div class="logo-container"> <img src="../../resources/images/extdotnet-logo.svg" /> </div> <div class="navigation-bar"> <div class="platform-selector-container"> @(Html.X().Button() .Cls("platform-selector") .Width(360) .Text("MVC Examples (4.1)") .Height(70) .ArrowVisible(false) .Menu(Html.X().Menu() .Cls("platform-selector-dropdown") .Plain(true) .Items( Html.X().MenuItem() .Text("Web Forms Examples (4.1)") .Href("http://examples.ext.net/") .Height(70) .Width(358) .Padding(12), Html.X().MenuItem() .Text("Mobile Examples (4.1)") .Href("http://mobile.ext.net/") .Height(70) .Width(358) .Padding(12), Html.X().MenuItem() .Text("MVC Mobile Examples (4.1)") .Href("http://mvc.mobile.ext.net/") .Height(70) .Width(358) .Padding(12) ) ) ) </div> <input type="checkbox" id="menu-button-checkbox" /> <label id="menu-button" for="menu-button-checkbox"> <span></span> </label> </div> </nav> </header> </text> ) )
Add remove method for cache
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Text; using System.Threading.Tasks; namespace Mozu.Api.Cache { public class CacheManager { private readonly ObjectCache _cache; private static readonly object _lockObj = new Object(); private static volatile CacheManager instance; private CacheManager() { _cache = MemoryCache.Default; } public static CacheManager Instance { get { if (instance == null) { lock (_lockObj) { if (instance == null) instance = new CacheManager(); } } return instance; } } public T Get<T>(string id) { return (T)_cache[id]; } public void Add<T>(T obj, string id) { if (!MozuConfig.EnableCache) return; if (_cache.Contains(id)) _cache.Remove(id); var policy = new CacheItemPolicy(); policy.SlidingExpiration = new TimeSpan(1, 0, 0); _cache.Set(id, obj, policy); } public void Update<T>(T obj, string id) { if (!MozuConfig.EnableCache) return; _cache.Remove(id); Add(obj, id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Text; using System.Threading.Tasks; namespace Mozu.Api.Cache { public class CacheManager { private readonly ObjectCache _cache; private static readonly object _lockObj = new Object(); private static volatile CacheManager instance; private CacheManager() { _cache = MemoryCache.Default; } public static CacheManager Instance { get { if (instance == null) { lock (_lockObj) { if (instance == null) instance = new CacheManager(); } } return instance; } } public T Get<T>(string id) { return (T)_cache[id]; } public void Add<T>(T obj, string id) { if (!MozuConfig.EnableCache) return; if (_cache.Contains(id)) _cache.Remove(id); var policy = new CacheItemPolicy(); policy.SlidingExpiration = new TimeSpan(1, 0, 0); _cache.Set(id, obj, policy); } public void Update<T>(T obj, string id) { if (!MozuConfig.EnableCache) return; _cache.Remove(id); Add(obj, id); } public void Remove(string id) { if (!MozuConfig.EnableCache) return; _cache.Remove(id); } } }
Fix ansi filename decoded as gibberish in zip file
using System.Globalization; using System.Text; namespace SharpCompress.Common { public class ArchiveEncoding { /// <summary> /// Default encoding to use when archive format doesn't specify one. /// </summary> public static Encoding Default; /// <summary> /// Encoding used by encryption schemes which don't comply with RFC 2898. /// </summary> public static Encoding Password; static ArchiveEncoding() { #if PORTABLE || NETFX_CORE Default = Encoding.UTF8; Password = Encoding.UTF8; #else Default = Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.OEMCodePage); Password = Encoding.Default; #endif } } }
using System.Globalization; using System.Text; namespace SharpCompress.Common { public class ArchiveEncoding { /// <summary> /// Default encoding to use when archive format doesn't specify one. /// </summary> public static Encoding Default; /// <summary> /// Encoding used by encryption schemes which don't comply with RFC 2898. /// </summary> public static Encoding Password; static ArchiveEncoding() { #if PORTABLE || NETFX_CORE Default = Encoding.UTF8; Password = Encoding.UTF8; #else Default = Encoding.Default; Password = Encoding.Default; #endif } } }
Update to use UTC instead of local time
using System; using System.Threading; namespace Shuttle.Core.Infrastructure { public static class ThreadSleep { public const int MaxStepSize = 1000; public static void While(int ms, IThreadState state) { // step size should be as large as possible, // max step size by default While(ms, state, MaxStepSize); } public static void While(int ms, IThreadState state, int step) { // don't sleep less than zero if (ms < 0) return; // step size must be positive and less than max step size if (step < 0 || step > MaxStepSize) step = MaxStepSize; // end time var end = DateTime.Now.AddMilliseconds(ms); // sleep time should be // 1) as large as possible to reduce burden on the os and improve accuracy // 2) less than the max step size to keep the thread responsive to thread state var remaining = (int)(end - DateTime.Now).TotalMilliseconds; while (state.Active && remaining > 0) { var sleep = remaining < step ? remaining : step; Thread.Sleep(sleep); remaining = (int)(end - DateTime.Now).TotalMilliseconds; } } } }
using System; using System.Threading; namespace Shuttle.Core.Infrastructure { public static class ThreadSleep { public const int MaxStepSize = 1000; public static void While(int ms, IThreadState state) { // step size should be as large as possible, // max step size by default While(ms, state, MaxStepSize); } public static void While(int ms, IThreadState state, int step) { // don't sleep less than zero if (ms < 0) return; // step size must be positive and less than max step size if (step < 0 || step > MaxStepSize) step = MaxStepSize; // end time var end = DateTime.UtcNow.AddMilliseconds(ms); // sleep time should be // 1) as large as possible to reduce burden on the os and improve accuracy // 2) less than the max step size to keep the thread responsive to thread state var remaining = (int)(end - DateTime.UtcNow).TotalMilliseconds; while (state.Active && remaining > 0) { var sleep = remaining < step ? remaining : step; Thread.Sleep(sleep); remaining = (int)(end - DateTime.UtcNow).TotalMilliseconds; } } } }
Return 0xFF for an undefined cartridge read rather than 0x00
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace elbgb_core.Memory { class NullCartridge : Cartridge { public NullCartridge(CartridgeHeader header, byte[] romData) : base(header, romData) { } public override byte ReadByte(ushort address) { return 0; } public override void WriteByte(ushort address, byte value) { return; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace elbgb_core.Memory { class NullCartridge : Cartridge { public NullCartridge(CartridgeHeader header, byte[] romData) : base(header, romData) { } public override byte ReadByte(ushort address) { return 0xFF; } public override void WriteByte(ushort address, byte value) { return; } } }
Change priority of StrokeWatcherScheduler to Highest.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Crevice.GestureMachine { using System.Threading; using System.Drawing; using Crevice.Core.FSM; using Crevice.Core.Events; using Crevice.Threading; public class GestureMachine : GestureMachine<GestureMachineConfig, ContextManager, EvaluationContext, ExecutionContext> { public GestureMachine( GestureMachineConfig gestureMachineConfig, CallbackManager callbackManager) : base(gestureMachineConfig, callbackManager, new ContextManager()) { } private readonly LowLatencyScheduler _strokeWatcherScheduler = new LowLatencyScheduler( "StrokeWatcherTaskScheduler", ThreadPriority.AboveNormal, 1); protected override TaskFactory StrokeWatcherTaskFactory => new TaskFactory(_strokeWatcherScheduler); public override bool Input(IPhysicalEvent evnt, Point? point) { lock (lockObject) { if (point.HasValue) { ContextManager.CursorPosition = point.Value; } return base.Input(evnt, point); } } protected override void Dispose(bool disposing) { if (disposing) { ContextManager.Dispose(); _strokeWatcherScheduler.Dispose(); } base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Crevice.GestureMachine { using System.Threading; using System.Drawing; using Crevice.Core.FSM; using Crevice.Core.Events; using Crevice.Threading; public class GestureMachine : GestureMachine<GestureMachineConfig, ContextManager, EvaluationContext, ExecutionContext> { public GestureMachine( GestureMachineConfig gestureMachineConfig, CallbackManager callbackManager) : base(gestureMachineConfig, callbackManager, new ContextManager()) { } private readonly LowLatencyScheduler _strokeWatcherScheduler = new LowLatencyScheduler("StrokeWatcherTaskScheduler", ThreadPriority.Highest, 1); protected override TaskFactory StrokeWatcherTaskFactory => new TaskFactory(_strokeWatcherScheduler); public override bool Input(IPhysicalEvent evnt, Point? point) { lock (lockObject) { if (point.HasValue) { ContextManager.CursorPosition = point.Value; } return base.Input(evnt, point); } } protected override void Dispose(bool disposing) { if (disposing) { ContextManager.Dispose(); _strokeWatcherScheduler.Dispose(); } base.Dispose(disposing); } } }
Make sure the OWIN sample runs
namespace OwinApp { using System; using Microsoft.Owin.Hosting; using Owin; using Nancy.Owin; public class Program { public static void Main(string[] args) { const string url = "http://localhost:5000"; using (WebApp.Start(url, Configuration)) { Console.WriteLine($"Listening at {url}..."); Console.ReadLine(); } } private static void Configuration(IAppBuilder app) { app.UseNancy(); } } }
namespace OwinApp { using System; using Microsoft.Owin.Hosting; using Nancy.Bootstrappers.Autofac; using Owin; using Nancy.Owin; public class Program { public static void Main(string[] args) { const string url = "http://localhost:5000"; using (WebApp.Start(url, Configuration)) { Console.WriteLine($"Listening at {url}..."); Console.ReadLine(); } } private static void Configuration(IAppBuilder app) { app.UseNancy(new AutofacBootstrapper()); } } }
Fix minor bug for mix mode.
using UnityEngine; using System.Collections; public class GP_ResourcePhase : Phase { public override void OnEnter() { base.OnEnter(); var hexes = TowerManager.Instance.GetHexagonsInRange(CurrentPlayer, TowerType.ResourceTower); var vision = RangeUtils.GetPlayerVisionServer(CurrentPlayer); hexes.IntersectWith(vision); TowerManager.Instance.RemoveHexagonsOccupied(hexes); CurrentPlayer.AddResource(hexes.Count); } }
using UnityEngine; using System.Collections; public class GP_ResourcePhase : Phase { /* public override void OnEnter() { base.OnEnter(); var hexes = TowerManager.Instance.GetHexagonsInRange(CurrentPlayer, TowerType.ResourceTower); var vision = RangeUtils.GetPlayerVisionServer(CurrentPlayer); hexes.IntersectWith(vision); TowerManager.Instance.RemoveHexagonsOccupied(hexes); CurrentPlayer.AddResource(hexes.Count); } */ public override void OnEnter() { base.OnEnter(); CurrentPlayer.AddResource(CurrentPlayer.Production); CurrentPlayer.RpcAddLog("Your resource is increased by " + CurrentPlayer.Production + "."); } }
Send keystrokes to the console main window
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Grr { public static class ConsoleExtensions { [DllImport("User32.dll")] static extern int SetForegroundWindow(IntPtr point); public static void WriteConsoleInput(Process target, string value) { SetForegroundWindow((IntPtr)target.Id); SendKeys.SendWait(value); SendKeys.SendWait("{Enter}"); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Grr { public static class ConsoleExtensions { [DllImport("User32.dll")] static extern int SetForegroundWindow(IntPtr point); public static void WriteConsoleInput(Process target, string value) { SetForegroundWindow(target.MainWindowHandle); SendKeys.SendWait(value); SendKeys.SendWait("{Enter}"); } } }
Correct names of test methods
using FluentAssertions; using NUnit.Framework; namespace MyInfluxDbClient.UnitTests { public class ShowSeriesTests : UnitTestsOf<ShowSeries> { [Test] public void Generate_Should_return_drop_series_When_constructed_empty() { SUT = new ShowSeries(); SUT.Generate().Should().Be("show series"); } [Test] public void Generate_Should_return_drop_series_with_measurement_When_from_is_specified() { SUT = new ShowSeries().FromMeasurement("orderCreated"); SUT.Generate().Should().Be("show series from \"orderCreated\""); } [Test] public void Generate_Should_return_drop_series_with_where_When_where_is_specified() { SUT = new ShowSeries().WhereTags("merchant='foo'"); SUT.Generate().Should().Be("show series where merchant='foo'"); } [Test] public void Generate_Should_return_drop_series_with_from_and_where_When_from_and_where_are_specified() { SUT = new ShowSeries().FromMeasurement("orderCreated").WhereTags("merchant='foo'"); SUT.Generate().Should().Be("show series from \"orderCreated\" where merchant='foo'"); } } }
using FluentAssertions; using NUnit.Framework; namespace MyInfluxDbClient.UnitTests { public class ShowSeriesTests : UnitTestsOf<ShowSeries> { [Test] public void Generate_Should_return_show_series_When_constructed_empty() { SUT = new ShowSeries(); SUT.Generate().Should().Be("show series"); } [Test] public void Generate_Should_return_show_series_with_measurement_When_from_is_specified() { SUT = new ShowSeries().FromMeasurement("orderCreated"); SUT.Generate().Should().Be("show series from \"orderCreated\""); } [Test] public void Generate_Should_return_show_series_with_where_When_where_is_specified() { SUT = new ShowSeries().WhereTags("merchant='foo'"); SUT.Generate().Should().Be("show series where merchant='foo'"); } [Test] public void Generate_Should_return_show_series_with_from_and_where_When_from_and_where_are_specified() { SUT = new ShowSeries().FromMeasurement("orderCreated").WhereTags("merchant='foo'"); SUT.Generate().Should().Be("show series from \"orderCreated\" where merchant='foo'"); } } }
Change starting line in script processor to 1 instead of 0 for easier debugging
using System; using System.IO; using System.Text; using System.Windows.Forms; using CefSharp; using CefSharp.WinForms; namespace TweetDck.Resources{ static class ScriptLoader{ private const string UrlPrefix = "td:"; public static string LoadResource(string name){ try{ return File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,name),Encoding.UTF8); }catch(Exception ex){ MessageBox.Show("Unfortunately, "+Program.BrandName+" could not load the "+name+" file. The program will continue running with limited functionality.\r\n\r\n"+ex.Message,Program.BrandName+" Has Failed :(",MessageBoxButtons.OK,MessageBoxIcon.Error); return null; } } public static void ExecuteFile(ChromiumWebBrowser browser, string file){ ExecuteScript(browser,LoadResource(file),"root:"+Path.GetFileNameWithoutExtension(file)); } public static void ExecuteFile(IFrame frame, string file){ ExecuteScript(frame,LoadResource(file),"root:"+Path.GetFileNameWithoutExtension(file)); } public static void ExecuteScript(ChromiumWebBrowser browser, string script, string identifier){ if (script == null)return; using(IFrame frame = browser.GetMainFrame()){ frame.ExecuteJavaScriptAsync(script,UrlPrefix+identifier); } } public static void ExecuteScript(IFrame frame, string script, string identifier){ if (script == null)return; frame.ExecuteJavaScriptAsync(script,UrlPrefix+identifier); } } }
using System; using System.IO; using System.Text; using System.Windows.Forms; using CefSharp; using CefSharp.WinForms; namespace TweetDck.Resources{ static class ScriptLoader{ private const string UrlPrefix = "td:"; public static string LoadResource(string name){ try{ return File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,name),Encoding.UTF8); }catch(Exception ex){ MessageBox.Show("Unfortunately, "+Program.BrandName+" could not load the "+name+" file. The program will continue running with limited functionality.\r\n\r\n"+ex.Message,Program.BrandName+" Has Failed :(",MessageBoxButtons.OK,MessageBoxIcon.Error); return null; } } public static void ExecuteFile(ChromiumWebBrowser browser, string file){ ExecuteScript(browser,LoadResource(file),"root:"+Path.GetFileNameWithoutExtension(file)); } public static void ExecuteFile(IFrame frame, string file){ ExecuteScript(frame,LoadResource(file),"root:"+Path.GetFileNameWithoutExtension(file)); } public static void ExecuteScript(ChromiumWebBrowser browser, string script, string identifier){ if (script == null)return; using(IFrame frame = browser.GetMainFrame()){ frame.ExecuteJavaScriptAsync(script,UrlPrefix+identifier,1); } } public static void ExecuteScript(IFrame frame, string script, string identifier){ if (script == null)return; frame.ExecuteJavaScriptAsync(script,UrlPrefix+identifier,1); } } }
Fix for segfault on end of Qt test
using System; using NUnit.Framework; using Gtk; using Qyoto; namespace Selene.Testing { [TestFixture] public partial class Harness { [TestFixtureSetUp] public void Setup() { #if GTK string[] Dummy = new string[] { }; Init.Check(ref Dummy); #endif #if QYOTO new QApplication(new string[] { } ); #endif } } }
using System; using NUnit.Framework; using Gtk; using Qyoto; namespace Selene.Testing { [TestFixture] public partial class Harness { [TestFixtureSetUp] public void Setup() { #if GTK string[] Dummy = new string[] { }; Init.Check(ref Dummy); #endif #if QYOTO new QApplication(new string[] { } ); #endif } [TestFixtureTearDown] public void Teardown() { QApplication.Exec(); } } }
Create a hysteresis observable transform.
using System.Collections; using System.Collections.Generic; using UniRx; using UnityEngine; public class GeneratedSignals { public static IObservable<float> CreateTriangleSignal(float period) { return Observable.IntervalFrame(1, FrameCountType.Update) .Scan(0f, (c, _) => c + Time.deltaTime) .Select(t => (period - Mathf.Abs(t % (2 * period) - period)) / period); } }
using System; using System.Collections; using System.Collections.Generic; using UniRx; using UnityEngine; public static class GeneratedSignals { public static IObservable<float> CreateTriangleSignal(float period) { return Observable.IntervalFrame(1, FrameCountType.Update) .Scan(0f, (c, _) => c + Time.deltaTime) .Select(t => (period - Mathf.Abs(t % (2 * period) - period)) / period); } public static IObservable<bool> Hysteresis<T>(this IObservable<T> obs, Func<T, T, float> compare, T enter, T exit, bool initialState = false) { return obs.Scan(initialState, (state, value) => { var switchState = (state && compare(value, exit) < 0) || (!state && compare(value, enter) > 0); return switchState ? !state : state; }) .DistinctUntilChanged(); } }
Fix media player allocation error
using System.Collections.Generic; using System.IO; using System.Threading; using DesktopWidgets.Properties; using WMPLib; namespace DesktopWidgets.Classes { public static class MediaPlayerStore { private static readonly List<WindowsMediaPlayer> _mediaPlayerList = new List<WindowsMediaPlayer>(); private static WindowsMediaPlayer GetAvailablePlayer() { try { for (var i = 0; i < Settings.Default.MaxConcurrentMediaPlayers; i++) { if (_mediaPlayerList.Count - 1 < i) _mediaPlayerList.Add(new WindowsMediaPlayer()); if (_mediaPlayerList[i].playState != WMPPlayState.wmppsPlaying) return _mediaPlayerList[i]; } } catch { // ignored } return _mediaPlayerList[0]; } public static void PlaySoundAsync(string path, double volume = 1) { new Thread(delegate() { Play(path, volume); }).Start(); } public static void Play(string path, double volume = 1) { var player = GetAvailablePlayer(); if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) return; player.settings.volume = (int) (volume*100); player.URL = path; } } }
using System.Collections.Generic; using System.IO; using System.Threading; using DesktopWidgets.Properties; using WMPLib; namespace DesktopWidgets.Classes { public static class MediaPlayerStore { private static readonly List<WindowsMediaPlayer> MediaPlayers = new List<WindowsMediaPlayer> { new WindowsMediaPlayer() }; private static WindowsMediaPlayer GetAvailablePlayer() { try { for (var i = 0; i < Settings.Default.MaxConcurrentMediaPlayers; i++) { if (MediaPlayers.Count - 1 >= i && MediaPlayers[i] == null) MediaPlayers.RemoveAt(i); if (MediaPlayers.Count - 1 < i) MediaPlayers.Add(new WindowsMediaPlayer()); if (MediaPlayers[i].playState != WMPPlayState.wmppsPlaying) return MediaPlayers[i]; } } catch { // ignored } return MediaPlayers[0]; } public static void PlaySoundAsync(string path, double volume = 1) { new Thread(delegate() { Play(path, volume); }).Start(); } public static void Play(string path, double volume = 1) { if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) return; var player = GetAvailablePlayer(); player.settings.volume = (int) (volume*100); player.URL = path; } } }
Add ability to specify xml root without decorating the target class.
using System; using System.IO; using System.Text.RegularExpressions; using System.Xml.Serialization; namespace Rock.Messaging.Routing { public class XmlMessageParser : IMessageParser { public string GetTypeName(Type type) { var xmlRootAttribute = Attribute.GetCustomAttribute(type, typeof(XmlRootAttribute)) as XmlRootAttribute; return xmlRootAttribute != null && !string.IsNullOrWhiteSpace(xmlRootAttribute.ElementName) ? xmlRootAttribute.ElementName : type.Name; } public string GetTypeName(string rawMessage) { var match = Regex.Match(rawMessage, @"<([a-zA-Z_][a-zA-Z0-9]*)[ >/]"); if (!match.Success) { throw new ArgumentException("Unable to find root xml element.", "rawMessage"); } return match.Groups[1].Value; } public object DeserializeMessage(string rawMessage, Type messageType) { var serializer = new XmlSerializer(messageType); using (var reader = new StringReader(rawMessage)) { return serializer.Deserialize(reader); } } } }
using System; using System.Collections.Concurrent; using System.IO; using System.Text.RegularExpressions; using System.Xml.Serialization; namespace Rock.Messaging.Routing { public class XmlMessageParser : IMessageParser { private readonly ConcurrentDictionary<Type, XmlRootAttribute> _xmlRootAttributes = new ConcurrentDictionary<Type, XmlRootAttribute>(); public void RegisterXmlRoot(Type messageType, string xmlRootElementName) { if (string.IsNullOrWhiteSpace(xmlRootElementName)) { XmlRootAttribute dummy; _xmlRootAttributes.TryRemove(messageType, out dummy); } else { _xmlRootAttributes.AddOrUpdate( messageType, t => new XmlRootAttribute(xmlRootElementName), (t, a) => new XmlRootAttribute(xmlRootElementName)); } } public string GetTypeName(Type messageType) { XmlRootAttribute xmlRootAttribute; if (!_xmlRootAttributes.TryGetValue(messageType, out xmlRootAttribute)) { xmlRootAttribute = Attribute.GetCustomAttribute(messageType, typeof(XmlRootAttribute)) as XmlRootAttribute; } return xmlRootAttribute != null && !string.IsNullOrWhiteSpace(xmlRootAttribute.ElementName) ? xmlRootAttribute.ElementName : messageType.Name; } public string GetTypeName(string rawMessage) { var match = Regex.Match(rawMessage, @"<([a-zA-Z_][a-zA-Z0-9]*)[ >/]"); if (!match.Success) { throw new ArgumentException("Unable to find root xml element.", "rawMessage"); } return match.Groups[1].Value; } public object DeserializeMessage(string rawMessage, Type messageType) { using (var reader = new StringReader(rawMessage)) { return GetXmlSerializer(messageType).Deserialize(reader); } } private XmlSerializer GetXmlSerializer(Type messageType) { XmlRootAttribute xmlRootAttribute; return _xmlRootAttributes.TryGetValue(messageType, out xmlRootAttribute) ? new XmlSerializer(messageType, xmlRootAttribute) : new XmlSerializer(messageType); } } }
Use pure in-memory db in development environment
using LiteDB; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace LanfeustBridge.Services { public class DbService { public DbService(DirectoryService directoryService) { var dataFile = Path.Combine(directoryService.DataDirectory, "lanfeust.db"); Db = new LiteDatabase(dataFile); } public LiteDatabase Db { get; } } }
using LiteDB; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace LanfeustBridge.Services { public class DbService { public DbService(DirectoryService directoryService, IHostingEnvironment hostingEnvironment) { if (hostingEnvironment.IsDevelopment()) { Db = new LiteDatabase(new MemoryStream()); } else { var dataFile = Path.Combine(directoryService.DataDirectory, "lanfeust.db"); Db = new LiteDatabase(dataFile); } } public LiteDatabase Db { get; } } }
Add logic to inject NAME in ViewBag based of Identity
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcNG.Controllers { public class ngAppController : BaseTSController { // // GET: /ngApp/main public ActionResult main() { //DON'T USE Index - DON'T WORK! ViewBag.WAIT = 5000; return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web using System.Web.Mvc; namespace MvcNG.Controllers { public class ngAppController : BaseTSController { // // GET: /ngApp/main public ActionResult main() { //DON'T USE Index - DON'T WORK! ViewBag.WAIT = 5000; if (User.Identity.IsAuthenticated) { ViewBag.NAME = User.Identity.Name; } else { ViewBag.NAME = "Pippo"; } return View(); } } }
Replace copyright with LICENSE reference
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("VulkanInfo GUI")] [assembly: AssemblyDescription("Small program to obtain information from the Vulkan Runtime.")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyProduct("Graphical User Interface for VulkanInfo")] [assembly: AssemblyCopyright("Copyright © 2016 - 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.1.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("VulkanInfo GUI")] [assembly: AssemblyDescription("Small program to obtain information from the Vulkan Runtime.")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyProduct("Graphical User Interface for VulkanInfo")] [assembly: AssemblyCopyright("See LICENSE file")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.1.0.0")]
Remove superfluous call to ToImmutableArray
using System; using System.Collections.Immutable; namespace ApiPorter.Patterns { public sealed partial class PatternSearch { private PatternSearch(string text, ImmutableArray<PatternVariable> variables) { Text = text; Variables = variables; } public static PatternSearch Create(string text, ImmutableArray<PatternVariable> variables) { if (text == null) throw new ArgumentNullException(nameof(text)); return new PatternSearch(text, variables.ToImmutableArray()); } public static PatternSearch Create(string text, params PatternVariable[] variables) { if (text == null) throw new ArgumentNullException(nameof(text)); var variableArray = variables == null ? ImmutableArray<PatternVariable>.Empty : variables.ToImmutableArray(); return Create(text, variableArray); } public string Text { get; } public ImmutableArray<PatternVariable> Variables { get; set; } } }
using System; using System.Collections.Immutable; namespace ApiPorter.Patterns { public sealed partial class PatternSearch { private PatternSearch(string text, ImmutableArray<PatternVariable> variables) { Text = text; Variables = variables; } public static PatternSearch Create(string text, ImmutableArray<PatternVariable> variables) { if (text == null) throw new ArgumentNullException(nameof(text)); return new PatternSearch(text, variables); } public static PatternSearch Create(string text, params PatternVariable[] variables) { if (text == null) throw new ArgumentNullException(nameof(text)); var variableArray = variables == null ? ImmutableArray<PatternVariable>.Empty : variables.ToImmutableArray(); return Create(text, variableArray); } public string Text { get; } public ImmutableArray<PatternVariable> Variables { get; set; } } }
Change "Note" default size / minimum size
using System.ComponentModel; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.Note { public class Settings : WidgetSettingsBase { public Settings() { Style.Width = 160; Style.Height = 132; } [DisplayName("Saved Text")] public string Text { get; set; } [Category("Style")] [DisplayName("Read Only")] public bool ReadOnly { get; set; } } }
using System.ComponentModel; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.Note { public class Settings : WidgetSettingsBase { public Settings() { Style.MinWidth = 160; Style.MinHeight = 132; } [DisplayName("Saved Text")] public string Text { get; set; } [Category("Style")] [DisplayName("Read Only")] public bool ReadOnly { get; set; } } }
Allow only one instance of application
using System; using System.IO; using System.Windows.Forms; namespace SteamShutdown { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var applicationContext = new CustomApplicationContext(); Application.Run(applicationContext); } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "SteamShutdown_Log.txt"); File.WriteAllText(path, e.ExceptionObject.ToString()); MessageBox.Show("Please send me the log file on GitHub or via E-Mail (Andreas.D.Korb@gmail.com)" + Environment.NewLine + path, "An Error occured"); } } }
using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; namespace SteamShutdown { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { string appProcessName = Path.GetFileNameWithoutExtension(Application.ExecutablePath); Process[] RunningProcesses = Process.GetProcessesByName(appProcessName); if (RunningProcesses.Length > 1) return; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var applicationContext = new CustomApplicationContext(); Application.Run(applicationContext); } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "SteamShutdown_Log.txt"); File.WriteAllText(path, e.ExceptionObject.ToString()); MessageBox.Show("Please send me the log file on GitHub or via E-Mail (Andreas.D.Korb@gmail.com)" + Environment.NewLine + path, "An Error occured"); } } }