Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix formatting of table load errors
using System; using Rant.Localization; namespace Rant.Vocabulary { /// <summary> /// Thrown when Rant encounters an error while loading a dictionary table. /// </summary> public sealed class RantTableLoadException : Exception { internal RantTableLoadException(string origin, int line, int col, string messageType, params object[] messageArgs) : base(Txtres.GetString("src-line-col", Txtres.GetString(messageType, messageArgs), line, col)) { Line = line; Column = col; Origin = origin; } /// <summary> /// Gets the line number on which the error occurred. /// </summary> public int Line { get; } /// <summary> /// Gets the column on which the error occurred. /// </summary> public int Column { get; } /// <summary> /// Gets a string describing where the table was loaded from. For tables loaded from disk, this will be the file path. /// </summary> public string Origin { get; } } }
using System; using Rant.Localization; namespace Rant.Vocabulary { /// <summary> /// Thrown when Rant encounters an error while loading a dictionary table. /// </summary> public sealed class RantTableLoadException : Exception { internal RantTableLoadException(string origin, int line, int col, string messageType, params object[] messageArgs) : base($"{Txtres.GetString("src-line-col", origin, line, col)} {Txtres.GetString(messageType, messageArgs)}") { Line = line; Column = col; Origin = origin; } /// <summary> /// Gets the line number on which the error occurred. /// </summary> public int Line { get; } /// <summary> /// Gets the column on which the error occurred. /// </summary> public int Column { get; } /// <summary> /// Gets a string describing where the table was loaded from. For tables loaded from disk, this will be the file path. /// </summary> public string Origin { get; } } }
Update default publishing url to point to v2 feed.
using System; namespace NuGet { public static class NuGetConstants { public static readonly string DefaultFeedUrl = "https://go.microsoft.com/fwlink/?LinkID=230477"; public static readonly string V1FeedUrl = "https://go.microsoft.com/fwlink/?LinkID=206669"; public static readonly string DefaultGalleryServerUrl = "http://go.microsoft.com/fwlink/?LinkID=207106"; public static readonly string DefaultSymbolServerUrl = "http://nuget.gw.symbolsource.org/Public/NuGet"; } }
using System; namespace NuGet { public static class NuGetConstants { public static readonly string DefaultFeedUrl = "https://go.microsoft.com/fwlink/?LinkID=230477"; public static readonly string V1FeedUrl = "https://go.microsoft.com/fwlink/?LinkID=206669"; public static readonly string DefaultGalleryServerUrl = "https://www.nuget.org"; public static readonly string DefaultSymbolServerUrl = "http://nuget.gw.symbolsource.org/Public/NuGet"; } }
Allow message TimeStamp to be set when deserializing
using System; namespace JustSaying.Models { public abstract class Message { protected Message() { TimeStamp = DateTime.UtcNow; Id = Guid.NewGuid(); } public Guid Id { get; set; } public DateTime TimeStamp { get; private set; } public string RaisingComponent { get; set; } public string Version{ get; private set; } public string SourceIp { get; private set; } public string Tenant { get; set; } public string Conversation { get; set; } //footprint in order to avoid the same message being processed multiple times. public virtual string UniqueKey() { return Id.ToString(); } } }
using System; namespace JustSaying.Models { public abstract class Message { protected Message() { TimeStamp = DateTime.UtcNow; Id = Guid.NewGuid(); } public Guid Id { get; set; } public DateTime TimeStamp { get; set; } public string RaisingComponent { get; set; } public string Version{ get; private set; } public string SourceIp { get; private set; } public string Tenant { get; set; } public string Conversation { get; set; } //footprint in order to avoid the same message being processed multiple times. public virtual string UniqueKey() { return Id.ToString(); } } }
Revert "registration of api controllers fixed"
using System.Reflection; using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; namespace ReSharperTnT { public class Bootstrapper { public static void Init() { var bootstrapper = new Bootstrapper(); var container = bootstrapper.CreateContainer(); var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver; } private readonly IContainer _container; public Bootstrapper() { var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .AsImplementedInterfaces(); _container = builder.Build(); } public IContainer CreateContainer() { return _container; } public T Get<T>() { return _container.Resolve<T>(); } } }
using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; namespace ReSharperTnT { public class Bootstrapper { static Bootstrapper() { Init(); } public static void Init() { var bootstrapper = new Bootstrapper(); var container = bootstrapper.CreateContainer(); var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver; } private readonly IContainer _container; public Bootstrapper() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .AsImplementedInterfaces(); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .Where(c=>c.Name.EndsWith("Controller")) .AsSelf(); _container = builder.Build(); } public IContainer CreateContainer() { return _container; } public T Get<T>() { return _container.Resolve<T>(); } } }
Fix possible cause of null bytes in config file
using System; using System.IO; using System.Runtime.InteropServices; namespace SyncTrayzor.Utils { public class AtomicFileStream : FileStream { private const string DefaultTempFileSuffix = ".tmp"; private readonly string path; private readonly string tempPath; public AtomicFileStream(string path) : this(path, TempFilePath(path)) { } public AtomicFileStream(string path, string tempPath) : base(tempPath, FileMode.Create, FileAccess.ReadWrite) { this.path = path ?? throw new ArgumentNullException("path"); this.tempPath = tempPath ?? throw new ArgumentNullException("tempPath"); } private static string TempFilePath(string path) { return path + DefaultTempFileSuffix; } public override void Close() { base.Close(); bool success = NativeMethods.MoveFileEx(this.tempPath, this.path, MoveFileFlags.ReplaceExisting | MoveFileFlags.WriteThrough); if (!success) Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error()); } [Flags] private enum MoveFileFlags { None = 0, ReplaceExisting = 1, CopyAllowed = 2, DelayUntilReboot = 4, WriteThrough = 8, CreateHardlink = 16, FailIfNotTrackable = 32, } private static class NativeMethods { [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool MoveFileEx( [In] string lpExistingFileName, [In] string lpNewFileName, [In] MoveFileFlags dwFlags); } } }
using System; using System.IO; using System.Runtime.InteropServices; namespace SyncTrayzor.Utils { public class AtomicFileStream : FileStream { private const string DefaultTempFileSuffix = ".tmp"; private readonly string path; private readonly string tempPath; public AtomicFileStream(string path) : this(path, TempFilePath(path)) { } public AtomicFileStream(string path, string tempPath) : base(tempPath, FileMode.Create, FileAccess.ReadWrite) { this.path = path ?? throw new ArgumentNullException("path"); this.tempPath = tempPath ?? throw new ArgumentNullException("tempPath"); } private static string TempFilePath(string path) { return path + DefaultTempFileSuffix; } protected override void Dispose(bool disposing) { base.Dispose(disposing); bool success = NativeMethods.MoveFileEx(this.tempPath, this.path, MoveFileFlags.ReplaceExisting | MoveFileFlags.WriteThrough); if (!success) Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error()); } [Flags] private enum MoveFileFlags { None = 0, ReplaceExisting = 1, CopyAllowed = 2, DelayUntilReboot = 4, WriteThrough = 8, CreateHardlink = 16, FailIfNotTrackable = 32, } private static class NativeMethods { [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool MoveFileEx( [In] string lpExistingFileName, [In] string lpNewFileName, [In] MoveFileFlags dwFlags); } } }
Apply policy when loading reflection only assemblys
using System; using System.IO; using System.Reflection; namespace ApiCheck.Loader { public sealed class AssemblyLoader : IDisposable { public AssemblyLoader() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomainOnReflectionOnlyAssemblyResolve; } public void Dispose() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CurrentDomainOnReflectionOnlyAssemblyResolve; } private Assembly CurrentDomainOnReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) { AssemblyName assemblyName = new AssemblyName(args.Name); string path = Path.Combine(Path.GetDirectoryName(args.RequestingAssembly.Location), assemblyName.Name + ".dll"); if (File.Exists(path)) { return Assembly.ReflectionOnlyLoadFrom(path); } return Assembly.ReflectionOnlyLoad(args.Name); } public Assembly ReflectionOnlyLoad(string path) { return Assembly.ReflectionOnlyLoadFrom(path); } } }
using System; using System.IO; using System.Reflection; namespace ApiCheck.Loader { public sealed class AssemblyLoader : IDisposable { public AssemblyLoader() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomainOnReflectionOnlyAssemblyResolve; } public void Dispose() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CurrentDomainOnReflectionOnlyAssemblyResolve; } private Assembly CurrentDomainOnReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) { AssemblyName assemblyName = new AssemblyName(args.Name); string path = Path.Combine(Path.GetDirectoryName(args.RequestingAssembly.Location), assemblyName.Name + ".dll"); if (File.Exists(path)) { return Assembly.ReflectionOnlyLoadFrom(path); } return Assembly.ReflectionOnlyLoad(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); } public Assembly ReflectionOnlyLoad(string path) { return Assembly.ReflectionOnlyLoadFrom(path); } } }
Use single arrow character for backspace.
 using Android.Content; using Android.Views; using Android.Widget; namespace Calculator.Droid { public class ButtonAdapter : BaseAdapter { Context context; string[] buttons = new string[] { "<-", "C", "±", "/", "7", "8", "9", "*", "4", "5", "6", "-", "1", "2", "3", "+", "0", ".", null, "=" }; public ButtonAdapter (Context context) { this.context = context; } public override Java.Lang.Object GetItem (int position) { return null; } public override long GetItemId (int position) { return 0; } public override View GetView (int position, View convertView, ViewGroup parent) { Button button = null; string text = buttons [position]; if (convertView != null) { button = (Button)convertView; } else { button = new Button (context); } if (text != null) { button.Text = text; } else { button.Visibility = ViewStates.Invisible; } return button; } public override int Count { get { return buttons.Length; } } } }
 using Android.Content; using Android.Views; using Android.Widget; namespace Calculator.Droid { public class ButtonAdapter : BaseAdapter { Context context; string[] buttons = new string[] { "←", "C", "±", "/", "7", "8", "9", "*", "4", "5", "6", "-", "1", "2", "3", "+", "0", ".", null, "=" }; public ButtonAdapter (Context context) { this.context = context; } public override Java.Lang.Object GetItem (int position) { return null; } public override long GetItemId (int position) { return 0; } public override View GetView (int position, View convertView, ViewGroup parent) { Button button = null; string text = buttons [position]; if (convertView != null) { button = (Button)convertView; } else { button = new Button (context); } if (text != null) { button.Text = text; } else { button.Visibility = ViewStates.Invisible; } return button; } public override int Count { get { return buttons.Length; } } } }
Update server side API for single multiple answer question
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model /// </summary> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
Update param name to match IWebHookHandler
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.WebHooks; using Newtonsoft.Json.Linq; namespace GenericReceivers.WebHooks { public class GenericJsonWebHookHandler : WebHookHandler { public GenericJsonWebHookHandler() { this.Receiver = "genericjson"; } public override Task ExecuteAsync(string generator, WebHookHandlerContext context) { // Get JSON from WebHook JObject data = context.GetDataOrDefault<JObject>(); // Get the action for this WebHook coming from the action query parameter in the URI string action = context.Actions.FirstOrDefault(); return Task.FromResult(true); } } }
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.WebHooks; using Newtonsoft.Json.Linq; namespace GenericReceivers.WebHooks { public class GenericJsonWebHookHandler : WebHookHandler { public GenericJsonWebHookHandler() { this.Receiver = "genericjson"; } public override Task ExecuteAsync(string receiver, WebHookHandlerContext context) { // Get JSON from WebHook JObject data = context.GetDataOrDefault<JObject>(); // Get the action for this WebHook coming from the action query parameter in the URI string action = context.Actions.FirstOrDefault(); return Task.FromResult(true); } } }
Revert "remove a suppression no longer needed"
using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0071:Simplify interpolation", Justification = "IDE0071 considerably decreases the performance of string construction")]
using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0071:Simplify interpolation", Justification = "IDE0071 considerably decreases the performance of string construction")] [assembly: SuppressMessage("Style", "IDE0071WithoutSuggestion")]
Make NP file exception class public
using System; namespace NPSharp.NP { internal class NpFileException : Exception { internal NpFileException(int error) : base(error == 1 ? @"File not found on NP server" : @"Internal error on NP server") { } internal NpFileException() : base(@"Could not fetch file from NP server.") { } } }
using System; namespace NPSharp.NP { public class NpFileException : Exception { internal NpFileException(int error) : base(error == 1 ? @"File not found on NP server" : @"Internal error on NP server") { } internal NpFileException() : base(@"Could not fetch file from NP server.") { } } }
Add virtual property to album model
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Bravo.Models { public class Album { [Required] public int AlbumId { get; set; } [Required, MaxLength(255), Display(Name = "Title")] public string AlbumName { get; set; } [Required] public int GenreId { get; set; } [Required] public int ArtistId { get; set; } public ICollection<Song> Songs { get; set; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Bravo.Models { public class Album { [Required] public int AlbumId { get; set; } [Required, MaxLength(255), Display(Name = "Title")] public string AlbumName { get; set; } [Required] public int GenreId { get; set; } [Required] public int ArtistId { get; set; } public virtual Genre Genre { get; set; } public virtual Artist Artist { get; set; } public ICollection<Song> Songs { get; set; } } }
Remove obsolete send message method
using System; using MessageBird.Objects; using MessageBird.Resources; using MessageBird.Net; namespace MessageBird { public class Client { private IRestClient restClient; private Client(IRestClient restClient) { this.restClient = restClient; } public static Client Create(IRestClient restClient) { return new Client(restClient); } public static Client CreateDefault(string accessKey) { return new Client(new RestClient(accessKey)); } public Message SendMessage(Message message) { Messages messageToSend = new Messages(message); Messages result = (Messages)restClient.Create(messageToSend); return result.Message; } public Message SendMessage(string originator, string body, long[] msisdns, MessageOptionalArguments optionalArguments = null) { Recipients recipients = new Recipients(msisdns); Message message = new Message(originator, body, recipients, optionalArguments); Messages messages = new Messages(message); Messages result = (Messages)restClient.Create(messages); return result.Message; } public Message ViewMessage(string id) { Messages messageToView = new Messages(id); Messages result = (Messages)restClient.Retrieve(messageToView); return result.Message; } } }
using System; using MessageBird.Objects; using MessageBird.Resources; using MessageBird.Net; namespace MessageBird { public class Client { private IRestClient restClient; private Client(IRestClient restClient) { this.restClient = restClient; } public static Client Create(IRestClient restClient) { return new Client(restClient); } public static Client CreateDefault(string accessKey) { return new Client(new RestClient(accessKey)); } public Message SendMessage(string originator, string body, long[] msisdns, MessageOptionalArguments optionalArguments = null) { Recipients recipients = new Recipients(msisdns); Message message = new Message(originator, body, recipients, optionalArguments); Messages messages = new Messages(message); Messages result = (Messages)restClient.Create(messages); return result.Message; } public Message ViewMessage(string id) { Messages messageToView = new Messages(id); Messages result = (Messages)restClient.Retrieve(messageToView); return result.Message; } } }
Refactor from RaceType to DerbyType
using System; using System.ComponentModel.DataAnnotations; using Derby.Infrastructure; namespace Derby.Models { public class Competition { public int Id { get; set; } public int PackId { get; set; } public string Title { get; set; } public string Location { get; set; } [Required] [Display(Name = "Race Type")] public RaceType RaceType { get; set; } [Display(Name = "Created Date")] public DateTime CreatedDate { get; set; } [Required] [Display(Name = "Event Date")] [DataType(DataType.Date)] public DateTime EventDate { get; set; } [Required] [Display(Name = "Number of Lanes")] public int LaneCount { get; set; } public string CreatedById { get; set; } public Pack Pack { get; set; } public bool Completed { get; set; } } }
using System; using System.ComponentModel.DataAnnotations; using Derby.Infrastructure; namespace Derby.Models { public class Competition { public int Id { get; set; } public int PackId { get; set; } public string Title { get; set; } public string Location { get; set; } [Required] [Display(Name = "Race Type")] public DerbyType RaceType { get; set; } [Display(Name = "Created Date")] public DateTime CreatedDate { get; set; } [Required] [Display(Name = "Event Date")] [DataType(DataType.Date)] public DateTime EventDate { get; set; } [Required] [Display(Name = "Number of Lanes")] public int LaneCount { get; set; } public string CreatedById { get; set; } public Pack Pack { get; set; } public bool Completed { get; set; } } }
Allow to encode/decode the registry
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using BabelMark; using Newtonsoft.Json; namespace EncryptApp { class Program { static int Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: passphrase"); return 1; } Environment.SetEnvironmentVariable(MarkdownRegistry.PassphraseEnv, args[0]); var entries = MarkdownRegistry.Instance.GetEntriesAsync().Result; foreach (var entry in entries) { if (!entry.Url.StartsWith("http")) { entry.Url = StringCipher.Decrypt(entry.Url, args[0]); } else { var originalUrl = entry.Url; entry.Url = StringCipher.Encrypt(entry.Url, args[0]); var testDecrypt = StringCipher.Decrypt(entry.Url, args[0]); if (originalUrl != testDecrypt) { Console.WriteLine("Unexpected error while encrypt/decrypt. Not matching"); return 1; } } } Console.WriteLine(JsonConvert.SerializeObject(entries, Formatting.Indented)); return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using BabelMark; using Newtonsoft.Json; namespace EncryptApp { class Program { static int Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: passphrase decode|encode"); return 1; } if (!(args[1] == "decode" || args[1] == "encode")) { Console.WriteLine("Usage: passphrase decode|encode"); Console.WriteLine($"Invalid argument ${args[1]}"); return 1; } var encode = args[1] == "encode"; Environment.SetEnvironmentVariable(MarkdownRegistry.PassphraseEnv, args[0]); var entries = MarkdownRegistry.Instance.GetEntriesAsync().Result; foreach (var entry in entries) { if (encode) { var originalUrl = entry.Url; entry.Url = StringCipher.Encrypt(entry.Url, args[0]); var testDecrypt = StringCipher.Decrypt(entry.Url, args[0]); if (originalUrl != testDecrypt) { Console.WriteLine("Unexpected error while encrypt/decrypt. Not matching"); return 1; } } } Console.WriteLine(JsonConvert.SerializeObject(entries, Formatting.Indented)); return 0; } } }
Switch to FirefoxDriver due to instability of PhantomJS headless testing.
using System; using OpenQA.Selenium.PhantomJS; using OpenQA.Selenium.Remote; namespace ExpressiveAnnotations.MvcWebSample.UITests { public class DriverFixture : IDisposable { public DriverFixture() // called before every test class { var service = PhantomJSDriverService.CreateDefaultService(); service.IgnoreSslErrors = true; service.WebSecurity = false; var options = new PhantomJSOptions(); Driver = new PhantomJSDriver(service, options, TimeSpan.FromSeconds(15)); // headless browser testing } public RemoteWebDriver Driver { get; private set; } protected virtual void Dispose(bool disposing) { if (disposing) { if (Driver != null) { Driver.Quit(); Driver = null; } } } public void Dispose() // called after every test class { Dispose(true); GC.SuppressFinalize(this); } } }
using System; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.PhantomJS; using OpenQA.Selenium.Remote; namespace ExpressiveAnnotations.MvcWebSample.UITests { public class DriverFixture : IDisposable { public DriverFixture() // called before every test class { //var service = PhantomJSDriverService.CreateDefaultService(); //service.IgnoreSslErrors = true; //service.WebSecurity = false; //var options = new PhantomJSOptions(); //Driver = new PhantomJSDriver(service, options, TimeSpan.FromSeconds(15)); // headless browser testing Driver = new FirefoxDriver(); } public RemoteWebDriver Driver { get; private set; } protected virtual void Dispose(bool disposing) { if (disposing) { if (Driver != null) { Driver.Quit(); Driver = null; } } } public void Dispose() // called after every test class { Dispose(true); GC.SuppressFinalize(this); } } }
Read value of OneWire device with address in first command-line argument
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OneWireConsoleScanner { class Program { static void Main(string[] args) { Console.WriteLine("OneWire scanner"); var ports = OneWire.OneWire.GetPortNames(); if (ports.Length == 0) { Console.WriteLine("No one availible port"); return; } var oneWire = new OneWire.OneWire(); foreach (var port in ports) { oneWire.PortName = port; try { oneWire.Open(); if (oneWire.ResetLine()) { List<OneWire.OneWire.Address> devices; oneWire.FindDevices(out devices); Console.WriteLine("Found {0} devices on port {1}", devices.Count, port); devices.ForEach(Console.WriteLine); } else { Console.WriteLine("No devices on port {0}", port); } } catch { Console.WriteLine("Can't scan port {0}", port); } finally { oneWire.Close(); } } } } }
using System; using System.Collections.Generic; namespace OneWireConsoleScanner { internal class Program { private static void Main(string[] args) { Console.WriteLine("OneWire scanner"); var ports = OneWire.OneWire.GetPortNames(); if (ports.Length == 0) { Console.WriteLine("No one availible port"); return; } var oneWire = new OneWire.OneWire(); foreach (var port in ports) { oneWire.PortName = port; try { oneWire.Open(); if (oneWire.ResetLine()) { if (args.Length > 0) { // when read concrete devices var sensor = new OneWire.SensorDS18B20(oneWire) { Address = OneWire.OneWire.Address.Parse(args[0]) }; if (sensor.UpdateValue()) { Console.WriteLine("Sensor's {0} value is {1} C", sensor.Address, sensor.Value); } } else { List<OneWire.OneWire.Address> devices; oneWire.FindDevices(out devices); Console.WriteLine("Found {0} devices on port {1}", devices.Count, port); devices.ForEach(Console.WriteLine); } } else { Console.WriteLine("No devices on port {0}", port); } } catch { Console.WriteLine("Can't scan port {0}", port); } finally { oneWire.Close(); } } } } }
Insert check user fields for null
using System.Collections.Generic; using System.Collections.ObjectModel; using Azimuth.DataAccess.Infrastructure; namespace Azimuth.DataAccess.Entities { public class User : BaseEntity { public virtual Name Name { get; set; } public virtual string ScreenName { get; set; } public virtual string Gender { get; set; } public virtual string Birthday { get; set; } public virtual string Photo { get; set; } public virtual int Timezone { get; set; } public virtual Location Location { get; set; } public virtual string Email { get; set; } public virtual ICollection<UserSocialNetwork> SocialNetworks { get; set; } public virtual ICollection<User> Followers { get; set; } public virtual ICollection<User> Following { get; set; } public virtual ICollection<PlaylistLike> PlaylistFollowing { get; set; } public User() { SocialNetworks = new List<UserSocialNetwork>(); Followers = new List<User>(); Following = new List<User>(); PlaylistFollowing = new List<PlaylistLike>(); } public override string ToString() { return Name.FirstName + Name.LastName + ScreenName + Gender + Email + Birthday + Timezone + Location.City + ", " + Location.Country + Photo; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Azimuth.DataAccess.Infrastructure; namespace Azimuth.DataAccess.Entities { public class User : BaseEntity { public virtual Name Name { get; set; } public virtual string ScreenName { get; set; } public virtual string Gender { get; set; } public virtual string Birthday { get; set; } public virtual string Photo { get; set; } public virtual int Timezone { get; set; } public virtual Location Location { get; set; } public virtual string Email { get; set; } public virtual ICollection<UserSocialNetwork> SocialNetworks { get; set; } public virtual ICollection<User> Followers { get; set; } public virtual ICollection<User> Following { get; set; } public virtual ICollection<PlaylistLike> PlaylistFollowing { get; set; } public User() { SocialNetworks = new List<UserSocialNetwork>(); Followers = new List<User>(); Following = new List<User>(); PlaylistFollowing = new List<PlaylistLike>(); } public override string ToString() { return Name.FirstName ?? String.Empty + Name.LastName ?? String.Empty + ScreenName ?? String.Empty + Gender ?? String.Empty + Email ?? String.Empty + Birthday ?? String.Empty + Timezone ?? String.Empty + ((Location != null) ? Location.City ?? String.Empty : String.Empty) + ", " + ((Location != null) ? Location.Country ?? String.Empty : String.Empty) + Photo ?? String.Empty; } } }
Fix mis-matched split string indices (username is 0, password is 1).
namespace Bakery.Security { using System; using System.Text; using Text; public class BasicAuthenticationParser : IBasicAuthenticationParser { private readonly IBase64Parser base64Parser; private readonly Encoding encoding; public BasicAuthenticationParser(IBase64Parser base64Parser, Encoding encoding) { this.base64Parser = base64Parser; this.encoding = encoding; } public IBasicAuthentication TryParse(String @string) { if (!@string.StartsWith("BASIC ", StringComparison.OrdinalIgnoreCase)) return null; var basicAuthenticationBase64 = @string.Substring(6); var basicAuthenticationBytes = base64Parser.TryParse(basicAuthenticationBase64); if (basicAuthenticationBytes == null) return null; var basicAuthenticationText = TryGetString(basicAuthenticationBytes); if (basicAuthenticationText == null) return null; var parts = basicAuthenticationText.Split(new Char[] { ':' }, 2); if (parts.Length != 2) return null; return new BasicAuthentication() { Password = parts[0], Username = parts[1] }; } private String TryGetString(Byte[] bytes) { try { return encoding.GetString(bytes); } catch { return null; } } } }
namespace Bakery.Security { using System; using System.Text; using Text; public class BasicAuthenticationParser : IBasicAuthenticationParser { private readonly IBase64Parser base64Parser; private readonly Encoding encoding; public BasicAuthenticationParser(IBase64Parser base64Parser, Encoding encoding) { this.base64Parser = base64Parser; this.encoding = encoding; } public IBasicAuthentication TryParse(String @string) { if (!@string.StartsWith("BASIC ", StringComparison.OrdinalIgnoreCase)) return null; var basicAuthenticationBase64 = @string.Substring(6); var basicAuthenticationBytes = base64Parser.TryParse(basicAuthenticationBase64); if (basicAuthenticationBytes == null) return null; var basicAuthenticationText = TryGetString(basicAuthenticationBytes); if (basicAuthenticationText == null) return null; var parts = basicAuthenticationText.Split(new Char[] { ':' }, 2); if (parts.Length != 2) return null; return new BasicAuthentication() { Password = parts[1], Username = parts[0] }; } private String TryGetString(Byte[] bytes) { try { return encoding.GetString(bytes); } catch { return null; } } } }
Add extension method to check eq mat dimensions
using System.Collections.Generic; using WalletWasabi.Helpers; using WalletWasabi.Crypto.Groups; namespace System.Linq { public static class Extensions { public static GroupElement Sum(this IEnumerable<GroupElement> groupElements) => groupElements.Aggregate(GroupElement.Infinity, (ge, acc) => ge + acc); public static IEnumerable<TResult> Zip<TFirst, TSecond, TThird, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, IEnumerable<TThird> third, Func<TFirst, TSecond, TThird, TResult> resultSelector) { Guard.NotNull(nameof(first), first); Guard.NotNull(nameof(second), second); Guard.NotNull(nameof(third), third); Guard.NotNull(nameof(resultSelector), resultSelector); using var e1 = first.GetEnumerator(); using var e2 = second.GetEnumerator(); using var e3 = third.GetEnumerator(); while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext()) { yield return resultSelector(e1.Current, e2.Current, e3.Current); } } } }
using System.Collections.Generic; using WalletWasabi.Helpers; using WalletWasabi.Crypto.Groups; using WalletWasabi.Crypto.ZeroKnowledge.LinearRelation; using WalletWasabi.Crypto; namespace System.Linq { public static class Extensions { public static GroupElement Sum(this IEnumerable<GroupElement> groupElements) => groupElements.Aggregate(GroupElement.Infinity, (ge, acc) => ge + acc); public static IEnumerable<TResult> Zip<TFirst, TSecond, TThird, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, IEnumerable<TThird> third, Func<TFirst, TSecond, TThird, TResult> resultSelector) { Guard.NotNull(nameof(first), first); Guard.NotNull(nameof(second), second); Guard.NotNull(nameof(third), third); Guard.NotNull(nameof(resultSelector), resultSelector); using var e1 = first.GetEnumerator(); using var e2 = second.GetEnumerator(); using var e3 = third.GetEnumerator(); while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext()) { yield return resultSelector(e1.Current, e2.Current, e3.Current); } } public static void CheckDimesions(this IEnumerable<Equation> equations, IEnumerable<ScalarVector> allResponses) { if (equations.Count() != allResponses.Count() || Enumerable.Zip(equations, allResponses).Any(x => x.First.Generators.Count() != x.Second.Count())) { throw new ArgumentException("The number of responses and the number of generators in the equations do not match."); } } } }
Rename cache refresh and make public
using UnityEngine; namespace HoloToolkit.Unity { public static class CameraCache { private static Camera cachedCamera; /// <summary> /// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet. /// </summary> public static Camera main { get { return cachedCamera ?? CacheMain(Camera.main); } } /// <summary> /// Set the cached camera to a new reference and return it /// </summary> /// <param name="newMain">New main camera to cache</param> /// <returns></returns> private static Camera CacheMain(Camera newMain) { return cachedCamera = newMain; } } }
using UnityEngine; namespace HoloToolkit.Unity { public static class CameraCache { private static Camera cachedCamera; /// <summary> /// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet. /// </summary> public static Camera main { get { return cachedCamera ?? Refresh(Camera.main); } } /// <summary> /// Set the cached camera to a new reference and return it /// </summary> /// <param name="newMain">New main camera to cache</param> /// <returns></returns> public static Camera Refresh(Camera newMain) { return cachedCamera = newMain; } } }
Add comments and the TTL and highPriority flags for android notifications
using System; namespace CertiPay.Common.Notifications { public class AndroidNotification : Notification { public static string QueueName { get; } = "AndroidNotifications"; // Message => Content /// <summary> /// The subject line of the email /// </summary> public String Title { get; set; } // TODO Android specific properties? Image, Sound, Action Button, Picture, Priority } }
using System; namespace CertiPay.Common.Notifications { /// <summary> /// Describes a notification sent to an Android device via Google Cloud Messaging /// </summary> public class AndroidNotification : Notification { public static string QueueName { get; } = "AndroidNotifications"; /// <summary> /// The subject line of the notification /// </summary> public String Title { get; set; } /// <summary> /// Maximum lifespan of the message, from 0 to 4 weeks, after which delivery attempts will expire. /// Setting this to 0 seconds will prevent GCM from throttling the "now or never" message. /// /// GCM defaults this to 4 weeks. /// </summary> public TimeSpan? TimeToLive { get; set; } /// <summary> /// Set high priority only if the message is time-critical and requires the user’s /// immediate interaction, and beware that setting your messages to high priority contributes /// more to battery drain compared to normal priority messages. /// </summary> public Boolean HighPriority { get; set; } = false; } }
Add nl to end of file
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ExtractCopyright.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] // 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("085a7785-c407-4623-80c0-bffd2b0d2475")] #if STRONG_NAME [assembly: AssemblyKeyFileAttribute("../palaso.snk")] #endif
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ExtractCopyright.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] // 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("085a7785-c407-4623-80c0-bffd2b0d2475")] #if STRONG_NAME [assembly: AssemblyKeyFileAttribute("../palaso.snk")] #endif
Add unit test that checks that a logger retrieved before the log manager is initialised can log correctly
using NUnit.Framework; namespace ZeroLog.Tests { [TestFixture] public class UninitializedLogManagerTests { [TearDown] public void Teardown() { LogManager.Shutdown(); } [Test] public void should_log_without_initialize() { LogManager.GetLogger("Test").Info($"Test"); } } }
using System; using NFluent; using NUnit.Framework; using ZeroLog.Configuration; namespace ZeroLog.Tests { [TestFixture, NonParallelizable] public class UninitializedLogManagerTests { private TestAppender _testAppender; [SetUp] public void SetUpFixture() { _testAppender = new TestAppender(true); } [TearDown] public void Teardown() { LogManager.Shutdown(); } [Test] public void should_log_without_initialize() { LogManager.GetLogger("Test").Info($"Test"); } [Test] public void should_log_correctly_when_logger_is_retrieved_before_log_manager_is_initialized() { var log = LogManager.GetLogger<LogManagerTests>(); LogManager.Initialize(new ZeroLogConfiguration { LogMessagePoolSize = 10, RootLogger = { Appenders = { _testAppender } } }); var signal = _testAppender.SetMessageCountTarget(1); log.Info("Lol"); Check.That(signal.Wait(TimeSpan.FromMilliseconds(100))).IsTrue(); } } }
Change default timeout to 30 seconds
using System; namespace Renci.SshClient { public class ConnectionInfo { public string Host { get; set; } public int Port { get; set; } public string Username { get; set; } public string Password { get; set; } public PrivateKeyFile KeyFile { get; set; } public TimeSpan Timeout { get; set; } public int RetryAttempts { get; set; } public int MaxSessions { get; set; } public ConnectionInfo() { // Set default connection values this.Port = 22; this.Timeout = TimeSpan.FromMinutes(30); this.RetryAttempts = 10; this.MaxSessions = 10; } } }
using System; namespace Renci.SshClient { public class ConnectionInfo { public string Host { get; set; } public int Port { get; set; } public string Username { get; set; } public string Password { get; set; } public PrivateKeyFile KeyFile { get; set; } public TimeSpan Timeout { get; set; } public int RetryAttempts { get; set; } public int MaxSessions { get; set; } public ConnectionInfo() { // Set default connection values this.Port = 22; this.Timeout = TimeSpan.FromSeconds(30); this.RetryAttempts = 10; this.MaxSessions = 10; } } }
Handle subdirectories during beatmap stable import
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.IO; namespace osu.Game.Database { public class LegacyBeatmapImporter : LegacyModelImporter<BeatmapSetInfo> { protected override string ImportFromStablePath => "."; protected override Storage PrepareStableStorage(StableStorage stableStorage) => stableStorage.GetSongStorage(); public LegacyBeatmapImporter(IModelImporter<BeatmapSetInfo> importer) : base(importer) { } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.IO; namespace osu.Game.Database { public class LegacyBeatmapImporter : LegacyModelImporter<BeatmapSetInfo> { protected override string ImportFromStablePath => "."; protected override Storage PrepareStableStorage(StableStorage stableStorage) => stableStorage.GetSongStorage(); protected override IEnumerable<string> GetStableImportPaths(Storage storage) { foreach (string beatmapDirectory in storage.GetDirectories(string.Empty)) { var beatmapStorage = storage.GetStorageForDirectory(beatmapDirectory); if (!beatmapStorage.GetFiles(string.Empty).ExcludeSystemFileNames().Any()) { // if a directory doesn't contain files, attempt looking for beatmaps inside of that directory. // this is a special behaviour in stable for beatmaps only, see https://github.com/ppy/osu/issues/18615. foreach (string beatmapInDirectory in GetStableImportPaths(beatmapStorage)) yield return beatmapStorage.GetFullPath(beatmapInDirectory); } else yield return storage.GetFullPath(beatmapDirectory); } } public LegacyBeatmapImporter(IModelImporter<BeatmapSetInfo> importer) : base(importer) { } } }
Update tests to use newer name for 'webapi' template
using Xunit; using Xunit.Abstractions; namespace Templates.Test { public class WebApiTemplateTest : TemplateTestBase { public WebApiTemplateTest(ITestOutputHelper output) : base(output) { } [Theory] [InlineData(null)] [InlineData("net461")] public void WebApiTemplate_Works(string targetFrameworkOverride) { RunDotNetNew("api", targetFrameworkOverride); foreach (var publish in new[] { false, true }) { using (var aspNetProcess = StartAspNetProcess(targetFrameworkOverride, publish)) { aspNetProcess.AssertOk("/api/values"); aspNetProcess.AssertNotFound("/"); } } } } }
using Xunit; using Xunit.Abstractions; namespace Templates.Test { public class WebApiTemplateTest : TemplateTestBase { public WebApiTemplateTest(ITestOutputHelper output) : base(output) { } [Theory] [InlineData(null)] [InlineData("net461")] public void WebApiTemplate_Works(string targetFrameworkOverride) { RunDotNetNew("webapi", targetFrameworkOverride); foreach (var publish in new[] { false, true }) { using (var aspNetProcess = StartAspNetProcess(targetFrameworkOverride, publish)) { aspNetProcess.AssertOk("/api/values"); aspNetProcess.AssertNotFound("/"); } } } } }
Enable error traces for Razor.
using Nancy; namespace Plating { public class Bootstrapper : DefaultNancyBootstrapper { public Bootstrapper() { Cassette.Nancy.CassetteNancyStartup.OptimizeOutput = true; } } }
using Nancy; namespace Plating { public class Bootstrapper : DefaultNancyBootstrapper { public Bootstrapper() { StaticConfiguration.DisableErrorTraces = false; Cassette.Nancy.CassetteNancyStartup.OptimizeOutput = true; } } }
Change class name to OrderingTypes.
namespace CompetitionPlatform.Helpers { public static class StreamsRoles { public const string Admin = "ADMIN"; } public static class ResultVoteTypes { public const string Admin = "ADMIN"; public const string Author = "AUTHOR"; } public static class OrderingConstants { public const string All = "All"; public const string Ascending = "Ascending"; public const string Descending = "Descending"; } public static class LykkeEmailDomains { public const string LykkeCom = "lykke.com"; public const string LykkexCom = "lykkex.com"; } }
namespace CompetitionPlatform.Helpers { public static class StreamsRoles { public const string Admin = "ADMIN"; } public static class ResultVoteTypes { public const string Admin = "ADMIN"; public const string Author = "AUTHOR"; } public static class OrderingTypes { public const string All = "All"; public const string Ascending = "Ascending"; public const string Descending = "Descending"; } public static class LykkeEmailDomains { public const string LykkeCom = "lykke.com"; public const string LykkexCom = "lykkex.com"; } }
Add BoolParameter and IntParameter to enum
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Snowflake.Ajax { /// <summary> /// A metadata attribute to indicate parameter methods /// Does not affect execution. /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public class AjaxMethodParameterAttribute : Attribute { public string ParameterName { get; set; } public AjaxMethodParameterType ParameterType { get; set; } } public enum AjaxMethodParameterType { StringParameter, ObjectParameter, ArrayParameter } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Snowflake.Ajax { /// <summary> /// A metadata attribute to indicate parameter methods /// Does not affect execution. /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public class AjaxMethodParameterAttribute : Attribute { public string ParameterName { get; set; } public AjaxMethodParameterType ParameterType { get; set; } } public enum AjaxMethodParameterType { StringParameter, ObjectParameter, ArrayParameter, BoolParameter, IntParameter } }
Add Refresh() Method to ISerachModule to allow forcing a sim to resend it's search data
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; namespace OpenSim.Framework { public interface ISearchModule { } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; namespace OpenSim.Framework { public interface ISearchModule { void Refresh(); } }
Use new return value of Guard.ExpectNode to refine casting...
namespace dotless.Core.Parser.Functions { using System.Linq; using Infrastructure; using Infrastructure.Nodes; using Tree; using Utils; public class RgbaFunction : Function { protected override Node Evaluate(Env env) { if (Arguments.Count == 2) { Guard.ExpectNode<Color>(Arguments[0], this, Location); Guard.ExpectNode<Number>(Arguments[1], this, Location); return new Color(((Color) Arguments[0]).RGB, ((Number) Arguments[1]).Value); } Guard.ExpectNumArguments(4, Arguments.Count, this, Location); Guard.ExpectAllNodes<Number>(Arguments, this, Location); var args = Arguments.Cast<Number>(); var rgb = args.Take(3); return new Color(rgb, args.ElementAt(3)); } } }
namespace dotless.Core.Parser.Functions { using System.Linq; using Infrastructure; using Infrastructure.Nodes; using Tree; using Utils; public class RgbaFunction : Function { protected override Node Evaluate(Env env) { if (Arguments.Count == 2) { var color = Guard.ExpectNode<Color>(Arguments[0], this, Location); var alpha = Guard.ExpectNode<Number>(Arguments[1], this, Location); return new Color(color.RGB, alpha.Value); } Guard.ExpectNumArguments(4, Arguments.Count, this, Location); Guard.ExpectAllNodes<Number>(Arguments, this, Location); var args = Arguments.Cast<Number>(); var rgb = args.Take(3); return new Color(rgb, args.ElementAt(3)); } } }
Add visual MessageBox when an unhandled crash is encountered
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace unBand { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private void Application_Exit(object sender, ExitEventArgs e) { unBand.Properties.Settings.Default.Save(); } private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { Telemetry.Client.TrackException(e.Exception); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace unBand { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private void Application_Exit(object sender, ExitEventArgs e) { unBand.Properties.Settings.Default.Save(); } private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { Telemetry.Client.TrackException(e.Exception); MessageBox.Show("An unhandled exception occurred - sorry about that, we're going to have to crash now :(\n\nYou can open a bug with a copy of this crash: hit Ctrl + C right now and then paste into a new bug at https://github.com/nachmore/unBand/issues.\n\n" + e.Exception.ToString(), "Imminent Crash", MessageBoxButton.OK, MessageBoxImage.Exclamation); } } }
Fix issue with trailing whitespace.
using System.IO; using System.Net.Http; using MyCouch.Extensions; using MyCouch.Serialization; namespace MyCouch.Responses.Factories { public class DocumentResponseFactory : ResponseFactoryBase { public DocumentResponseFactory(SerializationConfiguration serializationConfiguration) : base(serializationConfiguration) { } public virtual DocumentResponse Create(HttpResponseMessage httpResponse) { return Materialize(new DocumentResponse(), httpResponse, OnSuccessfulResponse, OnFailedResponse); } protected virtual void OnSuccessfulResponse(DocumentResponse response, HttpResponseMessage httpResponse) { using (var content = httpResponse.Content.ReadAsStream()) { if (ContentShouldHaveIdAndRev(httpResponse.RequestMessage)) PopulateDocumentHeaderFromResponseStream(response, content); else { PopulateMissingIdFromRequestUri(response, httpResponse); PopulateMissingRevFromRequestHeaders(response, httpResponse); } content.Position = 0; using (var reader = new StreamReader(content, MyCouchRuntime.DefaultEncoding)) { response.Content = reader.ReadToEnd(); } } } } }
using System.IO; using System.Net.Http; using System.Text; using MyCouch.Extensions; using MyCouch.Serialization; namespace MyCouch.Responses.Factories { public class DocumentResponseFactory : ResponseFactoryBase { public DocumentResponseFactory(SerializationConfiguration serializationConfiguration) : base(serializationConfiguration) { } public virtual DocumentResponse Create(HttpResponseMessage httpResponse) { return Materialize(new DocumentResponse(), httpResponse, OnSuccessfulResponse, OnFailedResponse); } protected virtual void OnSuccessfulResponse(DocumentResponse response, HttpResponseMessage httpResponse) { using (var content = httpResponse.Content.ReadAsStream()) { if (ContentShouldHaveIdAndRev(httpResponse.RequestMessage)) PopulateDocumentHeaderFromResponseStream(response, content); else { PopulateMissingIdFromRequestUri(response, httpResponse); PopulateMissingRevFromRequestHeaders(response, httpResponse); } content.Position = 0; var sb = new StringBuilder(); using (var reader = new StreamReader(content, MyCouchRuntime.DefaultEncoding)) { while (!reader.EndOfStream) { sb.Append(reader.ReadLine()); } } response.Content = sb.ToString(); sb.Clear(); } } } }
Use the user-specific appdata path for the repository cache
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using RepoZ.Api.Common; using RepoZ.Api.Common.Git; using RepoZ.Api.Git; namespace RepoZ.Api.Win.Git { public class WindowsRepositoryCache : FileRepositoryCache { public WindowsRepositoryCache(IErrorHandler errorHandler) : base(errorHandler) { } public override string GetFileName() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "RepoZ\\Repositories.cache"); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using RepoZ.Api.Common; using RepoZ.Api.Common.Git; using RepoZ.Api.Git; namespace RepoZ.Api.Win.Git { public class WindowsRepositoryCache : FileRepositoryCache { public WindowsRepositoryCache(IErrorHandler errorHandler) : base(errorHandler) { } public override string GetFileName() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RepoZ\\Repositories.cache"); } }
Remove unused directives from benchmarking
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using FreeImageAPI; using ImageMagick; using DS = DevILSharp; namespace Pfim.Benchmarks { public class DdsBenchmark { [Params("dxt1-simple.dds", "dxt3-simple.dds", "dxt5-simple.dds", "32-bit-uncompressed.dds")] public string Payload { get; set; } private byte[] data; [GlobalSetup] public void SetupData() { data = File.ReadAllBytes(Payload); DS.Bootstrap.Init(); } [Benchmark] public IImage Pfim() => Dds.Create(new MemoryStream(data)); [Benchmark] public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data)); [Benchmark] public int ImageMagick() { var settings = new MagickReadSettings { Format = MagickFormat.Dds }; 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.Dds)) { return image.Width; } } } }
using System.IO; using BenchmarkDotNet.Attributes; using FreeImageAPI; using ImageMagick; using DS = DevILSharp; namespace Pfim.Benchmarks { public class DdsBenchmark { [Params("dxt1-simple.dds", "dxt3-simple.dds", "dxt5-simple.dds", "32-bit-uncompressed.dds")] public string Payload { get; set; } private byte[] data; [GlobalSetup] public void SetupData() { data = File.ReadAllBytes(Payload); DS.Bootstrap.Init(); } [Benchmark] public IImage Pfim() => Dds.Create(new MemoryStream(data)); [Benchmark] public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data)); [Benchmark] public int ImageMagick() { var settings = new MagickReadSettings { Format = MagickFormat.Dds }; 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.Dds)) { return image.Width; } } } }
Update startup of sample to pass in the serviceProvider
using Glimpse.Host.Web.Owin; using Owin; namespace Glimpse.Owin.Sample { public class Startup { public void Configuration(IAppBuilder app) { app.Use<GlimpseMiddleware>(); app.UseWelcomePage(); app.UseErrorPage(); } } }
using Glimpse.Host.Web.Owin; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection.Fallback; using Owin; using System.Collections.Generic; namespace Glimpse.Owin.Sample { public class Startup { public void Configuration(IAppBuilder app) { var serviceDescriptors = new List<IServiceDescriptor>(); var serviceProvider = serviceDescriptors.BuildServiceProvider(); app.Use<GlimpseMiddleware>(serviceProvider); app.UseWelcomePage(); app.UseErrorPage(); } } }
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
Use List because IList isn't supported by FX.Configuration
using System; using System.Collections.Generic; namespace IntegrationEngine.Core.Configuration { public class IntegrationPointConfigurations { public IList<MailConfiguration> Mail { get; set; } public IList<RabbitMQConfiguration> RabbitMQ { get; set; } public IList<ElasticsearchConfiguration> Elasticsearch { get; set; } } }
using System; using System.Collections.Generic; namespace IntegrationEngine.Core.Configuration { public class IntegrationPointConfigurations { public List<MailConfiguration> Mail { get; set; } public List<RabbitMQConfiguration> RabbitMQ { get; set; } public List<ElasticsearchConfiguration> Elasticsearch { get; set; } } }
Remove unnecessary null check and associated comment
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Tests.Visual { /// <summary> /// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests. /// </summary> public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene { protected override void Update() { base.Update(); if (Beatmap.Value.TrackLoaded && Beatmap.Value.Track != null) // null check... wasn't required until now? { // note that this will override any mod rate application Beatmap.Value.Track.Tempo.Value = Clock.Rate; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Tests.Visual { /// <summary> /// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests. /// </summary> public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene { protected override void Update() { base.Update(); if (Beatmap.Value.TrackLoaded) { // note that this will override any mod rate application Beatmap.Value.Track.Tempo.Value = Clock.Rate; } } } }
Remove not common engine from base
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System; namespace Wangkanai.Detection.Models { [Flags] public enum Engine { Unknown = 0, // Unknown engine WebKit = 1, // iOs (Safari, WebViews, Chrome <28) Blink = 1 << 1, // Google Chrome, Opera v15+ Gecko = 1 << 2, // Firefox, Netscape Trident = 1 << 3, // IE, Outlook EdgeHTML = 1 << 4, // Microsoft Edge KHTML = 1 << 5, // Konqueror Presto = 1 << 6, // Goanna = 1 << 7, // Pale Moon NetSurf = 1 << 8, // NetSurf NetFront = 1 << 9, // Access NetFront Prince = 1 << 10, // Robin = 1 << 11, // The Bat! Servo = 1 << 12, // Mozilla & Samsung Tkhtml = 1 << 13, // hv3 Links2 = 1 << 14, // launched with -g Others = 1 << 15 // Others } }
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System; namespace Wangkanai.Detection.Models { [Flags] public enum Engine { Unknown = 0, // Unknown engine WebKit = 1, // iOs (Safari, WebViews, Chrome <28) Blink = 1 << 1, // Google Chrome, Opera v15+ Gecko = 1 << 2, // Firefox, Netscape Trident = 1 << 3, // IE, Outlook EdgeHTML = 1 << 4, // Microsoft Edge Servo = 1 << 12, // Mozilla & Samsung Others = 1 << 15 // Others } }
Fix APFT list sort by score
@model IEnumerable<APFT> <div class="page-header"> <h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1> </div> <table class="table table-striped" id="dt"> <thead> <tr> <th>Soldier</th> <th>Date</th> <th>Score</th> <th>Result</th> <th>Details</th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td> <a href="@Url.Action("Index", new { date = model.Date })"> @Html.DisplayFor(_ => model.Date) </a> </td> <td> @Html.DisplayFor(_ => model.TotalScore) @if(model.IsAlternateAerobicEvent) { <span class="label">Alt. Aerobic</span> } </td> <td> @if (model.IsPassing) { <span class="label label-success">Passing</span> } else { <span class="label label-danger">Failure</span> } </td> <td>@Html.ActionLink("Details", "Details", new { model.Id })</td> </tr> } </tbody> </table>
@model IEnumerable<APFT> <div class="page-header"> <h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1> </div> <table class="table table-striped" id="dt"> <thead> <tr> <th>Soldier</th> <th>Date</th> <th>Score</th> <th>Result</th> <th>Details</th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td> <a href="@Url.Action("Index", new { date = model.Date })"> @Html.DisplayFor(_ => model.Date) </a> </td> <td data-sort="@model.TotalScore"> @Html.DisplayFor(_ => model.TotalScore) @if(model.IsAlternateAerobicEvent) { <span class="label">Alt. Aerobic</span> } </td> <td> @if (model.IsPassing) { <span class="label label-success">Passing</span> } else { <span class="label label-danger">Failure</span> } </td> <td>@Html.ActionLink("Details", "Details", new { model.Id })</td> </tr> } </tbody> </table>
Fix grammer issue and more rewording
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Catch.Skinning { public enum CatchSkinColour { /// <summary> /// The colour to be used for the catcher while on hyper-dashing state. /// </summary> HyperDash, /// <summary> /// The colour to be used for hyper-dash fruits. /// </summary> HyperDashFruit, /// <summary> /// The colour to be used for the "exploding" catcher sprite on beginning of hyper-dashing. /// </summary> HyperDashAfterImage, } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Catch.Skinning { public enum CatchSkinColour { /// <summary> /// The colour to be used for the catcher while in hyper-dashing state. /// </summary> HyperDash, /// <summary> /// The colour to be used for fruits that grant the catcher the ability to hyper-dash. /// </summary> HyperDashFruit, /// <summary> /// The colour to be used for the "exploding" catcher sprite on beginning of hyper-dashing. /// </summary> HyperDashAfterImage, } }
Update header breadcrumb tab control
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays { public abstract class BreadcrumbControlOverlayHeader : TabControlOverlayHeader<string> { protected override OsuTabControl<string> CreateTabControl() => new OverlayHeaderBreadcrumbControl(); public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string> { public OverlayHeaderBreadcrumbControl() { RelativeSizeAxes = Axes.X; } protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value); private class ControlTabItem : BreadcrumbTabItem { protected override float ChevronSize => 8; public ControlTabItem(string value) : base(value) { Text.Font = Text.Font.With(size: 14); Chevron.Y = 3; Bar.Height = 0; } } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays { public abstract class BreadcrumbControlOverlayHeader : TabControlOverlayHeader<string> { protected override OsuTabControl<string> CreateTabControl() => new OverlayHeaderBreadcrumbControl(); public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string> { public OverlayHeaderBreadcrumbControl() { RelativeSizeAxes = Axes.X; Height = 47; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { AccentColour = colourProvider.Light2; } protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value); private class ControlTabItem : BreadcrumbTabItem { protected override float ChevronSize => 8; public ControlTabItem(string value) : base(value) { RelativeSizeAxes = Axes.Y; Text.Font = Text.Font.With(size: 14); Text.Anchor = Anchor.CentreLeft; Text.Origin = Anchor.CentreLeft; Chevron.Y = 1; Bar.Height = 0; } // base OsuTabItem makes font bold on activation, we don't want that here protected override void OnActivated() => FadeHovered(); protected override void OnDeactivated() => FadeUnhovered(); } } } }
Revise dropdowns for building unitypackages.
using UnityEditor; using UnityEngine; namespace PlayFab.Internal { public static class PlayFabEdExPackager { private static readonly string[] SdkAssets = { "Assets/PlayFabEditorExtensions" }; [MenuItem("PlayFab/Build PlayFab EdEx UnityPackage")] public static void BuildUnityPackage() { var packagePath = "C:/depot/sdks/UnityEditorExtensions/Packages/PlayFabEditorExtensions.unitypackage"; AssetDatabase.ExportPackage(SdkAssets, packagePath, ExportPackageOptions.Recurse); Debug.Log("Package built: " + packagePath); } } }
using UnityEditor; using UnityEngine; namespace PlayFab.Internal { public static class PlayFabEdExPackager { private static readonly string[] SdkAssets = { "Assets/PlayFabEditorExtensions" }; [MenuItem("PlayFab/Testing/Build PlayFab EdEx UnityPackage")] public static void BuildUnityPackage() { var packagePath = "C:/depot/sdks/UnityEditorExtensions/Packages/PlayFabEditorExtensions.unitypackage"; AssetDatabase.ExportPackage(SdkAssets, packagePath, ExportPackageOptions.Recurse); Debug.Log("Package built: " + packagePath); } } }
Increase project version number to 0.11.0
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.10.0.0")] [assembly: AssemblyFileVersion("0.10.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.11.0.0")] [assembly: AssemblyFileVersion("0.11.0.0")]
Check debugger is attached before writing something to it
#define Debug using System; using System.Collections.Generic; using System.Diagnostics; namespace Bit.ViewModel { public class BitExceptionHandler { public static BitExceptionHandler Current { get; set; } = new BitExceptionHandler(); public virtual void OnExceptionReceived(Exception exp, IDictionary<string, string> properties = null) { properties = properties ?? new Dictionary<string, string>(); if (exp != null) { Debug.WriteLine($"DateTime: {DateTime.Now.ToLongTimeString()} Message: {exp}", category: "ApplicationException"); } } } }
#define Debug using System; using System.Collections.Generic; using System.Diagnostics; namespace Bit.ViewModel { public class BitExceptionHandler { public static BitExceptionHandler Current { get; set; } = new BitExceptionHandler(); public virtual void OnExceptionReceived(Exception exp, IDictionary<string, string> properties = null) { properties = properties ?? new Dictionary<string, string>(); if (exp != null && Debugger.IsAttached) { Debug.WriteLine($"DateTime: {DateTime.Now.ToLongTimeString()} Message: {exp}", category: "ApplicationException"); } } } }
Use Any instead of Count > 0
using Microsoft.AspNetCore.Http; using NJsonSchema; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Porthor.ResourceRequestValidators.ContentValidators { /// <summary> /// Request validator for json content. /// </summary> public class JsonValidator : ContentValidatorBase { private readonly JsonSchema4 _schema; /// <summary> /// Constructs a new instance of <see cref="JsonValidator"/>. /// </summary> /// <param name="template">Template for json schema.</param> public JsonValidator(string template) : base(template) { _schema = JsonSchema4.FromJsonAsync(template).GetAwaiter().GetResult(); } /// <summary> /// Validates the content of the current <see cref="HttpContext"/> agains the json schema. /// </summary> /// <param name="context">Current context.</param> /// <returns> /// The <see cref="Task{HttpRequestMessage}"/> that represents the asynchronous query string validation process. /// Returns null if the content is valid agains the json schema. /// </returns> public override async Task<HttpResponseMessage> ValidateAsync(HttpContext context) { var errors = _schema.Validate(await StreamToString(context.Request.Body)); if (errors.Count > 0) { return new HttpResponseMessage(HttpStatusCode.BadRequest); } return null; } private Task<string> StreamToString(Stream stream) { var streamContent = new StreamContent(stream); stream.Position = 0; return streamContent.ReadAsStringAsync(); } } }
using Microsoft.AspNetCore.Http; using NJsonSchema; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Porthor.ResourceRequestValidators.ContentValidators { /// <summary> /// Request validator for json content. /// </summary> public class JsonValidator : ContentValidatorBase { private readonly JsonSchema4 _schema; /// <summary> /// Constructs a new instance of <see cref="JsonValidator"/>. /// </summary> /// <param name="template">Template for json schema.</param> public JsonValidator(string template) : base(template) { _schema = JsonSchema4.FromJsonAsync(template).GetAwaiter().GetResult(); } /// <summary> /// Validates the content of the current <see cref="HttpContext"/> agains the json schema. /// </summary> /// <param name="context">Current context.</param> /// <returns> /// The <see cref="Task{HttpRequestMessage}"/> that represents the asynchronous query string validation process. /// Returns null if the content is valid agains the json schema. /// </returns> public override async Task<HttpResponseMessage> ValidateAsync(HttpContext context) { var errors = _schema.Validate(await StreamToString(context.Request.Body)); if (errors.Any()) { return new HttpResponseMessage(HttpStatusCode.BadRequest); } return null; } private Task<string> StreamToString(Stream stream) { var streamContent = new StreamContent(stream); stream.Position = 0; return streamContent.ReadAsStringAsync(); } } }
Revert "Fixed a bug where closing the quicknotes window then clicking show/hide quicknotes on the settings window would crash the program."
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.Shapes; namespace Saveyour { /// <summary> /// Interaction logic for Settings.xaml /// </summary> public partial class Settings : Window, Module { Window qnotes; public Settings() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (qnotes.IsVisible) qnotes.Hide(); else if (qnotes.IsActive) qnotes.Show(); } public void addQNotes(Window module) { qnotes = module; } public String moduleID() { return "Settings"; } public Boolean update() { return false; } public String save() { return ""; } public Boolean load(String data) { return false; } public Boolean Equals(Module other) { return false; } } }
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.Shapes; namespace Saveyour { /// <summary> /// Interaction logic for Settings.xaml /// </summary> public partial class Settings : Window, Module { Window qnotes; public Settings() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (qnotes.IsVisible) qnotes.Hide(); else qnotes.Show(); } public void addQNotes(Window module) { qnotes = module; } public String moduleID() { return "Settings"; } public Boolean update() { return false; } public String save() { return ""; } public Boolean load(String data) { return false; } public Boolean Equals(Module other) { return false; } } }
Set env vars when updating VSTS variables
namespace Nerdbank.GitVersioning.CloudBuildServices { using System; using System.IO; /// <summary> /// /// </summary> /// <remarks> /// The VSTS-specific properties referenced here are documented here: /// https://msdn.microsoft.com/en-us/Library/vs/alm/Build/scripts/variables /// </remarks> internal class VisualStudioTeamServices : ICloudBuild { public bool IsPullRequest => false; // VSTS doesn't define this. public string BuildingTag => null; // VSTS doesn't define this. public string BuildingBranch => Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); public string BuildingRef => this.BuildingBranch; public string GitCommitId => null; public bool IsApplicable => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECTID")); public void SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[build.updatebuildnumber]{buildNumber}"); } public void SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[task.setvariable variable={name};]{value}"); } } }
namespace Nerdbank.GitVersioning.CloudBuildServices { using System; using System.IO; /// <summary> /// /// </summary> /// <remarks> /// The VSTS-specific properties referenced here are documented here: /// https://msdn.microsoft.com/en-us/Library/vs/alm/Build/scripts/variables /// </remarks> internal class VisualStudioTeamServices : ICloudBuild { public bool IsPullRequest => false; // VSTS doesn't define this. public string BuildingTag => null; // VSTS doesn't define this. public string BuildingBranch => Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); public string BuildingRef => this.BuildingBranch; public string GitCommitId => null; public bool IsApplicable => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECTID")); public void SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[build.updatebuildnumber]{buildNumber}"); SetEnvVariableForBuildVariable("Build.BuildNumber", buildNumber); } public void SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[task.setvariable variable={name};]{value}"); SetEnvVariableForBuildVariable(name, value); } private static void SetEnvVariableForBuildVariable(string name, string value) { string envVarName = name.ToUpperInvariant().Replace('.', '_'); Environment.SetEnvironmentVariable(envVarName, value); } } }
Set default size for window
using System.Windows; using Caliburn.Micro; using OctopusPuppet.Gui.ViewModels; namespace OctopusPuppet.Gui { public class AppBootstrapper : BootstrapperBase { public AppBootstrapper() { Initialize(); } protected override void OnStartup(object sender, StartupEventArgs e) { DisplayRootViewFor<DeploymentPlannerViewModel>(); } } }
using System.Collections.Generic; using System.Windows; using Caliburn.Micro; using OctopusPuppet.Gui.ViewModels; namespace OctopusPuppet.Gui { public class AppBootstrapper : BootstrapperBase { public AppBootstrapper() { Initialize(); } protected override void OnStartup(object sender, StartupEventArgs e) { var settings = new Dictionary<string, object> { { "SizeToContent", SizeToContent.Manual }, { "Height" , 768 }, { "Width" , 768 }, }; DisplayRootViewFor<DeploymentPlannerViewModel>(settings); } } }
Add helper method to return KeyModifier
using System; using System.Windows.Forms; using System.Xml.Serialization; namespace DeRange.Config { [Serializable] [XmlRoot(ElementName = "KeyboardShortcut")] public class KeyboardShortcut { public bool ShiftModifier { get; set; } public bool CtrlModifier { get; set; } public bool AltModifier { get; set; } public bool WinModifier { get; set; } public Keys Key { get; set; } } }
using System; using System.Windows.Forms; using System.Xml.Serialization; namespace DeRange.Config { [Serializable] [XmlRoot(ElementName = "KeyboardShortcut")] public class KeyboardShortcut { public bool ShiftModifier { get; set; } public bool CtrlModifier { get; set; } public bool AltModifier { get; set; } public bool WinModifier { get; set; } public Keys Key { get; set; } public KeyModifier KeyModifier { get { KeyModifier mod = KeyModifier.None; if (AltModifier) { mod |= KeyModifier.Alt; } if (WinModifier) { mod |= KeyModifier.Win; } if (ShiftModifier) { mod |= KeyModifier.Shift; } if (CtrlModifier) { mod |= KeyModifier.Ctrl; } return mod; } } } }
Change type signature of NotNullOrEmpty to string since it's only used for strings.
using System; namespace DevTyr.Gullap { public static class Guard { public static void NotNull (object obj, string argumentName) { if (obj == null) throw new ArgumentNullException(argumentName); } public static void NotNullOrEmpty (object obj, string argumentName) { NotNull (obj, argumentName); if (!(obj is String)) return; var val = (String)obj; if (string.IsNullOrWhiteSpace(val)) throw new ArgumentException(argumentName); } } }
using System; namespace DevTyr.Gullap { public static class Guard { public static void NotNull (object obj, string argumentName) { if (obj == null) throw new ArgumentNullException(argumentName); } public static void NotNullOrEmpty (string obj, string argumentName) { NotNull (obj, argumentName); if (string.IsNullOrWhiteSpace(obj)) throw new ArgumentException(argumentName); } } }
Make Visual Studio 2017 Enterprise happy
using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { foreach (var instruction in instructions) { if (instruction.operand == from) instruction.operand = to; yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } } }
using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) instruction.operand = to; yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } } }
Update text on countdown timer GUI
using UnityEngine; using System.Collections; public class CountDown : MonoBehaviour { public float maxTime = 600; //Because it is in seconds; private float curTime; private string prettyTime; // Use this for initialization void Start () { curTime = maxTime; } // Update is called once per frame void Update () { curTime -= Time.deltaTime; //Debug.Log(curTime); prettyTime = Mathf.FloorToInt(curTime/60) + ":" + Mathf.FloorToInt((60*(curTime/60 - Mathf.Floor(curTime/60)))); Debug.Log(prettyTime); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class CountDown : MonoBehaviour { public float maxTime = 600; //Because it is in seconds; private float curTime; private string prettyTime; private Text text; // Use this for initialization void Start () { curTime = maxTime; text = gameObject.GetComponent( typeof(Text) ) as Text; } // Update is called once per frame void Update () { curTime -= Time.deltaTime; //Debug.Log(curTime); prettyTime = Mathf.FloorToInt(curTime/60) + ":" + Mathf.FloorToInt((60*(curTime/60 - Mathf.Floor(curTime/60)))); //Debug.Log(prettyTime); text.text = prettyTime; } }
Fix file paths default value null
using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("File")] public class FilePath { public FilePath(string path) { Path = path; } public FilePath() { } [DisplayName("Path")] public string Path { get; set; } } }
using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("File")] public class FilePath { public FilePath(string path) { Path = path; } public FilePath() { } [DisplayName("Path")] public string Path { get; set; } = ""; } }
Make it Rain now rains blocks constantly
using UnityEngine; using System.Collections; public class MakeItRain : MonoBehaviour { private int numObjects = 20; private float minX = -4f; private float maxX = 4f; private GameObject rain; private GameObject rainClone; // Use this for initialization void Start() { // Here only for test Rain(); } // Update is called once per frame void Update() { } void Rain() { int whichRain = Random.Range(1, 4); switch (whichRain) { case 1: rain = GameObject.Find("Rain/healObj"); break; case 2: rain = GameObject.Find("Rain/safeObj"); break; case 3: rain = GameObject.Find("Rain/mediumObj"); break; default: rain = GameObject.Find("Rain/dangerousObj"); break; } for (int i = 0; i < numObjects; i++) { float x_rand = Random.Range(-4f, 4f); float y_rand = Random.Range(-1f, 1f); rainClone = (GameObject)Instantiate(rain, new Vector3(x_rand, rain.transform.position.y + y_rand, rain.transform.position.z), rain.transform.rotation); rainClone.GetComponent<Rigidbody2D>().gravityScale = 1; } } }
using UnityEngine; using System.Collections; public class MakeItRain : MonoBehaviour { private int numObjects = 20; private float minX = -4f; private float maxX = 4f; private GameObject rain; private GameObject rainClone; int count = 0; // Use this for initialization void Start() { } // Update is called once per frame // Just for test void Update() { if (count % 100 == 0) { Rain(); count++; } count++; } // Called only when dance is finished void Rain() { int whichRain = Random.Range(1, 5); switch (whichRain) { case 1: rain = GameObject.Find("Rain/healObj"); break; case 2: rain = GameObject.Find("Rain/safeObj"); break; case 3: rain = GameObject.Find("Rain/mediumObj"); break; default: rain = GameObject.Find("Rain/dangerousObj"); break; } for (int i = 0; i < numObjects; i++) { float x_rand = Random.Range(minX, maxX - rain.GetComponent<BoxCollider2D>().size.x); float y_rand = Random.Range(1f, 3f); rainClone = (GameObject)Instantiate(rain, new Vector3(x_rand, rain.transform.position.y - y_rand, rain.transform.position.z), rain.transform.rotation); rainClone.GetComponent<Rigidbody2D>().gravityScale = 1; } } }
Align failing CodeContracts case better to object Invariant.
using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace PGSolutions.Utilities.Monads.StaticContracts { using static Contract; public struct MaybeAssume<T> { ///<summary>Create a new Maybe{T}.</summary> private MaybeAssume(T value) : this() { Ensures(!HasValue || _value != null); _value = value; _hasValue = _value != null; } ///<summary>Returns whether this Maybe{T} has a value.</summary> public bool HasValue { get { return _hasValue; } } ///<summary>Extract value of the Maybe{T}, substituting <paramref name="defaultValue"/> as needed.</summary> [Pure] public T BitwiseOr(T defaultValue) { defaultValue.ContractedNotNull("defaultValue"); Ensures(Result<T>() != null); var result = !_hasValue ? defaultValue : _value; // Assume(result != null); return result; } /// <summary>The invariants enforced by this struct type.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [ContractInvariantMethod] [Pure] private void ObjectInvariant() { Invariant(!HasValue || _value != null); } readonly T _value; readonly bool _hasValue; } }
using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace PGSolutions.Utilities.Monads.StaticContracts { using static Contract; public struct Maybe<T> { ///<summary>Create a new Maybe{T}.</summary> private Maybe(T value) : this() { Ensures(!HasValue || _value != null); _value = value; _hasValue = _value != null; } ///<summary>Returns whether this Maybe{T} has a value.</summary> public bool HasValue { get { return _hasValue; } } ///<summary>Extract value of the Maybe{T}, substituting <paramref name="defaultValue"/> as needed.</summary> [Pure] public T BitwiseOr(T defaultValue) { defaultValue.ContractedNotNull("defaultValue"); Ensures(Result<T>() != null); var result = ! HasValue ? defaultValue : _value; // Assume(result != null); return result; } /// <summary>The invariants enforced by this struct type.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [ContractInvariantMethod] [Pure] private void ObjectInvariant() { Invariant(!HasValue || _value != null); } readonly T _value; readonly bool _hasValue; } }
Disable partitioning in the bootstrapper.
using System.Configuration; using Amazon.ServiceBus.DistributedMessages.Serializers; using ProjectExtensions.Azure.ServiceBus; using ProjectExtensions.Azure.ServiceBus.Autofac.Container; namespace PubSubUsingConfiguration { static internal class Bootstrapper { public static void Initialize() { var setup = new ServiceBusSetupConfiguration() { DefaultSerializer = new GZipXmlSerializer(), ServiceBusIssuerKey = ConfigurationManager.AppSettings["ServiceBusIssuerKey"], ServiceBusIssuerName = ConfigurationManager.AppSettings["ServiceBusIssuerName"], ServiceBusNamespace = ConfigurationManager.AppSettings["ServiceBusNamespace"], ServiceBusApplicationId = "AppName" }; setup.AssembliesToRegister.Add(typeof(TestMessageSubscriber).Assembly); BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigurationSettings(setup) .EnablePartitioning(true) .DefaultSerializer(new GZipXmlSerializer()) .Configure(); /* BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigFile() .ServiceBusApplicationId("AppName") .DefaultSerializer(new GZipXmlSerializer()) //.ServiceBusIssuerKey("[sb password]") //.ServiceBusIssuerName("owner") //.ServiceBusNamespace("[addresshere]") .RegisterAssembly(typeof(TestMessageSubscriber).Assembly) .Configure(); */ } } }
using System.Configuration; using Amazon.ServiceBus.DistributedMessages.Serializers; using ProjectExtensions.Azure.ServiceBus; using ProjectExtensions.Azure.ServiceBus.Autofac.Container; namespace PubSubUsingConfiguration { static internal class Bootstrapper { public static void Initialize() { var setup = new ServiceBusSetupConfiguration() { DefaultSerializer = new GZipXmlSerializer(), ServiceBusIssuerKey = ConfigurationManager.AppSettings["ServiceBusIssuerKey"], ServiceBusIssuerName = ConfigurationManager.AppSettings["ServiceBusIssuerName"], ServiceBusNamespace = ConfigurationManager.AppSettings["ServiceBusNamespace"], ServiceBusApplicationId = "AppName" }; setup.AssembliesToRegister.Add(typeof(TestMessageSubscriber).Assembly); BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigurationSettings(setup) //.EnablePartitioning(true) .DefaultSerializer(new GZipXmlSerializer()) .Configure(); /* BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigFile() .ServiceBusApplicationId("AppName") .DefaultSerializer(new GZipXmlSerializer()) //.ServiceBusIssuerKey("[sb password]") //.ServiceBusIssuerName("owner") //.ServiceBusNamespace("[addresshere]") .RegisterAssembly(typeof(TestMessageSubscriber).Assembly) .Configure(); */ } } }
Fix in API, added IsLocked field to nested schema.
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.ComponentModel.DataAnnotations; namespace Squidex.Areas.Api.Controllers.Schemas.Models { public sealed class CreateSchemaNestedFieldDto { /// <summary> /// The name of the field. Must be unique within the schema. /// </summary> [Required] [RegularExpression("^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*$")] public string Name { get; set; } /// <summary> /// Defines if the field is hidden. /// </summary> public bool IsHidden { get; set; } /// <summary> /// Defines if the field is disabled. /// </summary> public bool IsDisabled { get; set; } /// <summary> /// The field properties. /// </summary> [Required] public FieldPropertiesDto Properties { get; set; } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.ComponentModel.DataAnnotations; namespace Squidex.Areas.Api.Controllers.Schemas.Models { public sealed class CreateSchemaNestedFieldDto { /// <summary> /// The name of the field. Must be unique within the schema. /// </summary> [Required] [RegularExpression("^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*$")] public string Name { get; set; } /// <summary> /// Defines if the field is hidden. /// </summary> public bool IsHidden { get; set; } /// <summary> /// Defines if the field is locked. /// </summary> public bool IsLocked { get; set; } /// <summary> /// Defines if the field is disabled. /// </summary> public bool IsDisabled { get; set; } /// <summary> /// The field properties. /// </summary> [Required] public FieldPropertiesDto Properties { get; set; } } }
Adjust screen resolution to samsung galaxy s4
using UnityEngine; using UnityEngine.UI; using System.Collections; public class Menu : MonoBehaviour { public Canvas MainCanvas; static public int money = 1000; public void LoadOn() { //DontDestroyOnLoad(money); Application.LoadLevel(1); } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class Menu : MonoBehaviour { public Canvas MainCanvas; static public int money = 1000; public void LoadOn() { Screen.SetResolution(1080, 1920, true); //DontDestroyOnLoad(money); Application.LoadLevel(1); } }
Refactor the error caused by a failing assertion
using System; namespace TDDUnit { class Assert { public static void Equal(object expected, object actual) { if (!expected.Equals(actual)) { string message = string.Format("Expected: '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } } public static void NotEqual(object expected, object actual) { if (expected.Equals(actual)) { string message = string.Format("Expected: Not '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } } public static void That(bool condition) { Equal(true, condition); } } }
using System; namespace TDDUnit { class Assert { private static void Fail(object expected, object actual) { string message = string.Format("Expected: '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } public static void Equal(object expected, object actual) { if (!expected.Equals(actual)) { Fail(expected, actual); } } public static void NotEqual(object expected, object actual) { if (expected.Equals(actual)) { Fail(expected, actual); } } public static void That(bool condition) { Equal(true, condition); } } }
Clean up: removed empty line
using System; using Microsoft.Practices.Unity; namespace Topshelf.Unity.Sample { class Program { static void Main(string[] args) { // Create your container var container = new UnityContainer(); container.RegisterType<ISampleDependency, SampleDependency>(); container.RegisterType<SampleService>(); HostFactory.Run(c => { // Pass it to Topshelf c.UseUnityContainer(container); c.Service<SampleService>(s => { // Let Topshelf use it s.ConstructUsingUnityContainer(); s.WhenStarted((service, control) => service.Start()); s.WhenStopped((service, control) => service.Stop()); }); }); } } public class SampleService { private readonly ISampleDependency _sample; public SampleService(ISampleDependency sample) { _sample = sample; } public bool Start() { Console.WriteLine("Sample Service Started."); Console.WriteLine("Sample Dependency: {0}", _sample); return _sample != null; } public bool Stop() { return _sample != null; } } public interface ISampleDependency { } public class SampleDependency : ISampleDependency { } }
using System; using Microsoft.Practices.Unity; namespace Topshelf.Unity.Sample { class Program { static void Main(string[] args) { // Create your container var container = new UnityContainer(); container.RegisterType<ISampleDependency, SampleDependency>(); container.RegisterType<SampleService>(); HostFactory.Run(c => { // Pass it to Topshelf c.UseUnityContainer(container); c.Service<SampleService>(s => { // Let Topshelf use it s.ConstructUsingUnityContainer(); s.WhenStarted((service, control) => service.Start()); s.WhenStopped((service, control) => service.Stop()); }); }); } } public class SampleService { private readonly ISampleDependency _sample; public SampleService(ISampleDependency sample) { _sample = sample; } public bool Start() { Console.WriteLine("Sample Service Started."); Console.WriteLine("Sample Dependency: {0}", _sample); return _sample != null; } public bool Stop() { return _sample != null; } } public interface ISampleDependency { } public class SampleDependency : ISampleDependency { } }
Fix for 'new' setting button triggering if you hit enter when editing a setting.
using System; public partial class Settings : System.Web.UI.Page { //--------------------------------------------------------------------------- protected void Page_Load( object sender, EventArgs e ) { // Don't allow people to skip the login page. if( Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == null || (bool)Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == false ) { Response.Redirect( "Default.aspx" ); } dataSource.ConnectionString = Database.DB_CONNECTION_STRING; NewSetting.Click += OnNewClick; } //--------------------------------------------------------------------------- void OnNewClick( object sender, EventArgs e ) { Database.ExecSql( "DELETE FROM Setting WHERE [Key]='New Key'" ); Database.ExecSql( "INSERT INTO Setting VALUES ( 'New Key', 'New Value' )" ); settingsView.DataBind(); } //--------------------------------------------------------------------------- }
using System; public partial class Settings : System.Web.UI.Page { //--------------------------------------------------------------------------- protected void Page_Load( object sender, EventArgs e ) { // Don't allow people to skip the login page. if( Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == null || (bool)Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == false ) { Response.Redirect( "Default.aspx" ); } dataSource.ConnectionString = Database.DB_CONNECTION_STRING; NewSetting.Click += OnNewClick; settingsView.Focus(); } //--------------------------------------------------------------------------- void OnNewClick( object sender, EventArgs e ) { Database.ExecSql( "DELETE FROM Setting WHERE [Key]='New Key'" ); Database.ExecSql( "INSERT INTO Setting VALUES ( 'New Key', 'New Value' )" ); settingsView.DataBind(); settingsView.Focus(); } //--------------------------------------------------------------------------- }
Update List of ConnectorTypes to be compatible with ISOBUS.net List
/******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Kathleen Oneal - initial API and implementation * Joe Ross, Kathleen Oneal - added values *******************************************************************************/ namespace AgGateway.ADAPT.ApplicationDataModel.Equipment { public enum ConnectorTypeEnum { Unkown, ISO64893TractorDrawbar, ISO730ThreePointHitchSemiMounted, ISO730ThreePointHitchMounted, ISO64891HitchHook, ISO64892ClevisCoupling40, ISO64894PitonTypeCoupling, ISO56922PivotWagonHitch, ISO24347BallTypeHitch, } }
/******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Kathleen Oneal - initial API and implementation * Joe Ross, Kathleen Oneal - added values *******************************************************************************/ namespace AgGateway.ADAPT.ApplicationDataModel.Equipment { public enum ConnectorTypeEnum { Unkown, ISO64893TractorDrawbar, ISO730ThreePointHitchSemiMounted, ISO730ThreePointHitchMounted, ISO64891HitchHook, ISO64892ClevisCoupling40, ISO64894PitonTypeCoupling, ISO56922PivotWagonHitch, ISO24347BallTypeHitch, ChassisMountedSelfPropelled } }
Test fix- catching permission denied exceptions
using System; using System.Collections.Generic; using System.IO; namespace AGS.Engine.Desktop { public class DesktopFileSystem : IFileSystem { #region IFileSystem implementation public string StorageFolder => Directory.GetCurrentDirectory(); //todo: find a suitable save location on desktop public IEnumerable<string> GetFiles(string folder) { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetFiles(folder); } public IEnumerable<string> GetDirectories(string folder) { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetDirectories(folder); } public IEnumerable<string> GetLogicalDrives() => Directory.GetLogicalDrives(); public string GetCurrentDirectory() => Directory.GetCurrentDirectory(); public bool DirectoryExists(string folder) => Directory.Exists(folder); public bool FileExists(string path) => File.Exists(path); public Stream Open(string path) => File.OpenRead(path); public Stream Create(string path) => File.Create(path); public void Delete(string path) { File.Delete(path); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace AGS.Engine.Desktop { public class DesktopFileSystem : IFileSystem { #region IFileSystem implementation public string StorageFolder => Directory.GetCurrentDirectory(); //todo: find a suitable save location on desktop public IEnumerable<string> GetFiles(string folder) { try { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetFiles(folder); } catch (UnauthorizedAccessException) { Debug.WriteLine($"GetFiles: Permission denied for {folder}"); return new List<string>(); } } public IEnumerable<string> GetDirectories(string folder) { try { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetDirectories(folder); } catch (UnauthorizedAccessException) { Debug.WriteLine($"GetDirectories: Permission denied for {folder}"); return new List<string>(); } } public IEnumerable<string> GetLogicalDrives() => Directory.GetLogicalDrives(); public string GetCurrentDirectory() => Directory.GetCurrentDirectory(); public bool DirectoryExists(string folder) => Directory.Exists(folder); public bool FileExists(string path) => File.Exists(path); public Stream Open(string path) => File.OpenRead(path); public Stream Create(string path) => File.Create(path); public void Delete(string path) { File.Delete(path); } #endregion } }
Make version 4 digits to fix replacement regex
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyConfiguration("")] // If you change this version, make sure to change Build\build.proj accordingly [assembly: AssemblyVersion("28.0.0")] [assembly: AssemblyFileVersion("28.0.0")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyConfiguration("")] // If you change this version, make sure to change Build\build.proj accordingly [assembly: AssemblyVersion("28.0.0.0")] [assembly: AssemblyFileVersion("28.0.0.0")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)]
Update to beta1 for next release
using System.Resources; 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("Configgy")] [assembly: AssemblyDescription("Configgy: Configuration library for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Configgy")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 3 for release candidates, 4 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("1.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.1")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("1.0.0-alpha1")]
using System.Resources; 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("Configgy")] [assembly: AssemblyDescription("Configgy: Configuration library for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Configgy")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 3 for release candidates, 4 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("1.0.1.1")] [assembly: AssemblyFileVersion("1.0.1.1")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("1.0.1-beta1")]
Delete sender and edit constructor functions
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using FuzzyCore.Server; namespace FuzzyCore.Commands { public class GetFile { ConsoleMessage Message = new ConsoleMessage(); public void GetFileBytes(Data.JsonCommand Command) { try { byte[] file = File.ReadAllBytes(Command.FilePath + "\\" + Command.Text); if (file.Length > 0) { SendDataArray(file, Command.Client_Socket); Message.Write(Command.CommandType,ConsoleMessage.MessageType.SUCCESS); } } catch (Exception ex) { Message.Write(ex.Message, ConsoleMessage.MessageType.ERROR); } } public void SendDataArray(byte[] Data, Socket Client) { try { Thread.Sleep(100); Client.Send(Data); } catch (Exception ex) { Message.Write(ex.Message, ConsoleMessage.MessageType.ERROR); } } } }
using FuzzyCore.Data; using FuzzyCore.Server; using System; using System.IO; namespace FuzzyCore.Commands { public class GetFile { ConsoleMessage Message = new ConsoleMessage(); private String FilePath; private String FileName; private JsonCommand mCommand; public GetFile(Data.JsonCommand Command) { FilePath = Command.FilePath; FileName = Command.Text; this.mCommand = Command; } bool FileControl() { FileInfo mfileInfo = new FileInfo(FilePath); return mfileInfo.Exists; } public byte[] GetFileBytes() { if (FileControl()) { byte[] file = File.ReadAllBytes(FilePath + "/" + FileName); return file; } return new byte[0]; } public string GetFileText() { if (FileControl()) { return File.ReadAllText(FilePath + "/" + FileName); } return ""; } } }
Add write retry mechanism into the client.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace EchoClient { class Program { static void Main(string[] args) { Task main = MainAsync(args); main.Wait(); } static async Task MainAsync(string[] args) { TcpClient client = new TcpClient("::1", 8080); NetworkStream stream = client.GetStream(); StreamReader reader = new StreamReader(stream); StreamWriter writer = new StreamWriter(stream) { AutoFlush = true }; while (true) { Console.WriteLine("What to send?"); string line = Console.ReadLine(); await writer.WriteLineAsync(line); string response = await reader.ReadLineAsync(); Console.WriteLine($"Response from server {response}"); } client.Close(); } } }
using System; using System.IO; using System.Net.Sockets; using System.Threading.Tasks; namespace EchoClient { class Program { const int MAX_WRITE_RETRY = 3; const int WRITE_RETRY_DELAY_SECONDS = 3; static void Main(string[] args) { Task main = MainAsync(args); main.Wait(); } static async Task MainAsync(string[] args) { using (TcpClient client = new TcpClient("::1", 8080)) { using (NetworkStream stream = client.GetStream()) { using (StreamReader reader = new StreamReader(stream)) { using (StreamWriter writer = new StreamWriter(stream) { AutoFlush = true }) { while (true) { Console.WriteLine("What to send?"); string line = Console.ReadLine(); int writeTry = 0; bool writtenSuccessfully = false; while (!writtenSuccessfully && writeTry < MAX_WRITE_RETRY) { try { writeTry++; await writer.WriteLineAsync(line); writtenSuccessfully = true; } catch (Exception ex) { Console.WriteLine($"Failed to send data to server, try {writeTry} / {MAX_WRITE_RETRY}"); if (!writtenSuccessfully && writeTry == MAX_WRITE_RETRY) { Console.WriteLine($"Write retry reach, please check your connectivity with the server and try again. Error details: {Environment.NewLine}{ex.Message}"); } else { await Task.Delay(WRITE_RETRY_DELAY_SECONDS * 1000); } } } if (!writtenSuccessfully) { continue; } string response = await reader.ReadLineAsync(); Console.WriteLine($"Response from server {response}"); } } } } } } } }
Use expression bodied methods for compact code
using Alensia.Core.Input.Generic; using UnityEngine.Assertions; namespace Alensia.Core.Input { public class BindingKey<T> : IBindingKey<T> where T : IInput { public string Id { get; } public BindingKey(string id) { Assert.IsNotNull(id, "id != null"); Id = id; } public override bool Equals(object obj) { var item = obj as BindingKey<T>; return item != null && Id.Equals(item.Id); } public override int GetHashCode() { return Id.GetHashCode(); } } }
using Alensia.Core.Input.Generic; using UnityEngine.Assertions; namespace Alensia.Core.Input { public class BindingKey<T> : IBindingKey<T> where T : IInput { public string Id { get; } public BindingKey(string id) { Assert.IsNotNull(id, "id != null"); Id = id; } public override bool Equals(object obj) => Id.Equals((obj as BindingKey<T>)?.Id); public override int GetHashCode() => Id.GetHashCode(); } }
Fix build: react to EF namespace change
// 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 Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Metadata.ModelConventions; namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels { public static class TestModel { public static IModel Model { get { var builder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet()); builder.Entity<Product>() .Reference(p => p.ProductCategory) .InverseCollection(c => c.CategoryProducts) .ForeignKey(e => e.ProductCategoryId); return builder.Model; } } } }
// 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 Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Metadata.Conventions.Internal; namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels { public static class TestModel { public static IModel Model { get { var builder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet()); builder.Entity<Product>() .Reference(p => p.ProductCategory) .InverseCollection(c => c.CategoryProducts) .ForeignKey(e => e.ProductCategoryId); return builder.Model; } } } }
Update copyright year in assembly info
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AudioSharp")] [assembly: AssemblyCopyright("Copyright (c) 2015-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.3.0")] [assembly: AssemblyFileVersion("1.4.3.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AudioSharp")] [assembly: AssemblyCopyright("Copyright (c) 2015-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.3.0")] [assembly: AssemblyFileVersion("1.4.3.0")]
Update link to Update function
using System.Text; using DotNetRu.Utils.Helpers; using Newtonsoft.Json; namespace DotNetRu.Clients.UI { public class AppConfig { public string AppCenterAndroidKey { get; set; } public string AppCenteriOSKey { get; set; } public string PushNotificationsChannel { get; set; } public string UpdateFunctionURL { get; set; } public string TweetFunctionUrl { get; set; } public static AppConfig GetConfig() { #if DEBUG return new AppConfig() { AppCenterAndroidKey = "6f9a7703-8ca4-477e-9558-7e095f7d20aa", AppCenteriOSKey = "1e7f311f-1055-4ec9-8b00-0302015ab8ae", PushNotificationsChannel = "AuditUpdateDebug", UpdateFunctionURL = "https://dotnetruapp.azurewebsites.net/api/Update", TweetFunctionUrl = "https://dotnettweetservice.azurewebsites.net/api/Tweets" }; #endif #pragma warning disable CS0162 // Unreachable code detected var configBytes = ResourceHelper.ExtractResource("DotNetRu.Utils.Config.config.json"); var configBytesAsString = Encoding.UTF8.GetString(configBytes); return JsonConvert.DeserializeObject<AppConfig>(configBytesAsString); #pragma warning restore CS0162 // Unreachable code detected } } }
using System.Text; using DotNetRu.Utils.Helpers; using Newtonsoft.Json; namespace DotNetRu.Clients.UI { public class AppConfig { public string AppCenterAndroidKey { get; set; } public string AppCenteriOSKey { get; set; } public string PushNotificationsChannel { get; set; } public string UpdateFunctionURL { get; set; } public string TweetFunctionUrl { get; set; } public static AppConfig GetConfig() { #if DEBUG return new AppConfig() { AppCenterAndroidKey = "6f9a7703-8ca4-477e-9558-7e095f7d20aa", AppCenteriOSKey = "1e7f311f-1055-4ec9-8b00-0302015ab8ae", PushNotificationsChannel = "AuditUpdateDebug", UpdateFunctionURL = "https://dotnetruazure.azurewebsites.net/api/Update", TweetFunctionUrl = "https://dotnettweetservice.azurewebsites.net/api/Tweets" }; #endif #pragma warning disable CS0162 // Unreachable code detected var configBytes = ResourceHelper.ExtractResource("DotNetRu.Utils.Config.config.json"); var configBytesAsString = Encoding.UTF8.GetString(configBytes); return JsonConvert.DeserializeObject<AppConfig>(configBytesAsString); #pragma warning restore CS0162 // Unreachable code detected } } }
Update example, add long tap
using System; using System.Collections.Generic; using Xamarin.Forms; namespace XamExample { public partial class MyPage : ContentPage { public MyPage() { InitializeComponent(); var c = 0; XamEffects.TouchEffect.SetColor(plus, Color.White); XamEffects.Commands.SetTap(plus, new Command(() => { c++; counter.Text = $"Touches: {c}"; })); XamEffects.TouchEffect.SetColor(minus, Color.White); XamEffects.Commands.SetTap(minus, new Command(() => { c--; counter.Text = $"Touches: {c}"; })); } } }
using System; using System.Collections.Generic; using Xamarin.Forms; namespace XamExample { public partial class MyPage : ContentPage { public MyPage() { InitializeComponent(); var c = 0; XamEffects.TouchEffect.SetColor(plus, Color.White); XamEffects.Commands.SetTap(plus, new Command(() => { c++; counter.Text = $"Touches: {c}"; })); XamEffects.TouchEffect.SetColor(minus, Color.White); XamEffects.Commands.SetLongTap(minus, new Command(() => { c--; counter.Text = $"Touches: {c}"; })); } } }
Set Default Font to something that should be on all systems
using Mono.TextEditor.Highlighting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xwt.Drawing; namespace XwtPlus.TextEditor { public class TextEditorOptions { public Font EditorFont = Font.FromName("Consolas 13"); public IndentStyle IndentStyle = IndentStyle.Auto; public int TabSize = 4; public Color Background = Colors.White; public ColorScheme ColorScheme = SyntaxModeService.DefaultColorStyle; public bool CurrentLineNumberBold = true; } }
using Mono.TextEditor.Highlighting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xwt.Drawing; namespace XwtPlus.TextEditor { public class TextEditorOptions { public Font EditorFont = Font.SystemMonospaceFont; public IndentStyle IndentStyle = IndentStyle.Auto; public int TabSize = 4; public Color Background = Colors.White; public ColorScheme ColorScheme = SyntaxModeService.DefaultColorStyle; public bool CurrentLineNumberBold = true; } }
Build number removed from the version string, as this creates problems with NuGet dependencies.
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="VersionInfo.cs" company="Dani Michel"> // Dani Michel 2013 // </copyright> // -------------------------------------------------------------------------------------------------------------------- [assembly: System.Reflection.AssemblyCompany("Dani Michel")] [assembly: System.Reflection.AssemblyCopyright("Copyright © 2014")] [assembly: System.Reflection.AssemblyVersion("0.8.0.*")] [assembly: System.Reflection.AssemblyInformationalVersion("Belt 0.8.0")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="VersionInfo.cs" company="Dani Michel"> // Dani Michel 2013 // </copyright> // -------------------------------------------------------------------------------------------------------------------- [assembly: System.Reflection.AssemblyCompany("Dani Michel")] [assembly: System.Reflection.AssemblyCopyright("Copyright © 2014")] [assembly: System.Reflection.AssemblyVersion("0.8.1")] [assembly: System.Reflection.AssemblyInformationalVersion("Belt 0.8.1")]
Add Async suffix to async methods
using System; using System.Net; using LtiLibrary.Core.Outcomes.v2; using Newtonsoft.Json; using Xunit; namespace LtiLibrary.AspNet.Tests { public class LineItemsControllerUnitTests { [Fact] public void GetLineItemBeforePostReturnsNotFound() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var result = controller.Get(LineItemsController.LineItemId); Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode); } [Fact] public void PostLineItemReturnsValidLineItem() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var lineitem = new LineItem { LineItemOf = new Context { ContextId = LineItemsController.ContextId }, ReportingMethod = "res:Result" }; var result = controller.Post(LineItemsController.ContextId, lineitem); Assert.Equal(HttpStatusCode.Created, result.Result.StatusCode); var lineItem = JsonConvert.DeserializeObject<LineItem>(result.Result.Content.ReadAsStringAsync().Result); Assert.NotNull(lineItem); Assert.Equal(LineItemsController.LineItemId, lineItem.Id.ToString()); } [Fact] public void GetLineItemsBeforePostReturnsNotFound() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var result = controller.Get(); Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode); } } }
using System; using System.Net; using LtiLibrary.Core.Outcomes.v2; using Newtonsoft.Json; using Xunit; namespace LtiLibrary.AspNet.Tests { public class LineItemsControllerUnitTests { [Fact] public void GetLineItemBeforePostReturnsNotFound() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var result = controller.GetAsync(LineItemsController.LineItemId); Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode); } [Fact] public void PostLineItemReturnsValidLineItem() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var lineitem = new LineItem { LineItemOf = new Context { ContextId = LineItemsController.ContextId }, ReportingMethod = "res:Result" }; var result = controller.PostAsync(LineItemsController.ContextId, lineitem); Assert.Equal(HttpStatusCode.Created, result.Result.StatusCode); var lineItem = JsonConvert.DeserializeObject<LineItem>(result.Result.Content.ReadAsStringAsync().Result); Assert.NotNull(lineItem); Assert.Equal(LineItemsController.LineItemId, lineItem.Id.ToString()); } [Fact] public void GetLineItemsBeforePostReturnsNotFound() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var result = controller.GetAsync(); Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode); } } }
Support config from alternative source
using System.Collections.Generic; using System.Configuration; using System.Linq; namespace NLogger { public class CustomLogFactory<T> where T : NLoggerSection { private readonly List<ILogWriterRegistration<T>> _logWriterTypes; public CustomLogFactory() { _logWriterTypes= new List<ILogWriterRegistration<T>>(); } public void RegisterLogWriterType(ILogWriterRegistration<T> registration) { _logWriterTypes.Add(registration); } /// <summary> /// Create a logger using App.config or Web.config settings /// </summary> /// <returns></returns> public ILogger CreateLogger(string sectionName) { var config = (T) ConfigurationManager.GetSection(sectionName); if (config != null) { var writer = GetLogWriter(config); if (writer != null) { return new Logger(writer, config.LogLevel); } } return LoggerFactory.CreateLogger(config); } private ILogWriter GetLogWriter(T config) { var type = _logWriterTypes.FirstOrDefault(t => t.HasSection(config)); return type != null ? type.GetWriter(config) : null; } } }
using System.Collections.Generic; using System.Configuration; using System.Linq; namespace NLogger { public class CustomLogFactory<T> where T : NLoggerSection { private readonly List<ILogWriterRegistration<T>> _logWriterTypes; public CustomLogFactory() { _logWriterTypes= new List<ILogWriterRegistration<T>>(); } public void RegisterLogWriterType(ILogWriterRegistration<T> registration) { _logWriterTypes.Add(registration); } public ILogger CreateLogger(string sectionName, Configuration configFile) { var config = (T)configFile.GetSection(sectionName); return CreateLogger(config); } /// <summary> /// Create a logger using App.config or Web.config settings /// </summary> /// <returns></returns> public ILogger CreateLogger(string sectionName) { var config = (T) ConfigurationManager.GetSection(sectionName); return CreateLogger(config); } private ILogger CreateLogger(T config) { if (config != null) { var writer = GetLogWriter(config); if (writer != null) { return new Logger(writer, config.LogLevel); } } return LoggerFactory.CreateLogger(config); } private ILogWriter GetLogWriter(T config) { var type = _logWriterTypes.FirstOrDefault(t => t.HasSection(config)); return type != null ? type.GetWriter(config) : null; } } }
Handle overflows in line selection
using System; using MonoDevelop.Ide.Editor; using MonoDevelop.Ide.Editor.Extension; namespace JustEnoughVi { public abstract class ViMode { protected TextEditor Editor { get; set; } public Mode RequestedMode { get; internal set; } protected ViMode(TextEditor editor) { Editor = editor; RequestedMode = Mode.None; } public abstract void Activate(); public abstract void Deactivate(); public abstract bool KeyPress (KeyDescriptor descriptor); protected void SetSelectLines(int start, int end) { var startLine = start > end ? Editor.GetLine(end) : Editor.GetLine(start); var endLine = start > end ? Editor.GetLine(start) : Editor.GetLine(end); Editor.SetSelection(startLine.Offset, endLine.EndOffsetIncludingDelimiter); } } }
using System; using MonoDevelop.Ide.Editor; using MonoDevelop.Ide.Editor.Extension; namespace JustEnoughVi { public abstract class ViMode { protected TextEditor Editor { get; set; } public Mode RequestedMode { get; internal set; } protected ViMode(TextEditor editor) { Editor = editor; RequestedMode = Mode.None; } public abstract void Activate(); public abstract void Deactivate(); public abstract bool KeyPress (KeyDescriptor descriptor); protected void SetSelectLines(int start, int end) { start = Math.Min(start, Editor.LineCount); end = Math.Min(end, Editor.LineCount); var startLine = start > end ? Editor.GetLine(end) : Editor.GetLine(start); var endLine = start > end ? Editor.GetLine(start) : Editor.GetLine(end); Editor.SetSelection(startLine.Offset, endLine.EndOffsetIncludingDelimiter); } } }
Move marker file into App_Data a folder that can never be served
using System.IO; using Umbraco.Core.Configuration; namespace Umbraco.Core.IO { public class SystemFiles { public static string TinyMceConfig => SystemDirectories.Config + "/tinyMceConfig.config"; public static string TelemetricsIdentifier => SystemDirectories.Umbraco + "/telemetrics-id.umb"; // TODO: Kill this off we don't have umbraco.config XML cache we now have NuCache public static string GetContentCacheXml(IGlobalSettings globalSettings) { return Path.Combine(globalSettings.LocalTempPath, "umbraco.config"); } } }
using System.IO; using Umbraco.Core.Configuration; namespace Umbraco.Core.IO { public class SystemFiles { public static string TinyMceConfig => SystemDirectories.Config + "/tinyMceConfig.config"; public static string TelemetricsIdentifier => SystemDirectories.Data + "/telemetrics-id.umb"; // TODO: Kill this off we don't have umbraco.config XML cache we now have NuCache public static string GetContentCacheXml(IGlobalSettings globalSettings) { return Path.Combine(globalSettings.LocalTempPath, "umbraco.config"); } } }
Add supression for generated xaml class
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. Project-level // suppressions either have no target or are given a specific target // and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Error List, point to "Suppress Message(s)", and click "In Project // Suppression File". You do not need to add suppressions to this // file manually. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.Providers")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.ToolsOptionsUI")]
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. Project-level // suppressions either have no target or are given a specific target // and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Error List, point to "Suppress Message(s)", and click "In Project // Suppression File". You do not need to add suppressions to this // file manually. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.Providers")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.ToolsOptionsUI")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "XamlGeneratedNamespace")]
Add locking on join/leave operations
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoom { private object writeLock = new object(); public long RoomID { get; set; } public MultiplayerRoomState State { get; set; } private List<MultiplayerRoomUser> users = new List<MultiplayerRoomUser>(); public IReadOnlyList<MultiplayerRoomUser> Users { get { lock (writeLock) return users.ToArray(); } } public void Join(int user) { lock (writeLock) users.Add(new MultiplayerRoomUser(user)); } public void Leave(int user) { lock (writeLock) users.RemoveAll(u => u.UserID == user); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoom { private object writeLock = new object(); public long RoomID { get; set; } public MultiplayerRoomState State { get; set; } private List<MultiplayerRoomUser> users = new List<MultiplayerRoomUser>(); public IReadOnlyList<MultiplayerRoomUser> Users { get { lock (writeLock) return users.ToArray(); } } public MultiplayerRoomUser Join(int userId) { var user = new MultiplayerRoomUser(userId); lock (writeLock) users.Add(user); return user; } public MultiplayerRoomUser Leave(int userId) { lock (writeLock) { var user = users.Find(u => u.UserID == userId); if (user == null) return null; users.Remove(user); return user; } } } }
Print information about the exception when the bot fails to log in to the forum.
using System; using System.Threading.Tasks; using Mitternacht.Services; using NLog; namespace Mitternacht.Modules.Forum.Services { public class ForumService : IMService { private readonly IBotCredentials _creds; private readonly Logger _log; public GommeHDnetForumAPI.Forum Forum { get; private set; } public bool HasForumInstance => Forum != null; public bool LoggedIn => Forum?.LoggedIn ?? false; private Task _loginTask; public ForumService(IBotCredentials creds) { _creds = creds; _log = LogManager.GetCurrentClassLogger(); InitForumInstance(); } public void InitForumInstance() { _loginTask?.Dispose(); _loginTask = Task.Run(() => { try { Forum = new GommeHDnetForumAPI.Forum(_creds.ForumUsername, _creds.ForumPassword); _log.Info($"Initialized new Forum instance."); } catch(Exception e) { _log.Warn(e, $"Initializing new Forum instance failed."); } }); } } }
using System; using System.Threading.Tasks; using Mitternacht.Services; using NLog; namespace Mitternacht.Modules.Forum.Services { public class ForumService : IMService { private readonly IBotCredentials _creds; private readonly Logger _log; public GommeHDnetForumAPI.Forum Forum { get; private set; } public bool HasForumInstance => Forum != null; public bool LoggedIn => Forum?.LoggedIn ?? false; private Task _loginTask; public ForumService(IBotCredentials creds) { _creds = creds; _log = LogManager.GetCurrentClassLogger(); InitForumInstance(); } public void InitForumInstance() { _loginTask?.Dispose(); _loginTask = Task.Run(() => { try { Forum = new GommeHDnetForumAPI.Forum(_creds.ForumUsername, _creds.ForumPassword); _log.Info($"Initialized new Forum instance."); } catch(Exception e) { _log.Warn(e, $"Initializing new Forum instance failed: {e}"); } }); } } }
Add error handling for the client
using System; using Grpc.Core; using Hello; namespace HelloClient { class Program { public static void Main(string[] args) { Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure); var client = new HelloService.HelloServiceClient(channel); String user = "Euler"; var reply = client.SayHello(new HelloReq { Name = user }); Console.WriteLine(reply.Result); channel.ShutdownAsync().Wait(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } }
using System; using Grpc.Core; using Hello; namespace HelloClient { class Program { public static void Main(string[] args) { Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure); var client = new HelloService.HelloServiceClient(channel); // ideally you should check for errors here too var reply = client.SayHello(new HelloReq { Name = "Euler" }); Console.WriteLine(reply.Result); try { reply = client.SayHelloStrict(new HelloReq { Name = "Leonhard Euler" }); Console.WriteLine(reply.Result); } catch (RpcException e) { // ouch! // lets print the gRPC error message // which is "Length of `Name` cannot be more than 10 characters" Console.WriteLine(e.Status.Detail); // lets access the error code, which is `INVALID_ARGUMENT` Console.WriteLine(e.Status.StatusCode); // Want its int version for some reason? // you shouldn't actually do this, but if you need for debugging, // you can access `e.Status.StatusCode` which will give you `3` Console.WriteLine((int)e.Status.StatusCode); // Want to take specific action based on specific error? if (e.Status.StatusCode == Grpc.Core.StatusCode.InvalidArgument) { // do your thing } } channel.ShutdownAsync().Wait(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } }
Correct copy on the home page
@model IEnumerable<Article> @{ ViewData["Title"] = "Home Page"; } <div class="header clearfix"> <nav> <ul class="nav nav-pills pull-right"> <li role="presentation" class="active"><a href="/">Home</a></li> <li role="presentation"><a href="https://kenticocloud.com/" target="_blank">Kentico Cloud</a></li> <li role="presentation"><a href="https://app.kenticocloud.com/sign-up" target="_blank">Sign up</a></li> </ul> </nav> <h3 class="text-muted">Kentico Cloud Boilerplate</h3> </div> <div class="jumbotron"> <h1>Let's Get Started</h1> <p class="lead">This boilerplate includes a set of features and best practices to kick off your website development with Kentico Cloud smoothly. Take a look into the code how this page works.</p> <p><a class="btn btn-lg btn-success" href="https://github.com/Kentico/cloud-boilerplate-net#quick-start" target="_blank" role="button">Read the Quick Start</a></p> </div> <div class="row marketing"> <h2>Articles from the Dancing Goat Sample Site</h2> </div> <div class="row marketing"> @* This MVC helper method ensures that current model is rendered with suitable view from /Views/Shared/DisplayTemplates *@ @Html.DisplayForModel() </div>
@model IEnumerable<Article> @{ ViewData["Title"] = "Home Page"; } <div class="header clearfix"> <nav> <ul class="nav nav-pills pull-right"> <li role="presentation" class="active"><a href="/">Home</a></li> <li role="presentation"><a href="https://kenticocloud.com/" target="_blank">Kentico Cloud</a></li> <li role="presentation"><a href="https://app.kenticocloud.com/sign-up" target="_blank">Sign up</a></li> </ul> </nav> <h3 class="text-muted">Kentico Cloud Boilerplate</h3> </div> <div class="jumbotron"> <h1>Let's Get Started</h1> <p class="lead">This boilerplate includes a set of features and best practices to kick off your website development with Kentico Cloud smoothly. Take a look into the code to see how it works.</p> <p><a class="btn btn-lg btn-success" href="https://github.com/Kentico/cloud-boilerplate-net#quick-start" target="_blank" role="button">Read the Quick Start</a></p> </div> <div class="row marketing"> <h2>Articles from the Dancing Goat Sample Site</h2> </div> <div class="row marketing"> @* This MVC helper method ensures that current model is rendered with suitable view from /Views/Shared/DisplayTemplates *@ @Html.DisplayForModel() </div>
Decrease allocations in stack serializer
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { internal class StackSerializationDelegateProvider : SerializationDelegateProviderBase { public override bool CanHandle(Type type) { return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>); } private static JsonValue _Encode<T>(Stack<T> stack, JsonSerializer serializer) { var array = new JsonArray(); for (int i = 0; i < stack.Count; i++) { array.Add(serializer.Serialize(stack.ElementAt(i))); } return array; } private static Stack<T> _Decode<T>(JsonValue json, JsonSerializer serializer) { var stack = new Stack<T>(); for (int i = 0; i < json.Array.Count; i++) { stack.Push(serializer.Deserialize<T>(json.Array[i])); } return stack; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { internal class StackSerializationDelegateProvider : SerializationDelegateProviderBase { public override bool CanHandle(Type type) { return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>); } private static JsonValue _Encode<T>(Stack<T> stack, JsonSerializer serializer) { var values = new JsonValue[stack.Count]; for (int i = 0; i < values.Length; i++) { values[0] = serializer.Serialize(stack.ElementAt(i)); } return new JsonArray(values); } private static Stack<T> _Decode<T>(JsonValue json, JsonSerializer serializer) { var array = json.Array; var values = new T[array.Count]; for (int i = 0; i < values.Length; i++) { values[i] = serializer.Deserialize<T>(array[i]); } return new Stack<T>(values); } } }
Add method to calculate time
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace HeadRaceTimingSite.Models { public class Crew { public int CrewId { get; set; } public string Name { get; set; } public int StartNumber { get; set; } public List<Result> Results { get; set; } public int CompetitionId { get; set; } public Competition Competition { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace HeadRaceTimingSite.Models { public class Crew { public int CrewId { get; set; } public string Name { get; set; } public int StartNumber { get; set; } public TimeSpan? RunTime(TimingPoint startPoint, TimingPoint finishPoint) { Result start = Results.First(r => r.TimingPointId == startPoint.TimingPointId); Result finish = Results.First(r => r.TimingPointId == finishPoint.TimingPointId); if (start != null && finish != null) return finish.TimeOfDay - start.TimeOfDay; else return null; } public List<Result> Results { get; set; } public int CompetitionId { get; set; } public Competition Competition { get; set; } } }
Fix border highlight effects gets the wrong effect node
#if NETFX_CORE namespace HelixToolkit.UWP #else namespace HelixToolkit.Wpf.SharpDX #endif { using Model.Scene; /// <summary> /// Highlight the border of meshes /// </summary> public class PostEffectMeshBorderHighlight : PostEffectMeshOutlineBlur { protected override SceneNode OnCreateSceneNode() { return new NodePostEffectMeshOutlineBlur(); } } }
#if NETFX_CORE namespace HelixToolkit.UWP #else namespace HelixToolkit.Wpf.SharpDX #endif { using Model.Scene; /// <summary> /// Highlight the border of meshes /// </summary> public class PostEffectMeshBorderHighlight : PostEffectMeshOutlineBlur { protected override SceneNode OnCreateSceneNode() { return new NodePostEffectBorderHighlight(); } } }
Increase the message notification delay slightly.
#region Copyright 2014 Exceptionless // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // http://www.gnu.org/licenses/agpl-3.0.html #endregion using System; using System.Threading.Tasks; using CodeSmith.Core.Component; using Exceptionless.Core.Messaging; using Exceptionless.Core.Messaging.Models; using Exceptionless.Core.Plugins.EventProcessor; namespace Exceptionless.Core.Pipeline { [Priority(80)] public class NotifySignalRAction : EventPipelineActionBase { private readonly IMessagePublisher _publisher; public NotifySignalRAction(IMessagePublisher publisher) { _publisher = publisher; } protected override bool ContinueOnError { get { return true; } } public override void Process(EventContext ctx) { Task.Factory.StartNewDelayed(1000, () => _publisher.Publish(new EventOccurrence { Id = ctx.Event.Id, OrganizationId = ctx.Event.OrganizationId, ProjectId = ctx.Event.ProjectId, StackId = ctx.Event.StackId, Type = ctx.Event.Type, IsHidden = ctx.Event.IsHidden, IsFixed = ctx.Event.IsFixed, IsNotFound = ctx.Event.IsNotFound(), IsRegression = ctx.IsRegression })); } } }
#region Copyright 2014 Exceptionless // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // http://www.gnu.org/licenses/agpl-3.0.html #endregion using System; using System.Threading.Tasks; using CodeSmith.Core.Component; using Exceptionless.Core.Messaging; using Exceptionless.Core.Messaging.Models; using Exceptionless.Core.Plugins.EventProcessor; namespace Exceptionless.Core.Pipeline { [Priority(80)] public class NotifySignalRAction : EventPipelineActionBase { private readonly IMessagePublisher _publisher; public NotifySignalRAction(IMessagePublisher publisher) { _publisher = publisher; } protected override bool ContinueOnError { get { return true; } } public override void Process(EventContext ctx) { Task.Factory.StartNewDelayed(1500, () => _publisher.Publish(new EventOccurrence { Id = ctx.Event.Id, OrganizationId = ctx.Event.OrganizationId, ProjectId = ctx.Event.ProjectId, StackId = ctx.Event.StackId, Type = ctx.Event.Type, IsHidden = ctx.Event.IsHidden, IsFixed = ctx.Event.IsFixed, IsNotFound = ctx.Event.IsNotFound(), IsRegression = ctx.IsRegression })); } } }
Send game state to client.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public class GameController : BaseController { public ActionResult Metadata() { Game game = Game.GetInstance(base.GetPlayer()); if (game != null) { return Json(new { playing = true, opponent = game.opponent.name }, JsonRequestBehavior.AllowGet); } else { return Json(new { playing = false }, JsonRequestBehavior.AllowGet); } } public ActionResult Surrender() { Game game = Game.GetInstance(base.GetPlayer()); if (game != null) { game.Surrender(); } return null; } public ActionResult AddZeppelin() { Game game = Game.GetInstance(base.GetPlayer()); string typeStr = Request.Form["type"]; ZeppelinType type = (ZeppelinType)Enum.Parse(typeof(ZeppelinType), typeStr, true); int x = Int32.Parse(Request.Form["x"]); int y = Int32.Parse(Request.Form["y"]); bool rotDown = Boolean.Parse(Request.Form["rotDown"]); Zeppelin zeppelin = new Zeppelin(type, x, y, rotDown); bool zeppelinAdded = game.AddZeppelin(zeppelin); return Json(zeppelinAdded, JsonRequestBehavior.AllowGet); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public class GameController : BaseController { public ActionResult Metadata() { Game game = Game.GetInstance(base.GetPlayer()); if (game != null) { return Json(new { playing = true, opponent = game.opponent.name, gameState = game.gameState.ToString() }, JsonRequestBehavior.AllowGet); } else { return Json(new { playing = false }, JsonRequestBehavior.AllowGet); } } public ActionResult Surrender() { Game game = Game.GetInstance(base.GetPlayer()); if (game != null) { game.Surrender(); } return null; } public ActionResult AddZeppelin() { Game game = Game.GetInstance(base.GetPlayer()); string typeStr = Request.Form["type"]; ZeppelinType type = (ZeppelinType)Enum.Parse(typeof(ZeppelinType), typeStr, true); int x = Int32.Parse(Request.Form["x"]); int y = Int32.Parse(Request.Form["y"]); bool rotDown = Boolean.Parse(Request.Form["rotDown"]); Zeppelin zeppelin = new Zeppelin(type, x, y, rotDown); bool zeppelinAdded = game.AddZeppelin(zeppelin); return Json(zeppelinAdded, JsonRequestBehavior.AllowGet); } } }
Fix formatting in events so it will build
namespace Ductus.FluentDocker.Model.HostEvents { /// <summary> /// Base evnet emitte by the docker dameon using e.g. docker events. /// </summary> /// <remarks> /// See docker documentation https://docs.docker.com/engine/reference/commandline/events/ /// </remarks> public class Event { /// <summary> /// The type of the event. /// </summary> public EventType Type { get; set; } /// <summary> /// The event action /// </summary> public EventAction Action { get; set; } } }
namespace Ductus.FluentDocker.Model.HostEvents { /// <summary> /// Base evnet emitte by the docker dameon using e.g. docker events. /// </summary> /// <remarks> /// See docker documentation https://docs.docker.com/engine/reference/commandline/events/ /// </remarks> public class Event { /// <summary> /// The type of the event. /// </summary> public EventType Type { get; set; } /// <summary> /// The event action /// </summary> public EventAction Action { get; set; } } }
Allow strict Fake to permit access to overridden Object methods
namespace FakeItEasy.Core { using System; using static FakeItEasy.ObjectMembers; internal class StrictFakeRule : IFakeObjectCallRule { private readonly StrictFakeOptions options; public StrictFakeRule(StrictFakeOptions options) { this.options = options; } public int? NumberOfTimesToCall => null; public bool IsApplicableTo(IFakeObjectCall fakeObjectCall) { if (fakeObjectCall.Method.IsSameMethodAs(EqualsMethod)) { return !this.HasOption(StrictFakeOptions.AllowEquals); } if (fakeObjectCall.Method.IsSameMethodAs(GetHashCodeMethod)) { return !this.HasOption(StrictFakeOptions.AllowGetHashCode); } if (fakeObjectCall.Method.IsSameMethodAs(ToStringMethod)) { return !this.HasOption(StrictFakeOptions.AllowToString); } if (EventCall.TryGetEventCall(fakeObjectCall, out _)) { return !this.HasOption(StrictFakeOptions.AllowEvents); } return true; } public void Apply(IInterceptedFakeObjectCall fakeObjectCall) { string message = ExceptionMessages.CallToUnconfiguredMethodOfStrictFake(fakeObjectCall); if (EventCall.TryGetEventCall(fakeObjectCall, out _)) { message += Environment.NewLine + ExceptionMessages.HandleEventsOnStrictFakes; } throw new ExpectationException(message); } private bool HasOption(StrictFakeOptions flag) => (flag & this.options) == flag; } }
namespace FakeItEasy.Core { using System; using static FakeItEasy.ObjectMembers; internal class StrictFakeRule : IFakeObjectCallRule { private readonly StrictFakeOptions options; public StrictFakeRule(StrictFakeOptions options) { this.options = options; } public int? NumberOfTimesToCall => null; public bool IsApplicableTo(IFakeObjectCall fakeObjectCall) { if (fakeObjectCall.Method.HasSameBaseMethodAs(EqualsMethod)) { return !this.HasOption(StrictFakeOptions.AllowEquals); } if (fakeObjectCall.Method.HasSameBaseMethodAs(GetHashCodeMethod)) { return !this.HasOption(StrictFakeOptions.AllowGetHashCode); } if (fakeObjectCall.Method.HasSameBaseMethodAs(ToStringMethod)) { return !this.HasOption(StrictFakeOptions.AllowToString); } if (EventCall.TryGetEventCall(fakeObjectCall, out _)) { return !this.HasOption(StrictFakeOptions.AllowEvents); } return true; } public void Apply(IInterceptedFakeObjectCall fakeObjectCall) { string message = ExceptionMessages.CallToUnconfiguredMethodOfStrictFake(fakeObjectCall); if (EventCall.TryGetEventCall(fakeObjectCall, out _)) { message += Environment.NewLine + ExceptionMessages.HandleEventsOnStrictFakes; } throw new ExpectationException(message); } private bool HasOption(StrictFakeOptions flag) => (flag & this.options) == flag; } }
Set default value to BackgroundColor
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace OpenKh.Tools.LayoutViewer { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::System.Drawing.Color BackgroundColor { get { return ((global::System.Drawing.Color)(this["BackgroundColor"])); } set { this["BackgroundColor"] = value; } } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace OpenKh.Tools.LayoutViewer { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValue("Magenta")] public global::System.Drawing.Color BackgroundColor { get { return ((global::System.Drawing.Color)(this["BackgroundColor"])); } set { this["BackgroundColor"] = value; } } } }
Set the artist to the username
using Espera.Network; using Newtonsoft.Json; using System; namespace Espera.Core { public class SoundCloudSong : Song { public SoundCloudSong() : base(String.Empty, TimeSpan.Zero) { } [JsonProperty("artwork_url")] public Uri ArtworkUrl { get; set; } public string Description { get; set; } [JsonProperty("duration")] public int DurationMilliseconds { get { return (int)this.Duration.TotalMilliseconds; } set { this.Duration = TimeSpan.FromMilliseconds(value); } } public int Id { get; set; } [JsonProperty("streamable")] public bool IsStreamable { get; set; } public override bool IsVideo { get { return false; } } public override NetworkSongSource NetworkSongSource { get { return NetworkSongSource.Youtube; } } [JsonProperty("permalink_url")] public Uri PermaLinkUrl { get { return new Uri(this.OriginalPath); } set { this.OriginalPath = value.ToString(); } } [JsonProperty("stream_url")] public Uri StreamUrl { get { return new Uri(this.PlaybackPath); } set { this.PlaybackPath = value.ToString(); } } public User User { get; set; } } public class User { public string Username { get; set; } } }
using Espera.Network; using Newtonsoft.Json; using System; namespace Espera.Core { public class SoundCloudSong : Song { private User user; public SoundCloudSong() : base(String.Empty, TimeSpan.Zero) { } [JsonProperty("artwork_url")] public Uri ArtworkUrl { get; set; } public string Description { get; set; } [JsonProperty("duration")] public int DurationMilliseconds { get { return (int)this.Duration.TotalMilliseconds; } set { this.Duration = TimeSpan.FromMilliseconds(value); } } public int Id { get; set; } [JsonProperty("streamable")] public bool IsStreamable { get; set; } public override bool IsVideo { get { return false; } } public override NetworkSongSource NetworkSongSource { get { return NetworkSongSource.Youtube; } } [JsonProperty("permalink_url")] public Uri PermaLinkUrl { get { return new Uri(this.OriginalPath); } set { this.OriginalPath = value.ToString(); } } [JsonProperty("stream_url")] public Uri StreamUrl { get { return new Uri(this.PlaybackPath); } set { this.PlaybackPath = value.ToString(); } } public User User { get { return this.user; } set { this.user = value; this.Artist = value.Username; } } } public class User { public string Username { get; set; } } }
Change WM_DEVICECHANGE value to hexadecimal
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinUsbInit { class DeviceArrivalListener : NativeWindow { // Constant value was found in the "windows.h" header file. private const int WM_DEVICECHANGE = 537; private const int DBT_DEVICEARRIVAL = 0x8000; private readonly WinUsbInitForm _parent; public DeviceArrivalListener(WinUsbInitForm parent) { parent.HandleCreated += OnHandleCreated; parent.HandleDestroyed += OnHandleDestroyed; _parent = parent; } // Listen for the control's window creation and then hook into it. internal void OnHandleCreated(object sender, EventArgs e) { // Window is now created, assign handle to NativeWindow. AssignHandle(((WinUsbInitForm)sender).Handle); } internal void OnHandleDestroyed(object sender, EventArgs e) { // Window was destroyed, release hook. ReleaseHandle(); } protected override void WndProc(ref Message m) { // Listen for operating system messages if (m.Msg == WM_DEVICECHANGE && (int) m.WParam == DBT_DEVICEARRIVAL) { // Notify the form that this message was received. _parent.DeviceInserted(); } base.WndProc(ref m); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinUsbInit { class DeviceArrivalListener : NativeWindow { // Constant values was found in the "windows.h" header file. private const int WM_DEVICECHANGE = 0x219; private const int DBT_DEVICEARRIVAL = 0x8000; private readonly WinUsbInitForm _parent; public DeviceArrivalListener(WinUsbInitForm parent) { parent.HandleCreated += OnHandleCreated; parent.HandleDestroyed += OnHandleDestroyed; _parent = parent; } // Listen for the control's window creation and then hook into it. internal void OnHandleCreated(object sender, EventArgs e) { // Window is now created, assign handle to NativeWindow. AssignHandle(((WinUsbInitForm)sender).Handle); } internal void OnHandleDestroyed(object sender, EventArgs e) { // Window was destroyed, release hook. ReleaseHandle(); } protected override void WndProc(ref Message m) { // Listen for operating system messages if (m.Msg == WM_DEVICECHANGE && (int) m.WParam == DBT_DEVICEARRIVAL) { // Notify the form that this message was received. _parent.DeviceInserted(); } base.WndProc(ref m); } } }
Fix signature of undirected edge
using System; using System.Collections.Generic; namespace Graph { /// <summary> /// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>. /// </summary> /// <typeparam name="V"> /// The type used to create vertex (node) labels. /// </typeparam> /// <typeparam name="W"> /// The type used for the edge weight. /// </typeparam> public interface IUndirectedEdge<V, W> : IEdge<V, W>, IEquatable<IUndirectedEdge<V, W>> where V : struct, IEquatable<V> where W : struct, IComparable<W>, IEquatable<W> { /// <summary> /// The vertices comprising the <see cref="IUndirectedEdge{V}"/>. /// </summary> ISet<V> Vertices { get; } } }
using System; using System.Collections.Generic; namespace Graph { /// <summary> /// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>. /// </summary> /// <typeparam name="V"> /// The type used to create vertex (node) labels. /// </typeparam> /// <typeparam name="W"> /// The type used for the edge weight. /// </typeparam> public interface IUndirectedEdge<V, W> : IEdge<V, W>, IEquatable<IUndirectedEdge<V, W>> where V : struct, IEquatable<V> where W : struct, IComparable<W>, IEquatable<W> { } }
Fix temporary models for relations.
using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model = Model.Update (model); } return model; } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } }
using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model.ModifiedAt = new DateTime (); model = Model.Update (model); } return model; } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } }
Use new intent instead of reusing broadcast one.
using System; using Android.App; using Android.Content; using Android.Support.V4.Content; namespace Toggl.Joey.Net { [BroadcastReceiver (Permission = "com.google.android.c2dm.permission.SEND")] [IntentFilter (new string[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[]{ "com.toggl.timer" })] public class GcmBroadcastReceiver : WakefulBroadcastReceiver { public override void OnReceive (Context context, Intent intent) { var comp = new ComponentName (context, Java.Lang.Class.FromType (typeof(GcmService))); StartWakefulService (context, (intent.SetComponent (comp))); ResultCode = Result.Ok; } } }
using System; using Android.App; using Android.Content; using Android.Support.V4.Content; namespace Toggl.Joey.Net { [BroadcastReceiver (Permission = "com.google.android.c2dm.permission.SEND")] [IntentFilter (new string[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[]{ "com.toggl.timer" })] public class GcmBroadcastReceiver : WakefulBroadcastReceiver { public override void OnReceive (Context context, Intent intent) { var serviceIntent = new Intent (context, typeof(GcmService)); serviceIntent.ReplaceExtras (intent.Extras); StartWakefulService (context, serviceIntent); ResultCode = Result.Ok; } } }
Set character encoding when displaying html from markdown (BL-3785)
using System; using System.Drawing; using System.IO; using System.Windows.Forms; using MarkdownDeep; using SIL.IO; namespace SIL.Windows.Forms.ReleaseNotes { /// <summary> /// Shows a dialog for release notes; accepts html and markdown /// </summary> public partial class ShowReleaseNotesDialog : Form { private readonly string _path; private TempFile _temp; private readonly Icon _icon; public ShowReleaseNotesDialog(Icon icon, string path) { _path = path; _icon = icon; InitializeComponent(); } private void ShowReleaseNotesDialog_Load(object sender, EventArgs e) { string contents = File.ReadAllText(_path); var md = new Markdown(); _temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp File.WriteAllText(_temp.Path, md.Transform(contents)); _browser.Url = new Uri(_temp.Path); } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); // a bug in Mono requires us to wait to set Icon until handle created. Icon = _icon; } } }
using System; using System.Drawing; using System.IO; using System.Windows.Forms; using MarkdownDeep; using SIL.IO; namespace SIL.Windows.Forms.ReleaseNotes { /// <summary> /// Shows a dialog for release notes; accepts html and markdown /// </summary> public partial class ShowReleaseNotesDialog : Form { private readonly string _path; private TempFile _temp; private readonly Icon _icon; public ShowReleaseNotesDialog(Icon icon, string path) { _path = path; _icon = icon; InitializeComponent(); } private void ShowReleaseNotesDialog_Load(object sender, EventArgs e) { string contents = File.ReadAllText(_path); var md = new Markdown(); _temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp File.WriteAllText(_temp.Path, GetBasicHtmlFromMarkdown(md.Transform(contents))); _browser.Url = new Uri(_temp.Path); } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); // a bug in Mono requires us to wait to set Icon until handle created. Icon = _icon; } private string GetBasicHtmlFromMarkdown(string markdownHtml) { return string.Format("<html><head><meta charset=\"utf-8\"/></head><body>{0}</body></html>", markdownHtml); } } }