Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Mark settings as read only
using System.Configuration; namespace Signatory { public static class Settings { public static string Authority = ConfigurationManager.AppSettings["Authority"]; public static string GitHubKey = ConfigurationManager.AppSettings["GitHubKey"]; public static string GitHubSecret = ConfigurationManager.AppSettings["GitHubSecret"]; } }
using System.Configuration; namespace Signatory { public static class Settings { public static readonly string Authority = ConfigurationManager.AppSettings["Authority"]; public static readonly string GitHubKey = ConfigurationManager.AppSettings["GitHubKey"]; public static readonly string GitHubSecret = ConfigurationManager.AppSettings["GitHubSecret"]; } }
Remove NUnit attribute accidently left on a class. The attribute is pointless because the class has no tests.
using NUnit.Framework; using System; using System.Collections; using Symbooglix; using Microsoft.Boogie; using Microsoft.Basetypes; namespace ExprBuilderTests { [TestFixture()] public class ConstantFoldingExprBuilderTests : SimpleExprBuilderTestBase { protected Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder> GetSimpleAndConstantFoldingBuilder() { var simpleBuilder = GetSimpleBuilder(); var constantFoldingBuilder = new ConstantFoldingExprBuilder(simpleBuilder); return new Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder>(simpleBuilder, constantFoldingBuilder); } protected ConstantFoldingExprBuilder GetConstantFoldingBuilder() { return new ConstantFoldingExprBuilder(GetSimpleBuilder()); } } }
using NUnit.Framework; using System; using System.Collections; using Symbooglix; using Microsoft.Boogie; using Microsoft.Basetypes; namespace ExprBuilderTests { public class ConstantFoldingExprBuilderTests : SimpleExprBuilderTestBase { protected Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder> GetSimpleAndConstantFoldingBuilder() { var simpleBuilder = GetSimpleBuilder(); var constantFoldingBuilder = new ConstantFoldingExprBuilder(simpleBuilder); return new Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder>(simpleBuilder, constantFoldingBuilder); } protected ConstantFoldingExprBuilder GetConstantFoldingBuilder() { return new ConstantFoldingExprBuilder(GetSimpleBuilder()); } } }
Fix job cancelled showing up as State = Unknown
using System; using System.Collections.Generic; using System.Linq; namespace Contract.Models { public class FfmpegJobModel { public FfmpegJobModel() { Tasks = new List<FfmpegTaskModel>(); } public Guid JobCorrelationId { get; set; } public TranscodingJobState State { get { if (Tasks.All(x => x.State == TranscodingJobState.Done)) return TranscodingJobState.Done; if (Tasks.Any(j => j.State == TranscodingJobState.Failed)) return TranscodingJobState.Failed; if (Tasks.Any(j => j.State == TranscodingJobState.Paused)) return TranscodingJobState.Paused; if (Tasks.Any(j => j.State == TranscodingJobState.InProgress)) return TranscodingJobState.InProgress; if (Tasks.Any(j => j.State == TranscodingJobState.Queued)) return TranscodingJobState.Queued; return TranscodingJobState.Unknown; } } public DateTimeOffset Created { get; set; } public DateTimeOffset Needed { get; set; } public IEnumerable<FfmpegTaskModel> Tasks { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Contract.Models { public class FfmpegJobModel { public FfmpegJobModel() { Tasks = new List<FfmpegTaskModel>(); } public Guid JobCorrelationId { get; set; } public TranscodingJobState State { get { if (Tasks.All(x => x.State == TranscodingJobState.Done)) return TranscodingJobState.Done; if (Tasks.Any(j => j.State == TranscodingJobState.Failed)) return TranscodingJobState.Failed; if (Tasks.Any(j => j.State == TranscodingJobState.Paused)) return TranscodingJobState.Paused; if (Tasks.Any(j => j.State == TranscodingJobState.InProgress)) return TranscodingJobState.InProgress; if (Tasks.Any(j => j.State == TranscodingJobState.Queued)) return TranscodingJobState.Queued; if (Tasks.Any(j => j.State == TranscodingJobState.Canceled)) return TranscodingJobState.Canceled; return TranscodingJobState.Unknown; } } public DateTimeOffset Created { get; set; } public DateTimeOffset Needed { get; set; } public IEnumerable<FfmpegTaskModel> Tasks { get; set; } } }
Change the way characters are recognized.
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; using VRGIN.Core; using VRGIN.Helpers; namespace HoneySelectVR { internal class HoneyInterpreter : GameInterpreter { public HScene Scene; private IList<IActor> _Actors = new List<IActor>(); protected override void OnLevel(int level) { base.OnLevel(level); Scene = InitScene(GameObject.FindObjectOfType<HScene>()); } protected override void OnUpdate() { base.OnUpdate(); } private HScene InitScene(HScene scene) { _Actors.Clear(); if(scene) { StartCoroutine(DelayedInit()); } return scene; } IEnumerator DelayedInit() { yield return null; yield return null; var charFemaleField = typeof(HScene).GetField("chaFemale", BindingFlags.NonPublic | BindingFlags.Instance); var charMaleField = typeof(HScene).GetField("chaMale", BindingFlags.NonPublic | BindingFlags.Instance); var female = charFemaleField.GetValue(Scene) as CharFemale; var male = charMaleField.GetValue(Scene) as CharMale; if (male) { _Actors.Add(new HoneyActor(male)); } if (female) { _Actors.Add(new HoneyActor(female)); } VRLog.Info("Found {0} chars", _Actors.Count); } public override IEnumerable<IActor> Actors { get { return _Actors; } } } }
using Manager; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; using VRGIN.Core; using VRGIN.Helpers; using System.Linq; namespace HoneySelectVR { internal class HoneyInterpreter : GameInterpreter { public HScene Scene; private IList<HoneyActor> _Actors = new List<HoneyActor>(); protected override void OnLevel(int level) { base.OnLevel(level); Scene = GameObject.FindObjectOfType<HScene>(); StartCoroutine(DelayedInit()); } protected override void OnUpdate() { base.OnUpdate(); } IEnumerator DelayedInit() { var scene = Singleton<Scene>.Instance; if (!scene) VRLog.Error("No scene"); while(scene.IsNowLoading) { yield return null; } foreach(var actor in GameObject.FindObjectsOfType<CharInfo>()) { _Actors.Add(new HoneyActor(actor)); } _Actors = _Actors.OrderBy(a => a.Actor.Sex).ToList(); VRLog.Info("Found {0} chars", _Actors.Count); } public override IEnumerable<IActor> Actors { get { return _Actors.Cast<IActor>(); } } } }
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
Add instructions for using UITest REPL.
using System; using System.IO; using System.Linq; using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.Queries; namespace MyTrips.UITests { [TestFixture(Platform.iOS)] public class Tests { IApp app; Platform platform; public Tests(Platform platform) { this.platform = platform; } [SetUp] public void BeforeEachTest() { app = AppInitializer.StartApp(platform); } [Test] public void Repl() { app.Repl (); } } }
using System; using System.IO; using System.Linq; using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.Queries; namespace MyTrips.UITests { [TestFixture(Platform.iOS)] public class Tests { IApp app; Platform platform; public Tests(Platform platform) { this.platform = platform; } [SetUp] public void BeforeEachTest() { app = AppInitializer.StartApp(platform); } // If you would like to play around with the Xamarin.UITest REPL // uncomment out this method, and run this test with the NUnit test runner. // [Test] // public void Repl() // { // app.Repl (); // } } }
Enable setters and initialize lists from constructor (again)
using System; using System.Collections.Generic; namespace Arkivverket.Arkade.Core { public class ArchiveMetadata { public string ArchiveDescription { get; set; } public string AgreementNumber { get; set; } public List<MetadataEntityInformationUnit> ArchiveCreators { get; } = new List<MetadataEntityInformationUnit>(); public MetadataEntityInformationUnit Transferer { get; set; } public MetadataEntityInformationUnit Producer { get; set; } public List<MetadataEntityInformationUnit> Owners { get; } = new List<MetadataEntityInformationUnit>(); public string Recipient { get; set; } public MetadataSystemInformationUnit System { get; set; } public MetadataSystemInformationUnit ArchiveSystem { get; set; } public List<string> Comments { get; } = new List<string>(); public string History { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public DateTime ExtractionDate { get; set; } public string IncommingSeparator { get; set; } public string OutgoingSeparator { get; set; } } public class MetadataEntityInformationUnit { public string Entity { get; set; } public string ContactPerson { get; set; } public string Telephone { get; set; } public string Email { get; set; } } public class MetadataSystemInformationUnit { public string Name { get; set; } public string Version { get; set; } public string Type { get; set; } public string TypeVersion { get; set; } } }
using System; using System.Collections.Generic; namespace Arkivverket.Arkade.Core { public class ArchiveMetadata { public string ArchiveDescription { get; set; } public string AgreementNumber { get; set; } public List<MetadataEntityInformationUnit> ArchiveCreators { get; set; } public MetadataEntityInformationUnit Transferer { get; set; } public MetadataEntityInformationUnit Producer { get; set; } public List<MetadataEntityInformationUnit> Owners { get; set; } public string Recipient { get; set; } public MetadataSystemInformationUnit System { get; set; } public MetadataSystemInformationUnit ArchiveSystem { get; set; } public List<string> Comments { get; set; } public string History { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public DateTime ExtractionDate { get; set; } public string IncommingSeparator { get; set; } public string OutgoingSeparator { get; set; } public ArchiveMetadata() { ArchiveCreators = new List<MetadataEntityInformationUnit>(); Owners = new List<MetadataEntityInformationUnit>(); Comments = new List<string>(); } } public class MetadataEntityInformationUnit { public string Entity { get; set; } public string ContactPerson { get; set; } public string Telephone { get; set; } public string Email { get; set; } } public class MetadataSystemInformationUnit { public string Name { get; set; } public string Version { get; set; } public string Type { get; set; } public string TypeVersion { get; set; } } }
Add collection resolver to container
using System; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; namespace AppHarbor { public class AppHarborInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Component .For<AppHarborApi>()); container.Register(Component .For<AuthInfo>() .UsingFactoryMethod(x => { var token = Environment.GetEnvironmentVariable("AppHarborToken", EnvironmentVariableTarget.User); return new AuthInfo { AccessToken = token }; })); container.Register(Component .For<CommandDispatcher>()); } } }
using System; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using Castle.MicroKernel.Resolvers.SpecializedResolvers; namespace AppHarbor { public class AppHarborInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel)); container.Register(Component .For<AppHarborApi>()); container.Register(Component .For<AuthInfo>() .UsingFactoryMethod(x => { var token = Environment.GetEnvironmentVariable("AppHarborToken", EnvironmentVariableTarget.User); return new AuthInfo { AccessToken = token }; })); container.Register(Component .For<CommandDispatcher>()); } } }
Fix Azure host silo startup
using System; using Conreign.Cluster; using Microsoft.WindowsAzure.ServiceRuntime; using Orleans.Runtime.Configuration; using Orleans.Runtime.Host; namespace Conreign.Host.Azure { public class SiloRole : RoleEntryPoint { private AzureSilo _silo; public override void Run() { var env = RoleEnvironment.GetConfigurationSettingValue("Environment"); if (string.IsNullOrEmpty(env)) { throw new InvalidOperationException("Unable to determine environment."); } var config = ConreignSiloConfiguration.Load(Environment.CurrentDirectory, env); var orleansConfiguration = new ClusterConfiguration(); orleansConfiguration.Globals.DeploymentId = RoleEnvironment.DeploymentId; var conreignSilo = ConreignSilo.Configure(orleansConfiguration, config); _silo = new AzureSilo(); var started = _silo.Start(conreignSilo.OrleansConfiguration, conreignSilo.Configuration.SystemStorageConnectionString); if (!started) { throw new InvalidOperationException("Silo was not started."); } conreignSilo.Initialize(); _silo.Run(); } public override void OnStop() { _silo.Stop(); base.OnStop(); } } }
using System; using Conreign.Cluster; using Microsoft.WindowsAzure.ServiceRuntime; using Orleans.Runtime.Configuration; using Orleans.Runtime.Host; namespace Conreign.Host.Azure { public class SiloRole : RoleEntryPoint { private AzureSilo _silo; public override void Run() { var env = RoleEnvironment.GetConfigurationSettingValue("Environment"); if (string.IsNullOrEmpty(env)) { throw new InvalidOperationException("Unable to determine environment."); } var config = ConreignSiloConfiguration.Load(Environment.CurrentDirectory, env); var orleansConfiguration = new ClusterConfiguration(); orleansConfiguration.Globals.DeploymentId = RoleEnvironment.DeploymentId; var conreignSilo = ConreignSilo.Configure(orleansConfiguration, config); _silo = new AzureSilo(); var started = _silo.Start(conreignSilo.OrleansConfiguration, conreignSilo.Configuration.SystemStorageConnectionString); if (!started) { throw new InvalidOperationException("Silo was not started."); } _silo.Run(); } public override void OnStop() { _silo.Stop(); base.OnStop(); } } }
Write PBoolean and PInteger values.
#region License /********************************************************************************* * CompactSettingWriter.cs * * Copyright (c) 2004-2018 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *********************************************************************************/ #endregion using System.Text; namespace Sandra.UI.WF.Storage { /// <summary> /// Used by <see cref="AutoSave"/> to convert a <see cref="PMap"/> to its compact representation in JSON. /// </summary> internal class CompactSettingWriter : PValueVisitor { private readonly StringBuilder outputBuilder = new StringBuilder(); public string Output() => outputBuilder.ToString(); } }
#region License /********************************************************************************* * CompactSettingWriter.cs * * Copyright (c) 2004-2018 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *********************************************************************************/ #endregion using System.Globalization; using System.Text; namespace Sandra.UI.WF.Storage { /// <summary> /// Used by <see cref="AutoSave"/> to convert a <see cref="PMap"/> to its compact representation in JSON. /// </summary> internal class CompactSettingWriter : PValueVisitor { private readonly StringBuilder outputBuilder = new StringBuilder(); public override void VisitBoolean(PBoolean value) => outputBuilder.Append(value.Value ? JsonValue.True : JsonValue.False); public override void VisitInteger(PInteger value) => outputBuilder.Append(value.Value.ToString(CultureInfo.InvariantCulture)); public string Output() => outputBuilder.ToString(); } }
Include timestamp in generated logs
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="SonarSource SA and Microsoft Corporation"> // (c) SonarSource SA and Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Sonar.Common; namespace SonarProjectPropertiesGenerator { public class Program { public static int Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Expected to be called with exactly 4 arguments:"); Console.WriteLine(" 1) SonarQube Project Key"); Console.WriteLine(" 2) SonarQube Project Name"); Console.WriteLine(" 3) SonarQube Project Version"); Console.WriteLine(" 4) Dump folder path"); return 1; } var dumpFolderPath = args[3]; var projects = ProjectLoader.LoadFrom(dumpFolderPath); var contents = PropertiesWriter.ToString(new ConsoleLogger(), args[0], args[1], args[2], projects); File.WriteAllText(Path.Combine(dumpFolderPath, "sonar-project.properties"), contents, Encoding.ASCII); return 0; } } }
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="SonarSource SA and Microsoft Corporation"> // (c) SonarSource SA and Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Sonar.Common; namespace SonarProjectPropertiesGenerator { public class Program { public static int Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Expected to be called with exactly 4 arguments:"); Console.WriteLine(" 1) SonarQube Project Key"); Console.WriteLine(" 2) SonarQube Project Name"); Console.WriteLine(" 3) SonarQube Project Version"); Console.WriteLine(" 4) Dump folder path"); return 1; } var dumpFolderPath = args[3]; var projects = ProjectLoader.LoadFrom(dumpFolderPath); var contents = PropertiesWriter.ToString(new ConsoleLogger(includeTimestamp: true), args[0], args[1], args[2], projects); File.WriteAllText(Path.Combine(dumpFolderPath, "sonar-project.properties"), contents, Encoding.ASCII); return 0; } } }
Increase node agent version in preperation for the release
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Stratis.Bitcoin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Stratis.Bitcoin")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")] // 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.5.0")] [assembly: AssemblyFileVersion("1.0.5.0")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Stratis.Bitcoin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Stratis.Bitcoin")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")] // 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.7.0")] [assembly: AssemblyFileVersion("1.0.7.0")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
Fix unit tests, not sure why file paths have changed?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using AxeSoftware.Quest; namespace EditorControllerTests { [TestClass] public class TemplateTests { [TestMethod] public void TestTemplates() { string folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Substring(6).Replace("/", @"\"); string templateFolder = System.IO.Path.Combine(folder, @"..\..\..\WorldModel\WorldModel\Core"); Dictionary<string, string> templates = EditorController.GetAvailableTemplates(templateFolder); foreach (string template in templates.Values) { string tempFile = System.IO.Path.GetTempFileName(); EditorController.CreateNewGameFile(tempFile, template, "Test"); EditorController controller = new EditorController(); string errorsRaised = string.Empty; controller.ShowMessage += (string message) => { errorsRaised += message; }; bool result = controller.Initialise(tempFile, templateFolder); Assert.IsTrue(result, string.Format("Initialisation failed for template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised)); Assert.AreEqual(0, errorsRaised.Length, string.Format("Error loading game with template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised)); System.IO.File.Delete(tempFile); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using AxeSoftware.Quest; namespace EditorControllerTests { [TestClass] public class TemplateTests { [TestMethod] public void TestTemplates() { string folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Substring(6).Replace("/", @"\"); string templateFolder = System.IO.Path.Combine(folder, @"..\..\..\..\WorldModel\WorldModel\Core"); Dictionary<string, string> templates = EditorController.GetAvailableTemplates(templateFolder); foreach (string template in templates.Values) { string tempFile = System.IO.Path.GetTempFileName(); EditorController.CreateNewGameFile(tempFile, template, "Test"); EditorController controller = new EditorController(); string errorsRaised = string.Empty; controller.ShowMessage += (string message) => { errorsRaised += message; }; bool result = controller.Initialise(tempFile, templateFolder); Assert.IsTrue(result, string.Format("Initialisation failed for template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised)); Assert.AreEqual(0, errorsRaised.Length, string.Format("Error loading game with template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised)); System.IO.File.Delete(tempFile); } } } }
Put download stream in using statement (doesn't seem to have any effect though).
using System.IO; using System.Threading.Tasks; namespace TestCaseAutomator.TeamFoundation { /// <summary> /// Represents a TFS source controlled file. /// </summary> public class TfsFile : TfsSourceControlledItem { /// <summary> /// Initializes a new <see cref="TfsFile"/>. /// </summary> /// <param name="fileItem">The source controlled file</param> /// <param name="versionControl">TFS source control</param> public TfsFile(IVersionedItem fileItem, IVersionControl versionControl) : base(fileItem, versionControl) { } /// <summary> /// Downloads a file to a given file path. /// </summary> /// <param name="path">The local path to download to</param> public async Task DownloadToAsync(string path) { var downloadStream = Download(); var directoryPath = Path.GetDirectoryName(path); if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); using (var fileStream = File.OpenWrite(path)) await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false); } } }
using System.IO; using System.Threading.Tasks; namespace TestCaseAutomator.TeamFoundation { /// <summary> /// Represents a TFS source controlled file. /// </summary> public class TfsFile : TfsSourceControlledItem { /// <summary> /// Initializes a new <see cref="TfsFile"/>. /// </summary> /// <param name="fileItem">The source controlled file</param> /// <param name="versionControl">TFS source control</param> public TfsFile(IVersionedItem fileItem, IVersionControl versionControl) : base(fileItem, versionControl) { } /// <summary> /// Downloads a file to a given file path. /// </summary> /// <param name="path">The local path to download to</param> public async Task DownloadToAsync(string path) { var directoryPath = Path.GetDirectoryName(path); if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); using (var downloadStream = Download()) using (var fileStream = File.OpenWrite(path)) await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false); } } }
Set the DB Context to rebuild database when a model change is detected. Dangerous times for data =O
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace MakerFarm.Models { public class MakerfarmDBContext : DbContext { public MakerfarmDBContext() : base("DefaultConnection") { //Database.SetInitializer<MakerfarmDBContext>(new DropCreateDatabaseIfModelChanges<MakerfarmDBContext>()); } public DbSet<PrinterType> PrinterTypes { get; set; } public DbSet<PrintEvent> PrintEvents { get; set; } public DbSet<Print> Prints { get; set; } public DbSet<Material> Materials { get; set; } public DbSet<UserProfile> UserProfiles { get; set; } public DbSet<PrintErrorType> PrintErrorTypes { get; set; } public DbSet<Printer> Printers { get; set; } public DbSet<PrinterStatusLog> PrinterStatusLogs { set; get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace MakerFarm.Models { public class MakerfarmDBContext : DbContext { public MakerfarmDBContext() : base("DefaultConnection") { Database.SetInitializer<MakerfarmDBContext>(new DropCreateDatabaseIfModelChanges<MakerfarmDBContext>()); } public DbSet<PrinterType> PrinterTypes { get; set; } public DbSet<PrintEvent> PrintEvents { get; set; } public DbSet<Print> Prints { get; set; } public DbSet<Material> Materials { get; set; } public DbSet<UserProfile> UserProfiles { get; set; } public DbSet<PrintErrorType> PrintErrorTypes { get; set; } public DbSet<Printer> Printers { get; set; } public DbSet<PrinterStatusLog> PrinterStatusLogs { set; get; } } }
Change intro test to test full intro screen
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Timing; using osu.Game.Screens.Menu; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Menus { [TestFixture] public class TestSceneIntroSequence : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(OsuLogo), }; public TestSceneIntroSequence() { OsuLogo logo; var rateAdjustClock = new StopwatchClock(true); var framedClock = new FramedClock(rateAdjustClock); framedClock.ProcessFrame(); Add(new Container { RelativeSizeAxes = Axes.Both, Clock = framedClock, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, logo = new OsuLogo { Anchor = Anchor.Centre, } } }); AddStep(@"Restart", logo.PlayIntro); AddSliderStep("Playback speed", 0.0, 2.0, 1, v => rateAdjustClock.Rate = v); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Timing; using osu.Game.Screens; using osu.Game.Screens.Menu; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Menus { [TestFixture] public class TestSceneIntroSequence : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(OsuLogo), typeof(Intro), typeof(StartupScreen), typeof(OsuScreen) }; [Cached] private OsuLogo logo; public TestSceneIntroSequence() { var rateAdjustClock = new StopwatchClock(true); var framedClock = new FramedClock(rateAdjustClock); framedClock.ProcessFrame(); Add(new Container { RelativeSizeAxes = Axes.Both, Clock = framedClock, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, new OsuScreenStack(new Intro()) { RelativeSizeAxes = Axes.Both, }, logo = new OsuLogo { Anchor = Anchor.Centre, }, } }); AddSliderStep("Playback speed", 0.0, 2.0, 1, v => rateAdjustClock.Rate = v); } } }
Use EndsWith - nicer than LastIndexOf...
using System; using System.Linq; public class Bob { public string Hey(string input) { if (IsSilence(input)) { return "Fine. Be that way!"; } else if (IsShouting(input)) { return "Whoa, chill out!"; } else if (IsQuestion(input)) { return "Sure."; } else { return "Whatever."; } } private bool IsSilence(string input) { return input.Trim().Length == 0; } private bool IsQuestion(string input) { // last character is a question mark, ignoring trailing spaces input = input.Trim(); return input.LastIndexOf('?') == input.Length - 1; } private bool IsShouting(string input) { // has at least 1 character, and all upper case var alphas = input.Where(char.IsLetter); return alphas.Any() && alphas.All(char.IsUpper); } }
using System.Linq; public class Bob { public string Hey(string input) { if (IsSilence(input)) { return "Fine. Be that way!"; } else if (IsShouting(input)) { return "Whoa, chill out!"; } else if (IsQuestion(input)) { return "Sure."; } else { return "Whatever."; } } private bool IsSilence(string input) { return input.Trim().Length == 0; } private bool IsQuestion(string input) { // last character is a question mark, ignoring trailing spaces return input.Trim().EndsWith("?"); } private bool IsShouting(string input) { // has at least 1 character, and all upper case var alphas = input.Where(char.IsLetter); return alphas.Any() && alphas.All(char.IsUpper); } }
Update logging service area name
using Microsoft.SharePoint.Administration; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SPMin { public class SPMinLoggingService : SPDiagnosticsServiceBase { private static string AreaName = "Mavention"; private static SPMinLoggingService _instance; public static SPMinLoggingService Current { get { if (_instance == null) _instance = new SPMinLoggingService(); return _instance; } } private SPMinLoggingService() : base("SPMin Logging Service", SPFarm.Local) { } protected override IEnumerable<SPDiagnosticsArea> ProvideAreas() { List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea> { new SPDiagnosticsArea(AreaName, new List<SPDiagnosticsCategory> { new SPDiagnosticsCategory("SPMin", TraceSeverity.Unexpected, EventSeverity.Error) }) }; return areas; } public static void LogError(string errorMessage, TraceSeverity traceSeverity) { SPDiagnosticsCategory category = Current.Areas[AreaName].Categories["SPMin"]; Current.WriteTrace(0, category, traceSeverity, errorMessage); } } }
using Microsoft.SharePoint.Administration; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SPMin { public class SPMinLoggingService : SPDiagnosticsServiceBase { private static string AreaName = "SPMin"; private static SPMinLoggingService _instance; public static SPMinLoggingService Current { get { if (_instance == null) _instance = new SPMinLoggingService(); return _instance; } } private SPMinLoggingService() : base("SPMin Logging Service", SPFarm.Local) { } protected override IEnumerable<SPDiagnosticsArea> ProvideAreas() { List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea> { new SPDiagnosticsArea(AreaName, new List<SPDiagnosticsCategory> { new SPDiagnosticsCategory("SPMin", TraceSeverity.Unexpected, EventSeverity.Error) }) }; return areas; } public static void LogError(string errorMessage, TraceSeverity traceSeverity) { SPDiagnosticsCategory category = Current.Areas[AreaName].Categories["SPMin"]; Current.WriteTrace(0, category, traceSeverity, errorMessage); } } }
Add points to front and only add if moved a little bit
using System.Collections; using UnityEngine; namespace TrailAdvanced.PointSource { public class ObjectPointSource : AbstractPointSource { public Transform objectToFollow; protected override void Update() { base.Update(); points.AddToBack(objectToFollow.position); } } }
using System.Collections; using UnityEngine; namespace TrailAdvanced.PointSource { public class ObjectPointSource : AbstractPointSource { public Transform objectToFollow; private Vector3 _lastPosition; protected override void Start() { base.Start(); _lastPosition = objectToFollow.position; } protected override void Update() { base.Update(); float distance = Vector3.SqrMagnitude(objectToFollow.position - _lastPosition); if (distance > 0.0001f) { points.AddToFront(objectToFollow.position); } _lastPosition = objectToFollow.position; } } }
Handle parenthese in method name.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SourceBrowser.Search.ViewModels { public struct TokenViewModel { public string Id { get; } public string Path { get; } public string Username { get; } public string Repository { get; } public string FullName { get; } public string Name { get { if (FullName == null) return null; var splitName = FullName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); return splitName.Last(); } } public int LineNumber { get; } public TokenViewModel(string username, string repository, string path, string fullName, int lineNumber) { Id = System.IO.Path.Combine(username, repository, fullName); Username = username; Repository = repository; Path = path; FullName = fullName; LineNumber = lineNumber; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SourceBrowser.Search.ViewModels { public struct TokenViewModel { public string Id { get; } public string Path { get; } public string Username { get; } public string Repository { get; } public string FullName { get; } public string Name { get { if (FullName == null) return null; string currentName = FullName; var parensIndex = FullName.IndexOf("("); if(parensIndex != -1) { currentName = currentName.Remove(parensIndex, currentName.Length - parensIndex); } var splitName = currentName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); return splitName.Last(); } } public int LineNumber { get; } public TokenViewModel(string username, string repository, string path, string fullName, int lineNumber) { Id = username + "/" + repository + "/" + fullName; Username = username; Repository = repository; Path = path; FullName = fullName; LineNumber = lineNumber; } } }
Change way how benchmarks are discovered/executed
using System; using BenchmarkDotNet.Running; namespace LanguageExt.Benchmarks { class Program { static void Main(string[] args) { var summary1 = BenchmarkRunner.Run<HashMapAddBenchmark>(); Console.Write(summary1); var summary2 = BenchmarkRunner.Run<HashMapRandomReadBenchmark>(); Console.Write(summary2); } } }
using BenchmarkDotNet.Running; namespace LanguageExt.Benchmarks { class Program { static void Main(string[] args) => BenchmarkSwitcher .FromAssembly(typeof(Program).Assembly) .Run(args); } }
Fix default schema rule message.
using System.Collections.Generic; namespace Dictator { public class Rule { public string FieldPath { get; set; } public Constraint Constraint { get; set; } public List<object> Parameters { get; set; } public bool IsViolated { get; set; } public string Message { get; set; } public Rule() { Parameters = new List<object>(); Message = string.Format("Field '{0}' violated '{1}' constraint rule.", FieldPath, Constraint); } } }
using System.Collections.Generic; namespace Dictator { public class Rule { string _message = null; public string FieldPath { get; set; } public Constraint Constraint { get; set; } public List<object> Parameters { get; set; } public bool IsViolated { get; set; } public string Message { get { if (_message == null) { return string.Format("Field '{0}' violated '{1}' constraint rule.", FieldPath, Constraint); } return _message; } set { _message = value; } } public Rule() { Parameters = new List<object>(); } } }
Rename queue to stack to reflect its actual type
using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Abc.NCrafts.Quizz.Performance.Questions._021 { public class Answer2 { public static void Run() { var queue = new ConcurrentStack<int>(); // begin var producer = Task.Run(() => { foreach (var value in Enumerable.Range(1, 10000)) { queue.Push(value); } }); var consumer = Task.Run(() => { var spinWait = new SpinWait(); var value = 0; while (value != 10000) { if (!queue.TryPop(out value)) { spinWait.SpinOnce(); continue; } Logger.Log("Value: {0}", value); } }); Task.WaitAll(producer, consumer); // end } } }
using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Abc.NCrafts.Quizz.Performance.Questions._021 { public class Answer2 { public static void Run() { var stack = new ConcurrentStack<int>(); // begin var producer = Task.Run(() => { foreach (var value in Enumerable.Range(1, 10000)) { stack.Push(value); } }); var consumer = Task.Run(() => { var spinWait = new SpinWait(); var value = 0; while (value != 10000) { if (!stack.TryPop(out value)) { spinWait.SpinOnce(); continue; } Logger.Log("Value: {0}", value); } }); Task.WaitAll(producer, consumer); // end } } }
Modify routing initialization logic to pass test case.
namespace Nancy.AttributeRouting { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nancy.Bootstrapper; using Nancy.TinyIoc; /// <inheritdoc/> public class AttributeRoutingRegistration : IRegistrations { static AttributeRoutingRegistration() { IEnumerable<MethodBase> methods = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(assembly => assembly.SafeGetTypes()) .Where(type => !type.IsAbstract && (type.IsPublic || type.IsNestedPublic)) .SelectMany(GetMethodsWithRouteAttribute); foreach (MethodBase method in methods) { AttributeRoutingResolver.Routings.Register(method); } } /// <inheritdoc/> public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get { return null; } } /// <inheritdoc/> public IEnumerable<InstanceRegistration> InstanceRegistrations { get { return null; } } /// <inheritdoc/> public IEnumerable<TypeRegistration> TypeRegistrations { get { yield return new TypeRegistration(typeof(IUrlBuilder), typeof(UrlBuilder)); } } private static IEnumerable<MethodBase> GetMethodsWithRouteAttribute(Type type) { IEnumerable<MethodBase> methods = type .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(HasRouteAttribute); return methods; } private static bool HasRouteAttribute(MethodBase method) { return method.GetCustomAttributes<RouteAttribute>().Any(); } } }
namespace Nancy.AttributeRouting { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nancy.Bootstrapper; using Nancy.TinyIoc; /// <inheritdoc/> public class AttributeRoutingRegistration : IRegistrations { static AttributeRoutingRegistration() { IEnumerable<MethodBase> methods = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(assembly => assembly.SafeGetTypes()) .Where(DoesSupportType) .SelectMany(GetMethodsWithRouteAttribute); foreach (MethodBase method in methods) { AttributeRoutingResolver.Routings.Register(method); } } /// <inheritdoc/> public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get { return null; } } /// <inheritdoc/> public IEnumerable<InstanceRegistration> InstanceRegistrations { get { return null; } } /// <inheritdoc/> public IEnumerable<TypeRegistration> TypeRegistrations { get { yield return new TypeRegistration(typeof(IUrlBuilder), typeof(UrlBuilder)); } } private static IEnumerable<MethodBase> GetMethodsWithRouteAttribute(Type type) { IEnumerable<MethodBase> methods = type .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(HasRouteAttribute); return methods; } private static bool HasRouteAttribute(MethodBase method) { return method.GetCustomAttributes<RouteAttribute>().Any(); } private static bool DoesSupportType(Type type) { if (type.IsInterface) { return true; } else if (!type.IsAbstract && (type.IsPublic || type.IsNestedPublic)) { return true; } else { return false; } } } }
Fix shadow bug with mines exploding
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; [RequireComponent(typeof(SpriteRenderer))] public class SpriteShadow : MonoBehaviour { public Sprite ShadowSprite; public float ShadowDist = 0.1f; public bool UseParentSpr = true; public Transform MyTr { get; private set; } public SpriteRenderer MySpr { get; private set; } public SpriteRenderer ParentSpr { get; private set; } private void Awake() { MyTr = transform; ParentSpr = MyTr.parent.GetComponent<SpriteRenderer>(); MySpr = GetComponent<SpriteRenderer>(); } private void LateUpdate() { Vector2 lightDir = ((Vector2)Water.Instance.LightDir).normalized; MyTr.position = MyTr.parent.position - (Vector3)(lightDir * ShadowDist); if (UseParentSpr) ShadowSprite = ParentSpr.sprite; MySpr.sprite = ShadowSprite; } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; [RequireComponent(typeof(SpriteRenderer))] public class SpriteShadow : MonoBehaviour { public Sprite ShadowSprite; public float ShadowDist = 0.1f; public bool UseParentSpr = true; public Transform MyTr { get; private set; } public SpriteRenderer MySpr { get; private set; } public SpriteRenderer ParentSpr { get; private set; } private void Awake() { MyTr = transform; ParentSpr = MyTr.parent.GetComponent<SpriteRenderer>(); MySpr = GetComponent<SpriteRenderer>(); } private void LateUpdate() { if (!ParentSpr.enabled) { MySpr.enabled = false; return; } Vector2 lightDir = ((Vector2)Water.Instance.LightDir).normalized; MyTr.position = MyTr.parent.position - (Vector3)(lightDir * ShadowDist); if (UseParentSpr) ShadowSprite = ParentSpr.sprite; MySpr.sprite = ShadowSprite; } }
Use sbyte in integer index
namespace Codestellation.Pulsar.Cron { public struct IntegerIndex { public const int NotFound = -1; private readonly int[] _indexArray; public IntegerIndex(SimpleCronField field) { _indexArray = new int[field.Settings.MaxValue + 1]; for (int i = 0; i < _indexArray.Length; i++) { _indexArray[i] = NotFound; } foreach (var value in field.Values) { _indexArray[value] = value; } int next = NotFound; for (int i = _indexArray.Length - 1; i >= 0; i--) { var val = _indexArray[i]; if (val != NotFound) { next = val; } _indexArray[i] = next; } } public int GetValue(int value) { return _indexArray[value]; } } }
namespace Codestellation.Pulsar.Cron { public struct IntegerIndex { public const sbyte NotFound = -1; private readonly sbyte[] _indexArray; public IntegerIndex(SimpleCronField field) { _indexArray = new sbyte[field.Settings.MaxValue + 1]; for (int i = 0; i < _indexArray.Length; i++) { _indexArray[i] = NotFound; } foreach (var value in field.Values) { _indexArray[value] = (sbyte)value; } int next = NotFound; for (int i = _indexArray.Length - 1; i >= 0; i--) { var val = _indexArray[i]; if (val != NotFound) { next = val; } _indexArray[i] = (sbyte)next; } } public int GetValue(int value) { return _indexArray[value]; } } }
Increment version number to 1.3.5.1
namespace formulate.meta { /// <summary> /// Constants relating to Formulate itself (i.e., does not /// include constants used by Formulate). /// </summary> public class Constants { /// <summary> /// This is the version of Formulate. It is used on /// assemblies and during the creation of the /// installer package. /// </summary> /// <remarks> /// Do not reformat this code. A grunt task reads this /// version number with a regular expression. /// </remarks> public const string Version = "1.3.5.0"; /// <summary> /// The name of the Formulate package. /// </summary> public const string PackageName = "Formulate"; /// <summary> /// The name of the Formulate package, in camel case. /// </summary> public const string PackageNameCamelCase = "formulate"; } }
namespace formulate.meta { /// <summary> /// Constants relating to Formulate itself (i.e., does not /// include constants used by Formulate). /// </summary> public class Constants { /// <summary> /// This is the version of Formulate. It is used on /// assemblies and during the creation of the /// installer package. /// </summary> /// <remarks> /// Do not reformat this code. A grunt task reads this /// version number with a regular expression. /// </remarks> public const string Version = "1.3.5.1"; /// <summary> /// The name of the Formulate package. /// </summary> public const string PackageName = "Formulate"; /// <summary> /// The name of the Formulate package, in camel case. /// </summary> public const string PackageNameCamelCase = "formulate"; } }
Make tab colors work and stuff
@using StackExchange.Opserver.Models @using StackExchange.Profiling @{ Layout = null; } @helper RenderTab(TopTab tab) { if (tab.IsEnabled) { // Optimism! using (MiniProfiler.Current.Step("Render Tab: " + tab.Name)) { var status = tab.GetMonitorStatus?.Invoke() ?? MonitorStatus.Good; var badgeCount = tab.GetBadgeCount?.Invoke(); <li class="@(tab.IsCurrentTab ? "active" : null)"> <a class="@(status.TextClass())" href="@tab.Url" title="@(tab.GetTooltip?.Invoke())"> @tab.Name @if (badgeCount > 0) { <span class="badge" data-name="@tab.Name">@badgeCount.ToComma()</span> } </a> </li> } } } @if (!TopTabs.HideAll) { using (MiniProfiler.Current.Step("TopTabs")) { <ul class="nav navbar-nav navbar-right js-top-tabs"> @foreach (var tab in TopTabs.Tabs.Values) { @RenderTab(tab) } </ul> } }
@using StackExchange.Opserver.Models @using StackExchange.Profiling @{ Layout = null; } @helper RenderTab(TopTab tab) { if (tab.IsEnabled) { // Optimism! using (MiniProfiler.Current.Step("Render Tab: " + tab.Name)) { var status = tab.GetMonitorStatus?.Invoke() ?? MonitorStatus.Good; var badgeCount = tab.GetBadgeCount?.Invoke(); <li class="@(tab.IsCurrentTab ? "active" : null)"> <a href="@tab.Url" title="@(tab.GetTooltip?.Invoke())"> <span class="@(status.TextClass())">@tab.Name</span> @if (badgeCount > 0) { <span class="badge" data-name="@tab.Name">@badgeCount.ToComma()</span> } </a> </li> } } } @if (!TopTabs.HideAll) { using (MiniProfiler.Current.Step("TopTabs")) { <ul class="nav navbar-nav navbar-right js-top-tabs"> @foreach (var tab in TopTabs.Tabs.Values) { @RenderTab(tab) } </ul> } }
Fix EnablePart is not threadsafe
using System; using System.Collections.Generic; namespace MuffinFramework { public abstract class LayerBase<TArgs> : ILayerBase<TArgs> { private readonly object _lockObj = new object(); private readonly List<ILayerBase<TArgs>> _parts = new List<ILayerBase<TArgs>>(); private TArgs _args; public bool IsEnabled { get; private set; } public virtual void Enable(TArgs args) { lock (this._lockObj) { if (this.IsEnabled) throw new InvalidOperationException("LayerBase has already been enabled."); this.IsEnabled = true; } this._args = args; this.Enable(); } protected abstract void Enable(); protected TPart EnablePart<TPart, TProtocol>(TProtocol host) where TPart : class, ILayerPart<TProtocol, TArgs>, new() { var part = new TPart(); part.Enable(host, this._args); this._parts.Add(part); return part; } protected TPart EnablePart<TPart, TProtocol>() where TPart : class, ILayerPart<TProtocol, TArgs>, new() { var host = (TProtocol) (object) this; return this.EnablePart<TPart, TProtocol>(host); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposing) return; foreach (var part in this._parts) { part.Dispose(); } } } }
using System; using System.Collections.Generic; namespace MuffinFramework { public abstract class LayerBase<TArgs> : ILayerBase<TArgs> { private readonly object _lockObj = new object(); private readonly List<ILayerBase<TArgs>> _parts = new List<ILayerBase<TArgs>>(); private TArgs _args; public bool IsEnabled { get; private set; } public virtual void Enable(TArgs args) { lock (this._lockObj) { if (this.IsEnabled) throw new InvalidOperationException("LayerBase has already been enabled."); this.IsEnabled = true; } this._args = args; this.Enable(); } protected abstract void Enable(); protected TPart EnablePart<TPart, TProtocol>(TProtocol host) where TPart : class, ILayerPart<TProtocol, TArgs>, new() { var part = new TPart(); part.Enable(host, this._args); lock (this._lockObj) { this._parts.Add(part); } return part; } protected TPart EnablePart<TPart, TProtocol>() where TPart : class, ILayerPart<TProtocol, TArgs>, new() { var host = (TProtocol) (object) this; return this.EnablePart<TPart, TProtocol>(host); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposing) return; ILayerBase<TArgs>[] parts; lock (this._lockObj) { parts = this._parts.ToArray(); } foreach (var part in parts) { part.Dispose(); } } } }
Disable tinting option on iOS
using CrossPlatformTintedImage; using CrossPlatformTintedImage.iOS; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly:ExportRendererAttribute(typeof(TintedImage), typeof(TintedImageRenderer))] namespace CrossPlatformTintedImage.iOS { public class TintedImageRenderer : ImageRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Image> e) { base.OnElementChanged(e); SetTint(); } protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == TintedImage.TintColorProperty.PropertyName) SetTint(); } void SetTint() { if (Control?.Image != null && Element != null) { Control.Image = Control.Image.ImageWithRenderingMode(UIKit.UIImageRenderingMode.AlwaysTemplate); Control.TintColor = ((TintedImage) Element).TintColor.ToUIColor(); } } } }
using CrossPlatformTintedImage; using CrossPlatformTintedImage.iOS; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly:ExportRendererAttribute(typeof(TintedImage), typeof(TintedImageRenderer))] namespace CrossPlatformTintedImage.iOS { public class TintedImageRenderer : ImageRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Image> e) { base.OnElementChanged(e); SetTint(); } protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == TintedImage.TintColorProperty.PropertyName) SetTint(); } void SetTint() { if (Control?.Image == null || Element == null) return; if (((TintedImage)Element).TintColor == Color.Transparent) { //Turn off tinting Control.Image = Control.Image.ImageWithRenderingMode(UIKit.UIImageRenderingMode.Automatic); Control.TintColor = null; } else { //Apply tint color Control.Image = Control.Image.ImageWithRenderingMode(UIKit.UIImageRenderingMode.AlwaysTemplate); Control.TintColor = ((TintedImage)Element).TintColor.ToUIColor(); } } } }
Remove the 'lib' prefix for the native lib.
namespace QtWebKit { using Qyoto; using System; using System.Runtime.InteropServices; public class InitQtWebKit { [DllImport("libqtwebkit-sharp", CharSet=CharSet.Ansi)] static extern void Init_qtwebkit(); public static void InitSmoke() { Init_qtwebkit(); } } }
namespace QtWebKit { using Qyoto; using System; using System.Runtime.InteropServices; public class InitQtWebKit { [DllImport("qtwebkit-sharp", CharSet=CharSet.Ansi)] static extern void Init_qtwebkit(); public static void InitSmoke() { Init_qtwebkit(); } } }
Fix skinned taiko hit explosions not being removed on rewind
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Rulesets.Taiko.Skinning { public class LegacyHitExplosion : CompositeDrawable { public LegacyHitExplosion(Drawable sprite) { InternalChild = sprite; Anchor = Anchor.Centre; Origin = Anchor.Centre; AutoSizeAxes = Axes.Both; } protected override void LoadComplete() { base.LoadComplete(); const double animation_time = 120; this.FadeInFromZero(animation_time).Then().FadeOut(animation_time * 1.5); this.ScaleTo(0.6f) .Then().ScaleTo(1.1f, animation_time * 0.8) .Then().ScaleTo(0.9f, animation_time * 0.4) .Then().ScaleTo(1f, animation_time * 0.2); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Rulesets.Taiko.Skinning { public class LegacyHitExplosion : CompositeDrawable { public LegacyHitExplosion(Drawable sprite) { InternalChild = sprite; Anchor = Anchor.Centre; Origin = Anchor.Centre; AutoSizeAxes = Axes.Both; } protected override void LoadComplete() { base.LoadComplete(); const double animation_time = 120; this.FadeInFromZero(animation_time).Then().FadeOut(animation_time * 1.5); this.ScaleTo(0.6f) .Then().ScaleTo(1.1f, animation_time * 0.8) .Then().ScaleTo(0.9f, animation_time * 0.4) .Then().ScaleTo(1f, animation_time * 0.2); Expire(true); } } }
Fix (from SearchBox): Hotkeys are cleared constantly
using EarTrumpet.Extensions; using System; using System.Windows; using System.Windows.Controls; namespace EarTrumpet.UI.Behaviors { public class TextBoxEx { // ClearText: Clear TextBox or the parent ComboBox. public static bool GetClearText(DependencyObject obj) => (bool)obj.GetValue(ClearTextProperty); public static void SetClearText(DependencyObject obj, bool value) => obj.SetValue(ClearTextProperty, value); public static readonly DependencyProperty ClearTextProperty = DependencyProperty.RegisterAttached("ClearText", typeof(bool), typeof(TextBoxEx), new PropertyMetadata(false, ClearTextChanged)); private static void ClearTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { if ((bool)e.NewValue == true) { var parent = dependencyObject.FindVisualParent<ComboBox>(); if (parent != null) { parent.Text = ""; parent.SelectedItem = null; } else { ((TextBox)dependencyObject).Text = ""; } } } } }
using EarTrumpet.Extensions; using System; using System.Windows; using System.Windows.Controls; namespace EarTrumpet.UI.Behaviors { public class TextBoxEx { // ClearText: Clear TextBox or the parent ComboBox. public static bool GetClearText(DependencyObject obj) => (bool)obj.GetValue(ClearTextProperty); public static void SetClearText(DependencyObject obj, bool value) => obj.SetValue(ClearTextProperty, value); public static readonly DependencyProperty ClearTextProperty = DependencyProperty.RegisterAttached("ClearText", typeof(bool), typeof(TextBoxEx), new PropertyMetadata(false, ClearTextChanged)); private static void ClearTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { if ((bool)e.NewValue == true) { var parent = dependencyObject.FindVisualParent<ComboBox>(); if (parent != null) { parent.Text = ""; parent.SelectedItem = null; } else { // Ignore !IsLoaded to cleverly allow IsPressed=False to be our trigger but also // don't clear TextBoxes when they are initially created. var textBox = ((TextBox)dependencyObject); if (textBox.IsLoaded) { textBox.Text = ""; } } } } } }
Change IViewModelGenerator implementation registration type from Transient to Singleton.
using Microsoft.Extensions.DependencyInjection; namespace MicroNetCore.Rest.Models.ViewModels.Extensions { public static class ConfigurationExtensions { public static IServiceCollection AddViewModels(this IServiceCollection services) { services.AddSingleton<IViewModelTypeProvider, ViewModelTypeProvider>(); services.AddTransient<IViewModelGenerator, ViewModelGenerator>(); return services; } } }
using Microsoft.Extensions.DependencyInjection; namespace MicroNetCore.Rest.Models.ViewModels.Extensions { public static class ConfigurationExtensions { public static IServiceCollection AddViewModels(this IServiceCollection services) { services.AddSingleton<IViewModelTypeProvider, ViewModelTypeProvider>(); services.AddSingleton<IViewModelGenerator, ViewModelGenerator>(); return services; } } }
Add count to loading components logging
// 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.Development; using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Graphics; using osu.Framework.Lists; namespace osu.Framework.Logging { internal static class LoadingComponentsLogger { private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>(); public static void Add(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Add(component); } public static void Remove(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Remove(component); } public static void LogAndFlush() { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) { Logger.Log("⏳ Currently loading components"); foreach (var c in loading_components) Logger.Log($"- {c.GetType().ReadableName(),-16} LoadState:{c.LoadState,-5} Thread:{c.LoadThread.Name}"); loading_components.Clear(); } } } }
// 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 osu.Framework.Development; using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Graphics; using osu.Framework.Lists; namespace osu.Framework.Logging { internal static class LoadingComponentsLogger { private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>(); public static void Add(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Add(component); } public static void Remove(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Remove(component); } public static void LogAndFlush() { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) { Logger.Log($"⏳ Currently loading components ({loading_components.Count()})"); foreach (var c in loading_components) Logger.Log($"- {c.GetType().ReadableName(),-16} LoadState:{c.LoadState,-5} Thread:{c.LoadThread.Name}"); loading_components.Clear(); } } } }
Make sure bootstrapper runs pre application start
using System.Web.Routing; using SignalR; [assembly: WebActivator.PostApplicationStartMethod(typeof(ConsolR.Hosting.Bootstrapper), "PreApplicationStart")] namespace ConsolR.Hosting { public static class Bootstrapper { public static void PreApplicationStart() { var routes = RouteTable.Routes; routes.MapHttpHandler<Handler>("consolr"); routes.MapHttpHandler<Handler>("consolr/validate"); routes.MapConnection<ExecuteEndPoint>("consolr-execute", "consolr/execute/{*operation}"); } } }
using System.Web.Routing; using SignalR; [assembly: WebActivator.PreApplicationStartMethod(typeof(ConsolR.Hosting.Bootstrapper), "PreApplicationStart")] namespace ConsolR.Hosting { public static class Bootstrapper { public static void PreApplicationStart() { var routes = RouteTable.Routes; routes.MapHttpHandler<Handler>("consolr"); routes.MapHttpHandler<Handler>("consolr/validate"); routes.MapConnection<ExecuteEndPoint>("consolr-execute", "consolr/execute/{*operation}"); } } }
Implement all properties for collector settings
namespace SurveyMonkey.RequestSettings { public class CreateCollectorSettings { public enum TypeOption { Weblink, Email } public TypeOption Type { get; set; } public string Name { get; set; } } }
using System; using SurveyMonkey.Containers; namespace SurveyMonkey.RequestSettings { public class CreateCollectorSettings { public Collector.CollectorType Type { get; set; } public string Name { get; set; } public string ThankYouMessage { get; set; } public string DisqualificationMessage { get; set; } public DateTime? CloseDate { get; set; } public string ClosedPageMessage { get; set; } public string RedirectUrl { get; set; } public bool? DisplaySurveyResults { get; set; } public Collector.EditResponseOption? EditResponseType { get; set; } public Collector.AnonymousOption? AnonymousType { get; set; } public bool? AllowMultipleResponses { get; set; } public string Password { get; set; } public string SenderEmail { get; set; } } }
Make some changes by the solution
using System; //Problem 15.* Age after 10 Years //Write a program to read your birthday from the console and print how old you are now and how old you will be after 10 years. class AgeAfter10Years { public static int yearsNow; static void Main(string[] args) { Console.Write("Enter birtday year:"); int birthdayYear = int.Parse(Console.ReadLine()); Console.Write("Month:"); int month = int.Parse(Console.ReadLine()); Console.Write("Day"); int day = int.Parse(Console.ReadLine()); DateTime birthday = new DateTime(birthdayYear, month, day); DateTime now = DateTime.Now; Console.WriteLine(CalculateAge(birthday, now)); Console.WriteLine(Add10Years(yearsNow)); } static int CalculateAge(DateTime birthday, DateTime now) { yearsNow = now.Year - birthday.Year; if (birthday.Month > now.Month) { yearsNow--; } if (birthday.Month == now.Month && birthday.Day > now.Day) { yearsNow--; } return yearsNow; } static int Add10Years(int yearsNow) { int yearsAfter10 = yearsNow + 10; return yearsAfter10; } }
using System; //Problem 15.* Age after 10 Years //Write a program to read your birthday from the console and print how old you are now and how old you will be after 10 years. class AgeAfter10Years { public static int yearsNow; static void Main(string[] args) { Console.Write("Enter birtday year:"); string[] input = Console.ReadLine().Split(new char[] {'.'}, StringSplitOptions.RemoveEmptyEntries); int month = int.Parse(input[0]); int day = int.Parse(input[1]); int birthdayYear = int.Parse(input[2]); Console.WriteLine(day); if (birthdayYear > DateTime.Now.Year) { Console.WriteLine(0); Console.WriteLine(10); } else { DateTime birthday = new DateTime(birthdayYear, month, day); DateTime now = DateTime.Now; Console.WriteLine(CalculateAge(birthday, now)); Console.WriteLine(Add10Years(yearsNow)); } } static int CalculateAge(DateTime birthday, DateTime now) { yearsNow = now.Year - birthday.Year; if (birthday.Month > now.Month) { yearsNow--; } if (birthday.Month == now.Month && birthday.Day > now.Day) { yearsNow--; } return yearsNow; } static int Add10Years(int yearsNow) { int yearsAfter10 = yearsNow + 10; return yearsAfter10; } }
Fix the singleton instance field.
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using TTMouseclickSimulator.Core.Environment; namespace TTMouseclickSimulator.Core.ToontownRewritten.Environment { /// <summary> /// Environment interface for Toontown Rewritten. /// </summary> public class TTRWindowsEnvironment : AbstractWindowsEnvironment { private const string ProcessName = "TTREngine"; public static TTRWindowsEnvironment Instance = new TTRWindowsEnvironment(); private TTRWindowsEnvironment() { } public override Process FindProcess() { return FindProcessByName(ProcessName); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using TTMouseclickSimulator.Core.Environment; namespace TTMouseclickSimulator.Core.ToontownRewritten.Environment { /// <summary> /// Environment interface for Toontown Rewritten. /// </summary> public class TTRWindowsEnvironment : AbstractWindowsEnvironment { private const string ProcessName = "TTREngine"; public static TTRWindowsEnvironment Instance { get; } = new TTRWindowsEnvironment(); private TTRWindowsEnvironment() { } public override Process FindProcess() { return FindProcessByName(ProcessName); } } }
Update file version to 2.2.1.6
using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2017"; public const string Trademark = ""; public const string Version = "2.2.1.5"; } }
using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2017"; public const string Trademark = ""; public const string Version = "2.2.1.6"; } }
Use manual xml parsing for fast start-up
using System.IO; using System.Reflection; using System.Xml.Serialization; namespace IncrementalCompiler { public class Settings { public DebugSymbolFileType DebugSymbolFile; public PrebuiltOutputReuseType PrebuiltOutputReuse; public static Settings Default = new Settings { DebugSymbolFile = DebugSymbolFileType.Mdb, PrebuiltOutputReuse = PrebuiltOutputReuseType.WhenNoChange, }; public static Settings Load() { var fileName = Path.ChangeExtension(Assembly.GetEntryAssembly().Location, ".xml"); if (File.Exists(fileName) == false) return null; using (var stream = new FileStream(fileName, FileMode.Open)) { return Load(stream); } } public static Settings Load(Stream stream) { var deserializer = new XmlSerializer(typeof(Settings)); return (Settings)deserializer.Deserialize(stream); } public static void Save(Stream stream, Settings settings) { var serializer = new XmlSerializer(typeof(Settings)); serializer.Serialize(stream, settings); } } }
using System; using System.IO; using System.Reflection; using System.Xml.Linq; namespace IncrementalCompiler { public class Settings { public DebugSymbolFileType DebugSymbolFile; public PrebuiltOutputReuseType PrebuiltOutputReuse; public static Settings Default = new Settings { DebugSymbolFile = DebugSymbolFileType.Mdb, PrebuiltOutputReuse = PrebuiltOutputReuseType.WhenNoChange, }; public static Settings Load() { var fileName = Path.ChangeExtension(Assembly.GetEntryAssembly().Location, ".xml"); if (File.Exists(fileName) == false) return null; using (var stream = new FileStream(fileName, FileMode.Open)) { return Load(stream); } } public static Settings Load(Stream stream) { // To reduce start-up time, do manual parsing instead of using XmlSerializer var xdoc = XDocument.Load(stream).Element("Settings"); return new Settings { DebugSymbolFile = (DebugSymbolFileType)Enum.Parse(typeof(DebugSymbolFileType), xdoc.Element("DebugSymbolFile").Value), PrebuiltOutputReuse = (PrebuiltOutputReuseType)Enum.Parse(typeof(PrebuiltOutputReuseType), xdoc.Element("PrebuiltOutputReuse").Value), }; } } }
Remove comment no longer needed.
using Glimpse.Web; using Microsoft.Framework.Logging; using System; using System.Threading.Tasks; namespace Glimpse.Agent.Web { public class AgentProfiler : IRequestProfiler { private readonly string _requestIdKey = "RequestId"; private readonly IAgentBroker _messageBus; public AgentProfiler(IAgentBroker messageBus, ILoggerFactory loggingFactory) { _messageBus = messageBus; //// TODO: This is a REALLY bad place for this, not sure where else to put it //loggingFactory.AddProvider(new DefaultLoggerProvider(messageBus)); //var test = loggingFactory.Create("test"); //test.Write(LogLevel.Information, 123, new { Test = "test" }, null, (x, y) => { return ""; }); //// TODO: This is a REALLY bad place for this, not sure where else to put it } public async Task Begin(IHttpContext newContext) { var message = new BeginRequestMessage(newContext.Request); // TODO: Full out message more await _messageBus.SendMessage(message); } public async Task End(IHttpContext newContext) { var message = new EndRequestMessage(newContext.Request); // TODO: Full out message more await _messageBus.SendMessage(message); } } }
using Glimpse.Web; using Microsoft.Framework.Logging; using System; using System.Threading.Tasks; namespace Glimpse.Agent.Web { public class AgentProfiler : IRequestProfiler { private readonly string _requestIdKey = "RequestId"; private readonly IAgentBroker _messageBus; public AgentProfiler(IAgentBroker messageBus, ILoggerFactory loggingFactory) { _messageBus = messageBus; } public async Task Begin(IHttpContext newContext) { var message = new BeginRequestMessage(newContext.Request); // TODO: Full out message more await _messageBus.SendMessage(message); } public async Task End(IHttpContext newContext) { var message = new EndRequestMessage(newContext.Request); // TODO: Full out message more await _messageBus.SendMessage(message); } } }
Change port number 8888 to 8898
namespace Nancy.Demo.Hosting.Self { using System; using System.Diagnostics; using Nancy.Hosting.Self; class Program { static void Main() { using (var nancyHost = new NancyHost(new Uri("http://localhost:8888/nancy/"), new Uri("http://127.0.0.1:8888/nancy/"), new Uri("http://localhost:8889/nancytoo/"))) { nancyHost.Start(); Console.WriteLine("Nancy now listening - navigating to http://localhost:8888/nancy/. Press enter to stop"); try { Process.Start("http://localhost:8888/nancy/"); } catch (Exception) { } Console.ReadKey(); } Console.WriteLine("Stopped. Good bye!"); } } }
namespace Nancy.Demo.Hosting.Self { using System; using System.Diagnostics; using Nancy.Hosting.Self; class Program { static void Main() { using (var nancyHost = new NancyHost(new Uri("http://localhost:8888/nancy/"), new Uri("http://127.0.0.1:8898/nancy/"), new Uri("http://localhost:8889/nancytoo/"))) { nancyHost.Start(); Console.WriteLine("Nancy now listening - navigating to http://localhost:8888/nancy/. Press enter to stop"); try { Process.Start("http://localhost:8888/nancy/"); } catch (Exception) { } Console.ReadKey(); } Console.WriteLine("Stopped. Good bye!"); } } }
Remove Guid, fix typo and change to allowed seperator character
using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PerfIt { [EventSource(Name = "PerIt!Instrumentation", Guid = "{010380F8-40A7-45C3-B87B-FD4C6CC8700A}")] public class InstrumentationEventSource : EventSource { public static readonly InstrumentationEventSource Instance = new InstrumentationEventSource(); private InstrumentationEventSource() { } [Event(1, Level = EventLevel.Informational)] public void WriteInstrumentationEvent(string categoryName, string instanceName, long timeTakenMilli, string instrumentationContext = null) { this.WriteEvent(1, categoryName, instanceName, timeTakenMilli, instrumentationContext); } } }
using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PerfIt { [EventSource(Name = "PerfIt-Instrumentation")] public class InstrumentationEventSource : EventSource { public static readonly InstrumentationEventSource Instance = new InstrumentationEventSource(); private InstrumentationEventSource() { } [Event(1, Level = EventLevel.Informational)] public void WriteInstrumentationEvent(string categoryName, string instanceName, long timeTakenMilli, string instrumentationContext = null) { this.WriteEvent(1, categoryName, instanceName, timeTakenMilli, instrumentationContext); } } }
Rename "Total Tips" to "Tips"
@model Tipage.Web.Models.ViewModels.ShiftListViewModel @{ ViewData["Title"] = "Shifts"; } <h2>Shifts</h2> <h3 class="total-tip">@Html.DisplayNameFor(model => model.TotalTips) @Html.DisplayFor(model => model.TotalTips)</h3> <h3 class="total-tip">@Html.DisplayNameFor(model => model.AverageHourlyWage) @Html.DisplayFor(model => model.AverageHourlyWage)</h3> <hr/> <p> <a asp-action="Create">New Shift</a> </p> <table class="table"> <thead> <tr> <th> Date </th> <th> Total Tips </th> </tr> </thead> <tbody> @foreach (var item in Model.Shifts) { <tr> <td> <a asp-action="Details" asp-route-id="@item.Id">@item.Start.ToString("d") (@item.Start.DayOfWeek)</a> </td> <td> @Html.DisplayFor(s => item.TotalTips) </td> </tr> } </tbody> </table>
@model Tipage.Web.Models.ViewModels.ShiftListViewModel @{ ViewData["Title"] = "Shifts"; } <h2>Shifts</h2> <h3 class="total-tip">@Html.DisplayNameFor(model => model.TotalTips) @Html.DisplayFor(model => model.TotalTips)</h3> <h3 class="total-tip">@Html.DisplayNameFor(model => model.AverageHourlyWage) @Html.DisplayFor(model => model.AverageHourlyWage)</h3> <hr/> <p> <a asp-action="Create">New Shift</a> </p> <table class="table"> <thead> <tr> <th> Date </th> <th> Tips </th> </tr> </thead> <tbody> @foreach (var item in Model.Shifts) { <tr> <td> <a asp-action="Details" asp-route-id="@item.Id">@item.Start.ToString("d") (@item.Start.DayOfWeek)</a> </td> <td> @Html.DisplayFor(s => item.TotalTips) </td> </tr> } </tbody> </table>
Change LabelUrl property from string to List<String>
using System; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Batch : ShippoId { [JsonProperty (PropertyName = "object_status")] public string ObjectStatus { get; set; } [JsonProperty (PropertyName = "object_created")] public string ObjectCreated { get; set; } [JsonProperty (PropertyName = "object_updated")] public string ObjectUpdated { get; set; } [JsonProperty (PropertyName = "object_owner")] public string ObjectOwner { get; set; } [JsonProperty (PropertyName = "default_carrier_account")] public string DefaultCarrierAccount { get; set; } [JsonProperty (PropertyName = "default_servicelevel_token")] public string DefaultServicelevelToken { get; set; } [JsonProperty (PropertyName = "label_filetype")] public string LabelFiletype { get; set; } [JsonProperty (PropertyName = "metadata")] public string Metadata { get; set; } [JsonProperty (PropertyName = "batch_shipments")] public object BatchShipments { get; set; } [JsonProperty (PropertyName = "label_url")] public string LabelUrl { get; set; } [JsonProperty (PropertyName = "object_results")] public ObjectResults ObjectResults { get; set; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Batch : ShippoId { [JsonProperty (PropertyName = "object_status")] public string ObjectStatus { get; set; } [JsonProperty (PropertyName = "object_created")] public string ObjectCreated { get; set; } [JsonProperty (PropertyName = "object_updated")] public string ObjectUpdated { get; set; } [JsonProperty (PropertyName = "object_owner")] public string ObjectOwner { get; set; } [JsonProperty (PropertyName = "default_carrier_account")] public string DefaultCarrierAccount { get; set; } [JsonProperty (PropertyName = "default_servicelevel_token")] public string DefaultServicelevelToken { get; set; } [JsonProperty (PropertyName = "label_filetype")] public string LabelFiletype { get; set; } [JsonProperty (PropertyName = "metadata")] public string Metadata { get; set; } [JsonProperty (PropertyName = "batch_shipments")] public object BatchShipments { get; set; } [JsonProperty (PropertyName = "label_url")] public List<String> LabelUrl { get; set; } [JsonProperty (PropertyName = "object_results")] public ObjectResults ObjectResults { get; set; } } }
Refactor Log objects to class DTOs.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Eff.Core { public struct ExceptionLog { public string CallerMemberName; public string CallerFilePath; public int CallerLineNumber; public Exception Exception; } public struct ResultLog { public string CallerMemberName; public string CallerFilePath; public int CallerLineNumber; public object Result; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Eff.Core { public class ExceptionLog { public string CallerMemberName { get; set; } public string CallerFilePath { get; set; } public int CallerLineNumber { get; set; } public Exception Exception { get; set; } } public class ResultLog { public string CallerMemberName { get; set; } public string CallerFilePath { get; set; } public int CallerLineNumber { get; set; } public object Result { get; set; } } }
Remove STAThread from main function
using System; using System.Drawing; namespace TriDevs.TriCraftClassic { class Program { [STAThread] public static void Main(string[] args) { Window window = new Window(1280, 720); window.Run(60.0); } } }
using System; using System.Drawing; namespace TriDevs.TriCraftClassic { class Program { public static void Main(string[] args) { Window window = new Window(1280, 720); window.Run(60.0); } } }
Use field for metadata to prevent reloading every time a term is read
using KenticoInspector.Core.Models; using KenticoInspector.Core.Services.Interfaces; using System; using System.Collections.Generic; namespace KenticoInspector.Core { public abstract class AbstractReport<T> : IReport, IWithMetadata<T> where T : new() { protected readonly IReportMetadataService reportMetadataService; public AbstractReport(IReportMetadataService reportMetadataService) { this.reportMetadataService = reportMetadataService; } public string Codename => GetCodename(this.GetType()); public static string GetCodename(Type reportType) { return GetDirectParentNamespace(reportType); } public abstract IList<Version> CompatibleVersions { get; } public virtual IList<Version> IncompatibleVersions => new List<Version>(); public abstract IList<string> Tags { get; } public ReportMetadata<T> Metadata => reportMetadataService.GetReportMetadata<T>(Codename); public abstract ReportResults GetResults(); private static string GetDirectParentNamespace(Type reportType) { var fullNameSpace = reportType.Namespace; var indexAfterLastPeriod = fullNameSpace.LastIndexOf('.') + 1; return fullNameSpace.Substring(indexAfterLastPeriod, fullNameSpace.Length - indexAfterLastPeriod); } } }
using KenticoInspector.Core.Models; using KenticoInspector.Core.Services.Interfaces; using System; using System.Collections.Generic; namespace KenticoInspector.Core { public abstract class AbstractReport<T> : IReport, IWithMetadata<T> where T : new() { private ReportMetadata<T> metadata; protected readonly IReportMetadataService reportMetadataService; public AbstractReport(IReportMetadataService reportMetadataService) { this.reportMetadataService = reportMetadataService; } public string Codename => GetCodename(this.GetType()); public static string GetCodename(Type reportType) { return GetDirectParentNamespace(reportType); } public abstract IList<Version> CompatibleVersions { get; } public virtual IList<Version> IncompatibleVersions => new List<Version>(); public abstract IList<string> Tags { get; } public ReportMetadata<T> Metadata { get { return metadata ?? (metadata = reportMetadataService.GetReportMetadata<T>(Codename)); } } public abstract ReportResults GetResults(); private static string GetDirectParentNamespace(Type reportType) { var fullNameSpace = reportType.Namespace; var indexAfterLastPeriod = fullNameSpace.LastIndexOf('.') + 1; return fullNameSpace.Substring(indexAfterLastPeriod, fullNameSpace.Length - indexAfterLastPeriod); } } }
Make wind down max value 200%
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Graphics.Sprites; using osu.Game.Configuration; namespace osu.Game.Rulesets.Mods { public class ModWindDown : ModTimeRamp { public override string Name => "Wind Down"; public override string Acronym => "WD"; public override string Description => "Sloooow doooown..."; public override IconUsage? Icon => FontAwesome.Solid.ChevronCircleDown; public override double ScoreMultiplier => 1.0; [SettingSource("Initial rate", "The starting speed of the track")] public override BindableNumber<double> InitialRate { get; } = new BindableDouble { MinValue = 1, MaxValue = 1.5, Default = 1, Value = 1, Precision = 0.01, }; [SettingSource("Final rate", "The speed increase to ramp towards")] public override BindableNumber<double> FinalRate { get; } = new BindableDouble { MinValue = 0.5, MaxValue = 0.99, Default = 0.75, Value = 0.75, Precision = 0.01, }; public override Type[] IncompatibleMods => base.IncompatibleMods.Append(typeof(ModWindUp)).ToArray(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Graphics.Sprites; using osu.Game.Configuration; namespace osu.Game.Rulesets.Mods { public class ModWindDown : ModTimeRamp { public override string Name => "Wind Down"; public override string Acronym => "WD"; public override string Description => "Sloooow doooown..."; public override IconUsage? Icon => FontAwesome.Solid.ChevronCircleDown; public override double ScoreMultiplier => 1.0; [SettingSource("Initial rate", "The starting speed of the track")] public override BindableNumber<double> InitialRate { get; } = new BindableDouble { MinValue = 1, MaxValue = 2, Default = 1, Value = 1, Precision = 0.01, }; [SettingSource("Final rate", "The speed increase to ramp towards")] public override BindableNumber<double> FinalRate { get; } = new BindableDouble { MinValue = 0.5, MaxValue = 0.99, Default = 0.75, Value = 0.75, Precision = 0.01, }; public override Type[] IncompatibleMods => base.IncompatibleMods.Append(typeof(ModWindUp)).ToArray(); } }
Allow converting integers (UNIX timestamps) to DateTime instances.
using System; public static class IntegerExtensions { public static TimeSpan Days(this Int32 integer) { return TimeSpan.FromDays(integer); } public static TimeSpan Hours(this Int32 integer) { return TimeSpan.FromHours(integer); } public static TimeSpan Milliseconds(this Int32 integer) { return TimeSpan.FromMilliseconds(integer); } public static TimeSpan Minutes(this Int32 integer) { return TimeSpan.FromMinutes(integer); } public static TimeSpan Seconds(this Int32 integer) { return TimeSpan.FromSeconds(integer); } }
using System; public static class IntegerExtensions { private static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static TimeSpan Days(this Int32 integer) { return TimeSpan.FromDays(integer); } public static TimeSpan Hours(this Int32 integer) { return TimeSpan.FromHours(integer); } public static TimeSpan Milliseconds(this Int32 integer) { return TimeSpan.FromMilliseconds(integer); } public static TimeSpan Minutes(this Int32 integer) { return TimeSpan.FromMinutes(integer); } public static TimeSpan Seconds(this Int32 integer) { return TimeSpan.FromSeconds(integer); } public static DateTime ToDateTime(this Int64 integer, Boolean useMilliseconds = false) { return useMilliseconds ? UNIX_EPOCH.AddMilliseconds(integer) : UNIX_EPOCH.AddSeconds(integer); } }
Rename F grade to D
// 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.ComponentModel; namespace osu.Game.Scoring { public enum ScoreRank { [Description(@"F")] F, [Description(@"F")] D, [Description(@"C")] C, [Description(@"B")] B, [Description(@"A")] A, [Description(@"S")] S, [Description(@"S+")] SH, [Description(@"SS")] X, [Description(@"SS+")] XH, } }
// 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.ComponentModel; namespace osu.Game.Scoring { public enum ScoreRank { [Description(@"D")] F, [Description(@"D")] D, [Description(@"C")] C, [Description(@"B")] B, [Description(@"A")] A, [Description(@"S")] S, [Description(@"S+")] SH, [Description(@"SS")] X, [Description(@"SS+")] XH, } }
Correct version, managed by build script
using System.Reflection; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")]
using System.Reflection; [assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyInformationalVersion("0.0.0.*")]
Fix bug in "where" if-statement
using System; using System.Text; using NHibernate.Util; namespace NHibernate.Sql { /// <summary> /// An SQL <c>DELETE</c> statement /// </summary> public class Delete { private string tableName; private string[] primaryKeyColumnNames; private string versionColumnName; private string where; public Delete SetTableName(string tableName) { this.tableName = tableName; return this; } public string ToStatementString() { StringBuilder buf = new StringBuilder( tableName.Length + 10 ); buf.Append("delete from ") .Append(tableName) .Append(" where ") .Append( string.Join("=? and ", primaryKeyColumnNames) ) .Append("=?"); if (versionColumnName != null) { buf.Append(" and ") .Append(versionColumnName) .Append("=?"); if(where!=null) { buf.Append(" and ") .Append(where); } } return buf.ToString(); } public Delete SetWhere(string where) { this.where = where; return this; } public Delete SetPrimaryKeyColumnNames(string[] primaryKeyColumnNames) { this.primaryKeyColumnNames = primaryKeyColumnNames; return this; } public Delete SetVersionColumnName(string versionColumnName) { this.versionColumnName = versionColumnName; return this; } } }
using System; using System.Text; using NHibernate.Util; namespace NHibernate.Sql { /// <summary> /// An SQL <c>DELETE</c> statement /// </summary> public class Delete { private string tableName; private string[] primaryKeyColumnNames; private string versionColumnName; private string where; public Delete SetTableName(string tableName) { this.tableName = tableName; return this; } public string ToStatementString() { StringBuilder buf = new StringBuilder( tableName.Length + 10 ); buf.Append("delete from ") .Append(tableName) .Append(" where ") .Append( string.Join("=? and ", primaryKeyColumnNames) ) .Append("=?"); if(where!=null) { buf.Append(" and ") .Append(where); } if (versionColumnName != null) { buf.Append(" and ") .Append(versionColumnName) .Append("=?"); } return buf.ToString(); } public Delete SetWhere(string where) { this.where = where; return this; } public Delete SetPrimaryKeyColumnNames(params string[] primaryKeyColumnNames) { this.primaryKeyColumnNames = primaryKeyColumnNames; return this; } public Delete SetVersionColumnName(string versionColumnName) { this.versionColumnName = versionColumnName; return this; } } }
Add links and more info
@using Newtonsoft.Json; @{ string dataFile = Server.MapPath("~/App_Data/data.json"); string json = File.ReadAllText(dataFile); var data = (IEnumerable<dynamic>)JsonConvert.DeserializeObject(json); } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Forum Scorer</title> </head> <body> <div> Forum Scorer </div> <ul> @foreach (var user in data.OrderByDescending(u=>u.WeekScore)) { if (user.WeekScore == 0) { break; } <li>@user.Name: @user.WeekScore</li> } </ul> <ul> @foreach (var user in data.OrderByDescending(u => u.PreviousWeekScore)) { if (user.PreviousWeekScore == 0) { break; } <li>@user.Name: @user.PreviousWeekScore</li> } </ul> </body> </html>
@using Newtonsoft.Json; @{ string dataFile = Server.MapPath("~/App_Data/data.json"); string json = File.ReadAllText(dataFile); var data = (IEnumerable<dynamic>)JsonConvert.DeserializeObject(json); } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Forum Scorer</title> </head> <body> <h2>Forum Scorer</h2> <h3>This week's leaderboard (the week ends on Friday)</h3> <ul> @foreach (var user in data.OrderByDescending(u=>u.WeekScore)) { if (user.WeekScore == 0) { break; } <li><a href="https://social.msdn.microsoft.com/Profile/@user.Name/activity">@user.Name</a>: @user.WeekScore</li> } </ul> <h3>Last week's leaderboard</h3> <ul> @foreach (var user in data.OrderByDescending(u => u.PreviousWeekScore)) { if (user.PreviousWeekScore == 0) { break; } <li><a href="https://social.msdn.microsoft.com/Profile/@user.Name/activity">@user.Name</a>: @user.PreviousWeekScore</li> } </ul> <h3>Scoring notes</h3> Click on a user's name to see their activity detail on MSDN. Points are give as follows: <ul> <li>20 points for quickly answering a question</li> <li>15 points for answering a question</li> <li>5 points for contributing a helpful post</li> <li>1 for responding to a question (additional responses to the same question don't count)</li> </ul> </body> </html>
Add the same to the _viewimports file for the dotnet new template
@using Umbraco.Web.UI.NetCore @using Umbraco.Extensions @using Umbraco.Web.PublishedModels @using Umbraco.Cms.Core.Models.PublishedContent @using Microsoft.AspNetCore.Html @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using Umbraco.Web.UI.NetCore @using Umbraco.Extensions @using Umbraco.Web.PublishedModels @using Umbraco.Cms.Core.Models.PublishedContent @using Microsoft.AspNetCore.Html @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, Smidge @inject Smidge.SmidgeHelper SmidgeHelper
Make the login URL configurable.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dolstagis.Web.Lifecycle { public class LoginHandler : ILoginHandler { public object GetLogin(IHttpContext context) { return new RedirectResult("/login", Status.SeeOther); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dolstagis.Web.Lifecycle { public class LoginHandler : ILoginHandler { public string LoginUrl { get; set; } public LoginHandler() { LoginUrl = "~/login"; } public object GetLogin(IHttpContext context) { return new RedirectResult(LoginUrl, Status.SeeOther); } } }
Add output abbreviation text for named pipe relay client to service dispatcher to match the service proxy.
using hase.DevLib.Contract.FileSystemQuery; using hase.DevLib.Service.FileSystemQuery; using ProtoBuf; using System; using System.IO.Pipes; namespace hase.DevLib.Service { public class ServiceDispatcher { private static readonly string pipeName = nameof(FileSystemQueryService); private NamedPipeClientStream pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None); public void Run() { Console.WriteLine($"{pipeName} connecting to relay."); pipe.ConnectAsync(5000).Wait(); Console.WriteLine($"{pipeName} connected to relay."); while (true) { ProcessRequest(); } } private void ProcessRequest() { //Console.WriteLine($"Waiting to receive {pipeName} request."); var request = Serializer.DeserializeWithLengthPrefix<FileSystemQueryRequest>(pipe, PrefixStyle.Base128); Console.WriteLine($"Received {pipeName} request: {request}."); var service = new FileSystemQueryService(); FileSystemQueryResponse response = null; try { response = service.Execute(request); } catch (Exception ex) { } Console.WriteLine($"Sending {pipeName} response: {response}."); Serializer.SerializeWithLengthPrefix(pipe, response, PrefixStyle.Base128); //Console.WriteLine($"Sent {pipeName} response."); } } }
using hase.DevLib.Contract.FileSystemQuery; using hase.DevLib.Service.FileSystemQuery; using ProtoBuf; using System; using System.IO.Pipes; namespace hase.DevLib.Service { public class ServiceDispatcher { private static readonly string pipeName = nameof(FileSystemQueryService); private NamedPipeClientStream pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None); public void Run() { Console.WriteLine($"nprc:{pipeName} connecting to relay."); pipe.ConnectAsync(5000).Wait(); Console.WriteLine($"nprc:{pipeName} connected to relay."); while (true) { ProcessRequest(); } } private void ProcessRequest() { //Console.WriteLine($"nprc:Waiting to receive {pipeName} request."); var request = Serializer.DeserializeWithLengthPrefix<FileSystemQueryRequest>(pipe, PrefixStyle.Base128); Console.WriteLine($"nprc:Received {pipeName} request: {request}."); var service = new FileSystemQueryService(); FileSystemQueryResponse response = null; try { response = service.Execute(request); } catch (Exception ex) { } Console.WriteLine($"nprc:Sending {pipeName} response: {response}."); Serializer.SerializeWithLengthPrefix(pipe, response, PrefixStyle.Base128); //Console.WriteLine($"nprc:Sent {pipeName} response."); } } }
Check if resx file exists
using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Resources; using System.Text; namespace AzureFunctions.ResxConvertor { public class ResxConvertor { public void SaveResxAsTypeScriptFile(string[] resxFiles, string outputTSFilePAth) { var sb = new StringBuilder(); sb.AppendLine("// This file is auto generated"); sb.AppendLine(""); sb.AppendLine("export class PortalResources"); sb.AppendLine("{"); foreach (var resxFile in resxFiles) { ResXResourceReader rsxr = new ResXResourceReader(resxFile); foreach (DictionaryEntry d in rsxr) { sb.AppendLine(string.Format(" public static {0}: string = \"{0}\";", d.Key.ToString())); } //Close the reader. rsxr.Close(); } sb.AppendLine("}"); using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputTSFilePAth)) { file.WriteLine(sb.ToString()); } } } }
using Newtonsoft.Json.Linq; using System; using System.Collections; using System.IO; using System.Resources; using System.Text; namespace AzureFunctions.ResxConvertor { public class ResxConvertor { public void SaveResxAsTypeScriptFile(string[] resxFiles, string outputTSFilePAth) { var sb = new StringBuilder(); sb.AppendLine("// This file is auto generated"); sb.AppendLine(""); sb.AppendLine("export class PortalResources"); sb.AppendLine("{"); foreach (var resxFile in resxFiles) { if (File.Exists(resxFile)) { ResXResourceReader rsxr = new ResXResourceReader(resxFile); foreach (DictionaryEntry d in rsxr) { sb.AppendLine(string.Format(" public static {0}: string = \"{0}\";", d.Key.ToString())); } //Close the reader. rsxr.Close(); } } sb.AppendLine("}"); using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputTSFilePAth)) { file.WriteLine(sb.ToString()); } } } }
Update webhook test page design
@model EditWebhookViewModel @using BTCPayServer.Client.Models; @{ Layout = "../Shared/_NavLayout.cshtml"; ViewData.SetActivePageAndTitle(StoreNavPages.Webhooks, "Test Webhook", Context.GetStoreData().StoreName); } <div class="row"> <div class="col-lg-8"> <form method="post"> <h4 class="mb-3">@ViewData["PageTitle"]</h4> <ul class="list-group"> @foreach (var evt in new[] { ("Test InvoiceCreated event", WebhookEventType.InvoiceCreated), ("Test InvoiceReceivedPayment event", WebhookEventType.InvoiceReceivedPayment), ("Test InvoiceProcessing event", WebhookEventType.InvoiceProcessing), ("Test InvoiceExpired event", WebhookEventType.InvoiceExpired), ("Test InvoiceSettled event", WebhookEventType.InvoiceSettled), ("Test InvoiceInvalid event", WebhookEventType.InvoiceInvalid) }) { <li class="list-group-item"> <button type="submit" name="Type" class="btn btn-primary" value="@evt.Item2">@evt.Item1</button> </li> } </ul> </form> </div> </div>
@model EditWebhookViewModel @using BTCPayServer.Client.Models; @{ Layout = "../Shared/_NavLayout.cshtml"; ViewData.SetActivePageAndTitle(StoreNavPages.Webhooks, "Send a test event to a webhook endpoint", Context.GetStoreData().StoreName); } <div class="row"> <div class="col-lg-8"> <form method="post"> <h4 class="mb-3">@ViewData["PageTitle"]</h4> <div class="form-group"> <label for="Type">Event type</label> <select name="Type" id="Type" class="form-control w-auto"> @foreach (var evt in new[] { WebhookEventType.InvoiceCreated, WebhookEventType.InvoiceReceivedPayment, WebhookEventType.InvoiceProcessing, WebhookEventType.InvoiceExpired, WebhookEventType.InvoiceSettled, WebhookEventType.InvoiceInvalid }) { <option value="@evt"> @evt </option> } </select> </div> <button type="submit" class="btn btn-primary">Send test webhook</button> </form> </div> </div>
Handle closed /proc/self/fd/ in stream encode.
using System.Collections.Generic; using System.IO; using System.Linq; using Buzzbox_Common; using Buzzbox_Common.Encoders; namespace Buzzbox_Stream { class StreamEncode { public bool LoopForever; public bool ShuffleFields; private MtgEncodeFormatEncoder _encoder; private CardCollection _cardCollection; private StreamWriter _stream; public StreamEncode(CardCollection cardCollection, StreamWriter stream) { _encoder = new MtgEncodeFormatEncoder(); _cardCollection = cardCollection; _stream = stream; } public void ThreadEntry() { do { _cardCollection.Cards.Shuffle(); foreach (var card in _cardCollection.Cards) { var outputLine = _encoder.EncodeCard(card) + "\n\n"; if (ShuffleFields) { outputLine = ShuffleCardFields(outputLine); } //actually output _stream.Write(outputLine); } } while (LoopForever); _stream.Close(); } private string ShuffleCardFields(string cardLine) { cardLine = cardLine.TrimEnd('|').TrimStart('|'); List<string> fields = cardLine.Split('|').ToList(); fields.Shuffle(); return $"|{string.Join("|", fields)}|"; } } }
using System; using System.CodeDom; using System.Collections.Generic; using System.IO; using System.Linq; using Buzzbox_Common; using Buzzbox_Common.Encoders; namespace Buzzbox_Stream { class StreamEncode { public bool LoopForever; public bool ShuffleFields; private MtgEncodeFormatEncoder _encoder; private CardCollection _cardCollection; private StreamWriter _stream; public StreamEncode(CardCollection cardCollection, StreamWriter stream) { _encoder = new MtgEncodeFormatEncoder(); _cardCollection = cardCollection; _stream = stream; } public void ThreadEntry() { do { _cardCollection.Cards.Shuffle(); foreach (var card in _cardCollection.Cards) { var outputLine = _encoder.EncodeCard(card) + "\n\n"; if (ShuffleFields) { outputLine = ShuffleCardFields(outputLine); } //actually try to output try { _stream.Write(outputLine); } catch (Exception) { //fd was probably closed or otherwise no longer available return; } } } while (LoopForever); _stream.Close(); } private string ShuffleCardFields(string cardLine) { cardLine = cardLine.TrimEnd('|').TrimStart('|'); List<string> fields = cardLine.Split('|').ToList(); fields.Shuffle(); return $"|{string.Join("|", fields)}|"; } } }
Update how byte[] is mapped.
using System; using System.ComponentModel.DataAnnotations; using FluentNHibernate.Mapping; using UCDArch.Core.DomainModel; namespace Commencement.Core.Domain { public class Attachment : DomainObject { public Attachment() { PublicGuid = Guid.NewGuid(); } [Required] public virtual byte[] Contents { get; set; } [Required] [StringLength(50)] public virtual string ContentType { get; set; } [StringLength(250)] public virtual string FileName { get; set; } public virtual Guid PublicGuid { get; set; } } public class AttachmentMap : ClassMap<Attachment> { public AttachmentMap() { Id(x => x.Id); Map(x => x.Contents).CustomSqlType("BinaryBlob"); Map(x => x.ContentType); Map(x => x.FileName); Map(x => x.PublicGuid); } } }
using System; using System.ComponentModel.DataAnnotations; using FluentNHibernate.Mapping; using UCDArch.Core.DomainModel; namespace Commencement.Core.Domain { public class Attachment : DomainObject { public Attachment() { PublicGuid = Guid.NewGuid(); } [Required] public virtual byte[] Contents { get; set; } [Required] [StringLength(50)] public virtual string ContentType { get; set; } [StringLength(250)] public virtual string FileName { get; set; } public virtual Guid PublicGuid { get; set; } } public class AttachmentMap : ClassMap<Attachment> { public AttachmentMap() { Id(x => x.Id); Map(x => x.Contents).Length(Int32.MaxValue); Map(x => x.ContentType); Map(x => x.FileName); Map(x => x.PublicGuid); } } }
Fix editor not showing sign when time goes negative
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Game.Graphics.Sprites; using System; using osu.Framework.Allocation; using osu.Game.Graphics; namespace osu.Game.Screens.Edit.Components { public class TimeInfoContainer : BottomBarContainer { private readonly OsuSpriteText trackTimer; [Resolved] private EditorClock editorClock { get; set; } public TimeInfoContainer() { Children = new Drawable[] { trackTimer = new OsuSpriteText { Origin = Anchor.BottomLeft, RelativePositionAxes = Axes.Y, Font = OsuFont.GetFont(size: 22, fixedWidth: true), Y = 0.5f, } }; } protected override void Update() { base.Update(); trackTimer.Text = TimeSpan.FromMilliseconds(editorClock.CurrentTime).ToString(@"mm\:ss\:fff"); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Game.Graphics.Sprites; using System; using osu.Framework.Allocation; using osu.Game.Graphics; namespace osu.Game.Screens.Edit.Components { public class TimeInfoContainer : BottomBarContainer { private readonly OsuSpriteText trackTimer; [Resolved] private EditorClock editorClock { get; set; } public TimeInfoContainer() { Children = new Drawable[] { trackTimer = new OsuSpriteText { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, // intentionally fudged centre to avoid movement of the number portion when // going negative. X = -35, Font = OsuFont.GetFont(size: 25, fixedWidth: true), } }; } protected override void Update() { base.Update(); var timespan = TimeSpan.FromMilliseconds(editorClock.CurrentTime); trackTimer.Text = $"{(timespan < TimeSpan.Zero ? "-" : string.Empty)}{timespan:mm\\:ss\\:fff}"; } } }
Add proper transaction rollback logic on exception
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using Microsoft.EntityFrameworkCore.Storage; namespace osu.Game.Database { public class DatabaseWriteUsage : IDisposable { public readonly OsuDbContext Context; private readonly IDbContextTransaction transaction; private readonly Action<DatabaseWriteUsage> usageCompleted; public DatabaseWriteUsage(OsuDbContext context, Action<DatabaseWriteUsage> onCompleted) { Context = context; transaction = Context.BeginTransaction(); usageCompleted = onCompleted; } public bool PerformedWrite { get; private set; } private bool isDisposed; protected void Dispose(bool disposing) { if (isDisposed) return; isDisposed = true; PerformedWrite |= Context.SaveChanges(transaction) > 0; usageCompleted?.Invoke(this); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~DatabaseWriteUsage() { Dispose(false); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using Microsoft.EntityFrameworkCore.Storage; namespace osu.Game.Database { public class DatabaseWriteUsage : IDisposable { public readonly OsuDbContext Context; private readonly IDbContextTransaction transaction; private readonly Action<DatabaseWriteUsage> usageCompleted; public DatabaseWriteUsage(OsuDbContext context, Action<DatabaseWriteUsage> onCompleted) { Context = context; transaction = Context.BeginTransaction(); usageCompleted = onCompleted; } public bool PerformedWrite { get; private set; } private bool isDisposed; protected void Dispose(bool disposing) { if (isDisposed) return; isDisposed = true; try { PerformedWrite |= Context.SaveChanges(transaction) > 0; } catch (Exception e) { transaction?.Rollback(); throw; } finally { usageCompleted?.Invoke(this); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~DatabaseWriteUsage() { Dispose(false); } } }
Replace Send with ToJson so the library is independent from how you send it
using System; using Newtonsoft.Json; using RestSharp; namespace Rollbar { public class RollbarPayload { public RollbarPayload(string accessToken, RollbarData data) { if (string.IsNullOrWhiteSpace(accessToken)) { throw new ArgumentNullException("accessToken"); } if (data == null) { throw new ArgumentNullException("data"); } AccessToken = accessToken; RollbarData = data; } public void Send() { var http = new RestClient("https://api.rollbar.com"); var request = new RestRequest("/api/1/item/", Method.POST); request.AddParameter("application/json", JsonConvert.SerializeObject(this), ParameterType.RequestBody); http.Execute(request); } [JsonProperty("access_token", Required = Required.Always)] public string AccessToken { get; private set; } [JsonProperty("data", Required = Required.Always)] public RollbarData RollbarData { get; private set; } } }
using System; using Newtonsoft.Json; namespace Rollbar { public class RollbarPayload { public RollbarPayload(string accessToken, RollbarData data) { if (string.IsNullOrWhiteSpace(accessToken)) { throw new ArgumentNullException("accessToken"); } if (data == null) { throw new ArgumentNullException("data"); } AccessToken = accessToken; RollbarData = data; } public string ToJson() { return JsonConvert.SerializeObject(this); } [JsonProperty("access_token", Required = Required.Always)] public string AccessToken { get; private set; } [JsonProperty("data", Required = Required.Always)] public RollbarData RollbarData { get; private set; } } }
Reduce number of function calls.
using System; using System.Diagnostics; using System.Text; using ReClassNET.Util; namespace ReClassNET.MemorySearcher.Comparer { public class StringMemoryComparer : IMemoryComparer { public SearchCompareType CompareType => SearchCompareType.Equal; public bool CaseSensitive { get; } public Encoding Encoding { get; } public string Value { get; } public int ValueSize => Value.Length * Encoding.GetSimpleByteCountPerChar(); public StringMemoryComparer(string value, Encoding encoding, bool caseSensitive) { Value = value; Encoding = encoding; CaseSensitive = caseSensitive; } public bool Compare(byte[] data, int index, out SearchResult result) { result = null; var value = Encoding.GetString(data, index, Value.Length); if (!Value.Equals(value, CaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase)) { return false; } result = new StringSearchResult(value, Encoding); return true; } public bool Compare(byte[] data, int index, SearchResult previous, out SearchResult result) { #if DEBUG Debug.Assert(previous is StringSearchResult); #endif return Compare(data, index, out result); } } }
using System; using System.Diagnostics; using System.Text; using ReClassNET.Util; namespace ReClassNET.MemorySearcher.Comparer { public class StringMemoryComparer : IMemoryComparer { public SearchCompareType CompareType => SearchCompareType.Equal; public bool CaseSensitive { get; } public Encoding Encoding { get; } public string Value { get; } public int ValueSize { get; } public StringMemoryComparer(string value, Encoding encoding, bool caseSensitive) { Value = value; Encoding = encoding; CaseSensitive = caseSensitive; ValueSize = Value.Length * Encoding.GetSimpleByteCountPerChar(); } public bool Compare(byte[] data, int index, out SearchResult result) { result = null; var value = Encoding.GetString(data, index, Value.Length); if (!Value.Equals(value, CaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase)) { return false; } result = new StringSearchResult(value, Encoding); return true; } public bool Compare(byte[] data, int index, SearchResult previous, out SearchResult result) { #if DEBUG Debug.Assert(previous is StringSearchResult); #endif return Compare(data, index, out result); } } }
Fix namespace for Clear extension.
// 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 Microsoft.AspNet.Http.Features; namespace Microsoft.AspNet.Http.Extensions { public static class ResponseExtensions { public static void Clear(this HttpResponse response) { if (response.HasStarted) { throw new InvalidOperationException("The response cannot be cleared, it has already started sending."); } response.StatusCode = 200; response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = null; response.Headers.Clear(); if (response.Body.CanSeek) { response.Body.SetLength(0); } } } }
// 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 Microsoft.AspNet.Http.Features; namespace Microsoft.AspNet.Http { public static class ResponseExtensions { public static void Clear(this HttpResponse response) { if (response.HasStarted) { throw new InvalidOperationException("The response cannot be cleared, it has already started sending."); } response.StatusCode = 200; response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = null; response.Headers.Clear(); if (response.Body.CanSeek) { response.Body.SetLength(0); } } } }
Remove unnecessary enumerator.Reset() from foreach() handling -- causes problems with IEnumerable created from LINQ
#region using using Irony.Compiler; using System.Collections; using ScriptNET.Runtime; using System; #endregion namespace ScriptNET.Ast { /// <summary> /// ForEachStatement /// </summary> internal class ScriptForEachStatement : ScriptStatement { private Token name; private ScriptExpr expr; private ScriptStatement statement; public ScriptForEachStatement(AstNodeArgs args) : base(args) { name = (Token)ChildNodes[1]; expr = (ScriptExpr)ChildNodes[3]; statement = (ScriptStatement)ChildNodes[4]; } public override void Evaluate(IScriptContext context) { expr.Evaluate(context); IEnumerable enumeration = context.Result as IEnumerable; IEnumerator enumerator = null; if (enumeration != null) { enumerator = enumeration.GetEnumerator(); } else { IObjectBind bind = RuntimeHost.Binder.BindToMethod(context.Result, "GetEnumerator",new Type[0], new object[0]); if (bind != null) enumerator = bind.Invoke(context, null) as IEnumerator; } if (enumerator == null) throw new ScriptException("GetEnumerator() method did not found in object: " + context.Result.ToString()); enumerator.Reset(); while(enumerator.MoveNext()) { context.SetItem(name.Text, enumerator.Current); statement.Evaluate(context); if (context.IsBreak() || context.IsReturn()) { context.SetBreak(false); break; } if (context.IsContinue()) { context.SetContinue(false); } } } } }
#region using using Irony.Compiler; using System.Collections; using ScriptNET.Runtime; using System; #endregion namespace ScriptNET.Ast { /// <summary> /// ForEachStatement /// </summary> internal class ScriptForEachStatement : ScriptStatement { private Token name; private ScriptExpr expr; private ScriptStatement statement; public ScriptForEachStatement(AstNodeArgs args) : base(args) { name = (Token)ChildNodes[1]; expr = (ScriptExpr)ChildNodes[3]; statement = (ScriptStatement)ChildNodes[4]; } public override void Evaluate(IScriptContext context) { expr.Evaluate(context); IEnumerable enumeration = context.Result as IEnumerable; IEnumerator enumerator = null; if (enumeration != null) { enumerator = enumeration.GetEnumerator(); } else { IObjectBind bind = RuntimeHost.Binder.BindToMethod(context.Result, "GetEnumerator",new Type[0], new object[0]); if (bind != null) enumerator = bind.Invoke(context, null) as IEnumerator; } if (enumerator == null) throw new ScriptException("GetEnumerator() method did not found in object: " + context.Result.ToString()); // enumerator.Reset(); while(enumerator.MoveNext()) { context.SetItem(name.Text, enumerator.Current); statement.Evaluate(context); if (context.IsBreak() || context.IsReturn()) { context.SetBreak(false); break; } if (context.IsContinue()) { context.SetContinue(false); } } } } }
Remove some forgotten debugging code
using System; using System.IO; using System.Linq; namespace DotVVM.Compiler { public static class Program { private static void PrintHelp(TextWriter? writer = null) { var executableName = Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]); writer ??= Console.Error; writer.Write( $@"Usage: {executableName} [OPTIONS] <ASSEMBLY> <PROJECT_DIR> Arguments: <ASSEMBLY> Path to a DotVVM project assembly. <PROJECT_DIR> Path to a DotVVM project directory. Options: -h|-?|--help Print this help text. --list-props Print a list of DotVVM properties inside the assembly. "); } public static int Main(string[] args) { #if NETCOREAPP3_1_OR_GREATER var r = Microsoft.Extensions.DependencyModel.DependencyContext.Default.RuntimeLibraries .Where(l => l.Name.Contains("DotVVM")).ToArray(); var c = Microsoft.Extensions.DependencyModel.DependencyContext.Default.CompileLibraries .Where(l => l.Name.Contains("DotVVM")).ToArray(); foreach(var context in System.Runtime.Loader.AssemblyLoadContext.All) { context.Resolving += (c, n) => { return null; }; } #endif if (!CompilerArgs.TryParse(args, out var parsed)) { PrintHelp(Console.Error); return 1; } if (parsed.IsHelp) { PrintHelp(Console.Out); return 0; } var executor = ProjectLoader.GetExecutor(parsed.AssemblyFile.FullName); var success = executor.ExecuteCompile(parsed); return success ? 0 : 1; } } }
using System; using System.IO; using System.Linq; namespace DotVVM.Compiler { public static class Program { private static void PrintHelp(TextWriter? writer = null) { var executableName = Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]); writer ??= Console.Error; writer.Write( $@"Usage: {executableName} [OPTIONS] <ASSEMBLY> <PROJECT_DIR> Arguments: <ASSEMBLY> Path to a DotVVM project assembly. <PROJECT_DIR> Path to a DotVVM project directory. Options: -h|-?|--help Print this help text. --list-props Print a list of DotVVM properties inside the assembly. "); } public static int Main(string[] args) { if (!CompilerArgs.TryParse(args, out var parsed)) { PrintHelp(Console.Error); return 1; } if (parsed.IsHelp) { PrintHelp(Console.Out); return 0; } var executor = ProjectLoader.GetExecutor(parsed.AssemblyFile.FullName); var success = executor.ExecuteCompile(parsed); return success ? 0 : 1; } } }
Fix the wrong conditional statement.
using NuGet.OutputWindowConsole; using NuGetConsole; namespace NuGet.Dialog.PackageManagerUI { internal class SmartOutputConsoleProvider : IOutputConsoleProvider { private readonly IOutputConsoleProvider _baseProvider; private bool _isFirstTime = true; public SmartOutputConsoleProvider(IOutputConsoleProvider baseProvider) { _baseProvider = baseProvider; } public IConsole CreateOutputConsole(bool requirePowerShellHost) { IConsole console = _baseProvider.CreateOutputConsole(requirePowerShellHost); if (_isFirstTime) { // the first time the console is accessed after dialog is opened, we clear the console. console.Clear(); } else { _isFirstTime = false; } return console; } } }
using NuGet.OutputWindowConsole; using NuGetConsole; namespace NuGet.Dialog.PackageManagerUI { internal class SmartOutputConsoleProvider : IOutputConsoleProvider { private readonly IOutputConsoleProvider _baseProvider; private bool _isFirstTime = true; public SmartOutputConsoleProvider(IOutputConsoleProvider baseProvider) { _baseProvider = baseProvider; } public IConsole CreateOutputConsole(bool requirePowerShellHost) { IConsole console = _baseProvider.CreateOutputConsole(requirePowerShellHost); if (_isFirstTime) { // the first time the console is accessed after dialog is opened, we clear the console. console.Clear(); _isFirstTime = false; } return console; } } }
Change the sort text based on if there's a term or not
@model PackageListViewModel @{ ViewBag.Title = String.IsNullOrWhiteSpace(Model.SearchTerm) ? "Packages" : "Packages matching " + Model.SearchTerm; ViewBag.Tab = "Packages"; } <div class="search"> @if (!String.IsNullOrEmpty(Model.SearchTerm)) { <h1>Search for <i>@Model.SearchTerm</i> returned @Model.TotalCount @if (Model.TotalCount == 1) { <text>package</text> } else { <text>packages</text> }</h1> } else { <h1>@if (Model.TotalCount == 1) { <text>There is @Model.TotalCount package</text> } else { <text>There are @Model.TotalCount packages</text> }</h1> } @if (@Model.LastResultIndex > 0) { <h2>Displaying results @Model.FirstResultIndex - @Model.LastResultIndex.</h2> } </div> <span class="sorted-by">Sorted by Recent Installs</span> <ul id="searchResults"> @foreach (var package in Model.Items) { <li> @Html.Partial("_ListPackage", package) </li> } </ul> @ViewHelpers.PreviousNextPager(Model.Pager)
@model PackageListViewModel @{ ViewBag.Title = String.IsNullOrWhiteSpace(Model.SearchTerm) ? "Packages" : "Packages matching " + Model.SearchTerm; ViewBag.SortText = String.IsNullOrWhiteSpace(Model.SearchTerm) ? "recent installs" : "relevance"; ViewBag.Tab = "Packages"; } <div class="search"> @if (!String.IsNullOrEmpty(Model.SearchTerm)) { <h1>Search for <i>@Model.SearchTerm</i> returned @Model.TotalCount @if (Model.TotalCount == 1) { <text>package</text> } else { <text>packages</text> }</h1> } else { <h1>@if (Model.TotalCount == 1) { <text>There is @Model.TotalCount package</text> } else { <text>There are @Model.TotalCount packages</text> }</h1> } @if (@Model.LastResultIndex > 0) { <h2>Displaying results @Model.FirstResultIndex - @Model.LastResultIndex.</h2> } </div> <span class="sorted-by">sorted by @ViewBag.SortText</span> <ul id="searchResults"> @foreach (var package in Model.Items) { <li> @Html.Partial("_ListPackage", package) </li> } </ul> @ViewHelpers.PreviousNextPager(Model.Pager)
Replace app name for special cases in team city check
using System.Linq; using System.Text; using TeamCitySharp; using TeamCitySharp.Locators; namespace DTMF.Logic { public class TeamCity { public static bool IsRunning(StringBuilder sb, string appName) { //skip if not configured if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false; //Check for running builds var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]); client.ConnectAsGuest(); var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds()); if (builds.Any(f=>f.BuildTypeId.Contains(appName))) { Utilities.AppendAndSend(sb, "Build in progress. Sync disabled"); //foreach (var build in builds) //{ // Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>"); //} return true; } return false; } } }
using System.Linq; using System.Text; using TeamCitySharp; using TeamCitySharp.Locators; namespace DTMF.Logic { public class TeamCity { public static bool IsRunning(StringBuilder sb, string appName) { //remove prefix and suffixes from app names so same app can go to multiple places appName = appName.Replace(".Production", ""); appName = appName.Replace(".Development", ""); appName = appName.Replace(".Staging", ""); appName = appName.Replace(".Test", ""); //skip if not configured if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false; //Check for running builds var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]); client.ConnectAsGuest(); var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds()); if (builds.Any(f=>f.BuildTypeId.Contains(appName))) { Utilities.AppendAndSend(sb, "Build in progress. Sync disabled"); //foreach (var build in builds) //{ // Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>"); //} return true; } return false; } } }
Fix a bug in the 'ret void' implementation
using System; using Flame.Compiler; using LLVMSharp; using static LLVMSharp.LLVM; namespace Flame.LLVM.Codegen { /// <summary> /// A code block implementation that returns a value from a method. /// </summary> public sealed class ReturnBlock : CodeBlock { public ReturnBlock( LLVMCodeGenerator CodeGenerator, CodeBlock ReturnValue) { this.codeGen = CodeGenerator; this.retVal = ReturnValue; } private LLVMCodeGenerator codeGen; private CodeBlock retVal; /// <inheritdoc/> public override ICodeGenerator CodeGenerator => codeGen; /// <inheritdoc/> public override IType Type => PrimitiveTypes.Void; /// <inheritdoc/> public override BlockCodegen Emit(BasicBlockBuilder BasicBlock) { var retValCodegen = retVal.Emit(BasicBlock); BasicBlock = retValCodegen.BasicBlock; if (retVal.Type == PrimitiveTypes.Void) { var retVoid = BuildRetVoid(BasicBlock.Builder); return new BlockCodegen(BasicBlock, retVoid); } else { var ret = BuildRet(BasicBlock.Builder, retValCodegen.Value); return new BlockCodegen(BasicBlock, ret); } } } }
using System; using Flame.Compiler; using LLVMSharp; using static LLVMSharp.LLVM; namespace Flame.LLVM.Codegen { /// <summary> /// A code block implementation that returns a value from a method. /// </summary> public sealed class ReturnBlock : CodeBlock { public ReturnBlock( LLVMCodeGenerator CodeGenerator, CodeBlock ReturnValue) { this.codeGen = CodeGenerator; this.retVal = ReturnValue; } private LLVMCodeGenerator codeGen; private CodeBlock retVal; /// <inheritdoc/> public override ICodeGenerator CodeGenerator => codeGen; /// <inheritdoc/> public override IType Type => PrimitiveTypes.Void; private BlockCodegen EmitRetVoid(BasicBlockBuilder BasicBlock) { var retVoid = BuildRetVoid(BasicBlock.Builder); return new BlockCodegen(BasicBlock); } /// <inheritdoc/> public override BlockCodegen Emit(BasicBlockBuilder BasicBlock) { if (retVal == null) { return EmitRetVoid(BasicBlock); } var retValCodegen = retVal.Emit(BasicBlock); BasicBlock = retValCodegen.BasicBlock; if (retVal.Type == PrimitiveTypes.Void) { return EmitRetVoid(BasicBlock); } else { var ret = BuildRet(BasicBlock.Builder, retValCodegen.Value); return new BlockCodegen(BasicBlock, ret); } } } }
Make ToString() short and provide Details()
using System; namespace ShadowsOfShadows.Items { public abstract class Item { protected String Name { get; set; } protected String StatsString { get; set; } public Item(String name, String stats) { Name = name; StatsString = stats; } public override String ToString() { String result = Name + "\n" + "Statistics:\n" + StatsString; return result; } public abstract AllowedItem Allowed { get; } public virtual bool IsLike(Item item) { return false; } } }
using System; namespace ShadowsOfShadows.Items { public abstract class Item { protected string Name { get; set; } protected string StatsString { get; set; } public Item(string name, string stats) { Name = name; StatsString = stats; } public override string ToString() => Name; public string Details() { string result = Name + "\n" + "Statistics:\n" + StatsString; return result; } public abstract AllowedItem Allowed { get; } public virtual bool IsLike(Item item) { return false; } } }
Fix bug causing incorrect results when dateTime was >= dateTime.Now + 363d
#region Using using System; #endregion namespace PortableExtensions { /// <summary> /// Class containing some extension methods for <see cref="DateTime" />. /// </summary> public static partial class DateTimeEx { /// <summary> /// Calculates the difference between the year of the current and the given date time. /// </summary> /// <param name="dateTime">The date time value.</param> /// <returns>The difference between the year of the current and the given date time.</returns> public static Int32 Age( this DateTime dateTime ) { if ( DateTime.Today.Month < dateTime.Month || DateTime.Today.Month == dateTime.Month && DateTime.Today.Day < dateTime.Day ) return DateTime.Today.Year - dateTime.Year - 1; return DateTime.Today.Year - dateTime.Year; } } }
#region Using using System; #endregion namespace PortableExtensions { /// <summary> /// Class containing some extension methods for <see cref="DateTime" />. /// </summary> public static partial class DateTimeEx { /// <summary> /// Calculates the difference between the year of the current and the given date time. /// </summary> /// <remarks> /// <paramref name="now"/> can be samller than <paramref name="dateTime"/>, which results in negative results. /// </remarks> /// <param name="dateTime">The date time value.</param> /// <param name="now">The 'current' date used to caluculate the age, or null tu use <see cref="DateTime.Now" />.</param> /// <returns>The difference between the year of the current and the given date time.</returns> public static Int32 Age(this DateTime dateTime, DateTime? now = null) { var currentDate = now ?? DateTime.Now; if (dateTime.Year == currentDate.Year) return 0; var age = currentDate.Year - dateTime.Year; if (dateTime > currentDate && (currentDate.Month > dateTime.Month || currentDate.Day > dateTime.Day)) age ++; else if ( (currentDate.Month < dateTime.Month || (currentDate.Month == dateTime.Month && currentDate.Day < dateTime.Day))) age--; return age; } } }
Add the GetEnumeratorOfCopy extension method.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ChamberLib { public static class Collection { public static void AddRange<T>(ICollection<T> collection, IEnumerable<T> items) { foreach (T item in items) { collection.Add(item); } } public static void RemoveRange<T>(ICollection<T> collection, IEnumerable<T> items) { foreach (T item in items) { collection.Remove(item); } } public static void AddRange<T, U>(this ICollection<T> collection, IEnumerable<U> items) where U : T { foreach (U item in items) { collection.Add(item); } } public static void RemoveRange<T, U>(this ICollection<T> collection, IEnumerable<U> items) where U : T { foreach (U item in items) { collection.Remove(item); } } public static void RemoveKeys<TKey, TValue, U>(this IDictionary<TKey, TValue> dictionary, IEnumerable<U> keys) where U : TKey { foreach (U key in keys) { dictionary.Remove(key); } } public static void EnqueueRange<T>(this Queue<T> queue, IEnumerable<T> items) { foreach (T item in items) { queue.Enqueue(item); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ChamberLib { public static class Collection { public static void AddRange<T>(ICollection<T> collection, IEnumerable<T> items) { foreach (T item in items) { collection.Add(item); } } public static void RemoveRange<T>(ICollection<T> collection, IEnumerable<T> items) { foreach (T item in items) { collection.Remove(item); } } public static void AddRange<T, U>(this ICollection<T> collection, IEnumerable<U> items) where U : T { foreach (U item in items) { collection.Add(item); } } public static void RemoveRange<T, U>(this ICollection<T> collection, IEnumerable<U> items) where U : T { foreach (U item in items) { collection.Remove(item); } } public static void RemoveKeys<TKey, TValue, U>(this IDictionary<TKey, TValue> dictionary, IEnumerable<U> keys) where U : TKey { foreach (U key in keys) { dictionary.Remove(key); } } public static void EnqueueRange<T>(this Queue<T> queue, IEnumerable<T> items) { foreach (T item in items) { queue.Enqueue(item); } } // This method is useful if you intend to modify a collection while/after iterating over it. public static IEnumerable<T> GetEnumeratorOfCopy<T>(this IEnumerable<T> collection) { var array = collection.ToArray(); foreach (var item in array) { yield return item; } } } }
Fix exception not recording topic name.
using System; using System.Collections.Concurrent; using System.Linq; using KafkaNet.Model; using KafkaNet.Protocol; namespace KafkaNet { public class DefaultPartitionSelector : IPartitionSelector { private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>(); public Partition Select(Topic topic, string key) { if (topic == null) throw new ArgumentNullException("topic"); if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic)); //use round robing var partitions = topic.Partitions; if (key == null) { return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) => { var index = partitions.FindIndex(0, p => p.Equals(i)); if (index == -1) return partitions.First(); if (++index >= partitions.Count) return partitions.First(); return partitions[index]; }); } //use key hash var partitionId = Math.Abs(key.GetHashCode()) % partitions.Count; var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId); if (partition == null) throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}", partitionId, string.Join(",", partitions.Select(x => x.PartitionId)))); return partition; } } }
using System; using System.Collections.Concurrent; using System.Linq; using KafkaNet.Model; using KafkaNet.Protocol; namespace KafkaNet { public class DefaultPartitionSelector : IPartitionSelector { private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>(); public Partition Select(Topic topic, string key) { if (topic == null) throw new ArgumentNullException("topic"); if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic.Name)); //use round robing var partitions = topic.Partitions; if (key == null) { return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) => { var index = partitions.FindIndex(0, p => p.Equals(i)); if (index == -1) return partitions.First(); if (++index >= partitions.Count) return partitions.First(); return partitions[index]; }); } //use key hash var partitionId = Math.Abs(key.GetHashCode()) % partitions.Count; var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId); if (partition == null) throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}", partitionId, string.Join(",", partitions.Select(x => x.PartitionId)))); return partition; } } }
Throw when error form account service.
using System; using ServiceStack; using ServiceStack.Logging; namespace DiscourseAutoApprove.ServiceInterface { public interface IServiceStackAccountClient { UserServiceResponse GetUserSubscription(string emailAddress); } public class ServiceStackAccountClient : IServiceStackAccountClient { private static readonly ILog Log = LogManager.GetLogger(typeof(ServiceStackAccountClient)); private readonly string serviceUrl; public ServiceStackAccountClient(string url) { serviceUrl = url; } public UserServiceResponse GetUserSubscription(string emailAddress) { UserServiceResponse result = null; try { result = serviceUrl.Fmt(emailAddress).GetJsonFromUrl() .FromJson<UserServiceResponse>(); } catch (Exception e) { Log.Error(e.Message); } return result; } } public class UserServiceResponse { public DateTime? Expiry { get; set; } } }
using System; using ServiceStack; using ServiceStack.Logging; namespace DiscourseAutoApprove.ServiceInterface { public interface IServiceStackAccountClient { UserServiceResponse GetUserSubscription(string emailAddress); } public class ServiceStackAccountClient : IServiceStackAccountClient { private static readonly ILog Log = LogManager.GetLogger(typeof(ServiceStackAccountClient)); private readonly string serviceUrl; public ServiceStackAccountClient(string url) { serviceUrl = url; } public UserServiceResponse GetUserSubscription(string emailAddress) { UserServiceResponse result = null; try { result = serviceUrl.Fmt(emailAddress).GetJsonFromUrl() .FromJson<UserServiceResponse>(); } catch (Exception e) { Log.Error(e.Message); throw; } return result; } } public class UserServiceResponse { public DateTime? Expiry { get; set; } } }
Add "None" snap type to fix flags not working correctly
// 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; namespace osu.Game.Rulesets.Edit { [Flags] public enum SnapType { NearbyObjects = 0, Grids = 1, All = NearbyObjects | Grids, } }
// 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; namespace osu.Game.Rulesets.Edit { [Flags] public enum SnapType { None = 0, NearbyObjects = 1 << 0, Grids = 1 << 1, All = NearbyObjects | Grids, } }
Update default build for .NET Core.
using System; using System.Linq; using Nuke.Common; using Nuke.Common.Git; using Nuke.Common.Tools.GitVersion; using Nuke.Core; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Core.IO.FileSystemTasks; using static Nuke.Core.IO.PathConstruction; using static Nuke.Core.EnvironmentInfo; class Build : NukeBuild { // Auto-injection fields: // - [GitVersion] must have 'GitVersion.CommandLine' referenced // - [GitRepository] parses the origin from git config // - [Parameter] retrieves its value from command-line arguments or environment variables // //[GitVersion] readonly GitVersion GitVersion; //[GitRepository] readonly GitRepository GitRepository; //[Parameter] readonly string MyGetApiKey; // This is the application entry point for the build. // It also defines the default target to execute. public static int Main () => Execute<Build>(x => x.Compile); Target Clean => _ => _ // Disabled for safety. .OnlyWhen(() => false) .Executes(() => { DeleteDirectories(GlobDirectories(SourceDirectory, "**/bin", "**/obj")); EnsureCleanDirectory(OutputDirectory); }); Target Restore => _ => _ .DependsOn(Clean) .Executes(() => { DotNetRestore(SolutionDirectory); }); Target Compile => _ => _ .DependsOn(Restore) .Executes(() => { DotNetBuild(SolutionDirectory); }); }
using System; using System.Linq; using Nuke.Common; using Nuke.Common.Git; using Nuke.Common.Tools.GitVersion; using Nuke.Core; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Core.IO.FileSystemTasks; using static Nuke.Core.IO.PathConstruction; using static Nuke.Core.EnvironmentInfo; class Build : NukeBuild { // Auto-injection fields: // - [GitVersion] must have 'GitVersion.CommandLine' referenced // - [GitRepository] parses the origin from git config // - [Parameter] retrieves its value from command-line arguments or environment variables // //[GitVersion] readonly GitVersion GitVersion; //[GitRepository] readonly GitRepository GitRepository; //[Parameter] readonly string MyGetApiKey; // This is the application entry point for the build. // It also defines the default target to execute. public static int Main () => Execute<Build>(x => x.Compile); Target Clean => _ => _ // Disabled for safety. .OnlyWhen(() => false) .Executes(() => { DeleteDirectories(GlobDirectories(SourceDirectory, "**/bin", "**/obj")); EnsureCleanDirectory(OutputDirectory); }); Target Restore => _ => _ .DependsOn(Clean) .Executes(() => { DotNetRestore(s => DefaultDotNetRestore); }); Target Compile => _ => _ .DependsOn(Restore) .Executes(() => { DotNetBuild(s => DefaultDotNetCompile); }); }
Make if block more readable
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; namespace osu.Framework.Configuration { public abstract class BindableNumberWithPrecision<T> : BindableNumber<T> where T : struct { /// <summary> /// An event which is raised when <see cref="Precision"/> has changed (or manually via <see cref="TriggerPrecisionChange"/>). /// </summary> public event Action<T> PrecisionChanged; private T precision; /// <summary> /// The precision up to which the value of this bindable should be rounded. /// </summary> public T Precision { get => precision; set { if (precision.Equals(value)) return; precision = value; TriggerPrecisionChange(); } } protected BindableNumberWithPrecision(T value = default(T)) : base(value) { precision = DefaultPrecision; } public override void TriggerChange() { base.TriggerChange(); TriggerPrecisionChange(false); } protected void TriggerPrecisionChange(bool propagateToBindings = true) { PrecisionChanged?.Invoke(MinValue); if (propagateToBindings) Bindings?.ForEachAlive(b => { if (b is BindableNumberWithPrecision<T> other) other.Precision = Precision; }); } protected abstract T DefaultPrecision { get; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; namespace osu.Framework.Configuration { public abstract class BindableNumberWithPrecision<T> : BindableNumber<T> where T : struct { /// <summary> /// An event which is raised when <see cref="Precision"/> has changed (or manually via <see cref="TriggerPrecisionChange"/>). /// </summary> public event Action<T> PrecisionChanged; private T precision; /// <summary> /// The precision up to which the value of this bindable should be rounded. /// </summary> public T Precision { get => precision; set { if (precision.Equals(value)) return; precision = value; TriggerPrecisionChange(); } } protected BindableNumberWithPrecision(T value = default(T)) : base(value) { precision = DefaultPrecision; } public override void TriggerChange() { base.TriggerChange(); TriggerPrecisionChange(false); } protected void TriggerPrecisionChange(bool propagateToBindings = true) { PrecisionChanged?.Invoke(MinValue); if (!propagateToBindings) return; Bindings?.ForEachAlive(b => { if (b is BindableNumberWithPrecision<T> other) other.Precision = Precision; }); } protected abstract T DefaultPrecision { get; } } }
Add method to return a header value from a HTTP response
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Codenesium.DataConversionExtensions { public static class HTTPResponseHelper { public static HttpResponseMessage ToJSONResponse(this object obj, System.Net.HttpStatusCode statusCode) { var response = new HttpResponseMessage() { StatusCode = statusCode, Content = new StringContent(JsonConvert.SerializeObject(obj)) }; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); return response; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Codenesium.DataConversionExtensions { public static class HTTPResponseHelper { public static HttpResponseMessage ToJSONResponse(this object obj, System.Net.HttpStatusCode statusCode) { var response = new HttpResponseMessage() { StatusCode = statusCode, Content = new StringContent(JsonConvert.SerializeObject(obj)) }; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); return response; } public static string GetHeaderValue(this HttpResponseMessage message,string key) { IEnumerable<string> values; string value = string.Empty; if (message.Headers.TryGetValues(key, out values)) { value = values.FirstOrDefault(); } return value; } } }
Add Pow to MathF compat file.
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; namespace System { // MathF emulation on platforms which don't support it natively. internal static class MathF { public const float PI = (float)Math.PI; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Abs(float x) { return Math.Abs(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Acos(float x) { return (float)Math.Acos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Cos(float x) { return (float)Math.Cos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float IEEERemainder(float x, float y) { return (float)Math.IEEERemainder(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sin(float x) { return (float)Math.Sin(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sqrt(float x) { return (float)Math.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Tan(float x) { return (float)Math.Tan(x); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; namespace System { // MathF emulation on platforms which don't support it natively. internal static class MathF { public const float PI = (float)Math.PI; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Abs(float x) { return Math.Abs(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Acos(float x) { return (float)Math.Acos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Cos(float x) { return (float)Math.Cos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float IEEERemainder(float x, float y) { return (float)Math.IEEERemainder(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Pow(float x, float y) { return (float)Math.Pow(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sin(float x) { return (float)Math.Sin(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sqrt(float x) { return (float)Math.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Tan(float x) { return (float)Math.Tan(x); } } }
Fix the syntax error Travis works :D
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Spacecraft : MonoBehaviour { } SYNTAX ERROR :D
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Spacecraft : MonoBehaviour { }
Fix possible race condition in the Upgrade Callback
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace IceBuilder { public interface UpgradeProgressCallback { bool Canceled { get; set; } void Finished(); void ReportProgress(String project, int index); } public partial class UpgradeDialogProgress : Form, UpgradeProgressCallback { public UpgradeDialogProgress(int total) { InitializeComponent(); ProgressBar.Maximum = total; } private void CancelButton_Clicked(object sender, EventArgs e) { Canceled = true; } public bool Canceled { get; set; } public void ReportProgress(String project, int index) { InfoLabel.Text = String.Format("Upgrading project: {0}", project); ProgressBar.Value = index; } public void Finished() { Close(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace IceBuilder { public interface UpgradeProgressCallback { bool Canceled { get; set; } void Finished(); void ReportProgress(String project, int index); } public partial class UpgradeDialogProgress : Form, UpgradeProgressCallback { public UpgradeDialogProgress(int total) { InitializeComponent(); _canceled = false; ProgressBar.Maximum = total; } private void CancelButton_Clicked(object sender, EventArgs e) { Canceled = true; } private bool _canceled; public bool Canceled { get { lock (this) { return _canceled; } } set { lock (this) { _canceled = value; } } } public void ReportProgress(String project, int index) { InfoLabel.Text = String.Format("Upgrading project: {0}", project); ProgressBar.Value = index; } public void Finished() { Close(); } } }
Move the replace filter to internal
// stylecop.header using Strinken.Parser; namespace Strinken.Filters { /// <summary> /// This filter takes some couples of arguments, and replace each occurrence of each first argument by the second. /// </summary> public class ReplaceFilter : IFilter { /// <inheritdoc/> public string Description => "This filter takes some couples of arguments, and replace each occurrence of each first argument by the second."; /// <inheritdoc/> public string Name => "Replace"; /// <inheritdoc/> public string Usage => "{tag:replace+value1,replaceValue1,value2,replaceValue2...}"; /// <inheritdoc/> public string Resolve(string value, string[] arguments) { var newValue = value; for (int i = 0; i < arguments.Length / 2; i++) { newValue = newValue.Replace(arguments[i * 2], arguments[(i * 2) + 1]); } return newValue; } /// <inheritdoc/> public bool Validate(string[] arguments) => arguments?.Length > 0 && arguments?.Length % 2 == 0; } }
// stylecop.header using Strinken.Parser; namespace Strinken.Filters { /// <summary> /// This filter takes some couples of arguments, and replace each occurrence of each first argument by the second. /// </summary> internal class ReplaceFilter : IFilter { /// <inheritdoc/> public string Description => "This filter takes some couples of arguments, and replace each occurrence of each first argument by the second."; /// <inheritdoc/> public string Name => "Replace"; /// <inheritdoc/> public string Usage => "{tag:replace+value1,replaceValue1,value2,replaceValue2...}"; /// <inheritdoc/> public string Resolve(string value, string[] arguments) { var newValue = value; for (int i = 0; i < arguments.Length / 2; i++) { newValue = newValue.Replace(arguments[i * 2], arguments[(i * 2) + 1]); } return newValue; } /// <inheritdoc/> public bool Validate(string[] arguments) => arguments?.Length > 0 && arguments?.Length % 2 == 0; } }
Make PowerShellScripts class static per review.
namespace NuGet.VisualStudio { public class PowerShellScripts { public static readonly string Install = "install.ps1"; public static readonly string Uninstall = "uninstall.ps1"; public static readonly string Init = "init.ps1"; } }
namespace NuGet.VisualStudio { public static class PowerShellScripts { public static readonly string Install = "install.ps1"; public static readonly string Uninstall = "uninstall.ps1"; public static readonly string Init = "init.ps1"; } }
Revert AssemblyVersion to 2.1.0 because there are no breaking changes in this version
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Traffic Manager Management Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Traffic Manager management functions for managing the Microsoft Azure Traffic Manager service.")] [assembly: AssemblyVersion("2.2.0.0")] [assembly: AssemblyFileVersion("2.2.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Traffic Manager Management Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Traffic Manager management functions for managing the Microsoft Azure Traffic Manager service.")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.2.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
Add hold note tick judgement.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Rulesets.Mania.Judgements { public class HoldNoteTickJudgement : ManiaJudgement { } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Rulesets.Mania.Judgements { public class HoldNoteTickJudgement : ManiaJudgement { public override int NumericResultForScore(ManiaHitResult result) => 20; public override int NumericResultForAccuracy(ManiaHitResult result) => 0; // Don't count ticks into accuracy } }
Make sure that authorization of TraktCalendarUserDVDMoviesRequest is required
namespace TraktApiSharp.Tests.Experimental.Requests.Calendars.OAuth { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Calendars.OAuth; using TraktApiSharp.Objects.Get.Calendars; [TestClass] public class TraktCalendarUserDVDMoviesRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")] public void TestTraktCalendarUserDVDMoviesRequestIsNotAbstract() { typeof(TraktCalendarUserDVDMoviesRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")] public void TestTraktCalendarUserDVDMoviesRequestIsSealed() { typeof(TraktCalendarUserDVDMoviesRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")] public void TestTraktCalendarUserDVDMoviesRequestIsSubclassOfATraktCalendarUserRequest() { typeof(TraktCalendarUserDVDMoviesRequest).IsSubclassOf(typeof(ATraktCalendarUserRequest<TraktCalendarMovie>)).Should().BeTrue(); } } }
namespace TraktApiSharp.Tests.Experimental.Requests.Calendars.OAuth { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Calendars.OAuth; using TraktApiSharp.Objects.Get.Calendars; using TraktApiSharp.Requests; [TestClass] public class TraktCalendarUserDVDMoviesRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")] public void TestTraktCalendarUserDVDMoviesRequestIsNotAbstract() { typeof(TraktCalendarUserDVDMoviesRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")] public void TestTraktCalendarUserDVDMoviesRequestIsSealed() { typeof(TraktCalendarUserDVDMoviesRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")] public void TestTraktCalendarUserDVDMoviesRequestIsSubclassOfATraktCalendarUserRequest() { typeof(TraktCalendarUserDVDMoviesRequest).IsSubclassOf(typeof(ATraktCalendarUserRequest<TraktCalendarMovie>)).Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")] public void TestTraktCalendarUserDVDMoviesRequestHasAuthorizationRequired() { var request = new TraktCalendarUserDVDMoviesRequest(null); request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required); } } }
Fix crash error when login state is invalid
using System; using Agiil.Domain.Auth; using Agiil.Web.Models.Shared; using CSF.ORM; namespace Agiil.Web.Services.Auth { public class LoginStateReader { readonly IIdentityReader userReader; readonly IEntityData data; public LoginStateModel GetLoginState() { var userInfo = userReader.GetCurrentUserInfo(); return new LoginStateModel { UserInfo = userInfo, IsSiteAdmin = (userInfo != null)? data.Get(userInfo.Identity).SiteAdministrator : false, }; } public LoginStateReader(IIdentityReader userReader, IEntityData data) { this.userReader = userReader ?? throw new ArgumentNullException(nameof(userReader)); this.data = data ?? throw new ArgumentNullException(nameof(data)); } } }
using System; using Agiil.Domain.Auth; using Agiil.Web.Models.Shared; using CSF.ORM; namespace Agiil.Web.Services.Auth { public class LoginStateReader { readonly IIdentityReader userReader; readonly IEntityData data; public LoginStateModel GetLoginState() { var userInfo = userReader.GetCurrentUserInfo(); var user = (userInfo?.Identity != null) ? data.Get(userInfo.Identity) : null; return new LoginStateModel { UserInfo = userInfo, IsSiteAdmin = user?.SiteAdministrator == true, }; } public LoginStateReader(IIdentityReader userReader, IEntityData data) { this.userReader = userReader ?? throw new ArgumentNullException(nameof(userReader)); this.data = data ?? throw new ArgumentNullException(nameof(data)); } } }
Add sticky note 'GC Handicapping System'
<div class="sticky-notes"> </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 tests: difference was that the db was initialized in local and "/app/ensureBasicUser" is now "/ensureBasicUser".
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebApp.Tests { static class WebAppUrl { public const string EnsureBasicUser = "/app/ensureBasicUser"; public const string StartLoginUri = "/.webfront/c/startLogin"; public const string BasicLoginUri = "/.webfront/c/basicLogin"; public const string LoginUri = "/.webfront/c/unsafeDirectLogin"; public const string RefreshUri = "/.webfront/c/refresh"; public const string LogoutUri = "/.webfront/c/logout"; public const string TokenExplainUri = "/.webfront/token"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebApp.Tests { static class WebAppUrl { public const string EnsureBasicUser = "/ensureBasicUser"; public const string StartLoginUri = "/.webfront/c/startLogin"; public const string BasicLoginUri = "/.webfront/c/basicLogin"; public const string LoginUri = "/.webfront/c/unsafeDirectLogin"; public const string RefreshUri = "/.webfront/c/refresh"; public const string LogoutUri = "/.webfront/c/logout"; public const string TokenExplainUri = "/.webfront/token"; } }
Fix test for GT_INDEX_ADDR to forcibly compile with minopts
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; // GitHub 20040: operand ordering bug with GT_INDEX_ADDR // Requires minopts/tier0 to repro namespace GitHub_20040 { class Program { static int Main(string[] args) { var array = new byte[] {0x00, 0x01}; var reader = new BinaryTokenStreamReader(array); var val = reader.ReadByte(); if (val == 0x01) { Console.WriteLine("Pass"); return 100; } else { Console.WriteLine($"Fail: val=0x{val:x2}, expected 0x01"); return 0; } } } public class BinaryTokenStreamReader { private readonly byte[] currentBuffer; public BinaryTokenStreamReader(byte[] input) { this.currentBuffer = input; } byte[] CheckLength(out int offset) { // In the original code, this logic is more complicated. // It's simplified here to demonstrate the bug. offset = 1; return currentBuffer; } public byte ReadByte() { int offset; var buff = CheckLength(out offset); return buff[offset]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; // GitHub 20040: operand ordering bug with GT_INDEX_ADDR // Requires minopts/tier0 to repro namespace GitHub_20040 { class Program { static int Main(string[] args) { var array = new byte[] {0x00, 0x01}; var reader = new BinaryTokenStreamReader(array); var val = reader.ReadByte(); if (val == 0x01) { Console.WriteLine("Pass"); return 100; } else { Console.WriteLine($"Fail: val=0x{val:x2}, expected 0x01"); return 0; } } } public class BinaryTokenStreamReader { private readonly byte[] currentBuffer; public BinaryTokenStreamReader(byte[] input) { this.currentBuffer = input; } byte[] CheckLength(out int offset) { // In the original code, this logic is more complicated. // It's simplified here to demonstrate the bug. offset = 1; return currentBuffer; } [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] public byte ReadByte() { int offset; var buff = CheckLength(out offset); return buff[offset]; } } }
Add route for updating caches via fragment traversal
using Data; using Ninject; using Services; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace LCAToolAPI.API { public class FragmentTraversalController : ApiController { [Inject] private readonly IFragmentTraversal _fragmentTraversal ; public FragmentTraversalController(IFragmentTraversal fragmentTraversal) { if (fragmentTraversal == null) { throw new ArgumentNullException("fragmentTraversal is null"); } _fragmentTraversal = fragmentTraversal; } int scenarioId = 1; //GET api/<controller> [System.Web.Http.AcceptVerbs("GET", "POST")] [System.Web.Http.HttpGet] public void Traversal() { _fragmentTraversal.Traverse(scenarioId); } //// GET api/<controller> //public IEnumerable<string> Get() //{ // return new string[] { "value1", "value2" }; //} //// GET api/<controller>/5 //public string Get(int id) //{ // return "value"; //} //// POST api/<controller> //public void Post([FromBody]string value) //{ //} //// PUT api/<controller>/5 //public void Put(int id, [FromBody]string value) //{ //} //// DELETE api/<controller>/5 //public void Delete(int id) //{ //} } }
using Data; using Ninject; using Services; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace LCAToolAPI.API { public class FragmentTraversalController : ApiController { [Inject] private readonly IFragmentTraversal _fragmentTraversal ; public FragmentTraversalController(IFragmentTraversal fragmentTraversal) { if (fragmentTraversal == null) { throw new ArgumentNullException("fragmentTraversal is null"); } _fragmentTraversal = fragmentTraversal; } //int scenarioId = 1; //GET api/<controller> [Route("api/scenarios/{scenarioID}/updatecaches")] [System.Web.Http.AcceptVerbs("GET", "POST")] [System.Web.Http.HttpGet] public void Traversal(int scenarioId) { _fragmentTraversal.Traverse(scenarioId); } //// GET api/<controller> //public IEnumerable<string> Get() //{ // return new string[] { "value1", "value2" }; //} //// GET api/<controller>/5 //public string Get(int id) //{ // return "value"; //} //// POST api/<controller> //public void Post([FromBody]string value) //{ //} //// PUT api/<controller>/5 //public void Put(int id, [FromBody]string value) //{ //} //// DELETE api/<controller>/5 //public void Delete(int id) //{ //} } }
Fix compilation on Unity < 5.3.
#if !NO_UNITY using System; using UnityEngine; using UnityEngine.Events; namespace FullSerializer { partial class fsConverterRegistrar { // Disable the converter for the time being. Unity's JsonUtility API cannot be called from // within a C# ISerializationCallbackReceiver callback. // public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter; } } namespace FullSerializer.Internal.Converters { // The standard FS reflection converter has started causing Unity to crash when processing // UnityEvent. We can send the serialization through JsonUtility which appears to work correctly // instead. // // We have to support legacy serialization formats so importing works as expected. public class UnityEvent_Converter : fsConverter { public override bool CanProcess(Type type) { return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false; } public override bool RequestCycleSupport(Type storageType) { return false; } public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { Type objectType = (Type)instance; fsResult result = fsResult.Success; instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType); return result; } public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { fsResult result = fsResult.Success; serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance)); return result; } } } #endif
#if !NO_UNITY && UNITY_5_3_OR_NEWER using System; using UnityEngine; using UnityEngine.Events; namespace FullSerializer { partial class fsConverterRegistrar { // Disable the converter for the time being. Unity's JsonUtility API cannot be called from // within a C# ISerializationCallbackReceiver callback. // public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter; } } namespace FullSerializer.Internal.Converters { // The standard FS reflection converter has started causing Unity to crash when processing // UnityEvent. We can send the serialization through JsonUtility which appears to work correctly // instead. // // We have to support legacy serialization formats so importing works as expected. public class UnityEvent_Converter : fsConverter { public override bool CanProcess(Type type) { return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false; } public override bool RequestCycleSupport(Type storageType) { return false; } public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { Type objectType = (Type)instance; fsResult result = fsResult.Success; instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType); return result; } public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { fsResult result = fsResult.Success; serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance)); return result; } } } #endif
Disable locally failiny npm command test
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System.Threading.Tasks; using Microsoft.NodejsTools.Npm; using Microsoft.NodejsTools.Npm.SPI; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace NpmTests { [TestClass] public class NpmExecuteCommandTests { // https://nodejstools.codeplex.com/workitem/1575 [TestMethod, Priority(0), Timeout(180000)] public async Task TestNpmCommandProcessExitSucceeds() { var npmPath = NpmHelpers.GetPathToNpm(); var redirector = new NpmCommand.NpmCommandRedirector(new NpmBinCommand(null, false)); for (int j = 0; j < 200; j++) { await NpmHelpers.ExecuteNpmCommandAsync( redirector, npmPath, null, new[] {"config", "get", "registry"}, null); } } } }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System.Threading.Tasks; using Microsoft.NodejsTools.Npm; using Microsoft.NodejsTools.Npm.SPI; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace NpmTests { [TestClass] public class NpmExecuteCommandTests { // https://nodejstools.codeplex.com/workitem/1575 [Ignore] [TestMethod, Priority(0), Timeout(180000)] public async Task TestNpmCommandProcessExitSucceeds() { var npmPath = NpmHelpers.GetPathToNpm(); var redirector = new NpmCommand.NpmCommandRedirector(new NpmBinCommand(null, false)); for (int j = 0; j < 200; j++) { await NpmHelpers.ExecuteNpmCommandAsync( redirector, npmPath, null, new[] {"config", "get", "registry"}, null); } } } }
Change from Redirect to Proxy downloads
using System.Web.Mvc; using Cake.Web.Core.Content; namespace Cake.Web.Controllers { public class DownloadController : Controller { private readonly PackagesConfigContent _content; public DownloadController(PackagesConfigContent content) { _content = content; } public ActionResult Windows() { return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/build.ps1"); } public ActionResult PowerShell() { return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/build.ps1"); } public ActionResult Linux() { return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/build.sh"); } // ReSharper disable once InconsistentNaming public ActionResult OSX() { return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/build.sh"); } public ActionResult Bash() { return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/build.sh"); } public ActionResult Configuration() { return Redirect("https://raw.githubusercontent.com/cake-build/resources/master/cake.config"); } public ActionResult Packages() { var result = File(_content.Data, "text/xml", "packages.config"); Response.Charset = "utf-8"; return result; } } }
using System.Web.Mvc; using Cake.Web.Core.Content; namespace Cake.Web.Controllers { public class DownloadController : Controller { private readonly PackagesConfigContent _content; public DownloadController(PackagesConfigContent content) { _content = content; } public ActionResult Windows() { return Download("https://raw.githubusercontent.com/cake-build/resources/master/build.ps1"); } public ActionResult PowerShell() { return Download("https://raw.githubusercontent.com/cake-build/resources/master/build.ps1"); } public ActionResult Linux() { return Download("https://raw.githubusercontent.com/cake-build/resources/master/build.sh"); } // ReSharper disable once InconsistentNaming public ActionResult OSX() { return Download("https://raw.githubusercontent.com/cake-build/resources/master/build.sh"); } public ActionResult Bash() { return Download("https://raw.githubusercontent.com/cake-build/resources/master/build.sh"); } public ActionResult Configuration() { return Download("https://raw.githubusercontent.com/cake-build/resources/master/cake.config"); } public ActionResult Packages() { var result = File(_content.Data, "text/xml", "packages.config"); Response.Charset = "utf-8"; return result; } private ActionResult Download(string url) { using (var client = new System.Net.WebClient()) { return File( client.DownloadData(url), "text/plain; charset=utf-8" ); } } } }
Make sure the MainThreadScheduler is set properly
/// <summary> /// Used by the ModuleInit. All code inside the Initialize method is ran as soon as the assembly is loaded. /// </summary> public static class ModuleInitializer { /// <summary> /// Initializes the module. /// </summary> public static void Initialize() { } }
using System.Reactive.Concurrency; using ReactiveUI; /// <summary> /// Used by the ModuleInit. All code inside the Initialize method is ran as soon as the assembly is loaded. /// </summary> public static class ModuleInitializer { /// <summary> /// Initializes the module. /// </summary> public static void Initialize() { RxApp.MainThreadScheduler = new WaitForDispatcherScheduler(() => DispatcherScheduler.Current); } }
Add insulation bootstrapper to jobs.
using System; using Exceptionless.Core.Extensions; using Exceptionless.Core.Utility; using Foundatio.ServiceProvider; using SimpleInjector; namespace Exceptionless.Core.Jobs { public class JobBootstrapper : BootstrappedServiceProviderBase { public override IServiceProvider Bootstrap() { var container = new Container(); container.Options.AllowOverridingRegistrations = true; container.Options.PropertySelectionBehavior = new InjectAttributePropertySelectionBehavior(); container.RegisterPackage<Bootstrapper>(); return container; } } }
using System; using System.Reflection; using Exceptionless.Core.Extensions; using Exceptionless.Core.Utility; using Foundatio.ServiceProvider; using NLog.Fluent; using SimpleInjector; namespace Exceptionless.Core.Jobs { public class JobBootstrapper : BootstrappedServiceProviderBase { public override IServiceProvider Bootstrap() { var container = new Container(); container.Options.AllowOverridingRegistrations = true; container.Options.PropertySelectionBehavior = new InjectAttributePropertySelectionBehavior(); container.RegisterPackage<Bootstrapper>(); Assembly insulationAssembly = null; try { insulationAssembly = Assembly.Load("Exceptionless.Insulation"); } catch (Exception ex) { Log.Error().Message("Unable to load the insulation asssembly.").Exception(ex).Write(); } if (insulationAssembly != null) container.RegisterPackages(new[] { insulationAssembly }); return container; } } }