Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Create and release tooltip content on demand
using System; using System.Windows.Controls; using GitHub.InlineReviews.Views; using GitHub.InlineReviews.ViewModels; namespace GitHub.InlineReviews.Tags { public partial class ShowInlineCommentGlyph : UserControl { readonly CommentTooltipView commentTooltipView; public ShowInlineCommentGlyph() { InitializeComponent(); commentTooltipView = new CommentTooltipView(); ToolTip = commentTooltipView; ToolTipOpening += ShowInlineCommentGlyph_ToolTipOpening; } private void ShowInlineCommentGlyph_ToolTipOpening(object sender, ToolTipEventArgs e) { var tag = Tag as ShowInlineCommentTag; var viewModel = new CommentTooltipViewModel(); foreach (var comment in tag.Thread.Comments) { var commentViewModel = new TooltipCommentViewModel(comment.User, comment.Body, comment.CreatedAt); viewModel.Comments.Add(commentViewModel); } commentTooltipView.DataContext = viewModel; } } }
using System; using System.Windows.Controls; using GitHub.InlineReviews.Views; using GitHub.InlineReviews.ViewModels; namespace GitHub.InlineReviews.Tags { public partial class ShowInlineCommentGlyph : UserControl { readonly ToolTip toolTip; public ShowInlineCommentGlyph() { InitializeComponent(); toolTip = new ToolTip(); ToolTip = toolTip; } protected override void OnToolTipOpening(ToolTipEventArgs e) { var tag = Tag as ShowInlineCommentTag; var viewModel = new CommentTooltipViewModel(); foreach (var comment in tag.Thread.Comments) { var commentViewModel = new TooltipCommentViewModel(comment.User, comment.Body, comment.CreatedAt); viewModel.Comments.Add(commentViewModel); } var view = new CommentTooltipView(); view.DataContext = viewModel; toolTip.Content = view; } protected override void OnToolTipClosing(ToolTipEventArgs e) { toolTip.Content = null; } } }
Fix up youtube URL regex matching
using System.Collections.Generic; namespace Umbraco.Web.Media.EmbedProviders { public class YouTube : EmbedProviderBase { public override string ApiEndpoint => "https://www.youtube.com/oembed"; public override string[] UrlSchemeRegex => new string[] { @"youtu.be/.*", @"youtu.be/.*" }; public override Dictionary<string, string> RequestParams => new Dictionary<string, string>() { //ApiUrl/?format=json {"format", "json"} }; public override string GetMarkup(string url, int maxWidth = 0, int maxHeight = 0) { var requestUrl = base.GetEmbedProviderUrl(url, maxWidth, maxHeight); var oembed = base.GetJsonResponse<OEmbedResponse>(requestUrl); return oembed.GetHtml(); } } }
using System.Collections.Generic; namespace Umbraco.Web.Media.EmbedProviders { public class YouTube : EmbedProviderBase { public override string ApiEndpoint => "https://www.youtube.com/oembed"; public override string[] UrlSchemeRegex => new string[] { @"youtu.be/.*", @"youtube.com/watch.*" }; public override Dictionary<string, string> RequestParams => new Dictionary<string, string>() { //ApiUrl/?format=json {"format", "json"} }; public override string GetMarkup(string url, int maxWidth = 0, int maxHeight = 0) { var requestUrl = base.GetEmbedProviderUrl(url, maxWidth, maxHeight); var oembed = base.GetJsonResponse<OEmbedResponse>(requestUrl); return oembed.GetHtml(); } } }
Fix issue with Page calculation
using System; using Newtonsoft.Json; namespace ErgastApi.Responses { // TODO: Use internal/private constructors for all response types? public abstract class ErgastResponse { [JsonProperty("url")] public virtual string RequestUrl { get; private set; } [JsonProperty("limit")] public virtual int Limit { get; private set; } [JsonProperty("offset")] public virtual int Offset { get; private set; } [JsonProperty("total")] public virtual int TotalResults { get; private set; } // TODO: Note that it can be inaccurate if limit/offset do not correlate // TODO: Test with 0 values public virtual int Page => Offset / Limit + 1; // TODO: Test with 0 values public virtual int TotalPages => (int) Math.Ceiling(TotalResults / (double)Limit); // TODO: Test public virtual bool HasMorePages => TotalResults > Limit + Offset; } }
using System; using Newtonsoft.Json; namespace ErgastApi.Responses { // TODO: Use internal/private constructors for all response types? public abstract class ErgastResponse { [JsonProperty("url")] public string RequestUrl { get; protected set; } [JsonProperty("limit")] public int Limit { get; protected set; } [JsonProperty("offset")] public int Offset { get; protected set; } [JsonProperty("total")] public int TotalResults { get; protected set; } // TODO: Note that it can be inaccurate if limit/offset do not divide evenly public int Page { get { if (Limit <= 0) return 1; return (int) Math.Ceiling((double) Offset / Limit) + 1; } } // TODO: Test with 0 values public int TotalPages => (int) Math.Ceiling(TotalResults / (double) Limit); // TODO: Test public bool HasMorePages => TotalResults > Limit + Offset; } }
Add checking of Read() return value.
using System.Linq; using System.Text; namespace Modbus.IO { internal static class StreamResourceUtility { internal static string ReadLine(IStreamResource stream) { var result = new StringBuilder(); var singleByteBuffer = new byte[1]; do { stream.Read(singleByteBuffer, 0, 1); result.Append(Encoding.ASCII.GetChars(singleByteBuffer).First()); } while (!result.ToString().EndsWith(Modbus.NewLine)); return result.ToString().Substring(0, result.Length - Modbus.NewLine.Length); } } }
using System.Linq; using System.Text; namespace Modbus.IO { internal static class StreamResourceUtility { internal static string ReadLine(IStreamResource stream) { var result = new StringBuilder(); var singleByteBuffer = new byte[1]; do { if (0 == stream.Read(singleByteBuffer, 0, 1)) continue; result.Append(Encoding.ASCII.GetChars(singleByteBuffer).First()); } while (!result.ToString().EndsWith(Modbus.NewLine)); return result.ToString().Substring(0, result.Length - Modbus.NewLine.Length); } } }
Sort and remove unused usings
using GitHub.UI; using GitHub.VisualStudio.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; namespace GitHub.VisualStudio { public static class SharedResources { static readonly Dictionary<string, DrawingBrush> drawingBrushes = new Dictionary<string, DrawingBrush>(); public static DrawingBrush GetDrawingForIcon(Octicon icon, Brush color) { string name = icon.ToString(); if (drawingBrushes.ContainsKey(name)) return drawingBrushes[name]; var brush = new DrawingBrush() { Drawing = new GeometryDrawing() { Brush = color, Pen = new Pen(color, 1.0).FreezeThis(), Geometry = OcticonPath.GetGeometryForIcon(icon).FreezeThis() } .FreezeThis(), Stretch = Stretch.Uniform } .FreezeThis(); drawingBrushes.Add(name, brush); return brush; } } }
using System.Collections.Generic; using System.Windows.Media; using GitHub.UI; using GitHub.VisualStudio.UI; namespace GitHub.VisualStudio { public static class SharedResources { static readonly Dictionary<string, DrawingBrush> drawingBrushes = new Dictionary<string, DrawingBrush>(); public static DrawingBrush GetDrawingForIcon(Octicon icon, Brush color) { string name = icon.ToString(); if (drawingBrushes.ContainsKey(name)) return drawingBrushes[name]; var brush = new DrawingBrush() { Drawing = new GeometryDrawing() { Brush = color, Pen = new Pen(color, 1.0).FreezeThis(), Geometry = OcticonPath.GetGeometryForIcon(icon).FreezeThis() } .FreezeThis(), Stretch = Stretch.Uniform } .FreezeThis(); drawingBrushes.Add(name, brush); return brush; } } }
Add extra work to RedditBrowser sample
using Stylet.Samples.RedditBrowser.Events; using Stylet.Samples.RedditBrowser.RedditApi; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stylet.Samples.RedditBrowser.Pages { public class TaskbarViewModel : Screen { private IEventAggregator events; public string Subreddit { get; set; } public IEnumerable<SortMode> SortModes { get; private set; } public SortMode SelectedSortMode { get; set; } public TaskbarViewModel(IEventAggregator events) { this.events = events; this.SortModes = SortMode.AllModes; this.SelectedSortMode = SortMode.Hot; } public void Open() { this.events.Publish(new OpenSubredditEvent() { Subreddit = this.Subreddit, SortMode = this.SelectedSortMode }); } } }
using Stylet.Samples.RedditBrowser.Events; using Stylet.Samples.RedditBrowser.RedditApi; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stylet.Samples.RedditBrowser.Pages { public class TaskbarViewModel : Screen { private IEventAggregator events; public string Subreddit { get; set; } public IEnumerable<SortMode> SortModes { get; private set; } public SortMode SelectedSortMode { get; set; } public TaskbarViewModel(IEventAggregator events) { this.events = events; this.SortModes = SortMode.AllModes; this.SelectedSortMode = SortMode.Hot; } public bool CanOpen { get { return !String.IsNullOrWhiteSpace(this.Subreddit); } } public void Open() { this.events.Publish(new OpenSubredditEvent() { Subreddit = this.Subreddit, SortMode = this.SelectedSortMode }); } } }
Fix Sleep of the test program
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using XboxOnePadReader; namespace PadReaderTest { class Program { static void Main(string[] args) { ControllerReader myController = ControllerReader.Instance; int x = 0; while (x < 5) { Thread.Sleep(1); ++x; } myController.CloseController(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using XboxOnePadReader; namespace PadReaderTest { class Program { static void Main(string[] args) { ControllerReader myController = ControllerReader.Instance; int x = 0; while (x < 5) { Thread.Sleep(1000); ++x; } myController.CloseController(); } } }
Write Log message for test
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test1 : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test1 : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { Condole.Log("This log is added by Suzuki"); } }
Remove unused line of code
namespace OpenKh.Game { public class Global { public const int ResolutionWidth = 512; public const int ResolutionHeight = 416; public const int ResolutionRemixWidth = 684; public const float ResolutionReMixRatio = 0.925f; public const float ResolutionBoostRatio = 2; } }
namespace OpenKh.Game { public class Global { public const int ResolutionWidth = 512; public const int ResolutionHeight = 416; public const int ResolutionRemixWidth = 684; public const float ResolutionReMixRatio = 0.925f; } }
Update expected SR in test
// 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 NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Taiko.Difficulty; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Taiko.Tests { public class TaikoDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Taiko"; [TestCase(2.9811338051242915d, "diffcalc-test")] [TestCase(2.9811338051242915d, "diffcalc-test-strong")] public void Test(double expected, string name) => base.Test(expected, name); protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new TaikoDifficultyCalculator(new TaikoRuleset(), beatmap); protected override Ruleset CreateRuleset() => new TaikoRuleset(); } }
// 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 NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Taiko.Difficulty; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Taiko.Tests { public class TaikoDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Taiko"; [TestCase(2.2905937546434592d, "diffcalc-test")] [TestCase(2.2905937546434592d, "diffcalc-test-strong")] public void Test(double expected, string name) => base.Test(expected, name); protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new TaikoDifficultyCalculator(new TaikoRuleset(), beatmap); protected override Ruleset CreateRuleset() => new TaikoRuleset(); } }
Disable text tests for now
using System; using System.Drawing.Imaging; using System.IO; using NUnit.Framework; using ValveResourceFormat; using ValveResourceFormat.ResourceTypes; namespace Tests { public class TextureTests { [Test] public void Test() { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Textures"); var files = Directory.GetFiles(path, "*.vtex_c"); foreach (var file in files) { var resource = new Resource(); resource.Read(file); var bitmap = ((Texture)resource.Blocks[BlockType.DATA]).GenerateBitmap(); using (var ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Png); using (var expected = new FileStream(Path.ChangeExtension(file, "png"), FileMode.Open, FileAccess.Read)) { FileAssert.AreEqual(expected, ms); } } } } } }
using System; using System.Drawing.Imaging; using System.IO; using NUnit.Framework; using ValveResourceFormat; using ValveResourceFormat.ResourceTypes; namespace Tests { public class TextureTests { [Test] [Ignore("Need a better way of testing images rather than comparing the files directly")] public void Test() { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Textures"); var files = Directory.GetFiles(path, "*.vtex_c"); foreach (var file in files) { var resource = new Resource(); resource.Read(file); var bitmap = ((Texture)resource.Blocks[BlockType.DATA]).GenerateBitmap(); using (var ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Png); using (var expected = new FileStream(Path.ChangeExtension(file, "png"), FileMode.Open, FileAccess.Read)) { FileAssert.AreEqual(expected, ms); } } } } } }
Support to map swagger UI to application root url
using System; using Microsoft.AspNetCore.StaticFiles; using Swashbuckle.AspNetCore.SwaggerUI; namespace Microsoft.AspNetCore.Builder { public static class SwaggerUIBuilderExtensions { public static IApplicationBuilder UseSwaggerUI( this IApplicationBuilder app, Action<SwaggerUIOptions> setupAction) { var options = new SwaggerUIOptions(); setupAction?.Invoke(options); // Serve swagger-ui assets with the FileServer middleware, using a custom FileProvider // to inject parameters into "index.html" var fileServerOptions = new FileServerOptions { RequestPath = $"/{options.RoutePrefix}", FileProvider = new SwaggerUIFileProvider(options.IndexSettings.ToTemplateParameters()), EnableDefaultFiles = true, // serve index.html at /{options.RoutePrefix}/ }; fileServerOptions.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider(); app.UseFileServer(fileServerOptions); return app; } } }
using System; using Microsoft.AspNetCore.StaticFiles; using Swashbuckle.AspNetCore.SwaggerUI; namespace Microsoft.AspNetCore.Builder { public static class SwaggerUIBuilderExtensions { public static IApplicationBuilder UseSwaggerUI( this IApplicationBuilder app, Action<SwaggerUIOptions> setupAction) { var options = new SwaggerUIOptions(); setupAction?.Invoke(options); // Serve swagger-ui assets with the FileServer middleware, using a custom FileProvider // to inject parameters into "index.html" var fileServerOptions = new FileServerOptions { RequestPath = string.IsNullOrWhiteSpace(options.RoutePrefix) ? string.Empty : $"/{options.RoutePrefix}", FileProvider = new SwaggerUIFileProvider(options.IndexSettings.ToTemplateParameters()), EnableDefaultFiles = true, // serve index.html at /{options.RoutePrefix}/ }; fileServerOptions.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider(); app.UseFileServer(fileServerOptions); return app; } } }
Add registration options for hover request
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class MarkedString { public string Language { get; set; } public string Value { get; set; } } public class Hover { public MarkedString[] Contents { get; set; } public Range? Range { get; set; } } public class HoverRequest { public static readonly RequestType<TextDocumentPositionParams, Hover, object, object> Type = RequestType<TextDocumentPositionParams, Hover, object, object>.Create("textDocument/hover"); } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class MarkedString { public string Language { get; set; } public string Value { get; set; } } public class Hover { public MarkedString[] Contents { get; set; } public Range? Range { get; set; } } public class HoverRequest { public static readonly RequestType<TextDocumentPositionParams, Hover, object, TextDocumentRegistrationOptions> Type = RequestType<TextDocumentPositionParams, Hover, object, TextDocumentRegistrationOptions>.Create("textDocument/hover"); } }
Build Script - cleanup and filling out vars
//#tool nuget:?package=NUnit.ConsoleRunner&version=3.4.0 var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); // Define directories. var buildDir = Directory("./src/Example/bin") + Directory(configuration); Task("Clean") .Does(() => { CleanDirectory(buildDir); }); Task("Restore-NuGet-Packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore("./Live.Forms.iOS.sln"); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { if(IsRunningOnWindows()) { // Use MSBuild MSBuild("./Live.Forms.iOS.sln", settings => settings.SetConfiguration(configuration)); } else { // Use XBuild XBuild("./Live.Forms.iOS.sln", settings => settings.SetConfiguration(configuration)); } }); Task("Default") .IsDependentOn("Build"); RunTarget(target);
//#tool nuget:?package=NUnit.ConsoleRunner&version=3.4.0 string target = Argument("target", "Default"); string configuration = Argument("configuration", "Release"); // Define directories. var dirs = new[] { Directory("./Live.Forms/bin") + Directory(configuration), Directory("./Live.Forms.iOS/bin") + Directory(configuration), }; string sln = "./Live.Forms.iOS.sln"; Task("Clean") .Does(() => { foreach (var dir in dirs) CleanDirectory(dir); }); Task("Restore-NuGet-Packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore(sln); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { if(IsRunningOnWindows()) { // Use MSBuild MSBuild(sln, settings => settings .WithProperty("Platform", new[] { "iPhoneSimulator" }) .SetConfiguration(configuration)); } else { // Use XBuild XBuild(sln, settings => settings .WithProperty("Platform", new[] { "iPhoneSimulator" }) .SetConfiguration(configuration)); } }); Task("Default") .IsDependentOn("Build"); RunTarget(target);
Fix tests, but not seeding Database anymore
using System.Data.Entity; using Kandanda.Dal.DataTransferObjects; namespace Kandanda.Dal { public class KandandaDbContext : DbContext { public KandandaDbContext() { Database.SetInitializer(new SampleDataDbInitializer()); } public DbSet<Tournament> Tournaments { get; set; } public DbSet<Participant> Participants { get; set; } public DbSet<Match> Matches { get; set; } public DbSet<Place> Places { get; set; } public DbSet<Phase> Phases { get; set; } public DbSet<TournamentParticipant> TournamentParticipants { get; set; } } }
using System.Data.Entity; using Kandanda.Dal.DataTransferObjects; namespace Kandanda.Dal { public class KandandaDbContext : DbContext { public KandandaDbContext() { // TODO fix SetInitializer for tests Database.SetInitializer(new DropCreateDatabaseAlways<KandandaDbContext>()); } public DbSet<Tournament> Tournaments { get; set; } public DbSet<Participant> Participants { get; set; } public DbSet<Match> Matches { get; set; } public DbSet<Place> Places { get; set; } public DbSet<Phase> Phases { get; set; } public DbSet<TournamentParticipant> TournamentParticipants { get; set; } } }
Use Helper to create instance from assembly
 namespace nuPickers.Shared.DotNetDataSource { using nuPickers.Shared.Editor; using System; using System.Reflection; using System.Collections.Generic; using System.Linq; public class DotNetDataSource { public string AssemblyName { get; set; } public string ClassName { get; set; } public IEnumerable<DotNetDataSourceProperty> Properties { get; set; } public IEnumerable<EditorDataItem> GetEditorDataItems() { List<EditorDataItem> editorDataItems = new List<EditorDataItem>(); object dotNetDataSource = Activator.CreateInstance(this.AssemblyName, this.ClassName).Unwrap(); foreach (PropertyInfo propertyInfo in dotNetDataSource.GetType().GetProperties().Where(x => this.Properties.Select(y => y.Name).Contains(x.Name))) { if (propertyInfo.PropertyType == typeof(string)) { propertyInfo.SetValue(dotNetDataSource, this.Properties.Where(x => x.Name == propertyInfo.Name).Single().Value); } else { // TODO: log unexpected property type } } return ((IDotNetDataSource)dotNetDataSource) .GetEditorDataItems() .Select(x => new EditorDataItem() { Key = x.Key, Label = x.Value }); } } }
 namespace nuPickers.Shared.DotNetDataSource { using nuPickers.Shared.Editor; using System; using System.Reflection; using System.Collections.Generic; using System.Linq; public class DotNetDataSource { public string AssemblyName { get; set; } public string ClassName { get; set; } public IEnumerable<DotNetDataSourceProperty> Properties { get; set; } public IEnumerable<EditorDataItem> GetEditorDataItems() { List<EditorDataItem> editorDataItems = new List<EditorDataItem>(); object dotNetDataSource = Helper.GetAssembly(this.AssemblyName).CreateInstance(this.ClassName); foreach (PropertyInfo propertyInfo in dotNetDataSource.GetType().GetProperties().Where(x => this.Properties.Select(y => y.Name).Contains(x.Name))) { if (propertyInfo.PropertyType == typeof(string)) { propertyInfo.SetValue(dotNetDataSource, this.Properties.Where(x => x.Name == propertyInfo.Name).Single().Value); } else { // TODO: log unexpected property type } } return ((IDotNetDataSource)dotNetDataSource) .GetEditorDataItems() .Select(x => new EditorDataItem() { Key = x.Key, Label = x.Value }); } } }
Add date to status report
namespace Certify.Models.Shared { public class RenewalStatusReport { public string InstanceId { get; set; } public string MachineName { get; set; } public ManagedSite ManagedSite { get; set; } public string PrimaryContactEmail { get; set; } public string AppVersion { get; set; } } }
using System; namespace Certify.Models.Shared { public class RenewalStatusReport { public string InstanceId { get; set; } public string MachineName { get; set; } public ManagedSite ManagedSite { get; set; } public string PrimaryContactEmail { get; set; } public string AppVersion { get; set; } public DateTime? DateReported { get; set; } } }
Add `HasPriorLearning` to draft response
using System; using SFA.DAS.CommitmentsV2.Types; namespace SFA.DAS.CommitmentsV2.Api.Types.Responses { public sealed class GetDraftApprenticeshipResponse { public long Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Uln { get; set; } public string CourseCode { get; set; } public DeliveryModel DeliveryModel { get; set; } public string TrainingCourseName { get; set; } public string TrainingCourseVersion { get; set; } public string TrainingCourseOption { get; set; } public bool TrainingCourseVersionConfirmed { get; set; } public string StandardUId { get; set; } public int? Cost { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public DateTime? DateOfBirth { get; set; } public string Reference { get; set; } public Guid? ReservationId { get; set; } public bool IsContinuation { get; set; } public DateTime? OriginalStartDate { get; set; } public bool HasStandardOptions { get; set; } public int? EmploymentPrice { get; set; } public DateTime? EmploymentEndDate { get; set; } } }
using System; using SFA.DAS.CommitmentsV2.Types; namespace SFA.DAS.CommitmentsV2.Api.Types.Responses { public sealed class GetDraftApprenticeshipResponse { public long Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Uln { get; set; } public string CourseCode { get; set; } public DeliveryModel DeliveryModel { get; set; } public string TrainingCourseName { get; set; } public string TrainingCourseVersion { get; set; } public string TrainingCourseOption { get; set; } public bool TrainingCourseVersionConfirmed { get; set; } public string StandardUId { get; set; } public int? Cost { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public DateTime? DateOfBirth { get; set; } public string Reference { get; set; } public Guid? ReservationId { get; set; } public bool IsContinuation { get; set; } public DateTime? OriginalStartDate { get; set; } public bool HasStandardOptions { get; set; } public int? EmploymentPrice { get; set; } public DateTime? EmploymentEndDate { get; set; } public bool? HasPriorLearning { get; set; } } }
Fix FortuneTeller for .NET4 not unregistering from eureka on app shutdown
using Autofac; using Autofac.Integration.WebApi; using FortuneTellerService4.Models; using Pivotal.Discovery.Client; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Http; using System.Web.Routing; namespace FortuneTellerService4 { public class WebApiApplication : System.Web.HttpApplication { private IDiscoveryClient _client; protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); var config = GlobalConfiguration.Configuration; // Build application configuration ServerConfig.RegisterConfig("development"); // Create IOC container builder var builder = new ContainerBuilder(); // Register your Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Register IDiscoveryClient, etc. builder.RegisterDiscoveryClient(ServerConfig.Configuration); // Initialize and Register FortuneContext builder.RegisterInstance(SampleData.InitializeFortunes()).SingleInstance(); // Register FortuneRepository builder.RegisterType<FortuneRepository>().As<IFortuneRepository>().SingleInstance(); var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); // Start the Discovery client background thread _client = container.Resolve<IDiscoveryClient>(); } } }
using Autofac; using Autofac.Integration.WebApi; using FortuneTellerService4.Models; using Pivotal.Discovery.Client; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Http; using System.Web.Routing; namespace FortuneTellerService4 { public class WebApiApplication : System.Web.HttpApplication { private IDiscoveryClient _client; protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); var config = GlobalConfiguration.Configuration; // Build application configuration ServerConfig.RegisterConfig("development"); // Create IOC container builder var builder = new ContainerBuilder(); // Register your Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Register IDiscoveryClient, etc. builder.RegisterDiscoveryClient(ServerConfig.Configuration); // Initialize and Register FortuneContext builder.RegisterInstance(SampleData.InitializeFortunes()).SingleInstance(); // Register FortuneRepository builder.RegisterType<FortuneRepository>().As<IFortuneRepository>().SingleInstance(); var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); // Start the Discovery client background thread _client = container.Resolve<IDiscoveryClient>(); } protected void Application_End() { // Unregister current app with Service Discovery server _client.ShutdownAsync(); } } }
Add extra test for generic type for naming
using System; using Xunit; namespace Stunts.Tests { public class StuntNamingTests { [Theory] [InlineData("StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] public void GetNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetName(baseType, implementedInterfaces)); [Theory] [InlineData(StuntNaming.DefaultNamespace + ".StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] public void GetFullNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetFullName(baseType, implementedInterfaces)); } }
using System; using System.Collections.Generic; using Xunit; namespace Stunts.Tests { public class StuntNamingTests { [Theory] [InlineData("StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] [InlineData("IEnumerableOfIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(IEnumerable<IDisposable>), typeof(IServiceProvider))] public void GetNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetName(baseType, implementedInterfaces)); [Theory] [InlineData(StuntNaming.DefaultNamespace + ".StuntFactoryIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(StuntFactory), typeof(IServiceProvider), typeof(IDisposable))] [InlineData(StuntNaming.DefaultNamespace + ".IEnumerableOfIDisposableIServiceProvider" + StuntNaming.DefaultSuffix, typeof(IEnumerable<IDisposable>), typeof(IServiceProvider))] public void GetFullNameOrdersTypes(string expectedName, Type baseType, params Type[] implementedInterfaces) => Assert.Equal(expectedName, StuntNaming.GetFullName(baseType, implementedInterfaces)); } }
Disable broken test session thing.
using System; using System.Diagnostics.Eventing.Reader; using System.Net; using System.Net.Http; using Cogito.Net.Http; using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tracing.Session; using Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Utility; using Microsoft.Samples.Eventing; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Cogito.Tests.Net.Http { [TestClass] public class HttpMessageEventSourceTests { [TestMethod] public void Test_EventSource() { EventSourceAnalyzer.InspectAll(HttpMessageEventSource.Current); } [TestMethod] public void Test_Request() { using (var session = new TraceEventSession("MyRealTimeSession")) { session.Source.Dynamic.All += data => Console.WriteLine("GOT Event " + data); session.EnableProvider(TraceEventProviders.GetEventSourceGuidFromName("Cogito-Net-Http-Messages")); HttpMessageEventSource.Current.Request(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.tempuri.com")) { }); session.Source.Process(); } } [TestMethod] public void Test_Response() { HttpMessageEventSource.Current.Response(new HttpResponseMessage(HttpStatusCode.OK)); } } }
using System; using System.Diagnostics.Eventing.Reader; using System.Net; using System.Net.Http; using Cogito.Net.Http; using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tracing.Session; using Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Utility; using Microsoft.Samples.Eventing; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Cogito.Tests.Net.Http { [TestClass] public class HttpMessageEventSourceTests { [TestMethod] public void Test_EventSource() { EventSourceAnalyzer.InspectAll(HttpMessageEventSource.Current); } //[TestMethod] //public void Test_Request() //{ // using (var session = new TraceEventSession("MyRealTimeSession")) // { // session.Source.Dynamic.All += data => Console.WriteLine("GOT Event " + data); // session.EnableProvider(TraceEventProviders.GetEventSourceGuidFromName("Cogito-Net-Http-Messages")); // HttpMessageEventSource.Current.Request(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.tempuri.com")) // { // }); // session.Source.Process(); // } //} //[TestMethod] //public void Test_Response() //{ // HttpMessageEventSource.Current.Response(new HttpResponseMessage(HttpStatusCode.OK)); //} } }
Fix bug - command parameter is always null.
#region Using using System.Collections.Generic; using System.Windows.Input; using PuppyFramework.Services; #endregion namespace PuppyFramework.MenuService { public class MenuItem : MenuItemBase { #region Fields private ObservableSortedList<MenuItemBase> _children; private string _title; #endregion #region Properties public object CommandParamter { get; set; } public CommandBinding CommandBinding { get; set; } public ObservableSortedList<MenuItemBase> Children { get { return _children; } private set { SetProperty(ref _children, value); } } public string Title { get { return _title; } protected set { SetProperty(ref _title, value); } } #endregion #region Constructors public MenuItem(string title, double weight) : base(weight) { Title = title; Children = new ObservableSortedList<MenuItemBase>(); HiddenFlag = false; } #endregion #region Methods public void AddChild(MenuItemBase child, IComparer<MenuItemBase> menuItemComparer = null) { Children.Add(child); if (menuItemComparer != null) { Children.Sort(menuItemComparer); } } public bool RemoveChild(MenuItemBase child) { return Children.Remove(child); } #endregion } }
#region Using using System.Collections.Generic; using System.Windows.Input; using PuppyFramework.Services; #endregion namespace PuppyFramework.MenuService { public class MenuItem : MenuItemBase { #region Fields private ObservableSortedList<MenuItemBase> _children; private string _title; #endregion #region Properties public object CommandParameter { get; set; } public CommandBinding CommandBinding { get; set; } public ObservableSortedList<MenuItemBase> Children { get { return _children; } private set { SetProperty(ref _children, value); } } public string Title { get { return _title; } protected set { SetProperty(ref _title, value); } } #endregion #region Constructors public MenuItem(string title, double weight) : base(weight) { Title = title; Children = new ObservableSortedList<MenuItemBase>(); HiddenFlag = false; } #endregion #region Methods public void AddChild(MenuItemBase child, IComparer<MenuItemBase> menuItemComparer = null) { Children.Add(child); if (menuItemComparer != null) { Children.Sort(menuItemComparer); } } public bool RemoveChild(MenuItemBase child) { return Children.Remove(child); } #endregion } }
Fix AddSmtpSender extension methods to property add service
using FluentEmail.Core.Interfaces; using FluentEmail.Smtp; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Net; using System.Net.Mail; namespace Microsoft.Extensions.DependencyInjection { public static class FluentEmailSmtpBuilderExtensions { public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, SmtpClient smtpClient) { builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(smtpClient))); return builder; } public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port) => AddSmtpSender(builder, new SmtpClient(host, port)); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port, string username, string password) => AddSmtpSender(builder, new SmtpClient(host, port) { EnableSsl = true, Credentials = new NetworkCredential (username, password) }); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, Func<SmtpClient> clientFactory) { builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(clientFactory))); return builder; } } }
using FluentEmail.Core.Interfaces; using FluentEmail.Smtp; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Net; using System.Net.Mail; namespace Microsoft.Extensions.DependencyInjection { public static class FluentEmailSmtpBuilderExtensions { public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, SmtpClient smtpClient) { builder.Services.TryAdd(ServiceDescriptor.Singleton<ISender>(x => new SmtpSender(smtpClient))); return builder; } public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port) => AddSmtpSender(builder, () => new SmtpClient(host, port)); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, string host, int port, string username, string password) => AddSmtpSender(builder, () => new SmtpClient(host, port) { EnableSsl = true, Credentials = new NetworkCredential (username, password) }); public static FluentEmailServicesBuilder AddSmtpSender(this FluentEmailServicesBuilder builder, Func<SmtpClient> clientFactory) { builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new SmtpSender(clientFactory))); return builder; } } }
Fix x-container-experiment-seed failure in .NET Framework branches
using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using MirrorSharp.Advanced; using SharpLab.Server.Common; namespace SharpLab.Server.MirrorSharp { [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public class SetOptionsFromClient : ISetOptionsFromClientExtension { private const string Optimize = "x-optimize"; private const string Target = "x-target"; private readonly IDictionary<string, ILanguageAdapter> _languages; public SetOptionsFromClient(IReadOnlyList<ILanguageAdapter> languages) { _languages = languages.ToDictionary(l => l.LanguageName); } public bool TrySetOption(IWorkSession session, string name, string value) { switch (name) { case Optimize: _languages[session.LanguageName].SetOptimize(session, value); return true; case Target: session.SetTargetName(value); _languages[session.LanguageName].SetOptionsForTarget(session, value); return true; default: return false; } } } }
using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using MirrorSharp.Advanced; using SharpLab.Server.Common; namespace SharpLab.Server.MirrorSharp { [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public class SetOptionsFromClient : ISetOptionsFromClientExtension { private const string Optimize = "x-optimize"; private const string Target = "x-target"; private const string ContainerExperimentSeed = "x-container-experiment-seed"; private readonly IDictionary<string, ILanguageAdapter> _languages; public SetOptionsFromClient(IReadOnlyList<ILanguageAdapter> languages) { _languages = languages.ToDictionary(l => l.LanguageName); } public bool TrySetOption(IWorkSession session, string name, string value) { switch (name) { case Optimize: _languages[session.LanguageName].SetOptimize(session, value); return true; case Target: session.SetTargetName(value); _languages[session.LanguageName].SetOptionsForTarget(session, value); return true; case ContainerExperimentSeed: // not supported in .NET Framework return true; default: return false; } } } }
Remove 'Positions Vacant' sticky note
<div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> comes into effect 3 April, 2017 </p> </div> </div> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> Positions Vacant </h1> <p> ACA would like your help! <a href="/position-vacant">Positions Vacant</a> </p> </div> </div> </div>
<div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> comes into effect 3 April, 2017 </p> </div> </div> </div>
Fix showing digits - show '1' instead of 'D1'
using System; namespace GitIStage { internal sealed class ConsoleCommand { private readonly Action _handler; private readonly ConsoleKey _key; public readonly string Description; private readonly ConsoleModifiers _modifiers; public ConsoleCommand(Action handler, ConsoleKey key, string description) { _handler = handler; _key = key; Description = description; _modifiers = 0; } public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description) { _handler = handler; _key = key; _modifiers = modifiers; Description = description; } public void Execute() { _handler(); } public bool MatchesKey(ConsoleKeyInfo keyInfo) { return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers; } public string GetCommandShortcut() { string key = _key.ToString().Replace("Arrow", ""); if (_modifiers != 0) { return $"{_modifiers.ToString().Replace("Control", "Ctrl")} + {key.ToString()}"; } else return key.ToString(); } } }
using System; namespace GitIStage { internal sealed class ConsoleCommand { private readonly Action _handler; private readonly ConsoleKey _key; public readonly string Description; private readonly ConsoleModifiers _modifiers; public ConsoleCommand(Action handler, ConsoleKey key, string description) { _handler = handler; _key = key; Description = description; _modifiers = 0; } public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description) { _handler = handler; _key = key; _modifiers = modifiers; Description = description; } public void Execute() { _handler(); } public bool MatchesKey(ConsoleKeyInfo keyInfo) { return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers; } public string GetCommandShortcut() { string key = _key.ToString().Replace("Arrow", ""); if (key.StartsWith("D") && key.Length == 2) key = key.Replace("D", ""); if (_modifiers != 0) return $"{_modifiers.ToString().Replace("Control", "Ctrl")} + {key.ToString()}"; else return key.ToString(); } } }
Create Pool Tests work. removed obsolete tests
using Hyperledger.Indy.PoolApi; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Threading.Tasks; namespace Hyperledger.Indy.Test.PoolTests { [TestClass] public class CreatePoolTest : IndyIntegrationTestBase { [TestMethod] public async Task TestCreatePoolWorksForNullConfig() { var file = File.Create("testCreatePoolWorks.txn"); PoolUtils.WriteTransactions(file, 1); await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", null); } [TestMethod] public async Task TestCreatePoolWorksForConfigJSON() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", configJson); } [TestMethod] public async Task TestCreatePoolWorksForTwice() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("pool1", configJson); var ex = await Assert.ThrowsExceptionAsync<PoolLedgerConfigExistsException>(() => Pool.CreatePoolLedgerConfigAsync("pool1", configJson) );; } } }
using Hyperledger.Indy.PoolApi; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Threading.Tasks; namespace Hyperledger.Indy.Test.PoolTests { [TestClass] public class CreatePoolTest : IndyIntegrationTestBase { [TestMethod] public async Task TestCreatePoolWorksForNullConfig() { string poolConfigName = "testCreatePoolWorks"; var file = File.Create(string.Format("{0}.txn", poolConfigName)); PoolUtils.WriteTransactions(file, 1); await Pool.CreatePoolLedgerConfigAsync(poolConfigName, null); } [TestMethod] public async Task TestCreatePoolWorksForConfigJSON() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", configJson); } [TestMethod] public async Task TestCreatePoolWorksForTwice() { var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn"); var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/'); var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path); await Pool.CreatePoolLedgerConfigAsync("pool1", configJson); var ex = await Assert.ThrowsExceptionAsync<PoolLedgerConfigExistsException>(() => Pool.CreatePoolLedgerConfigAsync("pool1", configJson) );; } } }
Handle other kinds of deserialization exceptions
using Auth0.Core.Serialization; using Newtonsoft.Json; using System; using System.Net.Http; using System.Threading.Tasks; namespace Auth0.Core { /// <summary> /// Error information captured from a failed API request. /// </summary> [JsonConverter(typeof(ApiErrorConverter))] public class ApiError { /// <summary> /// Description of the failing HTTP Status Code. /// </summary> [JsonProperty("error")] public string Error { get; set; } /// <summary> /// Error code returned by the API. /// </summary> [JsonProperty("errorCode")] public string ErrorCode { get; set; } /// <summary> /// Description of the error. /// </summary> [JsonProperty("message")] public string Message { get; set; } /// <summary> /// Parse a <see cref="HttpResponseMessage"/> into an <see cref="ApiError"/> asynchronously. /// </summary> /// <param name="response"><see cref="HttpResponseMessage"/> to parse.</param> /// <returns><see cref="Task"/> representing the operation and associated <see cref="ApiError"/> on /// successful completion.</returns> public static async Task<ApiError> Parse(HttpResponseMessage response) { if (response == null || response.Content == null) return null; var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (String.IsNullOrEmpty(content)) return null; try { return JsonConvert.DeserializeObject<ApiError>(content); } catch (JsonSerializationException) { return new ApiError { Error = content, Message = content }; } } } }
using Auth0.Core.Serialization; using Newtonsoft.Json; using System; using System.Net.Http; using System.Threading.Tasks; namespace Auth0.Core { /// <summary> /// Error information captured from a failed API request. /// </summary> [JsonConverter(typeof(ApiErrorConverter))] public class ApiError { /// <summary> /// Description of the failing HTTP Status Code. /// </summary> [JsonProperty("error")] public string Error { get; set; } /// <summary> /// Error code returned by the API. /// </summary> [JsonProperty("errorCode")] public string ErrorCode { get; set; } /// <summary> /// Description of the error. /// </summary> [JsonProperty("message")] public string Message { get; set; } /// <summary> /// Parse a <see cref="HttpResponseMessage"/> into an <see cref="ApiError"/> asynchronously. /// </summary> /// <param name="response"><see cref="HttpResponseMessage"/> to parse.</param> /// <returns><see cref="Task"/> representing the operation and associated <see cref="ApiError"/> on /// successful completion.</returns> public static async Task<ApiError> Parse(HttpResponseMessage response) { if (response == null || response.Content == null) return null; var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (String.IsNullOrEmpty(content)) return null; try { return JsonConvert.DeserializeObject<ApiError>(content); } catch (JsonException) { return new ApiError { Error = content, Message = content }; } } } }
Fix MySql do not support Milliseconds
using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.MySql { public class MySqlQuoter : GenericQuoter { public override string OpenQuote { get { return "`"; } } public override string CloseQuote { get { return "`"; } } public override string QuoteValue(object value) { return base.QuoteValue(value).Replace(@"\", @"\\"); } public override string FromTimeSpan(System.TimeSpan value) { return System.String.Format("{0}{1}:{2}:{3}.{4}{0}" , ValueQuote , value.Hours + (value.Days * 24) , value.Minutes , value.Seconds , value.Milliseconds); } } }
using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.MySql { public class MySqlQuoter : GenericQuoter { public override string OpenQuote { get { return "`"; } } public override string CloseQuote { get { return "`"; } } public override string QuoteValue(object value) { return base.QuoteValue(value).Replace(@"\", @"\\"); } public override string FromTimeSpan(System.TimeSpan value) { return System.String.Format("{0}{1:00}:{2:00}:{3:00}{0}" , ValueQuote , value.Hours + (value.Days * 24) , value.Minutes , value.Seconds); } } }
Fix for treating enum types as primitives due non-enumeration facets
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Schema; namespace Codge.Generator.Presentations.Xsd { public static class XmlSchemaExtensions { public static bool IsEmptyType(this XmlSchemaComplexType type) { return type.ContentModel == null && type.Attributes.Count == 0 && type.ContentType.ToString() == "Empty"; } public static IEnumerable<XmlSchemaEnumerationFacet> GetEnumerationFacets(this XmlSchemaSimpleType simpleType) { if (simpleType.Content != null) { var restriction = simpleType.Content as XmlSchemaSimpleTypeRestriction; if (restriction != null && restriction.Facets != null && restriction.Facets.Count > 0) { foreach (var facet in restriction.Facets) { var item = facet as XmlSchemaEnumerationFacet; if (item == null) yield break; yield return item; } } } yield break; } public static bool IsEnumeration(this XmlSchemaSimpleType simpleType) { return GetEnumerationFacets(simpleType).Any(); } } }
using System.Collections.Generic; using System.Linq; using System.Xml.Schema; namespace Codge.Generator.Presentations.Xsd { public static class XmlSchemaExtensions { public static bool IsEmptyType(this XmlSchemaComplexType type) { return type.ContentModel == null && type.Attributes.Count == 0 && type.ContentType.ToString() == "Empty"; } public static IEnumerable<XmlSchemaEnumerationFacet> GetEnumerationFacets(this XmlSchemaSimpleType simpleType) { if (simpleType.Content != null) { var restriction = simpleType.Content as XmlSchemaSimpleTypeRestriction; if (restriction != null && restriction.Facets != null && restriction.Facets.Count > 0) { foreach (var facet in restriction.Facets) { var item = facet as XmlSchemaEnumerationFacet; if (item != null) yield return item; } } } yield break; } public static bool IsEnumeration(this XmlSchemaSimpleType simpleType) { return GetEnumerationFacets(simpleType).Any(); } } }
Add testing of different strengths
// 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 NUnit.Framework; using osu.Game.Rulesets.Osu.Mods; namespace osu.Game.Rulesets.Osu.Tests.Mods { public class TestSceneOsuModAimAssist : OsuModTestScene { [Test] public void TestAimAssist() { var mod = new OsuModAimAssist(); CreateModTest(new ModTestData { Autoplay = false, Mod = mod, }); } } }
// 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 NUnit.Framework; using osu.Game.Rulesets.Osu.Mods; namespace osu.Game.Rulesets.Osu.Tests.Mods { public class TestSceneOsuModAimAssist : OsuModTestScene { [TestCase(0.1f)] [TestCase(0.5f)] [TestCase(1)] public void TestAimAssist(float strength) { CreateModTest(new ModTestData { Mod = new OsuModAimAssist { AssistStrength = { Value = strength }, }, PassCondition = () => true, Autoplay = false, }); } } }
Check for null in IsNetworkAvailable implementation
using davClassLibrary.Common; using davClassLibrary.DataAccess; using UniversalSoundBoard.DataAccess; using Windows.Networking.Connectivity; namespace UniversalSoundboard.Common { public class GeneralMethods : IGeneralMethods { public bool IsNetworkAvailable() { var connection = NetworkInformation.GetInternetConnectionProfile(); var networkCostType = connection.GetConnectionCost().NetworkCostType; return !(networkCostType != NetworkCostType.Unrestricted && networkCostType != NetworkCostType.Unknown); } public DavEnvironment GetEnvironment() { return FileManager.Environment; } } }
using davClassLibrary.Common; using davClassLibrary.DataAccess; using UniversalSoundBoard.DataAccess; using Windows.Networking.Connectivity; namespace UniversalSoundboard.Common { public class GeneralMethods : IGeneralMethods { public bool IsNetworkAvailable() { var connection = NetworkInformation.GetInternetConnectionProfile(); if (connection == null) return false; var networkCostType = connection.GetConnectionCost().NetworkCostType; return !(networkCostType != NetworkCostType.Unrestricted && networkCostType != NetworkCostType.Unknown); } public DavEnvironment GetEnvironment() { return FileManager.Environment; } } }
Fix namespace in httpclient registration
using JoinRpg.Web.CheckIn; using JoinRpg.Web.ProjectCommon; using JoinRpg.Web.ProjectMasterTools.ResponsibleMaster; using JoinRpg.Web.ProjectMasterTools.Subscribe; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; namespace JoinRpg.Blazor.Client.ApiClients; public static class HttpClientRegistration { private static WebAssemblyHostBuilder AddHttpClient<TClient, TImplementation>( this WebAssemblyHostBuilder builder) where TClient : class where TImplementation : class, TClient { _ = builder.Services.AddHttpClient<TClient, TImplementation>( client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)); return builder; } public static WebAssemblyHostBuilder AddHttpClients(this WebAssemblyHostBuilder builder) { return builder .AddHttpClient<IGameSubscribeClient, GameSubscribeClient>() .AddHttpClient<ICharacterGroupsClient, CharacterGroupsClient>() .AddHttpClient<ICheckInClient, CheckInClient>() .AddHttpClient<IResponsibleMasterRuleClient, ApiClients.ResponsibleMasterRuleClient>(); } }
using JoinRpg.Web.CheckIn; using JoinRpg.Web.ProjectCommon; using JoinRpg.Web.ProjectMasterTools.ResponsibleMaster; using JoinRpg.Web.ProjectMasterTools.Subscribe; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; namespace JoinRpg.Blazor.Client.ApiClients; public static class HttpClientRegistration { private static WebAssemblyHostBuilder AddHttpClient<TClient, TImplementation>( this WebAssemblyHostBuilder builder) where TClient : class where TImplementation : class, TClient { _ = builder.Services.AddHttpClient<TClient, TImplementation>( client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)); return builder; } public static WebAssemblyHostBuilder AddHttpClients(this WebAssemblyHostBuilder builder) { return builder .AddHttpClient<IGameSubscribeClient, GameSubscribeClient>() .AddHttpClient<ICharacterGroupsClient, CharacterGroupsClient>() .AddHttpClient<ICheckInClient, CheckInClient>() .AddHttpClient<IResponsibleMasterRuleClient, ResponsibleMasterRuleClient>(); } }
Add PlaySound as a debugging 'tool'
using System; using System.Threading; namespace Bumblebee.Extensions { public static class Debugging { public static T DebugPrint<T>(this T obj) { Console.WriteLine(obj.ToString()); return obj; } public static T DebugPrint<T>(this T obj, string message) { Console.WriteLine(message); return obj; } public static T DebugPrint<T>(this T obj, Func<T, object> func) { Console.WriteLine(func.Invoke(obj)); return obj; } public static T Pause<T>(this T block, int seconds) { if (seconds > 0) Thread.Sleep(1000 * seconds); return block; } } }
using System; using System.Threading; namespace Bumblebee.Extensions { public static class Debugging { public static T DebugPrint<T>(this T obj) { Console.WriteLine(obj.ToString()); return obj; } public static T DebugPrint<T>(this T obj, string message) { Console.WriteLine(message); return obj; } public static T DebugPrint<T>(this T obj, Func<T, object> func) { Console.WriteLine(func.Invoke(obj)); return obj; } public static T PlaySound<T>(this T obj, int pause = 0) { System.Media.SystemSounds.Exclamation.Play(); return obj.Pause(pause); } public static T Pause<T>(this T block, int seconds) { if (seconds > 0) Thread.Sleep(1000 * seconds); return block; } } }
Add check for Mono for LogicalCallContext
using System.Runtime.Remoting.Messaging; namespace Criteo.Profiling.Tracing { internal static class TraceContext { private const string TraceCallContextKey = "crto_trace"; public static Trace Get() { return CallContext.LogicalGetData(TraceCallContextKey) as Trace; } public static void Set(Trace trace) { CallContext.LogicalSetData(TraceCallContextKey, trace); } public static void Clear() { CallContext.FreeNamedDataSlot(TraceCallContextKey); } } }
using System; using System.Runtime.Remoting.Messaging; namespace Criteo.Profiling.Tracing { internal static class TraceContext { private const string TraceCallContextKey = "crto_trace"; private static readonly bool IsRunningOnMono = (Type.GetType("Mono.Runtime") != null); public static Trace Get() { if (IsRunningOnMono) return null; return CallContext.LogicalGetData(TraceCallContextKey) as Trace; } public static void Set(Trace trace) { if (IsRunningOnMono) return; CallContext.LogicalSetData(TraceCallContextKey, trace); } public static void Clear() { if (IsRunningOnMono) return; CallContext.FreeNamedDataSlot(TraceCallContextKey); } } }
Add test when IResponse not set
using System.Collections.Generic; using System.Collections.Immutable; using Octokit; using NSubstitute; using NUnit.Framework; using GitHub.Extensions; public class ApiExceptionExtensionsTests { public class TheIsGitHubApiExceptionMethod { [TestCase("Not-GitHub-Request-Id", false)] [TestCase("X-GitHub-Request-Id", true)] [TestCase("x-github-request-id", true)] public void NoGitHubRequestId(string key, bool expect) { var ex = CreateApiException(new Dictionary<string, string> { { key, "ANYTHING" } }); var result = ApiExceptionExtensions.IsGitHubApiException(ex); Assert.That(result, Is.EqualTo(expect)); } static ApiException CreateApiException(Dictionary<string, string> headers) { var response = Substitute.For<IResponse>(); response.Headers.Returns(headers.ToImmutableDictionary()); var ex = new ApiException(response); return ex; } } }
using System.Collections.Generic; using System.Collections.Immutable; using Octokit; using NSubstitute; using NUnit.Framework; using GitHub.Extensions; public class ApiExceptionExtensionsTests { public class TheIsGitHubApiExceptionMethod { [TestCase("Not-GitHub-Request-Id", false)] [TestCase("X-GitHub-Request-Id", true)] [TestCase("x-github-request-id", true)] public void NoGitHubRequestId(string key, bool expect) { var ex = CreateApiException(new Dictionary<string, string> { { key, "ANYTHING" } }); var result = ApiExceptionExtensions.IsGitHubApiException(ex); Assert.That(result, Is.EqualTo(expect)); } [Test] public void NoResponse() { var ex = new ApiException(); var result = ApiExceptionExtensions.IsGitHubApiException(ex); Assert.That(result, Is.EqualTo(false)); } static ApiException CreateApiException(Dictionary<string, string> headers) { var response = Substitute.For<IResponse>(); response.Headers.Returns(headers.ToImmutableDictionary()); var ex = new ApiException(response); return ex; } } }
Allow rotation lock on Android to function properly
// 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 Android.App; using Android.Content.PM; using Android.OS; using Android.Views; using osu.Framework.Android; namespace osu.Android { [Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullSensor, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = false)] public class OsuGameActivity : AndroidGameActivity { protected override Framework.Game CreateGame() => new OsuGameAndroid(); protected override void OnCreate(Bundle savedInstanceState) { // The default current directory on android is '/'. // On some devices '/' maps to the app data directory. On others it maps to the root of the internal storage. // In order to have a consistent current directory on all devices the full path of the app data directory is set as the current directory. System.Environment.CurrentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); } } }
// 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 Android.App; using Android.Content.PM; using Android.OS; using Android.Views; using osu.Framework.Android; namespace osu.Android { [Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullUser, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = false)] public class OsuGameActivity : AndroidGameActivity { protected override Framework.Game CreateGame() => new OsuGameAndroid(); protected override void OnCreate(Bundle savedInstanceState) { // The default current directory on android is '/'. // On some devices '/' maps to the app data directory. On others it maps to the root of the internal storage. // In order to have a consistent current directory on all devices the full path of the app data directory is set as the current directory. System.Environment.CurrentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); } } }
Add detail panel, currently empty
using Gtk; using Mono.Addins; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Gui.Components; namespace MonoDevelop.AddinMaker.AddinBrowser { class AddinBrowserWidget : VBox { ExtensibleTreeView treeView; public AddinBrowserWidget (AddinRegistry registry) { Registry = registry; Build (); foreach (var addin in registry.GetAddins ()) { treeView.AddChild (addin); } } void Build () { //TODO: make extensible? treeView = new ExtensibleTreeView ( new NodeBuilder[] { new AddinNodeBuilder (), new ExtensionFolderNodeBuilder (), new ExtensionNodeBuilder (), new ExtensionPointNodeBuilder (), new ExtensionPointFolderNodeBuilder (), new DependencyFolderNodeBuilder (), new DependencyNodeBuilder (), }, new TreePadOption[0] ); treeView.Tree.Selection.Mode = SelectionMode.Single; PackStart (treeView, true, true, 0); ShowAll (); } public void SetToolbar (DocumentToolbar toolbar) { } public AddinRegistry Registry { get; private set; } } }
using Gtk; using Mono.Addins; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Gui.Components; namespace MonoDevelop.AddinMaker.AddinBrowser { class AddinBrowserWidget : HPaned { ExtensibleTreeView treeView; public AddinBrowserWidget (AddinRegistry registry) { Registry = registry; Build (); foreach (var addin in registry.GetAddins ()) { treeView.AddChild (addin); } } void Build () { //TODO: make extensible? treeView = new ExtensibleTreeView ( new NodeBuilder[] { new AddinNodeBuilder (), new ExtensionFolderNodeBuilder (), new ExtensionNodeBuilder (), new ExtensionPointNodeBuilder (), new ExtensionPointFolderNodeBuilder (), new DependencyFolderNodeBuilder (), new DependencyNodeBuilder (), }, new TreePadOption[0] ); treeView.Tree.Selection.Mode = SelectionMode.Single; treeView.WidthRequest = 300; Pack1 (treeView, false, false); SetDetail (null); ShowAll (); } void SetDetail (Widget detail) { var child2 = Child2; if (child2 != null) { Remove (child2); } detail = detail ?? new Label (); detail.WidthRequest = 300; detail.Show (); Pack2 (detail, true, false); } public void SetToolbar (DocumentToolbar toolbar) { } public AddinRegistry Registry { get; private set; } } }
Fix download didn't start by close response in getFileDetail, implement FillCredential method
using System; using System.Net; using System.Threading; using System.Threading.Tasks; using TirkxDownloader.Framework; namespace TirkxDownloader.Models { public class DetailProvider { public async Task GetFileDetail(DownloadInfo detail, CancellationToken ct) { try { var request = (HttpWebRequest)HttpWebRequest.Create(detail.DownloadLink); request.Method = "HEAD"; var response = await request.GetResponseAsync(ct); detail.FileSize = response.ContentLength; } catch (OperationCanceledException) { } } public bool FillCredential(string doamin) { throw new NotImplementedException(); } } }
using System; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using TirkxDownloader.Framework; using TirkxDownloader.Models; namespace TirkxDownloader.Models { public class DetailProvider { private AuthorizationManager _authenticationManager; public DetailProvider(AuthorizationManager authenticationManager) { _authenticationManager = authenticationManager; } public async Task GetFileDetail(DownloadInfo detail, CancellationToken ct) { try { var request = (HttpWebRequest)HttpWebRequest.Create(detail.DownloadLink); request.Method = "HEAD"; var response = await request.GetResponseAsync(ct); detail.FileSize = response.ContentLength; response.Close(); } catch (OperationCanceledException) { } } public async Task FillCredential(HttpWebRequest request) { string targetDomain = ""; string domain = request.Host; AuthorizationInfo authorizationInfo = _authenticationManager.GetCredential(domain); using (StreamReader str = new StreamReader("Target domain.dat", Encoding.UTF8)) { string storedDomian; while ((storedDomian = await str.ReadLineAsync()) != null) { if (storedDomian.Like(domain)) { targetDomain = storedDomian; // if it isn't wildcards, it done if (!storedDomian.Contains("*")) { break; } } } } AuthorizationInfo credential = _authenticationManager.GetCredential(targetDomain); if (credential != null) { var netCredential = new NetworkCredential(credential.Username, credential.Password, domain); request.Credentials = netCredential; } else { // if no credential was found, try to use default credential request.UseDefaultCredentials = true; } } } }
Remove the ignore attribute once again
// 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.Linq; using NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Screens.Play.HUD; using osu.Game.Skinning; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene { protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); [Test] [Ignore("HUD components broken, remove when fixed.")] public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin) { if (withModifiedSkin) { AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f)); AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget)); AddStep("exit player", () => Player.Exit()); CreateTest(null); } AddAssert("legacy HUD combo counter hidden", () => { return Player.ChildrenOfType<LegacyComboCounter>().All(c => !c.ChildrenOfType<Container>().Single().IsPresent); }); } } }
// 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.Linq; using NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Screens.Play.HUD; using osu.Game.Skinning; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene { protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); [Test] public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin) { if (withModifiedSkin) { AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f)); AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget)); AddStep("exit player", () => Player.Exit()); CreateTest(null); } AddAssert("legacy HUD combo counter hidden", () => { return Player.ChildrenOfType<LegacyComboCounter>().All(c => !c.ChildrenOfType<Container>().Single().IsPresent); }); } } }
Fix 404 error when calling GetMammals, incorrect route
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script> <script> var data = (function ($) { var getData = (function() { $.ajax({ method: "GET", url: "GetMammals", dataType: "json", success: function (response) { print(response); }, failure: function (response) { alert(response.d); } }); }); function print(data) { document.write( data.Dog.Name + ": " + data.Dog.Type + " / " + data.Cat.Name + ": " + data.Cat.Type ); } return { getData: getData } })(jQuery); </script> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <script> data.getData(); </script> </div> </body> </html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script> <script> var data = (function ($) { var getData = (function() { $.ajax({ method: "GET", url: "@Url.Action("GetMammals", "Home")", dataType: "json", success: function (response) { print(response); }, failure: function (response) { alert(response.d); } }); }); function print(data) { document.write( data.Dog.Name + ": " + data.Dog.Type + " / " + data.Cat.Name + ": " + data.Cat.Type ); } return { getData: getData } })(jQuery); </script> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <script> data.getData(); </script> </div> </body> </html>
Add response DTO marker interface for service documentation
using ServiceStack.ServiceHost; namespace License.Manager.Core.Model { [Route("/customers", "POST")] [Route("/customers/{Id}", "PUT, DELETE")] [Route("/customers/{Id}", "GET, OPTIONS")] public class Customer : EntityBase { public string Name { get; set; } public string Company { get; set; } public string Email { get; set; } } }
using ServiceStack.ServiceHost; namespace License.Manager.Core.Model { [Route("/customers", "POST")] [Route("/customers/{Id}", "PUT, DELETE")] [Route("/customers/{Id}", "GET, OPTIONS")] public class Customer : EntityBase, IReturn<Customer> { public string Name { get; set; } public string Company { get; set; } public string Email { get; set; } } }
Fix compiling error on .net451
/***************************************************************************** * * ReoGrid - .NET Spreadsheet Control * * https://reogrid.net/ * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR * PURPOSE. * * Author: Jing Lu <jingwood at unvell.com> * * Copyright (c) 2012-2021 Jing Lu <jingwood at unvell.com> * Copyright (c) 2012-2016 unvell.com, all rights reserved. * ****************************************************************************/ #if PRINT #if WPF using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Xps; using System.Windows.Xps.Packaging; using unvell.ReoGrid.Print; namespace unvell.ReoGrid.Print { partial class PrintSession { internal void Init() { } public void Dispose() { } /// <summary> /// Start output document to printer. /// </summary> public void Print() { throw new NotImplementedException("WPF Print is not implemented yet. Try use Windows Form version to print document as XPS file."); } } } namespace unvell.ReoGrid { partial class Worksheet { } } #endif // WPF #endif // PRINT
/***************************************************************************** * * ReoGrid - .NET Spreadsheet Control * * https://reogrid.net/ * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR * PURPOSE. * * Author: Jing Lu <jingwood at unvell.com> * * Copyright (c) 2012-2021 Jing Lu <jingwood at unvell.com> * Copyright (c) 2012-2016 unvell.com, all rights reserved. * ****************************************************************************/ #if PRINT #if WPF using System; using System.Collections.Generic; using System.Linq; using System.Text; using unvell.ReoGrid.Print; namespace unvell.ReoGrid.Print { partial class PrintSession { internal void Init() { } public void Dispose() { } /// <summary> /// Start output document to printer. /// </summary> public void Print() { throw new NotImplementedException("WPF Print is not implemented yet. Try use Windows Form version to print document as XPS file."); } } } namespace unvell.ReoGrid { partial class Worksheet { } } #endif // WPF #endif // PRINT
Add documentation for show airs.
namespace TraktApiSharp.Objects.Get.Shows { using Newtonsoft.Json; /// <summary> /// The air time of a Trakt show. /// </summary> public class TraktShowAirs { /// <summary> /// The day of week on which the show airs. /// </summary> [JsonProperty(PropertyName = "day")] public string Day { get; set; } /// <summary> /// The time of day at which the show airs. /// </summary> [JsonProperty(PropertyName = "time")] public string Time { get; set; } /// <summary> /// The time zone id (Olson) for the location in which the show airs. /// </summary> [JsonProperty(PropertyName = "timezone")] public string TimeZoneId { get; set; } } }
namespace TraktApiSharp.Objects.Get.Shows { using Newtonsoft.Json; /// <summary>The air time of a Trakt show.</summary> public class TraktShowAirs { /// <summary>Gets or sets the day of week on which the show airs.</summary> [JsonProperty(PropertyName = "day")] public string Day { get; set; } /// <summary>Gets or sets the time of day at which the show airs.</summary> [JsonProperty(PropertyName = "time")] public string Time { get; set; } /// <summary>Gets or sets the time zone id (Olson) for the location in which the show airs.</summary> [JsonProperty(PropertyName = "timezone")] public string TimeZoneId { get; set; } } }
Remove delay test for CI for now
using LanguageExt; using static LanguageExt.Prelude; using System; using System.Reactive.Linq; using System.Threading; using Xunit; namespace LanguageExtTests { public class DelayTests { [Fact] public void DelayTest1() { var span = TimeSpan.FromMilliseconds(500); var till = DateTime.Now.Add(span); var v = 0; delay(() => 1, span).Subscribe(x => v = x); while( DateTime.Now < till.AddMilliseconds(20) ) { Assert.True(v == 0); Thread.Sleep(1); } while (DateTime.Now < till.AddMilliseconds(100)) { Thread.Sleep(1); } Assert.True(v == 1); } } }
using LanguageExt; using static LanguageExt.Prelude; using System; using System.Reactive.Linq; using System.Threading; using Xunit; namespace LanguageExtTests { public class DelayTests { #if !CI [Fact] public void DelayTest1() { var span = TimeSpan.FromMilliseconds(500); var till = DateTime.Now.Add(span); var v = 0; delay(() => 1, span).Subscribe(x => v = x); while( DateTime.Now < till ) { Assert.True(v == 0); Thread.Sleep(1); } while (DateTime.Now < till.AddMilliseconds(100)) { Thread.Sleep(1); } Assert.True(v == 1); } #endif } }
Fix failing style check... second attempt
using System; using Newtonsoft.Json.Linq; namespace Saule.Serialization { internal class ResourceDeserializer { private readonly JToken _object; private readonly Type _target; public ResourceDeserializer(JToken @object, Type target) { _object = @object; _target = target; } public object Deserialize() { return ToFlatStructure(_object).ToObject(_target); } private JToken ToFlatStructure(JToken json) { var array = json["data"] as JArray; if (array == null) { var obj = json["data"] as JObject; if (obj == null) { return null; } return SingleToFlatStructure(json["data"] as JObject); } var result = new JArray(); foreach (var child in array) { result.Add(SingleToFlatStructure(child as JObject)); } return result; } private JToken SingleToFlatStructure(JObject child) { var result = new JObject(); if (child["id"] != null) { result["id"] = child["id"]; } foreach (var attr in child["attributes"] ?? new JArray()) { var prop = attr as JProperty; result.Add(prop?.Name.ToPascalCase(), prop?.Value); } foreach (var rel in child["relationships"] ?? new JArray()) { var prop = rel as JProperty; result.Add(prop?.Name.ToPascalCase(), ToFlatStructure(prop?.Value)); } return result; } } }
using System; using Newtonsoft.Json.Linq; namespace Saule.Serialization { internal class ResourceDeserializer { private readonly JToken _object; private readonly Type _target; public ResourceDeserializer(JToken @object, Type target) { _object = @object; _target = target; } public object Deserialize() { return ToFlatStructure(_object).ToObject(_target); } private JToken ToFlatStructure(JToken json) { var array = json["data"] as JArray; if (array == null) { var obj = json["data"] as JObject; if (obj == null) { return null; } return SingleToFlatStructure(json["data"] as JObject); } var result = new JArray(); foreach (var child in array) { result.Add(SingleToFlatStructure(child as JObject)); } return result; } private JToken SingleToFlatStructure(JObject child) { var result = new JObject(); if (child["id"] != null) { result["id"] = child["id"]; } foreach (var attr in child["attributes"] ?? new JArray()) { var prop = attr as JProperty; result.Add(prop?.Name.ToPascalCase(), prop?.Value); } foreach (var rel in child["relationships"] ?? new JArray()) { var prop = rel as JProperty; result.Add(prop?.Name.ToPascalCase(), ToFlatStructure(prop?.Value)); } return result; } } }
Clear record before start new recording
using UnityEngine; namespace UnityTouchRecorder { public class TouchRecorderController : MonoBehaviour { UnityTouchRecorderPlugin plugin = new UnityTouchRecorderPlugin(); [SerializeField] TouchRecorderView view; void Awake() { Object.DontDestroyOnLoad(gameObject); view.OpenMenuButton.onClick.AddListener(() => { view.SetMenuActive(!view.IsMenuActive); }); view.StartRecordingButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.StartRecording(); }); view.PlayButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.Play(view.Repeat, view.Interval); }); view.StopButton.onClick.AddListener(() => { view.OpenMenuButton.gameObject.SetActive(true); view.StopButton.gameObject.SetActive(false); plugin.StopRecording(); plugin.Stop(); }); } } }
using UnityEngine; namespace UnityTouchRecorder { public class TouchRecorderController : MonoBehaviour { UnityTouchRecorderPlugin plugin = new UnityTouchRecorderPlugin(); [SerializeField] TouchRecorderView view; void Awake() { Object.DontDestroyOnLoad(gameObject); view.OpenMenuButton.onClick.AddListener(() => { view.SetMenuActive(!view.IsMenuActive); }); view.StartRecordingButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.Clear(); plugin.StartRecording(); }); view.PlayButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.Play(view.Repeat, view.Interval); }); view.StopButton.onClick.AddListener(() => { view.OpenMenuButton.gameObject.SetActive(true); view.StopButton.gameObject.SetActive(false); plugin.StopRecording(); plugin.Stop(); }); } } }
Use placeholder expressions, {nr} doesn't work because of ConfigNode beign weird
/** * Language Patches Framework * Translates the game into different Languages * Copyright (c) 2016 Thomas P. * Licensed under the terms of the MIT License */ using System; namespace LanguagePatches { /// <summary> /// A class that represents a text translation /// </summary> public class Translation { /// <summary> /// The original message, uses Regex syntax /// </summary> public String text { get; set; } /// <summary> /// The replacement message, uses String.Format syntax /// </summary> public String translation { get; set; } /// <summary> /// Creates a new Translation component from a config node /// </summary> /// <param name="node">The config node where the </param> public Translation(ConfigNode node) { // Check for original text if (!node.HasValue("text")) throw new Exception("The config node is missing the text value!"); // Check for translation if (!node.HasValue("translation")) throw new Exception("The config node is missing the translation value!"); // Assign the new texts text = node.GetValue("text"); translation = node.GetValue("translation"); } } }
/** * Language Patches Framework * Translates the game into different Languages * Copyright (c) 2016 Thomas P. * Licensed under the terms of the MIT License */ using System; using System.Text.RegularExpressions; namespace LanguagePatches { /// <summary> /// A class that represents a text translation /// </summary> public class Translation { /// <summary> /// The original message, uses Regex syntax /// </summary> public String text { get; set; } /// <summary> /// The replacement message, uses String.Format syntax /// </summary> public String translation { get; set; } /// <summary> /// Creates a new Translation component from a config node /// </summary> /// <param name="node">The config node where the </param> public Translation(ConfigNode node) { // Check for original text if (!node.HasValue("text")) throw new Exception("The config node is missing the text value!"); // Check for translation if (!node.HasValue("translation")) throw new Exception("The config node is missing the translation value!"); // Assign the new texts text = node.GetValue("text"); translation = node.GetValue("translation"); // Replace variable placeholders translation = Regex.Replace(translation, @"@(\d*)", "{$1}"); } } }
Update server side API for single multiple answer question
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var questions = _dbContext.SingleMultipleAnswerQuestion.ToList(); return questions; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } }
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var questions = _dbContext.SingleMultipleAnswerQuestion.ToList(); return questions; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } }
Remove erroneous "$" symbol from "bling string."
namespace Bakery.Configuration.Properties { using System; public class PropertyNotFoundException : Exception { private readonly String propertyName; public PropertyNotFoundException(String propertyName) { this.propertyName = propertyName; } public override String Message { get { return $"Property \"${propertyName}\" not found."; } } } }
namespace Bakery.Configuration.Properties { using System; public class PropertyNotFoundException : Exception { private readonly String propertyName; public PropertyNotFoundException(String propertyName) { this.propertyName = propertyName; } public override String Message { get { return $"Property \"{propertyName}\" not found."; } } } }
Change default Search URL Prefix
using System.ComponentModel; using System.Windows; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.Search { public class Settings : WidgetSettingsBase { public Settings() { Style.Width = 150; Style.FramePadding = new Thickness(0); } [Category("General")] [DisplayName("URL Prefix")] public string BaseUrl { get; set; } = "http://"; [Category("General")] [DisplayName("URL Suffix")] public string URLSuffix { get; set; } } }
using System.ComponentModel; using System.Windows; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.Search { public class Settings : WidgetSettingsBase { public Settings() { Style.Width = 150; Style.FramePadding = new Thickness(0); } [Category("General")] [DisplayName("URL Prefix")] public string BaseUrl { get; set; } = "https://www.google.com/search?q="; [Category("General")] [DisplayName("URL Suffix")] public string URLSuffix { get; set; } } }
Fix encoding issue while the query string parameters contains Chinese characters
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; namespace Exceptionless.Core.Extensions { public static class UriExtensions { public static string ToQueryString(this NameValueCollection collection) { return collection.AsKeyValuePairs().ToQueryString(); } public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> collection) { return collection.ToConcatenatedString(pair => pair.Key == null ? pair.Value : $"{pair.Key}={pair.Value}", "&"); } /// <summary> /// Converts the legacy NameValueCollection into a strongly-typed KeyValuePair sequence. /// </summary> private static IEnumerable<KeyValuePair<string, string>> AsKeyValuePairs(this NameValueCollection collection) { return collection.AllKeys.Select(key => new KeyValuePair<string, string>(key, collection.Get(key))); } public static string GetBaseUrl(this Uri uri) { return uri.Scheme + "://" + uri.Authority + uri.AbsolutePath; } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; namespace Exceptionless.Core.Extensions { public static class UriExtensions { public static string ToQueryString(this NameValueCollection collection) { return collection.AsKeyValuePairs().ToQueryString(); } public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> collection) { return collection.ToConcatenatedString(pair => pair.Key == null ? pair.Value : $"{pair.Key}={System.Web.HttpUtility.UrlEncode(pair.Value)}", "&"); } /// <summary> /// Converts the legacy NameValueCollection into a strongly-typed KeyValuePair sequence. /// </summary> private static IEnumerable<KeyValuePair<string, string>> AsKeyValuePairs(this NameValueCollection collection) { return collection.AllKeys.Select(key => new KeyValuePair<string, string>(key, collection.Get(key))); } public static string GetBaseUrl(this Uri uri) { return uri.Scheme + "://" + uri.Authority + uri.AbsolutePath; } } }
Make TestUserProfile service more derivation friendly
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4.Test { public class TestUserProfileService : IProfileService { private readonly ILogger<TestUserProfileService> _logger; private readonly TestUserStore _users; public TestUserProfileService(TestUserStore users, ILogger<TestUserProfileService> logger) { _users = users; _logger = logger; } public Task GetProfileDataAsync(ProfileDataRequestContext context) { _logger.LogDebug("Get profile called for subject {subject} from client {client} with claim types{claimTypes} via {caller}", context.Subject.GetSubjectId(), context.Client.ClientName ?? context.Client.ClientId, context.RequestedClaimTypes, context.Caller); if (context.RequestedClaimTypes.Any()) { var user = _users.FindBySubjectId(context.Subject.GetSubjectId()); context.AddFilteredClaims(user.Claims); } return Task.FromResult(0); } public Task IsActiveAsync(IsActiveContext context) { context.IsActive = true; return Task.FromResult(0); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4.Test { public class TestUserProfileService : IProfileService { protected readonly ILogger Logger; protected readonly TestUserStore Users; public TestUserProfileService(TestUserStore users, ILogger<TestUserProfileService> logger) { Users = users; Logger = logger; } public virtual Task GetProfileDataAsync(ProfileDataRequestContext context) { Logger.LogDebug("Get profile called for subject {subject} from client {client} with claim types {claimTypes} via {caller}", context.Subject.GetSubjectId(), context.Client.ClientName ?? context.Client.ClientId, context.RequestedClaimTypes, context.Caller); if (context.RequestedClaimTypes.Any()) { var user = Users.FindBySubjectId(context.Subject.GetSubjectId()); context.AddFilteredClaims(user.Claims); } return Task.FromResult(0); } public virtual Task IsActiveAsync(IsActiveContext context) { context.IsActive = true; return Task.FromResult(0); } } }
Add description for mania special style
// 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.Game.Graphics.UserInterfaceV2; using osu.Game.Screens.Edit.Setup; namespace osu.Game.Rulesets.Mania.Edit.Setup { public class ManiaSetupSection : RulesetSetupSection { private LabelledSwitchButton specialStyle; public ManiaSetupSection() : base(new ManiaRuleset().RulesetInfo) { } [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { specialStyle = new LabelledSwitchButton { Label = "Use special (N+1) style", Current = { Value = Beatmap.BeatmapInfo.SpecialStyle } } }; } protected override void LoadComplete() { base.LoadComplete(); specialStyle.Current.BindValueChanged(_ => updateBeatmap()); } private void updateBeatmap() { Beatmap.BeatmapInfo.SpecialStyle = specialStyle.Current.Value; } } }
// 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.Game.Graphics.UserInterfaceV2; using osu.Game.Screens.Edit.Setup; namespace osu.Game.Rulesets.Mania.Edit.Setup { public class ManiaSetupSection : RulesetSetupSection { private LabelledSwitchButton specialStyle; public ManiaSetupSection() : base(new ManiaRuleset().RulesetInfo) { } [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { specialStyle = new LabelledSwitchButton { Label = "Use special (N+1) style", Description = "Changes one column to act as a classic \"scratch\" or \"special\" column, which can be moved around by the user's skin (to the left/right/centre). Generally used in 5k (4+1) or 8key (7+1) configurations.", Current = { Value = Beatmap.BeatmapInfo.SpecialStyle } } }; } protected override void LoadComplete() { base.LoadComplete(); specialStyle.Current.BindValueChanged(_ => updateBeatmap()); } private void updateBeatmap() { Beatmap.BeatmapInfo.SpecialStyle = specialStyle.Current.Value; } } }
Refactor away property setter usages to allow Color to be immutable.
namespace dotless.Core.Plugins { using System; using Parser.Infrastructure.Nodes; using Parser.Tree; using Utils; using System.ComponentModel; [Description("Automatically spins all colors in a less file"), DisplayName("ColorSpin")] public class ColorSpinPlugin : VisitorPlugin { public double Spin { get; set; } public ColorSpinPlugin(double spin) { Spin = spin; } public override VisitorPluginType AppliesTo { get { return VisitorPluginType.AfterEvaluation; } } public override Node Execute(Node node, out bool visitDeeper) { visitDeeper = true; if(node is Color) { var color = node as Color; var hslColor = HslColor.FromRgbColor(color); hslColor.Hue += Spin/360.0d; var newColor = hslColor.ToRgbColor(); //node = new Color(newColor.R, newColor.G, newColor.B); color.R = newColor.R; color.G = newColor.G; color.B = newColor.B; } return node; } } }
namespace dotless.Core.Plugins { using Parser.Infrastructure.Nodes; using Parser.Tree; using Utils; using System.ComponentModel; [Description("Automatically spins all colors in a less file"), DisplayName("ColorSpin")] public class ColorSpinPlugin : VisitorPlugin { public double Spin { get; set; } public ColorSpinPlugin(double spin) { Spin = spin; } public override VisitorPluginType AppliesTo { get { return VisitorPluginType.AfterEvaluation; } } public override Node Execute(Node node, out bool visitDeeper) { visitDeeper = true; var color = node as Color; if (color == null) return node; var hslColor = HslColor.FromRgbColor(color); hslColor.Hue += Spin/360.0d; var newColor = hslColor.ToRgbColor(); return newColor.ReducedFrom<Color>(color); } } }
Add support of Patch Creator 1.0.0.9
namespace SIM.Tool.Windows.MainWindowComponents { using System.IO; using System.Windows; using Sitecore.Diagnostics.Base; using Sitecore.Diagnostics.Base.Annotations; using SIM.Core; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; [UsedImplicitly] public class CreateSupportPatchButton : IMainWindowButton { #region Public methods public bool IsEnabled(Window mainWindow, Instance instance) { return true; } public void OnClick(Window mainWindow, Instance instance) { if (instance == null) { WindowHelper.ShowMessage("Choose an instance first"); return; } var product = instance.Product; Assert.IsNotNull(product, $"The {instance.ProductFullName} distributive is not available in local repository. You need to get it first."); var version = product.Version + "." + product.Update; CoreApp.RunApp("iexplore", $"http://dl.sitecore.net/updater/pc/CreatePatch.application?p1={version}&p2={instance.Name}&p3={instance.WebRootPath}"); NuGetHelper.UpdateSettings(); NuGetHelper.GeneratePackages(new FileInfo(product.PackagePath)); foreach (var module in instance.Modules) { NuGetHelper.GeneratePackages(new FileInfo(module.PackagePath)); } } #endregion } }
namespace SIM.Tool.Windows.MainWindowComponents { using System; using System.IO; using System.Windows; using Sitecore.Diagnostics.Base; using Sitecore.Diagnostics.Base.Annotations; using SIM.Core; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; [UsedImplicitly] public class CreateSupportPatchButton : IMainWindowButton { #region Public methods public bool IsEnabled(Window mainWindow, Instance instance) { return true; } public void OnClick(Window mainWindow, Instance instance) { if (instance == null) { WindowHelper.ShowMessage("Choose an instance first"); return; } var product = instance.Product; Assert.IsNotNull(product, $"The {instance.ProductFullName} distributive is not available in local repository. You need to get it first."); var version = product.Version + "." + product.Update; var args = new[] { version, instance.Name, instance.WebRootPath }; var dir = Environment.ExpandEnvironmentVariables("%APPDATA%\\Sitecore\\CreatePatch"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllLines(Path.Combine(dir, "args.txt"), args); CoreApp.RunApp("iexplore", $"http://dl.sitecore.net/updater/pc/CreatePatch.application"); NuGetHelper.UpdateSettings(); NuGetHelper.GeneratePackages(new FileInfo(product.PackagePath)); foreach (var module in instance.Modules) { NuGetHelper.GeneratePackages(new FileInfo(module.PackagePath)); } } #endregion } }
Fix new test failing on headless runs
// 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. #nullable disable using NUnit.Framework; using osu.Framework.Graphics; using osu.Game.Screens.Select; using osuTK; namespace osu.Game.Tests.Visual.SongSelect { public class TestSceneDifficultyRangeFilterControl : OsuTestScene { [Test] public void TestBasic() { Child = new DifficultyRangeFilterControl { Width = 200, Anchor = Anchor.Centre, Origin = Anchor.Centre, Scale = new Vector2(3), }; } } }
// 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. #nullable disable using NUnit.Framework; using osu.Framework.Graphics; using osu.Game.Screens.Select; using osuTK; namespace osu.Game.Tests.Visual.SongSelect { public class TestSceneDifficultyRangeFilterControl : OsuTestScene { [Test] public void TestBasic() { AddStep("create control", () => { Child = new DifficultyRangeFilterControl { Width = 200, Anchor = Anchor.Centre, Origin = Anchor.Centre, Scale = new Vector2(3), }; }); } } }
Use external console when running DNX apps.
// // DnxProjectConfiguration.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (c) 2015 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using MonoDevelop.Projects; namespace MonoDevelop.Dnx { public class DnxProjectConfiguration : DotNetProjectConfiguration { public DnxProjectConfiguration (string name) : base (name) { } public DnxProjectConfiguration () { } } }
// // DnxProjectConfiguration.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (c) 2015 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using MonoDevelop.Projects; namespace MonoDevelop.Dnx { public class DnxProjectConfiguration : DotNetProjectConfiguration { public DnxProjectConfiguration (string name) : base (name) { ExternalConsole = true; } public DnxProjectConfiguration () { ExternalConsole = true; } } }
Increase number of tests total
using System; using System.Linq; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BudgetAnalyser.UnitTest { [TestClass] public class MetaTest { private const int ExpectedMinimumTests = 836; [TestMethod] public void ListAllTests() { Assembly assembly = GetType().Assembly; var count = 0; foreach (Type type in assembly.ExportedTypes) { var testClassAttrib = type.GetCustomAttribute<TestClassAttribute>(); if (testClassAttrib != null) { foreach (MethodInfo method in type.GetMethods()) { if (method.GetCustomAttribute<TestMethodAttribute>() != null) { Console.WriteLine("{0} {1} - {2}", ++count, type.FullName, method.Name); } } } } } [TestMethod] public void NoDecreaseInTests() { int count = CountTests(); Console.WriteLine(count); Assert.IsTrue(count >= ExpectedMinimumTests); } [TestMethod] public void UpdateNoDecreaseInTests() { int count = CountTests(); Assert.IsFalse(count > ExpectedMinimumTests + 10, "Update the minimum expected number of tests to " + count); } private int CountTests() { Assembly assembly = GetType().Assembly; int count = (from type in assembly.ExportedTypes let testClassAttrib = type.GetCustomAttribute<TestClassAttribute>() where testClassAttrib != null select type.GetMethods().Count(method => method.GetCustomAttribute<TestMethodAttribute>() != null)).Sum(); return count; } } }
using System; using System.Linq; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BudgetAnalyser.UnitTest { [TestClass] public class MetaTest { private const int ExpectedMinimumTests = 868; [TestMethod] public void ListAllTests() { Assembly assembly = GetType().Assembly; var count = 0; foreach (Type type in assembly.ExportedTypes) { var testClassAttrib = type.GetCustomAttribute<TestClassAttribute>(); if (testClassAttrib != null) { foreach (MethodInfo method in type.GetMethods()) { if (method.GetCustomAttribute<TestMethodAttribute>() != null) { Console.WriteLine("{0} {1} - {2}", ++count, type.FullName, method.Name); } } } } } [TestMethod] public void NoDecreaseInTests() { int count = CountTests(); Console.WriteLine(count); Assert.IsTrue(count >= ExpectedMinimumTests); } [TestMethod] public void UpdateNoDecreaseInTests() { int count = CountTests(); Assert.IsFalse(count > ExpectedMinimumTests + 10, "Update the minimum expected number of tests to " + count); } private int CountTests() { Assembly assembly = GetType().Assembly; int count = (from type in assembly.ExportedTypes let testClassAttrib = type.GetCustomAttribute<TestClassAttribute>() where testClassAttrib != null select type.GetMethods().Count(method => method.GetCustomAttribute<TestMethodAttribute>() != null)).Sum(); return count; } } }
Add warning for UWP that it works only in x86 yet
using System; using System.IO; using System.Runtime.InteropServices; using Windows.Storage; namespace Urho.UWP { public static class UwpUrhoInitializer { internal static void OnInited() { var folder = ApplicationData.Current.LocalFolder.Path; } } }
using System; using System.IO; using System.Runtime.InteropServices; using Windows.Storage; namespace Urho.UWP { public static class UwpUrhoInitializer { internal static void OnInited() { var folder = ApplicationData.Current.LocalFolder.Path; if (IntPtr.Size == 8) { throw new NotSupportedException("x86_64 is not supported yet. Please use x86."); } } } }
Change menu partial view type
@inherits UmbracoViewPage<MenuViewModel> <a href="#menu" id="menu-link"> <i class="fa fa-bars" aria-hidden="true"></i> <i class="fa fa-times" aria-hidden="true"></i> </a> <div id="menu"> <div class="pure-menu"> <span class="pure-menu-heading">@Model.SiteName</span> <ul class="pure-menu-list"> @foreach (var item in Model.MenuItems) { var selected = Model.Content.Path.Split(',').Select(int.Parse).Contains(item.Id); <li class="pure-menu-item @(selected ? "pure-menu-selected": "")"> <a href="@item.Url" class="pure-menu-link"> @item.Name </a> </li> } </ul> </div> </div>
@model MenuViewModel <a href="#menu" id="menu-link"> <i class="fa fa-bars" aria-hidden="true"></i> <i class="fa fa-times" aria-hidden="true"></i> </a> <div id="menu"> <div class="pure-menu"> <span class="pure-menu-heading">@Model.SiteName</span> <ul class="pure-menu-list"> @foreach (var item in Model.MenuItems) { var selected = Model.Content.Path.Split(',').Select(int.Parse).Contains(item.Id); <li class="pure-menu-item @(selected ? "pure-menu-selected": "")"> <a href="@item.Url" class="pure-menu-link"> @item.Name </a> </li> } </ul> </div> </div>
Use new OAID reading method
using System; using System.Runtime.InteropServices; using UnityEngine; namespace com.adjust.sdk.oaid { #if UNITY_ANDROID public class AdjustOaidAndroid { private static AndroidJavaClass ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); public static void ReadOaid() { if (ajcAdjustOaid == null) { ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); } ajcAdjustOaid.CallStatic("readOaid"); } public static void DoNotReadOaid() { if (ajcAdjustOaid == null) { ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); } ajcAdjustOaid.CallStatic("doNotReadOaid"); } } #endif }
using System; using System.Runtime.InteropServices; using UnityEngine; namespace com.adjust.sdk.oaid { #if UNITY_ANDROID public class AdjustOaidAndroid { private static AndroidJavaClass ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); private static AndroidJavaObject ajoCurrentActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"); public static void ReadOaid() { if (ajcAdjustOaid == null) { ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); } ajcAdjustOaid.CallStatic("readOaid", ajoCurrentActivity); } public static void DoNotReadOaid() { if (ajcAdjustOaid == null) { ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); } ajcAdjustOaid.CallStatic("doNotReadOaid"); } } #endif }
Make internals (in particular Runtime.*) visible to the tests.
using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyProduct("Python for .NET")] [assembly: AssemblyVersion("4.0.0.1")] [assembly: AssemblyDefaultAlias("Python.Runtime.dll")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyCopyright("MIT License")] [assembly: AssemblyFileVersion("2.0.0.2")] [assembly: NeutralResourcesLanguage("en")] #if PYTHON27 [assembly: AssemblyTitle("Python.Runtime for Python 2.7")] [assembly: AssemblyDescription("Python Runtime for Python 2.7")] #elif PYTHON33 [assembly: AssemblyTitle("Python.Runtime for Python 3.3")] [assembly: AssemblyDescription("Python Runtime for Python 3.3")] #elif PYTHON34 [assembly: AssemblyTitle("Python.Runtime for Python 3.4")] [assembly: AssemblyDescription("Python Runtime for Python 3.4")] #elif PYTHON35 [assembly: AssemblyTitle("Python.Runtime for Python 3.5")] [assembly: AssemblyDescription("Python Runtime for Python 3.5")] #elif PYTHON36 [assembly: AssemblyTitle("Python.Runtime for Python 3.6")] [assembly: AssemblyDescription("Python Runtime for Python 3.6")] #elif PYTHON37 [assembly: AssemblyTitle("Python.Runtime for Python 3.7")] [assembly: AssemblyDescription("Python Runtime for Python 3.7")] #endif
using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: AssemblyProduct("Python for .NET")] [assembly: AssemblyVersion("4.0.0.1")] [assembly: AssemblyDefaultAlias("Python.Runtime.dll")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyCopyright("MIT License")] [assembly: AssemblyFileVersion("2.0.0.2")] [assembly: NeutralResourcesLanguage("en")] [assembly: InternalsVisibleTo("Python.EmbeddingTest")]
Fix FxCop warning CA1018 (attributes should have AttributeUsage)
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.CompilerServices { // Custom attribute to indicating a TypeDef is a discardable attribute. public class DiscardableAttribute : Attribute { public DiscardableAttribute() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.CompilerServices { // Custom attribute to indicating a TypeDef is a discardable attribute. [AttributeUsage(AttributeTargets.All)] public class DiscardableAttribute : Attribute { public DiscardableAttribute() { } } }
Rephrase parsing to the end of input in terms of Map.
using System.Diagnostics.CodeAnalysis; namespace Parsley; public static class ParserExtensions { public static bool TryParse<TItem, TValue>( this Parser<TItem, TValue> parse, ReadOnlySpan<TItem> input, [NotNullWhen(true)] out TValue? value, [NotNullWhen(false)] out ParseError? error) { var parseToEnd = from result in parse from end in Grammar.EndOfInput<TItem>() select result; return TryPartialParse(parseToEnd, input, out int index, out value, out error); } public static bool TryPartialParse<TItem, TValue>( this Parser<TItem, TValue> parse, ReadOnlySpan<TItem> input, out int index, [NotNullWhen(true)] out TValue? value, [NotNullWhen(false)] out ParseError? error) { index = 0; value = parse(input, ref index, out var succeeded, out var expectation); if (succeeded) { error = null; #pragma warning disable CS8762 // Parameter must have a non-null value when exiting in some condition. return true; #pragma warning restore CS8762 // Parameter must have a non-null value when exiting in some condition. } error = new ParseError(index, expectation!); return false; } }
using System.Diagnostics.CodeAnalysis; namespace Parsley; public static class ParserExtensions { public static bool TryParse<TItem, TValue>( this Parser<TItem, TValue> parse, ReadOnlySpan<TItem> input, [NotNullWhen(true)] out TValue? value, [NotNullWhen(false)] out ParseError? error) { var parseToEnd = Grammar.Map(parse, Grammar.EndOfInput<TItem>(), (result, _) => result); return TryPartialParse(parseToEnd, input, out int index, out value, out error); } public static bool TryPartialParse<TItem, TValue>( this Parser<TItem, TValue> parse, ReadOnlySpan<TItem> input, out int index, [NotNullWhen(true)] out TValue? value, [NotNullWhen(false)] out ParseError? error) { index = 0; value = parse(input, ref index, out var succeeded, out var expectation); if (succeeded) { error = null; #pragma warning disable CS8762 // Parameter must have a non-null value when exiting in some condition. return true; #pragma warning restore CS8762 // Parameter must have a non-null value when exiting in some condition. } error = new ParseError(index, expectation!); return false; } }
Fix tab names on node views
using System.ComponentModel; namespace StackExchange.Opserver.Views.Dashboard { public enum CurrentStatusTypes { [Description("None")] None = 0, Stats = 1, Interfaces = 2, [Description("VM Info")] VMHost = 3, [Description("Elastic")] Elastic = 4, HAProxy = 5, [Description("SQL Instance")] SQLInstance = 6, [Description("Active SQL")] SQLActive = 7, [Description("Top SQL")] SQLTop = 8, [Description("Redis Info")] Redis = 9 } }
using System.ComponentModel; namespace StackExchange.Opserver.Views.Dashboard { public enum CurrentStatusTypes { [Description("None")] None = 0, [Description("Stats")] Stats = 1, [Description("Interfaces")] Interfaces = 2, [Description("VM Info")] VMHost = 3, [Description("Elastic")] Elastic = 4, [Description("HAProxy")] HAProxy = 5, [Description("SQL Instance")] SQLInstance = 6, [Description("Active SQL")] SQLActive = 7, [Description("Top SQL")] SQLTop = 8, [Description("Redis Info")] Redis = 9 } }
Add the time as a title to the order notes date.
@model ReviewOrderViewModel <section id="notes" class="ui-corner-all display-form"> <header class="ui-corner-top ui-widget-header"> <div class="col1 showInNav">Order Notes</div> <div class="col2"> <a href="#" class="button" id="add-note">Add Note</a> </div> </header> <div class="section-contents"> @if (!Model.Comments.Any()) { <span class="notes-not-found">There Are No Notes Attached To This Order</span> } <table class="noicon"> <tbody> @foreach (var notes in Model.Comments.OrderBy(o => o.DateCreated)) { <tr> <td>@notes.DateCreated.ToString("d")</td> <td>@notes.Text</td> <td>@notes.User.FullName</td> </tr> } </tbody> </table> </div> @*<footer class="ui-corner-bottom"></footer>*@ </section> <div id="notes-dialog" title="Add Order Notes" style="display:none;"> <textarea id="notes-box" style="width: 370px; height: 110px;"></textarea> </div> <script id="comment-template" type="text/x-jquery-tmpl"> <tr> <td>${datetime}</td> <td>${txt}</td> <td>${user}</td> </tr> </script>
@model ReviewOrderViewModel <section id="notes" class="ui-corner-all display-form"> <header class="ui-corner-top ui-widget-header"> <div class="col1 showInNav">Order Notes</div> <div class="col2"> <a href="#" class="button" id="add-note">Add Note</a> </div> </header> <div class="section-contents"> @if (!Model.Comments.Any()) { <span class="notes-not-found">There Are No Notes Attached To This Order</span> } <table class="noicon"> <tbody> @foreach (var notes in Model.Comments.OrderBy(o => o.DateCreated)) { <tr> <td title="@notes.DateCreated.ToString("T")">@notes.DateCreated.ToString("d")</td> <td>@notes.Text</td> <td>@notes.User.FullName</td> </tr> } </tbody> </table> </div> @*<footer class="ui-corner-bottom"></footer>*@ </section> <div id="notes-dialog" title="Add Order Notes" style="display:none;"> <textarea id="notes-box" style="width: 370px; height: 110px;"></textarea> </div> <script id="comment-template" type="text/x-jquery-tmpl"> <tr> <td>${datetime}</td> <td>${txt}</td> <td>${user}</td> </tr> </script>
Add resources to the automated tests too
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Testing; namespace osu.Framework.Tests { public class AutomatedVisualTestGame : Game { public AutomatedVisualTestGame() { Add(new TestBrowserTestRunner(new TestBrowser())); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Allocation; using osu.Framework.IO.Stores; using osu.Framework.Testing; namespace osu.Framework.Tests { public class AutomatedVisualTestGame : Game { [BackgroundDependencyLoader] private void load() { Resources.AddStore(new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.Tests.exe"), "Resources")); } public AutomatedVisualTestGame() { Add(new TestBrowserTestRunner(new TestBrowser())); } } }
Increment version number to sync up with NuGet
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XeroApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xero")] [assembly: AssemblyProduct("XeroApi")] [assembly: AssemblyCopyright("Copyright © Xero 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")] // 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.0.0.5")] [assembly: AssemblyFileVersion("1.0.0.6")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XeroApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xero")] [assembly: AssemblyProduct("XeroApi")] [assembly: AssemblyCopyright("Copyright © Xero 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")] // 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.0.0.7")] [assembly: AssemblyFileVersion("1.0.0.7")]
Update OData WebAPI to 5.5.0.0
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.4.0.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.4.0.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft OData Web API")] #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.5.0.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.5.0.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft OData Web API")] #endif
Fix sizing of embedded (wrapped) native NSViews
using System; using Xwt.Backends; using Xwt.Drawing; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; #else using Foundation; using AppKit; using ObjCRuntime; #endif namespace Xwt.Mac { public class EmbedNativeWidgetBackend : ViewBackend, IEmbeddedWidgetBackend { NSView innerView; public EmbedNativeWidgetBackend () { } public override void Initialize () { ViewObject = new WidgetView (EventSink, ApplicationContext); if (innerView != null) { var aView = innerView; innerView = null; SetNativeView (aView); } } public void SetContent (object nativeWidget) { if (nativeWidget is NSView) { if (ViewObject == null) innerView = (NSView)nativeWidget; else SetNativeView ((NSView)nativeWidget); } } void SetNativeView (NSView aView) { if (innerView != null) innerView.RemoveFromSuperview (); innerView = aView; innerView.Frame = Widget.Bounds; Widget.AddSubview (innerView); } } }
using System; using Xwt.Backends; using Xwt.Drawing; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; #else using Foundation; using AppKit; using ObjCRuntime; #endif namespace Xwt.Mac { public class EmbedNativeWidgetBackend : ViewBackend, IEmbeddedWidgetBackend { NSView innerView; public EmbedNativeWidgetBackend () { } public override void Initialize () { ViewObject = new WidgetView (EventSink, ApplicationContext); if (innerView != null) { var aView = innerView; innerView = null; SetNativeView (aView); } } public void SetContent (object nativeWidget) { if (nativeWidget is NSView) { if (ViewObject == null) innerView = (NSView)nativeWidget; else SetNativeView ((NSView)nativeWidget); } } void SetNativeView (NSView aView) { if (innerView != null) innerView.RemoveFromSuperview (); innerView = aView; innerView.Frame = Widget.Bounds; innerView.AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable; innerView.TranslatesAutoresizingMaskIntoConstraints = true; Widget.AutoresizesSubviews = true; Widget.AddSubview (innerView); } } }
Fix - Modificata la generazione del Codice Richiesta e del Codice Chiamata come richiesto nella riunone dell'11-07-2019
using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso; using SO115App.FakePersistenceJSon.GestioneIntervento; using SO115App.Models.Servizi.Infrastruttura.GestioneSoccorso.GenerazioneCodiciRichiesta; using System; namespace SO115App.FakePersistence.JSon.Utility { public class GeneraCodiceRichiesta : IGeneraCodiceRichiesta { public string Genera(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; string nuovoNumero = GetMaxCodice.GetMax().ToString(); return string.Format("{0}-{1}-{2:D5}", codiceProvincia, ultimeDueCifreAnno, nuovoNumero); } public string GeneraCodiceChiamata(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; int giorno = DateTime.UtcNow.Day; int mese = DateTime.UtcNow.Month; int nuovoNumero = GetMaxCodice.GetMaxCodiceChiamata(); string returnString = string.Format("{0}-{1}-{2}-{3}_{4:D5}", codiceProvincia, giorno, mese, ultimeDueCifreAnno, nuovoNumero); return returnString; } } }
using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso; using SO115App.FakePersistenceJSon.GestioneIntervento; using SO115App.Models.Servizi.Infrastruttura.GestioneSoccorso.GenerazioneCodiciRichiesta; using System; namespace SO115App.FakePersistence.JSon.Utility { public class GeneraCodiceRichiesta : IGeneraCodiceRichiesta { public string Genera(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; string nuovoNumero = GetMaxCodice.GetMax().ToString(); return string.Format("{0}{1}{2:D5}", codiceProvincia.Split('.')[0], ultimeDueCifreAnno, nuovoNumero); } public string GeneraCodiceChiamata(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; int giorno = DateTime.UtcNow.Day; int mese = DateTime.UtcNow.Month; int nuovoNumero = GetMaxCodice.GetMaxCodiceChiamata(); string returnString = string.Format("{0}{1}{2}{3}{4:D5}", codiceProvincia.Split('.')[0], giorno, mese, ultimeDueCifreAnno, nuovoNumero); return returnString; } } }
Add comments to public methods
using System.Web.Script.Serialization; namespace JsonConfig { public static class JsonConfigManager { #region Fields private static readonly IConfigFileLoader ConfigFileLoader = new ConfigFileLoader(); private static dynamic _defaultConfig; #endregion #region Public Members public static dynamic DefaultConfig { get { if (_defaultConfig == null) { _defaultConfig = GetConfig(ConfigFileLoader.LoadDefaultConfigFile()); } return _defaultConfig; } } public static dynamic GetConfig(string json) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); return serializer.Deserialize(json, typeof(object)); } public static dynamic LoadConfig(string filePath) { return GetConfig(ConfigFileLoader.LoadConfigFile(filePath)); } #endregion } }
using System.Web.Script.Serialization; namespace JsonConfig { public static class JsonConfigManager { #region Fields private static readonly IConfigFileLoader ConfigFileLoader = new ConfigFileLoader(); private static dynamic _defaultConfig; #endregion #region Public Members /// <summary> /// Gets the default config dynamic object, which should be a file named app.json.config located at the root of your project /// </summary> public static dynamic DefaultConfig { get { if (_defaultConfig == null) { _defaultConfig = GetConfig(ConfigFileLoader.LoadDefaultConfigFile()); } return _defaultConfig; } } /// <summary> /// Get a config dynamic object from the json /// </summary> /// <param name="json">Json string</param> /// <returns>The dynamic config object</returns> public static dynamic GetConfig(string json) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); return serializer.Deserialize(json, typeof(object)); } /// <summary> /// Load a config from a specified file /// </summary> /// <param name="filePath">Config file path</param> /// <returns>The dynamic config object</returns> public static dynamic LoadConfig(string filePath) { return GetConfig(ConfigFileLoader.LoadConfigFile(filePath)); } #endregion } }
Fix to ajax restoration of the cart.
@{ if (Layout.IsCartPage != true) { Script.Require("jQuery"); Script.Include("shoppingcart.js", "shoppingcart.min.js"); <div class="shopping-cart-container minicart" data-load="@Url.Action("NakedCart", "ShoppingCart", new {area="Nwazet.Commerce"})" data-update="@Url.Action("AjaxUpdate", "ShoppingCart", new {area="Nwazet.Commerce"})" data-token="@Html.AntiForgeryTokenValueOrchard()"></div> } }
@{ if (Layout.IsCartPage != true) { Script.Require("jQuery"); Script.Include("shoppingcart.js", "shoppingcart.min.js"); <div class="shopping-cart-container minicart" data-load="@Url.Action("NakedCart", "ShoppingCart", new {area="Nwazet.Commerce"})" data-update="@Url.Action("AjaxUpdate", "ShoppingCart", new {area="Nwazet.Commerce"})" data-token="@Html.AntiForgeryTokenValueOrchard()"></div> <script type="text/javascript"> var Nwazet = window.Nwazet || {}; Nwazet.WaitWhileWeRestoreYourCart = "@T("Please wait while we restore your shopping cart...")"; Nwazet.FailedToLoadCart = "@T("Failed to load the cart")"; </script> } }
Change levy run date to 24th
using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ImportLevyDeclarationsJob { private readonly IMessageSession _messageSession; public ImportLevyDeclarationsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 15 20 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ImportLevyDeclarationsCommand()); } } }
using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ImportLevyDeclarationsJob { private readonly IMessageSession _messageSession; public ImportLevyDeclarationsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 10 24 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ImportLevyDeclarationsCommand()); } } }
Remove Application Insights modules and initializers
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site.Integration { using Microsoft.ApplicationInsights.DependencyCollector; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.DependencyInjection; internal static class IServiceCollectionExtensions { internal static void DisableApplicationInsights(this IServiceCollection services) { // Disable dependency tracking to work around https://github.com/Microsoft/ApplicationInsights-dotnet-server/pull/1006 services.Configure<TelemetryConfiguration>((p) => p.DisableTelemetry = true); services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>( (module, _) => { module.DisableDiagnosticSourceInstrumentation = true; module.DisableRuntimeInstrumentation = true; module.SetComponentCorrelationHttpHeaders = false; module.IncludeDiagnosticSourceActivities.Clear(); }); } } }
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site.Integration { using Microsoft.ApplicationInsights.DependencyCollector; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; internal static class IServiceCollectionExtensions { internal static void DisableApplicationInsights(this IServiceCollection services) { // Disable dependency tracking to work around https://github.com/Microsoft/ApplicationInsights-dotnet-server/pull/1006 services.Configure<TelemetryConfiguration>((p) => p.DisableTelemetry = true); services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>( (module, _) => { module.DisableDiagnosticSourceInstrumentation = true; module.DisableRuntimeInstrumentation = true; module.SetComponentCorrelationHttpHeaders = false; module.IncludeDiagnosticSourceActivities.Clear(); }); services.RemoveAll<ITelemetryInitializer>(); services.RemoveAll<ITelemetryModule>(); } } }
Remove auto-generated warning from handwritten file
// ------------------------------------------------------------------------- // Managed wrapper for QSize // Generated from qt-gui.xml on 07/24/2011 11:57:03 // // This file was auto generated. Do not edit. // ------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; using Mono.Cxxi; namespace Qt.Gui { [StructLayout (LayoutKind.Sequential)] public struct QSize { public int wd; public int ht; public QSize (int w, int h) { wd = w; ht = h; } } }
using System; using System.Runtime.InteropServices; using Mono.Cxxi; namespace Qt.Gui { [StructLayout (LayoutKind.Sequential)] public struct QSize { public int wd; public int ht; public QSize (int w, int h) { wd = w; ht = h; } } }
Change the names to be in line with the problem at hand.
using Ninject; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FunWithNinject.OpenGenerics { [TestFixture] public class OpenGenericsTests { public interface ILogger<T> { Type GenericParam { get; } } public class Logger<T> : ILogger<T> { public Type GenericParam { get { return typeof(T); } } } public class DependsOnLogger { public DependsOnLogger(ILogger<int> intLogger) { GenericParam = intLogger.GenericParam; } public Type GenericParam { get; set; } } [Test] public void OpenGenericBinding() { using (var k = new StandardKernel()) { // Assemble k.Bind(typeof(ILogger<>)).To(typeof(Logger<>)); // Act var dependsOn = k.Get<DependsOnLogger>(); // Assert Assert.AreEqual(typeof(int), dependsOn.GenericParam); } } } }
using Ninject; using NUnit.Framework; using System; namespace FunWithNinject.OpenGenerics { [TestFixture] public class OpenGenericsTests { [Test] public void OpenGenericBinding() { using (var k = new StandardKernel()) { // Assemble k.Bind(typeof(IAutoCache<>)).To(typeof(AutoCache<>)); // Act var dependsOn = k.Get<DependsOnLogger>(); // Assert Assert.AreEqual(typeof(int), dependsOn.CacheType); } } #region Types public interface IAutoCache<T> { Type CacheType { get; } } public class AutoCache<T> : IAutoCache<T> { public Type CacheType { get { return typeof(T); } } } public class DependsOnLogger { public DependsOnLogger(IAutoCache<int> intCacher) { CacheType = intCacher.CacheType; } public Type CacheType { get; set; } } #endregion } }
Set up references for event command unit tests
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Sogeti.Capstone.CQS.Integration.Tests { [TestClass] public class EventCommands { [TestMethod] public void CreateEventCommand() { } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Sogeti.Capstone.CQS.Integration.Tests { [TestClass] public class EventCommands { [TestMethod] public void CreateEventCommand() { } } }
Update state to be used after redirect
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"]))); builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest() ? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"]))); builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()|| context.IsFunctionsPortalRequest() ? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }
Add Rank to returned scores
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Nether.Data.Leaderboard; namespace Nether.Web.Features.Leaderboard { public class LeaderboardGetResponseModel { public List<LeaderboardEntry> Entries { get; set; } public class LeaderboardEntry { public static implicit operator LeaderboardEntry(GameScore score) { return new LeaderboardEntry { Gamertag = score.Gamertag, Score = score.Score }; } /// <summary> /// Gamertag /// </summary> public string Gamertag { get; set; } /// <summary> /// Scores /// </summary> public int Score { get; set; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Nether.Data.Leaderboard; namespace Nether.Web.Features.Leaderboard { public class LeaderboardGetResponseModel { public List<LeaderboardEntry> Entries { get; set; } public class LeaderboardEntry { public static implicit operator LeaderboardEntry(GameScore score) { return new LeaderboardEntry { Gamertag = score.Gamertag, Score = score.Score, Rank = score.Rank }; } /// <summary> /// Gamertag /// </summary> public string Gamertag { get; set; } /// <summary> /// Scores /// </summary> public int Score { get; set; } public long Rank { get; set; } } } }
Add correct JSON serialization for enum type
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Alexa.NET.Management.Api { public class CustomApiEndpoint { [JsonProperty("uri")] public string Uri { get; set; } [JsonProperty("sslCertificateType")] public SslCertificateType SslCertificateType { get; set; } } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.Text; namespace Alexa.NET.Management.Api { public class CustomApiEndpoint { [JsonProperty("uri")] public string Uri { get; set; } [JsonProperty("sslCertificateType"), JsonConverter(typeof(StringEnumConverter))] public SslCertificateType SslCertificateType { get; set; } } }
Update Stripe test API key from their docs
using System; using System.Linq; namespace Stripe.Tests { static class Constants { public const string ApiKey = @"8GSx9IL9MA0iJ3zcitnGCHonrXWiuhMf"; } }
using System; using System.Linq; namespace Stripe.Tests { static class Constants { public const string ApiKey = @"sk_test_BQokikJOvBiI2HlWgH4olfQ2"; } }
Migrate from ASP.NET Core 2.0 to 2.1
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Senparc.Weixin.MP.CoreSample { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Senparc.Weixin.MP.CoreSample { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
Remove laziness from edges' GetHashCode method
using System; using System.Collections.Generic; using System.Diagnostics; namespace Basics.Structures.Graphs { [DebuggerDisplay("{Source}->{Target}")] public class Edge<T> : IEquatable<Edge<T>> where T : IEquatable<T> { private readonly Lazy<int> _hashCode; public Edge(T source, T target) { Source = source; Target = target; _hashCode = new Lazy<int>(() => { var sourceHashCode = Source.GetHashCode(); return ((sourceHashCode << 5) + sourceHashCode) ^ Target.GetHashCode(); }); } public T Source { get; private set; } public T Target { get; private set; } public bool IsSelfLooped { get { return Source.Equals(Target); } } public static bool operator ==(Edge<T> a, Edge<T> b) { return a.Equals(b); } public static bool operator !=(Edge<T> a, Edge<T> b) { return !a.Equals(b); } public bool Equals(Edge<T> other) { return !Object.ReferenceEquals(other, null) && this.Source.Equals(other.Source) && this.Target.Equals(other.Target); } public override bool Equals(object obj) { return Equals(obj as Edge<T>); } public override int GetHashCode() { return _hashCode.Value; } public override string ToString() { return Source + "->" + Target; } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Basics.Structures.Graphs { [DebuggerDisplay("{Source}->{Target}")] public class Edge<T> : IEquatable<Edge<T>> where T : IEquatable<T> { public Edge(T source, T target) { Source = source; Target = target; } public T Source { get; private set; } public T Target { get; private set; } public bool IsSelfLooped { get { return Source.Equals(Target); } } public static bool operator ==(Edge<T> a, Edge<T> b) { return a.Equals(b); } public static bool operator !=(Edge<T> a, Edge<T> b) { return !a.Equals(b); } public bool Equals(Edge<T> other) { return !Object.ReferenceEquals(other, null) && this.Source.Equals(other.Source) && this.Target.Equals(other.Target); } public override bool Equals(object obj) { return Equals(obj as Edge<T>); } public override int GetHashCode() { var sourceHashCode = Source.GetHashCode(); return ((sourceHashCode << 5) + sourceHashCode) ^ Target.GetHashCode(); } public override string ToString() { return Source + "->" + Target; } } }
Add simple method to read back in a Post from disk
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; namespace BlogTemplate.Models { public class BlogDataStore { const string StorageFolder = "BlogFiles"; public void SavePost(Post post) { Directory.CreateDirectory(StorageFolder); string outputFilePath = $"{StorageFolder}\\{post.Slug}.xml"; XmlDocument doc = new XmlDocument(); XmlElement rootNode = doc.CreateElement("Post"); doc.AppendChild(rootNode); rootNode.AppendChild(doc.CreateElement("Slug")).InnerText = post.Slug; rootNode.AppendChild(doc.CreateElement("Title")).InnerText = post.Title; rootNode.AppendChild(doc.CreateElement("Body")).InnerText = post.Body; doc.Save(outputFilePath); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; namespace BlogTemplate.Models { public class BlogDataStore { const string StorageFolder = "BlogFiles"; public void SavePost(Post post) { Directory.CreateDirectory(StorageFolder); string outputFilePath = $"{StorageFolder}\\{post.Slug}.xml"; XmlDocument doc = new XmlDocument(); XmlElement rootNode = doc.CreateElement("Post"); doc.AppendChild(rootNode); rootNode.AppendChild(doc.CreateElement("Slug")).InnerText = post.Slug; rootNode.AppendChild(doc.CreateElement("Title")).InnerText = post.Title; rootNode.AppendChild(doc.CreateElement("Body")).InnerText = post.Body; doc.Save(outputFilePath); } public Post GetPost(string slug) { string expectedFilePath = $"{StorageFolder}\\{slug}.xml"; if(File.Exists(expectedFilePath)) { string fileContent = File.ReadAllText(expectedFilePath); XmlDocument doc = new XmlDocument(); doc.LoadXml(fileContent); Post post = new Post(); post.Slug = doc.GetElementsByTagName("Slug").Item(0).InnerText; post.Title = doc.GetElementsByTagName("Title").Item(0).InnerText; post.Body = doc.GetElementsByTagName("Body").Item(0).InnerText; return post; } return null; } } }
Add identifying tag to MassTransit health checks.
namespace MassTransit { using AspNetCoreIntegration; using AspNetCoreIntegration.HealthChecks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Monitoring.Health; /// <summary> /// These are the updated extensions compatible with the container registration code. They should be used, for real. /// </summary> public static class HostedServiceConfigurationExtensions { /// <summary> /// Adds the MassTransit <see cref="IHostedService" />, which includes a bus and endpoint health check. /// Use it together with UseHealthCheck to get more detailed diagnostics. /// </summary> /// <param name="services"></param> public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services) { AddHealthChecks(services); return services.AddSingleton<IHostedService, MassTransitHostedService>(); } public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services, IBusControl bus) { AddHealthChecks(services); return services.AddSingleton<IHostedService>(p => new BusHostedService(bus)); } static void AddHealthChecks(IServiceCollection services) { services.AddOptions(); services.AddHealthChecks(); services.AddSingleton<IConfigureOptions<HealthCheckServiceOptions>>(provider => new ConfigureBusHealthCheckServiceOptions(provider.GetServices<IBusHealth>(), new[] {"ready"})); } } }
namespace MassTransit { using AspNetCoreIntegration; using AspNetCoreIntegration.HealthChecks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Monitoring.Health; /// <summary> /// These are the updated extensions compatible with the container registration code. They should be used, for real. /// </summary> public static class HostedServiceConfigurationExtensions { /// <summary> /// Adds the MassTransit <see cref="IHostedService" />, which includes a bus and endpoint health check. /// Use it together with UseHealthCheck to get more detailed diagnostics. /// </summary> /// <param name="services"></param> public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services) { AddHealthChecks(services); return services.AddSingleton<IHostedService, MassTransitHostedService>(); } public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services, IBusControl bus) { AddHealthChecks(services); return services.AddSingleton<IHostedService>(p => new BusHostedService(bus)); } static void AddHealthChecks(IServiceCollection services) { services.AddOptions(); services.AddHealthChecks(); services.AddSingleton<IConfigureOptions<HealthCheckServiceOptions>>(provider => new ConfigureBusHealthCheckServiceOptions(provider.GetServices<IBusHealth>(), new[] {"ready", "masstransit"})); } } }
Reduce shake transform count by one for more aesthetic behaviour
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Graphics.Containers { /// <summary> /// A container that adds the ability to shake its contents. /// </summary> public class ShakeContainer : Container { /// <summary> /// Shake the contents of this container. /// </summary> public void Shake() { const float shake_amount = 8; const float shake_duration = 30; this.MoveToX(shake_amount, shake_duration / 2, Easing.OutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(0, shake_duration / 2, Easing.InSine); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Graphics.Containers { /// <summary> /// A container that adds the ability to shake its contents. /// </summary> public class ShakeContainer : Container { /// <summary> /// Shake the contents of this container. /// </summary> public void Shake() { const float shake_amount = 8; const float shake_duration = 30; this.MoveToX(shake_amount, shake_duration / 2, Easing.OutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(0, shake_duration / 2, Easing.InSine); } } }
Remove call to Application.Current.Dispatcher.CheckAccess() - seems there's a null point happening on a rare instance when Application.Current.Dispatcher is null Rely on parent calling code to execute on the correct thread (which it was already executing on the UI Thread)
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows; using System.Windows.Input; namespace CefSharp.Wpf { internal class DelegateCommand : ICommand { private readonly Action commandHandler; private readonly Func<bool> canExecuteHandler; public event EventHandler CanExecuteChanged; public DelegateCommand(Action commandHandler, Func<bool> canExecuteHandler = null) { this.commandHandler = commandHandler; this.canExecuteHandler = canExecuteHandler; } public void Execute(object parameter) { commandHandler(); } public bool CanExecute(object parameter) { return canExecuteHandler == null || canExecuteHandler(); } public void RaiseCanExecuteChanged() { if (!Application.Current.Dispatcher.CheckAccess()) { Application.Current.Dispatcher.BeginInvoke((Action) RaiseCanExecuteChanged); return; } if (CanExecuteChanged != null) { CanExecuteChanged(this, new EventArgs()); } } } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows.Input; namespace CefSharp.Wpf { internal class DelegateCommand : ICommand { private readonly Action commandHandler; private readonly Func<bool> canExecuteHandler; public event EventHandler CanExecuteChanged; public DelegateCommand(Action commandHandler, Func<bool> canExecuteHandler = null) { this.commandHandler = commandHandler; this.canExecuteHandler = canExecuteHandler; } public void Execute(object parameter) { commandHandler(); } public bool CanExecute(object parameter) { return canExecuteHandler == null || canExecuteHandler(); } public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) { CanExecuteChanged(this, new EventArgs()); } } } }
Comment for validation error rendering
@inherits Umbraco.Web.Mvc.UmbracoViewPage<FormEditor.Fields.IFieldWithValidation> @if (Model.Invalid) { <div class="text-danger validation-error"> @Model.ErrorMessage </div> }
@inherits Umbraco.Web.Mvc.UmbracoViewPage<FormEditor.Fields.IFieldWithValidation> @* for the NoScript rendering, this is solely rendered server side *@ @if (Model.Invalid) { <div class="text-danger validation-error"> @Model.ErrorMessage </div> }
Remove return xml comments, not valid anymore
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface IDownloadHandler { /// <summary> /// Called before a download begins. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">Callback interface used to asynchronously continue a download.</param> /// <returns>Return True to continue the download otherwise return False to cancel the download</returns> void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback); /// <summary> /// Called when a download's status or progress information has been updated. This may be called multiple times before and after <see cref="OnBeforeDownload"/>. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">The callback used to Cancel/Pause/Resume the process</param> /// <returns>Return True to cancel, otherwise False to allow the download to continue.</returns> void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback); } }
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface IDownloadHandler { /// <summary> /// Called before a download begins. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">Callback interface used to asynchronously continue a download.</param> void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback); /// <summary> /// Called when a download's status or progress information has been updated. This may be called multiple times before and after <see cref="OnBeforeDownload"/>. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">The callback used to Cancel/Pause/Resume the process</param> void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback); } }
Fix content root for non-windows xunit tests with no app domains
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.StaticFiles { public static class StaticFilesTestServer { public static TestServer Create(Action<IApplicationBuilder> configureApp, Action<IServiceCollection> configureServices = null) { Action<IServiceCollection> defaultConfigureServices = services => { }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new [] { new KeyValuePair<string, string>("webroot", ".") }) .Build(); var builder = new WebHostBuilder() .UseConfiguration(configuration) .Configure(configureApp) .ConfigureServices(configureServices ?? defaultConfigureServices); return new TestServer(builder); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.PlatformAbstractions; namespace Microsoft.AspNetCore.StaticFiles { public static class StaticFilesTestServer { public static TestServer Create(Action<IApplicationBuilder> configureApp, Action<IServiceCollection> configureServices = null) { var contentRootNet451 = PlatformServices.Default.Runtime.OperatingSystemPlatform == Platform.Windows ? "." : "../../../../test/Microsoft.AspNetCore.StaticFiles.Tests"; Action<IServiceCollection> defaultConfigureServices = services => { }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new [] { new KeyValuePair<string, string>("webroot", ".") }) .Build(); var builder = new WebHostBuilder() #if NET451 .UseContentRoot(contentRootNet451) #endif .UseConfiguration(configuration) .Configure(configureApp) .ConfigureServices(configureServices ?? defaultConfigureServices); return new TestServer(builder); } } }
Change obsolete signature for method Error
using System; using System.Threading; using NLog; using NLogConfig = NLog.Config; namespace BrowserLog.NLog.Demo { class Program { static void Main(string[] args) { LogManager.Configuration = new NLogConfig.XmlLoggingConfiguration("NLog.config", true); var logger = LogManager.GetLogger("*", typeof(Program)); logger.Info("Hello!"); Thread.Sleep(1000); for (int i = 0; i < 100000; i++) { logger.Info("Hello this is a log from a server-side process!"); Thread.Sleep(100); logger.Warn("Hello this is a warning from a server-side process!"); logger.Debug("... and here is another log again ({0})", i); Thread.Sleep(200); try { ThrowExceptionWithStackTrace(4); } catch (Exception ex) { logger.Error("An error has occured, really?", ex); } Thread.Sleep(1000); } } static void ThrowExceptionWithStackTrace(int depth) { if (depth == 0) { throw new Exception("A fake exception to show an example"); } ThrowExceptionWithStackTrace(--depth); } } }
using System; using System.Threading; using NLog; using NLogConfig = NLog.Config; namespace BrowserLog.NLog.Demo { class Program { static void Main(string[] args) { LogManager.Configuration = new NLogConfig.XmlLoggingConfiguration("NLog.config", true); var logger = LogManager.GetLogger("*", typeof(Program)); logger.Info("Hello!"); Thread.Sleep(1000); for (int i = 0; i < 100000; i++) { logger.Info("Hello this is a log from a server-side process!"); Thread.Sleep(100); logger.Warn("Hello this is a warning from a server-side process!"); logger.Debug("... and here is another log again ({0})", i); Thread.Sleep(200); try { ThrowExceptionWithStackTrace(4); } catch (Exception ex) { logger.Error(ex, "An error has occured, really?"); } Thread.Sleep(1000); } } static void ThrowExceptionWithStackTrace(int depth) { if (depth == 0) { throw new Exception("A fake exception to show an example"); } ThrowExceptionWithStackTrace(--depth); } } }
Add escaping to query string parsing
using System; using System.Collections.Specialized; using System.Text.RegularExpressions; namespace Winston.Net { static class Extensions { public static NameValueCollection ParseQueryString(this Uri uri) { var result = new NameValueCollection(); var query = uri.Query; // remove anything other than query string from url if (query.Contains("?")) { query = query.Substring(query.IndexOf('?') + 1); } foreach (string vp in Regex.Split(query, "&")) { var singlePair = Regex.Split(vp, "="); if (singlePair.Length == 2) { result.Add(singlePair[0], singlePair[1]); } else { // only one key with no value specified in query string result.Add(singlePair[0], string.Empty); } } return result; } } }
using System; using System.Collections.Specialized; using System.Text.RegularExpressions; namespace Winston.Net { static class Extensions { public static NameValueCollection ParseQueryString(this Uri uri) { var result = new NameValueCollection(); var query = uri.Query; // remove anything other than query string from url if (query.Contains("?")) { query = query.Substring(query.IndexOf('?') + 1); } foreach (string vp in Regex.Split(query, "&")) { var singlePair = Regex.Split(vp, "="); if (singlePair.Length == 2) { result.Add(Uri.UnescapeDataString(singlePair[0]), Uri.UnescapeDataString(singlePair[1])); } else { // only one key with no value specified in query string result.Add(Uri.UnescapeDataString(singlePair[0]), string.Empty); } } return result; } } }
Fix editor legacy beatmap skins not receiving transformer
// 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.Game.Skinning; #nullable enable namespace osu.Game.Screens.Edit { /// <summary> /// A <see cref="SkinProvidingContainer"/> that fires <see cref="ISkinSource.SourceChanged"/> when users have made a change to the beatmap skin /// of the map being edited. /// </summary> public class EditorSkinProvidingContainer : RulesetSkinProvidingContainer { private readonly EditorBeatmapSkin? beatmapSkin; public EditorSkinProvidingContainer(EditorBeatmap editorBeatmap) : base(editorBeatmap.PlayableBeatmap.BeatmapInfo.Ruleset.CreateInstance(), editorBeatmap.PlayableBeatmap, editorBeatmap.BeatmapSkin) { beatmapSkin = editorBeatmap.BeatmapSkin; } protected override void LoadComplete() { base.LoadComplete(); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged += TriggerSourceChanged; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged -= TriggerSourceChanged; } } }
// 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.Game.Skinning; #nullable enable namespace osu.Game.Screens.Edit { /// <summary> /// A <see cref="SkinProvidingContainer"/> that fires <see cref="ISkinSource.SourceChanged"/> when users have made a change to the beatmap skin /// of the map being edited. /// </summary> public class EditorSkinProvidingContainer : RulesetSkinProvidingContainer { private readonly EditorBeatmapSkin? beatmapSkin; public EditorSkinProvidingContainer(EditorBeatmap editorBeatmap) : base(editorBeatmap.PlayableBeatmap.BeatmapInfo.Ruleset.CreateInstance(), editorBeatmap.PlayableBeatmap, editorBeatmap.BeatmapSkin?.Skin) { beatmapSkin = editorBeatmap.BeatmapSkin; } protected override void LoadComplete() { base.LoadComplete(); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged += TriggerSourceChanged; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged -= TriggerSourceChanged; } } }
Add the new managers to the root context.
using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } }
using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>(); injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext(); IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>(); injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } }
Set anti-forgery token unique claim type
using System; using System.Web.Mvc; using System.Web.Routing; namespace SimplestMvc5Auth { public class Global : System.Web.HttpApplication { private static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); } protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }
using System; using System.Security.Claims; using System.Web.Helpers; using System.Web.Mvc; using System.Web.Routing; namespace SimplestMvc5Auth { public class Global : System.Web.HttpApplication { private static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); } protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name; } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }
Use 'long' datatype for IDs in sample applications to avoid warnings.
// Copyright (c) on/off it-solutions gmbh. All rights reserved. // Licensed under the MIT license. See license.txt file in the project root for license information. #pragma warning disable SA1402 // FileMayOnlyContainASingleType #pragma warning disable SA1649 // FileNameMustMatchTypeName namespace InfoCarrierSample { using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; public class Blog { public decimal Id { get; set; } public decimal AuthorId { get; set; } public Author Author { get; set; } public IList<Post> Posts { get; set; } } public class Post { public decimal Id { get; set; } public decimal BlogId { get; set; } public DateTime CreationDate { get; set; } public string Title { get; set; } public Blog Blog { get; set; } } public class Author { public decimal Id { get; set; } public string Name { get; set; } } public class BloggingContext : DbContext { public BloggingContext(DbContextOptions options) : base(options) { } public DbSet<Blog> Blogs { get; set; } public DbSet<Author> Authors { get; set; } } }
// Copyright (c) on/off it-solutions gmbh. All rights reserved. // Licensed under the MIT license. See license.txt file in the project root for license information. #pragma warning disable SA1402 // FileMayOnlyContainASingleType #pragma warning disable SA1649 // FileNameMustMatchTypeName namespace InfoCarrierSample { using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; public class Blog { public long Id { get; set; } public long AuthorId { get; set; } public Author Author { get; set; } public IList<Post> Posts { get; set; } } public class Post { public long Id { get; set; } public long BlogId { get; set; } public DateTime CreationDate { get; set; } public string Title { get; set; } public Blog Blog { get; set; } } public class Author { public long Id { get; set; } public string Name { get; set; } } public class BloggingContext : DbContext { public BloggingContext(DbContextOptions options) : base(options) { } public DbSet<Blog> Blogs { get; set; } public DbSet<Author> Authors { get; set; } } }
Make hft-server runtime options not based on HFTArgsDirect
using System; namespace HappyFunTimes { public class HFTRuntimeOptions : HFTArgsDirect { public HFTRuntimeOptions(string prefix) : base(prefix) { } public string dataPath = ""; public string url = ""; public string id = ""; public string name = ""; public string gameId = "HFTUnity"; // this is kind of left over from when one server supported mutiple games public string controllerFilename = ""; public bool disconnectPlayersIfGameDisconnects = true; public bool installationMode = false; public bool master = false; public bool showInList = true; public bool showMessages; public bool debug; public bool startServer; public bool dns; public bool captivePortal; public string serverPort = ""; public string rendezvousUrl; } }
using System; namespace HappyFunTimes { public class HFTRuntimeOptions { public string dataPath = ""; public string url = ""; public string id = ""; public string name = ""; public string gameId = "HFTUnity"; // this is kind of left over from when one server supported mutiple games public string controllerFilename = ""; public bool disconnectPlayersIfGameDisconnects = true; public bool installationMode = false; public bool master = false; public bool showInList = true; public bool showMessages; public bool debug; public bool startServer; public bool dns; public bool captivePortal; public string serverPort = ""; public string rendezvousUrl; public string args; } }
Remove the obsolete UseTypedRouting method
namespace Microsoft.AspNetCore.Builder { using Routing; using System; public static class RouteBuilderExtensions { /// <summary> /// Allows using typed expression based link generation in ASP.NET Core MVC application. /// </summary> [Obsolete("UseTypedRouting is no longer needed and will be removed in the next version. Call 'AddMvc().AddTypedRouting()' instead.")] public static IRouteBuilder UseTypedRouting(this IRouteBuilder routeBuilder) { return routeBuilder; } } }
namespace Microsoft.AspNetCore.Builder { using Routing; using System; public static class RouteBuilderExtensions { } }