Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Remove unused method on DateTimeOffsetConvertrer and consolidated code
using System; namespace AllReady.Providers { public interface IConvertDateTimeOffset { DateTimeOffset ConvertDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0); DateTimeOffset ConvertDateTimeOffsetTo(TimeZoneInfo timeZoneInfo, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0); } public class DateTimeOffsetConverter : IConvertDateTimeOffset { public DateTimeOffset ConvertDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0) { return ConvertDateTimeOffsetTo(FindSystemTimeZoneBy(timeZoneId), dateTimeOffset, hour, minute, second); } public DateTimeOffset ConvertDateTimeOffsetTo(TimeZoneInfo timeZoneInfo, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0) { return new DateTimeOffset(dateTimeOffset.Year, dateTimeOffset.Month, dateTimeOffset.Day, hour, minute, second, timeZoneInfo.GetUtcOffset(dateTimeOffset)); //both of these implemenations lose the ability to specificy the hour, minute and second unless the given dateTimeOffset value being passed into this method //already has those values set //1. //return TimeZoneInfo.ConvertTime(dateTimeOffset, timeZoneInfo); //2. //var timeSpan = timeZoneInfo.GetUtcOffset(dateTimeOffset); //return dateTimeOffset.ToOffset(timeSpan); } private static TimeZoneInfo FindSystemTimeZoneBy(string timeZoneId) { return TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); } } }
using System; namespace AllReady.Providers { public interface IConvertDateTimeOffset { DateTimeOffset ConvertDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0); } public class DateTimeOffsetConverter : IConvertDateTimeOffset { public DateTimeOffset ConvertDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0) { var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); return new DateTimeOffset(dateTimeOffset.Year, dateTimeOffset.Month, dateTimeOffset.Day, hour, minute, second, timeZoneInfo.GetUtcOffset(dateTimeOffset)); } } }
Add a placeholder cover URL for users.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using Newtonsoft.Json; namespace osu.Game.Users { public class User { [JsonProperty(@"id")] public long Id = 1; [JsonProperty(@"username")] public string Username; public Country Country; public Team Team; [JsonProperty(@"colour")] public string Colour; } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using Newtonsoft.Json; namespace osu.Game.Users { public class User { [JsonProperty(@"id")] public long Id = 1; [JsonProperty(@"username")] public string Username; public Country Country; public Team Team; [JsonProperty(@"colour")] public string Colour; public string CoverUrl = @"https://assets.ppy.sh/user-profile-covers/2/08cad88747c235a64fca5f1b770e100f120827ded1ffe3b66bfcd19c940afa65.jpeg"; } }
Write an additional line after creating application
using System; using System.Linq; namespace AppHarbor.Commands { public class CreateCommand : ICommand { private readonly IAppHarborClient _appHarborClient; private readonly IApplicationConfiguration _applicationConfiguration; public CreateCommand(IAppHarborClient appHarborClient, IApplicationConfiguration applicationConfiguration) { _appHarborClient = appHarborClient; _applicationConfiguration = applicationConfiguration; } public void Execute(string[] arguments) { if (arguments.Length == 0) { throw new CommandException("An application name must be provided to create an application"); } var result = _appHarborClient.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()); Console.WriteLine("Created application \"{0}\" | URL: https://{0}.apphb.com", result.ID); _applicationConfiguration.SetupApplication(result.ID, _appHarborClient.GetUser()); } } }
using System; using System.Linq; namespace AppHarbor.Commands { public class CreateCommand : ICommand { private readonly IAppHarborClient _appHarborClient; private readonly IApplicationConfiguration _applicationConfiguration; public CreateCommand(IAppHarborClient appHarborClient, IApplicationConfiguration applicationConfiguration) { _appHarborClient = appHarborClient; _applicationConfiguration = applicationConfiguration; } public void Execute(string[] arguments) { if (arguments.Length == 0) { throw new CommandException("An application name must be provided to create an application"); } var result = _appHarborClient.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()); Console.WriteLine("Created application \"{0}\" | URL: https://{0}.apphb.com", result.ID); Console.WriteLine(""); _applicationConfiguration.SetupApplication(result.ID, _appHarborClient.GetUser()); } } }
Add missing using statement in word-count
using System.Text.RegularExpressions; using System.Collections.Generic; public class Phrase { private readonly string _phrase; public Phrase(string phrase) { if (phrase == null) throw new ArgumentNullException("phrase"); _phrase = phrase; } public IDictionary<string, int> WordCount() { var counts = new Dictionary<string, int>(); Match match = Regex.Match(_phrase.ToLower(), @"\w+'\w+|\w+"); while(match.Success) { string word = match.Value; if(!counts.ContainsKey(word)) { counts[word] = 0; } counts[word]++; match = match.NextMatch(); } return counts; } }
using System; using System.Text.RegularExpressions; using System.Collections.Generic; public class Phrase { private readonly string _phrase; public Phrase(string phrase) { if (phrase == null) throw new ArgumentNullException("phrase"); _phrase = phrase; } public IDictionary<string, int> WordCount() { var counts = new Dictionary<string, int>(); Match match = Regex.Match(_phrase.ToLower(), @"\w+'\w+|\w+"); while(match.Success) { string word = match.Value; if(!counts.ContainsKey(word)) { counts[word] = 0; } counts[word]++; match = match.NextMatch(); } return counts; } }
Enable tests parallelization for all build configurations
#if DEBUG using NUnit.Framework; [assembly: LevelOfParallelism(4)] [assembly: Parallelizable(ParallelScope.Fixtures)] #endif
using NUnit.Framework; [assembly: Parallelizable(ParallelScope.Fixtures)]
Allow OuterLoop on a class
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Xunit.Sdk; namespace Xunit { /// <summary> /// Apply this attribute to your test method to specify a outer-loop category. /// </summary> [TraitDiscoverer("Xunit.NetCore.Extensions.OuterLoopTestsDiscoverer", "Xunit.NetCore.Extensions")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class OuterLoopAttribute : Attribute, ITraitAttribute { public OuterLoopAttribute() { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Xunit.Sdk; namespace Xunit { /// <summary> /// Apply this attribute to your test method to specify a outer-loop category. /// </summary> [TraitDiscoverer("Xunit.NetCore.Extensions.OuterLoopTestsDiscoverer", "Xunit.NetCore.Extensions")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] public class OuterLoopAttribute : Attribute, ITraitAttribute { public OuterLoopAttribute() { } } }
Test push for appveyor nuget restore
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 CheckUp2 { public partial class MainWindow : Form { public MainWindow() { InitializeComponent(); } } }
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 CheckUp2 { public partial class MainWindow : Form { public MainWindow() { InitializeComponent(); } } }
Change interface parameter name to match it's type name
namespace KInspector.Core { /// <summary> /// The interface to implement to add a functionality to this application. /// Add DLL with implementation of this interface to the same folder as executing assembly to auto-load /// all of them. /// </summary> public interface IModule { /// <summary> /// Returns the metadata of the module /// </summary> /// <example> /// <![CDATA[ /// public ModuleMetadata GetModuleMetadata() /// { /// return new ModuleMetadata() /// { /// Name = "EventLog Information", /// Versions = new List<string>() { "8.0", "8.1" }, /// Comment = "Checks event log for information like 404 pages and logged exceptions.", /// ResultType = ModuleResultsType.Table /// }; /// } /// ]]> /// </example> ModuleMetadata GetModuleMetadata(); /// <summary> /// Returns the whole result set of the module. /// </summary> /// <example> /// <![CDATA[ /// public ModuleResults GetResults(InstanceInfo instanceInfo, DatabaseService dbService) /// { /// var dbService = new DatabaseService(config); /// var results = dbService.ExecuteAndGetPrintsFromFile("EventLogInfoModule.sql"); /// /// return new ModuleResults() /// { /// Result = results, /// ResultComment = "Check event log for more details!" /// }; /// } /// ]]> /// </example> ModuleResults GetResults(InstanceInfo config, DatabaseService dbService); } }
namespace KInspector.Core { /// <summary> /// The interface to implement to add a functionality to this application. /// Add DLL with implementation of this interface to the same folder as executing assembly to auto-load /// all of them. /// </summary> public interface IModule { /// <summary> /// Returns the metadata of the module /// </summary> /// <example> /// <![CDATA[ /// public ModuleMetadata GetModuleMetadata() /// { /// return new ModuleMetadata() /// { /// Name = "EventLog Information", /// Versions = new List<string>() { "8.0", "8.1" }, /// Comment = "Checks event log for information like 404 pages and logged exceptions.", /// ResultType = ModuleResultsType.Table /// }; /// } /// ]]> /// </example> ModuleMetadata GetModuleMetadata(); /// <summary> /// Returns the whole result set of the module. /// </summary> /// <example> /// <![CDATA[ /// public ModuleResults GetResults(InstanceInfo instanceInfo, DatabaseService dbService) /// { /// var dbService = new DatabaseService(config); /// var results = dbService.ExecuteAndGetPrintsFromFile("EventLogInfoModule.sql"); /// /// return new ModuleResults() /// { /// Result = results, /// ResultComment = "Check event log for more details!" /// }; /// } /// ]]> /// </example> ModuleResults GetResults(InstanceInfo instanceInfo, DatabaseService dbService); } }
Revert "Convert mapping async exceptions to Promise"
namespace Miruken.Map { using System; using Callback; using Concurrency; public class MappingHandler : Handler, IMapping { public object Map(object source, object typeOrInstance, object format = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (typeOrInstance == null) throw new ArgumentNullException(nameof(typeOrInstance)); var mapFrom = new Mapping(source, typeOrInstance, format); return Composer.Handle(mapFrom) ? mapFrom.Result : Unhandled<object>(); } public Promise MapAsync(object source, object typeOrInstance, object format) { if (source == null) throw new ArgumentNullException(nameof(source)); if (typeOrInstance == null) throw new ArgumentNullException(nameof(typeOrInstance)); var mapFrom = new Mapping(source, typeOrInstance, format) { WantsAsync = true }; try { return Composer.Handle(mapFrom) ? (Promise)mapFrom.Result : Unhandled<Promise>(); } catch (Exception ex) { return Promise.Rejected(ex); } } } }
namespace Miruken.Map { using System; using Callback; using Concurrency; public class MappingHandler : Handler, IMapping { public object Map(object source, object typeOrInstance, object format = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (typeOrInstance == null) throw new ArgumentNullException(nameof(typeOrInstance)); var mapFrom = new Mapping(source, typeOrInstance, format); return Composer.Handle(mapFrom) ? mapFrom.Result : Unhandled<object>(); } public Promise MapAsync(object source, object typeOrInstance, object format) { if (source == null) throw new ArgumentNullException(nameof(source)); if (typeOrInstance == null) throw new ArgumentNullException(nameof(typeOrInstance)); var mapFrom = new Mapping(source, typeOrInstance, format) { WantsAsync = true }; return Composer.Handle(mapFrom) ? (Promise)mapFrom.Result : Unhandled<Promise>(); } } }
Remove obsolete clip clear request code
using System; namespace clipman.ViewModels { class SettingsPanelViewModel { public void ClearClips() { ClearRequested?.Invoke(this, EventArgs.Empty); } public event EventHandler ClearRequested; } }
using System; namespace clipman.ViewModels { class SettingsPanelViewModel { } }
Use explicit operators, since they are no longer used implicitly
// 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. #nullable enable using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CodeStyle { internal partial class CodeStyleOption2<T> { [return: NotNullIfNotNull("option")] public static implicit operator CodeStyleOption<T>?(CodeStyleOption2<T>? option) { if (option == null) { return null; } return new CodeStyleOption<T>(option.Value, (NotificationOption?)option.Notification); } [return: NotNullIfNotNull("option")] public static implicit operator CodeStyleOption2<T>?(CodeStyleOption<T>? option) { return option?.UnderlyingOption; } } }
// 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. #nullable enable using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CodeStyle { internal partial class CodeStyleOption2<T> { [return: NotNullIfNotNull("option")] public static explicit operator CodeStyleOption<T>?(CodeStyleOption2<T>? option) { if (option == null) { return null; } return new CodeStyleOption<T>(option.Value, (NotificationOption?)option.Notification); } [return: NotNullIfNotNull("option")] public static explicit operator CodeStyleOption2<T>?(CodeStyleOption<T>? option) { return option?.UnderlyingOption; } } }
Test for exception for now until we can get a proper test image.
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using System.IO; using ImageMagick; using Xunit; namespace Magick.NET.Tests { public class TheAvifCoder { [Fact] public void ShouldEncodeAndDecodeAlphaChannel() { using (var input = new MagickImage(Files.TestPNG)) { input.Resize(new Percentage(15)); using (var stream = new MemoryStream()) { input.Write(stream, MagickFormat.Avif); stream.Position = 0; using (var output = new MagickImage(stream)) { Assert.True(output.HasAlpha); Assert.Equal(MagickFormat.Avif, output.Format); Assert.Equal(input.Width, output.Width); Assert.Equal(input.Height, output.Height); } } } } [Fact] public void ShouldIgnoreEmptyExifProfile() { using (var image = new MagickImage(Files.Coders.EmptyExifAVIF)) { Assert.Equal(1, image.Width); Assert.Equal(1, image.Height); ColorAssert.Equal(MagickColors.Magenta, image, 1, 1); } } } }
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using System.IO; using ImageMagick; using Xunit; namespace Magick.NET.Tests { public class TheAvifCoder { [Fact] public void ShouldEncodeAndDecodeAlphaChannel() { using (var input = new MagickImage(Files.TestPNG)) { input.Resize(new Percentage(15)); using (var stream = new MemoryStream()) { input.Write(stream, MagickFormat.Avif); stream.Position = 0; using (var output = new MagickImage(stream)) { Assert.True(output.HasAlpha); Assert.Equal(MagickFormat.Avif, output.Format); Assert.Equal(input.Width, output.Width); Assert.Equal(input.Height, output.Height); } } } } [Fact] public void ShouldIgnoreEmptyExifProfile() { using (var image = new MagickImage()) { try { image.Read(Files.Coders.EmptyExifAVIF); } catch (MagickCorruptImageErrorException exception) { Assert.Contains("Invalid clean-aperture specification", exception.Message); } } } } }
Support configuring an existing option value.
using System.Collections.Immutable; using LanguageExt; namespace ExRam.Gremlinq.Core { public struct GremlinqOptions { private readonly IImmutableDictionary<GremlinqOption, object> _options; public GremlinqOptions(IImmutableDictionary<GremlinqOption, object> options) { _options = options; } public TValue GetValue<TValue>(GremlinqOption<TValue> option) { return (_options?.TryGetValue(option)) .ToOption() .Bind(x => x) .Map(optionValue => (TValue)optionValue) .IfNone(option.DefaultValue); } public GremlinqOptions SetValue<TValue>(GremlinqOption<TValue> option, TValue value) { return new GremlinqOptions(_options ?? ImmutableDictionary<GremlinqOption, object>.Empty.SetItem(option, value)); } } }
using System; using System.Collections.Immutable; using LanguageExt; namespace ExRam.Gremlinq.Core { public struct GremlinqOptions { private readonly IImmutableDictionary<GremlinqOption, object> _options; public GremlinqOptions(IImmutableDictionary<GremlinqOption, object> options) { _options = options; } public TValue GetValue<TValue>(GremlinqOption<TValue> option) { return (_options?.TryGetValue(option)) .ToOption() .Bind(x => x) .Map(optionValue => (TValue)optionValue) .IfNone(option.DefaultValue); } public GremlinqOptions SetValue<TValue>(GremlinqOption<TValue> option, TValue value) { return new GremlinqOptions(_options ?? ImmutableDictionary<GremlinqOption, object>.Empty.SetItem(option, value)); } public GremlinqOptions ConfigureValue<TValue>(GremlinqOption<TValue> option, Func<TValue, TValue> configuration) { return SetValue(option, configuration(GetValue(option))); } } }
Add default ctor to class. bugid: 417
using System; using Csla; using Csla.Serialization; namespace Csla.Security { /// <summary> /// Criteria class for passing a /// username/password pair to a /// custom identity class. /// </summary> [Serializable] public class UsernameCriteria : CriteriaBase { /// <summary> /// Username property definition. /// </summary> public static PropertyInfo<string> UsernameProperty = RegisterProperty(typeof(UsernameCriteria), new PropertyInfo<string>("Username", "Username")); /// <summary> /// Gets the username. /// </summary> public string Username { get { return ReadProperty(UsernameProperty); } private set { LoadProperty(UsernameProperty, value); } } /// <summary> /// Password property definition. /// </summary> public static PropertyInfo<string> PasswordProperty = RegisterProperty(typeof(UsernameCriteria), new PropertyInfo<string>("Password", "Password")); /// <summary> /// Gets the password. /// </summary> public string Password { get { return ReadProperty(PasswordProperty); } private set { LoadProperty(PasswordProperty, value); } } /// <summary> /// Creates a new instance of the object. /// </summary> /// <param name="username"> /// Username value. /// </param> /// <param name="password"> /// Password value. /// </param> public UsernameCriteria(string username, string password) { this.Username = username; this.Password = password; } } }
using System; using Csla; using Csla.Serialization; namespace Csla.Security { /// <summary> /// Criteria class for passing a /// username/password pair to a /// custom identity class. /// </summary> [Serializable] public class UsernameCriteria : CriteriaBase { /// <summary> /// Username property definition. /// </summary> public static PropertyInfo<string> UsernameProperty = RegisterProperty(typeof(UsernameCriteria), new PropertyInfo<string>("Username", "Username")); /// <summary> /// Gets the username. /// </summary> public string Username { get { return ReadProperty(UsernameProperty); } private set { LoadProperty(UsernameProperty, value); } } /// <summary> /// Password property definition. /// </summary> public static PropertyInfo<string> PasswordProperty = RegisterProperty(typeof(UsernameCriteria), new PropertyInfo<string>("Password", "Password")); /// <summary> /// Gets the password. /// </summary> public string Password { get { return ReadProperty(PasswordProperty); } private set { LoadProperty(PasswordProperty, value); } } /// <summary> /// Creates a new instance of the object. /// </summary> /// <param name="username"> /// Username value. /// </param> /// <param name="password"> /// Password value. /// </param> public UsernameCriteria(string username, string password) { this.Username = username; this.Password = password; } /// <summary> /// Creates a new instance of the object. /// </summary> #if SILVERLIGHT public UsernameCriteria() { } #else protected UsernameCriteria() { } #endif } }
Use AutoFixture for injecting argument string array
using AppHarbor.Commands; using Moq; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoMoq; using Ploeh.AutoFixture.Xunit; using Xunit.Extensions; namespace AppHarbor.Tests.Commands { public class CreateCommandTest { private readonly IFixture _fixture; public CreateCommandTest() { _fixture = new Fixture().Customize(new AutoMoqCustomization()); } [Theory, AutoCommandData] public void ShouldCreateApplication([Frozen]Mock<IAppHarborClient> client, CreateCommand command) { command.Execute(new string[] { "foo", "bar" }); client.Verify(x => x.CreateApplication("foo", "bar"), Times.Once()); } } }
using System.Linq; using AppHarbor.Commands; using Moq; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoMoq; using Ploeh.AutoFixture.Xunit; using Xunit.Extensions; namespace AppHarbor.Tests.Commands { public class CreateCommandTest { private readonly IFixture _fixture; public CreateCommandTest() { _fixture = new Fixture().Customize(new AutoMoqCustomization()); } [Theory, AutoCommandData] public void ShouldCreateApplication([Frozen]Mock<IAppHarborClient> client, CreateCommand command, string[] arguments) { command.Execute(arguments); client.Verify(x => x.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()), Times.Once()); } } }
Return the highest supported version except where equal to the client version.
using System.Threading.Tasks; using System.Collections.Generic; using System.Linq; using Version = Msg.Core.Versioning; namespace Msg.Core.Versioning { public static class VersionNegotiator { [System.Obsolete("This method is deprecated us VersionNegotiator.Select instead.")] public static async Task<Version> NegotiateVersionAsync (IEnumerable<VersionRange> supportedVersions) { return await Task.FromResult (supportedVersions.First ().UpperBoundInclusive); } public static Version Select (ClientVersion client, ServerSupportedVersions server) { return new ServerVersion(0,0,0); } } }
using System.Threading.Tasks; using System.Collections.Generic; using System.Linq; using Version = Msg.Core.Versioning; namespace Msg.Core.Versioning { public static class VersionNegotiator { [System.Obsolete("This method is deprecated us VersionNegotiator.Select instead.")] public static async Task<Version> NegotiateVersionAsync (IEnumerable<VersionRange> supportedVersions) { return await Task.FromResult (supportedVersions.First ().UpperBoundInclusive); } public static Version Select (ClientVersion clientVersion, ServerSupportedVersions serverSupportedVersions) { var serverVersion = GetDefaultServerVersion (serverSupportedVersions); return clientVersion == serverVersion ? new AcceptedVersion (clientVersion) : serverVersion; } static ServerVersion GetDefaultServerVersion (IEnumerable<VersionRange> supportedVersions) { var highestSupportedVersion = supportedVersions .OrderBy (x => x.UpperBoundInclusive) .First () .UpperBoundInclusive; return new ServerVersion (highestSupportedVersion.Major, highestSupportedVersion.Minor, highestSupportedVersion.Revision); } } }
Remove unused usings from a newly added 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 Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { /// <summary> /// Complexify makes inferred names explicit for tuple elements and anonymous type members. This /// class considers which ones of those can be simplified (after the refactoring was done). /// If the inferred name of the member matches, the explicit name (from Complexify) can be removed. /// </summary> internal partial class CSharpInferredMemberNameReducer : AbstractCSharpReducer { private static readonly ObjectPool<IReductionRewriter> s_pool = new ObjectPool<IReductionRewriter>( () => new Rewriter(s_pool)); public CSharpInferredMemberNameReducer() : base(s_pool) { } } }
// 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 Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { /// <summary> /// Complexify makes inferred names explicit for tuple elements and anonymous type members. This /// class considers which ones of those can be simplified (after the refactoring was done). /// If the inferred name of the member matches, the explicit name (from Complexify) can be removed. /// </summary> internal partial class CSharpInferredMemberNameReducer : AbstractCSharpReducer { private static readonly ObjectPool<IReductionRewriter> s_pool = new ObjectPool<IReductionRewriter>( () => new Rewriter(s_pool)); public CSharpInferredMemberNameReducer() : base(s_pool) { } } }
Mark as obsolete for future removal
using System; using System.Diagnostics; using JetBrains.Annotations; namespace EnsureThat { public static class Ensure { public static bool IsActive { get; private set; } = true; public static void Off() => IsActive = false; public static void On() => IsActive = true; [DebuggerStepThrough] public static Param<T> That<T>([NoEnumeration]T value, string name = Param.DefaultName) => new Param<T>(name, value); [DebuggerStepThrough] public static Param<T> That<T>(Func<T> expression, string name = Param.DefaultName) => new Param<T>( name, expression.Invoke()); [DebuggerStepThrough] public static TypeParam ThatTypeFor<T>(T value, string name = Param.DefaultName) => new TypeParam(name, value.GetType()); } }
using System; using System.Diagnostics; using JetBrains.Annotations; namespace EnsureThat { public static class Ensure { public static bool IsActive { get; private set; } = true; public static void Off() => IsActive = false; public static void On() => IsActive = true; [DebuggerStepThrough] [Obsolete("Use EnsureArg instead. This version will eventually be removed.", false)] public static Param<T> That<T>([NoEnumeration]T value, string name = Param.DefaultName) => new Param<T>(name, value); [DebuggerStepThrough] [Obsolete("Use EnsureArg instead. This version will eventually be removed.", false)] public static Param<T> That<T>(Func<T> expression, string name = Param.DefaultName) => new Param<T>( name, expression.Invoke()); [DebuggerStepThrough] [Obsolete("Use EnsureArg instead. This version will eventually be removed.", false)] public static TypeParam ThatTypeFor<T>(T value, string name = Param.DefaultName) => new TypeParam(name, value.GetType()); } }
Change version due to API Change
using System.Reflection; [assembly: AssemblyTitle("Garlic")] [assembly: AssemblyDescription("Google Analytics Client for .Net")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCompany("Dusty Burwell")] [assembly: AssemblyProduct("Garlic Google Analytics Client")] [assembly: AssemblyCopyright("Copyright © Dusty Burwell 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; [assembly: AssemblyTitle("Garlic")] [assembly: AssemblyDescription("Google Analytics Client for .Net")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCompany("Dusty Burwell")] [assembly: AssemblyProduct("Garlic Google Analytics Client")] [assembly: AssemblyCopyright("Copyright © Dusty Burwell 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
Fix Coaction() for tau action
using System; using System.Collections.Generic; using System.Linq; namespace CIV.Processes { public static class Extensions { /// <summary> /// Coaction of the specified action. /// </summary> /// <returns>The coaction: 'action if action does not start /// with ' and vice versa</returns> /// <param name="action">A CCS action</param> public static String Coaction(this String action) { return action.StartsWith("'", StringComparison.InvariantCultureIgnoreCase) ? action.Substring(1) : String.Format("'{0}", action); } public static IEnumerable<Transition> WeakTransitions(this IProcess process) { var transitions = process.Transitions(); var result = ( from t in transitions where t.Label != "tau" select t ); foreach(var t in transitions.Where(x => x.Label == "tau")) { result.Concat(t.Process.WeakTransitions()); } return result; } } }
using System; using System.Collections.Generic; using System.Linq; namespace CIV.Processes { public static class Extensions { /// <summary> /// Coaction of the specified action. /// </summary> /// <returns>The coaction: 'action if action does not start /// with ' and vice versa</returns> /// <param name="action">A CCS action</param> public static String Coaction(this String action) { if (action == "tau") return "tau"; return action.StartsWith("'", StringComparison.InvariantCultureIgnoreCase) ? action.Substring(1) : String.Format("'{0}", action); } public static IEnumerable<Transition> WeakTransitions(this IProcess process) { var transitions = process.Transitions(); var result = ( from t in transitions where t.Label != "tau" select t ); foreach(var t in transitions.Where(x => x.Label == "tau")) { result.Concat(t.Process.WeakTransitions()); } return result; } } }
Make sure code is jitted before perf test
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Perf.DiffPlex { public class PerfTester { public void Run(Action action) { const double count = 5; var times = new List<double>(); var timer = new Stopwatch(); var totalTime = new Stopwatch(); double maxTime = 0; double minTime = double.MaxValue; Console.WriteLine(); Console.WriteLine("Time before run: {0}", DateTime.Now); Console.WriteLine("Running {0} times.", count); totalTime.Start(); for (var i = 0; i < count; i++) { timer.Start(); action(); timer.Stop(); maxTime = Math.Max(maxTime, timer.ElapsedMilliseconds); minTime = Math.Min(minTime, timer.ElapsedMilliseconds); times.Add(timer.ElapsedMilliseconds); timer.Reset(); } totalTime.Stop(); Console.WriteLine(); Console.WriteLine("Time after run: {0}", DateTime.Now); Console.WriteLine("Elapsed: {0}ms", totalTime.ElapsedMilliseconds); Console.WriteLine("Diffs Per Second: {0}", (count / totalTime.ElapsedMilliseconds) * 1000); Console.WriteLine("Average: {0}ms", times.Average()); Console.WriteLine("Max time for a call: {0}ms", maxTime); Console.WriteLine("Min time for a call: {0}ms", minTime); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Perf.DiffPlex { public class PerfTester { public void Run(Action action) { const double count = 5; var times = new List<double>(); var timer = new Stopwatch(); var totalTime = new Stopwatch(); double maxTime = 0; double minTime = double.MaxValue; Console.WriteLine("Ensuring code is Jitted"); action(); Console.WriteLine(); Console.WriteLine("Time before run: {0}", DateTime.Now); Console.WriteLine("Running {0} times.", count); totalTime.Start(); for (var i = 0; i < count; i++) { timer.Start(); action(); timer.Stop(); maxTime = Math.Max(maxTime, timer.ElapsedMilliseconds); minTime = Math.Min(minTime, timer.ElapsedMilliseconds); times.Add(timer.ElapsedMilliseconds); timer.Reset(); } totalTime.Stop(); Console.WriteLine(); Console.WriteLine("Time after run: {0}", DateTime.Now); Console.WriteLine("Elapsed: {0}ms", totalTime.ElapsedMilliseconds); Console.WriteLine("Diffs Per Second: {0}", (count / totalTime.ElapsedMilliseconds) * 1000); Console.WriteLine("Average: {0}ms", times.Average()); Console.WriteLine("Max time for a call: {0}ms", maxTime); Console.WriteLine("Min time for a call: {0}ms", minTime); } } }
Make tests use console log handler
using NUnit.Framework; using QuantConnect.Logging; [SetUpFixture] public class AssemblyInitialize { [SetUp] public void SetLogHandler() { // save output to file as well Log.LogHandler = new CompositeLogHandler(); } }
using NUnit.Framework; using QuantConnect.Logging; [SetUpFixture] public class AssemblyInitialize { [SetUp] public void SetLogHandler() { // save output to file as well Log.LogHandler = new ConsoleLogHandler(); } }
Fix for automapper castle component
namespace Hiperion.Infrastructure.Ioc { #region References using System.Configuration; using System.Web.Http; using AutoMapper; using Automapper; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using EF; using EF.Interfaces; using Mappings; #endregion public class WindsorInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { var connectionString = ConfigurationManager.ConnectionStrings["HiperionDb"].ConnectionString; container.Register( Component.For<IMappingEngine>() .Instance(Mapper.Engine), Component.For<IDbContext>() .ImplementedBy<HiperionDbContext>() .LifestylePerWebRequest() .DependsOn(Parameter.ForKey("connectionString").Eq(connectionString)), Component.For(typeof (EntityResolver<>)) .ImplementedBy(typeof (EntityResolver<>)) .LifestyleTransient(), Component.For(typeof (ManyToManyEntityResolver<,>)) .ImplementedBy(typeof (ManyToManyEntityResolver<,>)) .LifestyleTransient(), Types.FromThisAssembly() .Where(type => (type.Name.EndsWith("Services") || type.Name.EndsWith("Repository") || type.Name.EndsWith("Resolver") || type.Name.EndsWith("Controller")) && type.IsClass) .WithService.DefaultInterfaces() .LifestyleTransient() ); AutomapperConfiguration.Configure(container.Resolve); GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(container); } } }
namespace Hiperion.Infrastructure.Ioc { #region References using System.Configuration; using System.Web.Http; using AutoMapper; using Automapper; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using EF; using EF.Interfaces; using Mappings; #endregion public class WindsorInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { var connectionString = ConfigurationManager.ConnectionStrings["HiperionDb"].ConnectionString; container.Register( Component.For<IMappingEngine>() .UsingFactoryMethod(() => Mapper.Engine), Component.For<IDbContext>() .ImplementedBy<HiperionDbContext>() .LifestylePerWebRequest() .DependsOn(Parameter.ForKey("connectionString").Eq(connectionString)), Component.For(typeof (EntityResolver<>)) .ImplementedBy(typeof (EntityResolver<>)) .LifestyleTransient(), Component.For(typeof (ManyToManyEntityResolver<,>)) .ImplementedBy(typeof (ManyToManyEntityResolver<,>)) .LifestyleTransient(), Types.FromThisAssembly() .Where(type => (type.Name.EndsWith("Services") || type.Name.EndsWith("Repository") || type.Name.EndsWith("Resolver") || type.Name.EndsWith("Controller")) && type.IsClass) .WithService.DefaultInterfaces() .LifestyleTransient() ); AutomapperConfiguration.Configure(container.Resolve); GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(container); } } }
Make ConvertPath to allow this functionality to be modified to allow for slashes in path
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace SoapCore { /// <summary> /// This tuner truncates the incoming http request to the last path-part. ie. /DynamicPath/Service.svc becomes /Service.svc /// Register this tuner in ConfigureServices: services.AddSoapServiceOperationTuner(new TrailingServicePathTuner()); /// </summary> public class TrailingServicePathTuner { public void ConvertPath(HttpContext httpContext) { string trailingPath = httpContext.Request.Path.Value.Substring(httpContext.Request.Path.Value.LastIndexOf('/')); httpContext.Request.Path = new PathString(trailingPath); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace SoapCore { /// <summary> /// This tuner truncates the incoming http request to the last path-part. ie. /DynamicPath/Service.svc becomes /Service.svc /// Register this tuner in ConfigureServices: services.AddSoapServiceOperationTuner(new TrailingServicePathTuner()); /// </summary> public class TrailingServicePathTuner { public virtual void ConvertPath(HttpContext httpContext) { string trailingPath = httpContext.Request.Path.Value.Substring(httpContext.Request.Path.Value.LastIndexOf('/')); httpContext.Request.Path = new PathString(trailingPath); } } }
Revert "Revert "Modified the Import class""
namespace GiveCRM.ImportExport { public class ExcelImport { } }
using NPOI; namespace GiveCRM.ImportExport { public class ExcelImport { } }
Allow settings custom command line params.
using System; using DSL; namespace Revenj.Http { static class Program { static void Main(string[] args) { var server = Platform.Start<HttpServer>(); Console.WriteLine("Starting server"); server.Run(); } } }
using System; using System.Configuration; using DSL; namespace Revenj.Http { static class Program { static void Main(string[] args) { foreach (var arg in args) { var i = arg.IndexOf('='); if (i != -1) { var name = arg.Substring(0, i); var value = arg.Substring(i + 1); ConfigurationManager.AppSettings[name] = value; } } var server = Platform.Start<HttpServer>(); Console.WriteLine("Starting server"); server.Run(); } } }
Check that a particular replacement is working well
// <copyright file="ValSimpleTest.cs" company="Microsoft">Copyright Microsoft 2010</copyright> using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LINQToTTreeLib.Variables { /// <summary>This class contains parameterized unit tests for ValSimple</summary> [TestClass] public partial class ValSimpleTest { #if false /// <summary>Test stub for .ctor(String)</summary> [PexMethod] internal ValSimple Constructor(string v) { ValSimple target = new ValSimple(v, typeof(int)); Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!"); return target; } [PexMethod] internal ValSimple TestCTorWithType(string v, Type t) { ValSimple target = new ValSimple(v, t); Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!"); Assert.IsNotNull(target.Type, "Expected some value for the type!"); return target; } #endif } }
// <copyright file="ValSimpleTest.cs" company="Microsoft">Copyright Microsoft 2010</copyright> using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LINQToTTreeLib.Variables { /// <summary>This class contains parameterized unit tests for ValSimple</summary> [TestClass] public partial class ValSimpleTest { #if false /// <summary>Test stub for .ctor(String)</summary> [PexMethod] internal ValSimple Constructor(string v) { ValSimple target = new ValSimple(v, typeof(int)); Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!"); return target; } [PexMethod] internal ValSimple TestCTorWithType(string v, Type t) { ValSimple target = new ValSimple(v, t); Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!"); Assert.IsNotNull(target.Type, "Expected some value for the type!"); return target; } #endif [TestMethod] public void RenameMethodCall() { var target = new ValSimple("(*aNTH1F_1233).Fill(((double)aInt32_326),1.0*((1.0*1.0)*1.0))", typeof(int)); target.RenameRawValue("aInt32_326", "aInt32_37"); Assert.AreEqual("(*aNTH1F_1233).Fill(((double)aInt32_37),1.0*((1.0*1.0)*1.0))", target.RawValue); } } }
Add extension to decode a string from an ArraySegment<byte>.
using System; namespace MySql.Data { internal static class Utility { public static void Dispose<T>(ref T disposable) where T : class, IDisposable { if (disposable != null) { disposable.Dispose(); disposable = null; } } } }
using System; using System.Text; namespace MySql.Data { internal static class Utility { public static void Dispose<T>(ref T disposable) where T : class, IDisposable { if (disposable != null) { disposable.Dispose(); disposable = null; } } public static string GetString(this Encoding encoding, ArraySegment<byte> arraySegment) => encoding.GetString(arraySegment.Array, arraySegment.Offset, arraySegment.Count); } }
Fix IRC Manager disconnect command
using System; using System.Collections; /// <summary>Commands for the IRC Connection Holdable.</summary> public static class IRCConnectionManagerCommands { [Command(@"disconnect")] public static IEnumerator Disconnect(IRCConnectionManagerHoldable holdable) { bool allowed = false; yield return null; yield return new object[] { "streamer", new Action(() => { allowed = true; holdable.ConnectButton.OnInteract(); holdable.ConnectButton.OnInteractEnded(); }), new Action(() => Audio.PlaySound(KMSoundOverride.SoundEffect.Strike, holdable.transform)) }; if (!allowed) yield return "sendtochaterror only the streamer may use the IRC disconnect button."; } }
using System; using System.Collections; /// <summary>Commands for the IRC Connection Holdable.</summary> public static class IRCConnectionManagerCommands { [Command(@"disconnect")] public static IEnumerator Disconnect(TwitchHoldable holdable, string user, bool isWhisper) => holdable.RespondToCommand(user, string.Empty, isWhisper, Disconnect(holdable.Holdable.GetComponent<IRCConnectionManagerHoldable>())); private static IEnumerator Disconnect(IRCConnectionManagerHoldable holdable) { bool allowed = false; yield return null; yield return new object[] { "streamer", new Action(() => { allowed = true; holdable.ConnectButton.OnInteract(); holdable.ConnectButton.OnInteractEnded(); }), new Action(() => Audio.PlaySound(KMSoundOverride.SoundEffect.Strike, holdable.transform)) }; if (!allowed) yield return "sendtochaterror only the streamer may use the IRC disconnect button."; } }
Remove redundant AddOptions which is now a default hosting service
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Text.Encodings.Web; using Microsoft.AspNet.Routing; using Microsoft.AspNet.Routing.Internal; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.ObjectPool; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Contains extension methods to <see cref="IServiceCollection"/>. /// </summary> public static class RoutingServiceCollectionExtensions { public static IServiceCollection AddRouting(this IServiceCollection services) { return AddRouting(services, configureOptions: null); } public static IServiceCollection AddRouting( this IServiceCollection services, Action<RouteOptions> configureOptions) { services.AddOptions(); services.TryAddTransient<IInlineConstraintResolver, DefaultInlineConstraintResolver>(); services.TryAddSingleton(UrlEncoder.Default); services.TryAddSingleton<ObjectPoolProvider>(new DefaultObjectPoolProvider()); services.TryAddSingleton<ObjectPool<UriBuildingContext>>(s => { var provider = s.GetRequiredService<ObjectPoolProvider>(); var encoder = s.GetRequiredService<UrlEncoder>(); return provider.Create<UriBuildingContext>(new UriBuilderContextPooledObjectPolicy(encoder)); }); if (configureOptions != null) { services.Configure(configureOptions); } return services; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Text.Encodings.Web; using Microsoft.AspNet.Routing; using Microsoft.AspNet.Routing.Internal; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.ObjectPool; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Contains extension methods to <see cref="IServiceCollection"/>. /// </summary> public static class RoutingServiceCollectionExtensions { public static IServiceCollection AddRouting(this IServiceCollection services) { return AddRouting(services, configureOptions: null); } public static IServiceCollection AddRouting( this IServiceCollection services, Action<RouteOptions> configureOptions) { services.TryAddTransient<IInlineConstraintResolver, DefaultInlineConstraintResolver>(); services.TryAddSingleton(UrlEncoder.Default); services.TryAddSingleton<ObjectPoolProvider>(new DefaultObjectPoolProvider()); services.TryAddSingleton<ObjectPool<UriBuildingContext>>(s => { var provider = s.GetRequiredService<ObjectPoolProvider>(); var encoder = s.GetRequiredService<UrlEncoder>(); return provider.Create<UriBuildingContext>(new UriBuilderContextPooledObjectPolicy(encoder)); }); if (configureOptions != null) { services.Configure(configureOptions); } return services; } } }
Fix timeline tick display test making two instances of the component
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Screens.Edit.Compose.Components; using osu.Game.Screens.Edit.Compose.Components.Timeline; using osuTK; namespace osu.Game.Tests.Visual.Editing { [TestFixture] public class TestSceneTimelineTickDisplay : TimelineTestScene { public override Drawable CreateTestComponent() => new TimelineTickDisplay(); [BackgroundDependencyLoader] private void load() { BeatDivisor.Value = 4; Add(new BeatDivisorControl(BeatDivisor) { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Margin = new MarginPadding(30), Size = new Vector2(90) }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Screens.Edit.Compose.Components; using osuTK; namespace osu.Game.Tests.Visual.Editing { [TestFixture] public class TestSceneTimelineTickDisplay : TimelineTestScene { public override Drawable CreateTestComponent() => Empty(); // tick display is implicitly inside the timeline. [BackgroundDependencyLoader] private void load() { BeatDivisor.Value = 4; Add(new BeatDivisorControl(BeatDivisor) { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Margin = new MarginPadding(30), Size = new Vector2(90) }); } } }
Simplify the editor to work for any object
using System.Linq; using UnityEngine; using UnityEditor; namespace EasyButtons { /// <summary> /// Base class for making EasyButtons work /// </summary> public abstract class ButtonEditorBase : Editor { public override void OnInspectorGUI() { // Loop through all methods with the Button attribute and no arguments foreach (var method in target.GetType().GetMethods() .Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0) .Where(m => m.GetParameters().Length == 0)) { // Draw a button which invokes the method if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name))) { method.Invoke(target, null); } } // Draw the rest of the inspector as usual DrawDefaultInspector(); } } /// <summary> /// Custom inspector for MonoBehaviour including derived classes. /// </summary> [CustomEditor(typeof(MonoBehaviour), true)] public class MonoBehaviourEditor : ButtonEditorBase { } /// <summary> /// Custom inspector for ScriptableObject including derived classes. /// </summary> [CustomEditor(typeof(ScriptableObject), true)] public class ScriptableObjectEditor : ButtonEditorBase { } }
using System.Linq; using UnityEngine; using UnityEditor; namespace EasyButtons { /// <summary> /// Custom inspector for Object including derived classes. /// </summary> [CustomEditor(typeof(Object), true)] public class ObjectEditor : Editor { public override void OnInspectorGUI() { // Loop through all methods with the Button attribute and no arguments foreach (var method in target.GetType().GetMethods() .Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0) .Where(m => m.GetParameters().Length == 0)) { // Draw a button which invokes the method if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name))) { method.Invoke(target, null); } } // Draw the rest of the inspector as usual DrawDefaultInspector(); } } }
Fix error message building when no specific errors defined
using System; using System.Collections.Generic; using System.Linq; namespace SFA.DAS.EmployerUsers.Application { public class InvalidRequestException : Exception { public Dictionary<string,string> ErrorMessages { get; private set; } public InvalidRequestException(Dictionary<string,string> errorMessages) : base(BuildErrorMessage(errorMessages)) { this.ErrorMessages = errorMessages; } private static string BuildErrorMessage(Dictionary<string, string> errorMessages) { return "Request is invalid:\n" + errorMessages.Select(kvp => $"{kvp.Key}: {kvp.Value}").Aggregate((x, y) => $"{x}\n{y}"); } } }
using System; using System.Collections.Generic; using System.Linq; namespace SFA.DAS.EmployerUsers.Application { public class InvalidRequestException : Exception { public Dictionary<string, string> ErrorMessages { get; private set; } public InvalidRequestException(Dictionary<string, string> errorMessages) : base(BuildErrorMessage(errorMessages)) { this.ErrorMessages = errorMessages; } private static string BuildErrorMessage(Dictionary<string, string> errorMessages) { if (errorMessages.Count == 0) { return "Request is invalid"; } return "Request is invalid:\n" + errorMessages.Select(kvp => $"{kvp.Key}: {kvp.Value}").Aggregate((x, y) => $"{x}\n{y}"); } } }
Change HTML table header generation to use the correct th HTML tag.
using System.Text; namespace SnippetsToMarkdown.Commands { class WriteHeaderHtmlCommand : ICommand { private string directory; public WriteHeaderHtmlCommand(string directory) { this.directory = directory; } public void WriteToOutput(StringBuilder output) { output.AppendLine("<h4>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h4>"); output.AppendLine("<br />"); output.AppendLine("<table>"); output.AppendLine("<thead>"); output.AppendLine("<tr>"); output.AppendLine("<td>Shortcut</td>"); output.AppendLine("<td>Name</td>"); output.AppendLine("</tr>"); output.AppendLine("</thead>"); output.AppendLine("<tbody>"); } } }
using System.Text; namespace SnippetsToMarkdown.Commands { class WriteHeaderHtmlCommand : ICommand { private string directory; public WriteHeaderHtmlCommand(string directory) { this.directory = directory; } public void WriteToOutput(StringBuilder output) { output.AppendLine("<h4>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h4>"); output.AppendLine("<br />"); output.AppendLine("<table>"); output.AppendLine("<thead>"); output.AppendLine("<tr>"); output.AppendLine("<th>Shortcut</th>"); output.AppendLine("<th>Name</th>"); output.AppendLine("</tr>"); output.AppendLine("</thead>"); output.AppendLine("<tbody>"); } } }
Use random app name to avoid 409 conflict error
using System.Linq; using Kudu.Core.Deployment; using Kudu.FunctionalTests.Infrastructure; using Kudu.TestHarness; using Xunit; namespace Kudu.FunctionalTests { public class GitStabilityTests { [Fact] public void NSimpleDeployments() { string repositoryName = "HelloKudu"; string cloneUrl = "https://github.com/KuduApps/HelloKudu.git"; using (Git.Clone(repositoryName, cloneUrl)) { for (int i = 0; i < 5; i++) { string applicationName = repositoryName + i; ApplicationManager.Run(applicationName, appManager => { // Act appManager.AssertGitDeploy(repositoryName); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, "Hello Kudu"); }); } } } } }
using System.Linq; using Kudu.Core.Deployment; using Kudu.FunctionalTests.Infrastructure; using Kudu.TestHarness; using Xunit; namespace Kudu.FunctionalTests { public class GitStabilityTests { [Fact] public void NSimpleDeployments() { string repositoryName = "HelloKudu"; string cloneUrl = "https://github.com/KuduApps/HelloKudu.git"; using (Git.Clone(repositoryName, cloneUrl)) { for (int i = 0; i < 5; i++) { string applicationName = KuduUtils.GetRandomWebsiteName(repositoryName + i); ApplicationManager.Run(applicationName, appManager => { // Act appManager.AssertGitDeploy(repositoryName); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, "Hello Kudu"); }); } } } } }
Replace recursive file enumeration with a stack based approach
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Framework.Logging; namespace OmniSharp.Utilities { public class DirectoryEnumerator { private ILogger _logger; public DirectoryEnumerator(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<DirectoryEnumerator>(); } public IEnumerable<string> SafeEnumerateFiles(string path, string searchPattern) { if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path)) { yield break; } string[] files = null; string[] directories = null; try { // Get the files and directories now so we can get any exceptions up front files = Directory.GetFiles(path, searchPattern); directories = Directory.GetDirectories(path); } catch (UnauthorizedAccessException) { _logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", path)); yield break; } catch (PathTooLongException) { _logger.LogWarning(string.Format("Path {0} is too long, skipping", path)); yield break; } foreach (var file in files) { yield return file; } foreach (var file in directories.SelectMany(x => SafeEnumerateFiles(x, searchPattern))) { yield return file; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Framework.Logging; namespace OmniSharp.Utilities { public class DirectoryEnumerator { private ILogger _logger; public DirectoryEnumerator(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<DirectoryEnumerator>(); } public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*") { var allFiles = Enumerable.Empty<string>(); var directoryStack = new Stack<string>(); directoryStack.Push(target); while (directoryStack.Any()) { var current = directoryStack.Pop(); try { allFiles = allFiles.Concat(GetFiles(current, pattern)); foreach (var subdirectory in GetSubdirectories(current)) { directoryStack.Push(subdirectory); } } catch (UnauthorizedAccessException) { _logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current)); } } return allFiles; } private IEnumerable<string> GetFiles(string path, string pattern) { try { return Directory.EnumerateFiles(path, pattern, SearchOption.TopDirectoryOnly); } catch (PathTooLongException) { _logger.LogWarning(string.Format("Path {0} is too long, skipping", path)); return Enumerable.Empty<string>(); } } private IEnumerable<string> GetSubdirectories(string path) { try { return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly); } catch (PathTooLongException) { _logger.LogWarning(string.Format("Path {0} is too long, skipping", path)); return Enumerable.Empty<string>(); } } } }
Allow multiple rule instances in autofac activator
using System; using System.Collections.Generic; using Autofac; using NRules.Fluent; using NRules.Fluent.Dsl; namespace NRules.Integration.Autofac { /// <summary> /// Rule activator that uses Autofac DI container. /// </summary> public class AutofacRuleActivator : IRuleActivator { private readonly ILifetimeScope _container; public AutofacRuleActivator(ILifetimeScope container) { _container = container; } public IEnumerable<Rule> Activate(Type type) { if (_container.IsRegistered(type)) yield return (Rule) _container.Resolve(type); yield return (Rule)Activator.CreateInstance(type); } } }
using System; using System.Collections.Generic; using Autofac; using NRules.Fluent; using NRules.Fluent.Dsl; namespace NRules.Integration.Autofac { /// <summary> /// Rule activator that uses Autofac DI container. /// </summary> public class AutofacRuleActivator : IRuleActivator { private readonly ILifetimeScope _container; public AutofacRuleActivator(ILifetimeScope container) { _container = container; } public IEnumerable<Rule> Activate(Type type) { if (_container.IsRegistered(type)) { var collectionType = typeof (IEnumerable<>).MakeGenericType(type); return (IEnumerable<Rule>)_container.Resolve(collectionType); } return ActivateDefault(type); } private static IEnumerable<Rule> ActivateDefault(Type type) { yield return (Rule) Activator.CreateInstance(type); } } }
Use nameof operator instead of magic string.
using System; using System.Collections.Generic; using System.IO; namespace DupImage { /// <summary> /// Structure for containing image information and hash values. /// </summary> public class ImageStruct { /// <summary> /// Construct a new ImageStruct from FileInfo. /// </summary> /// <param name="file">FileInfo to be used.</param> public ImageStruct(FileInfo file) { if (file == null) throw new ArgumentNullException("file"); ImagePath = file.FullName; // Init Hash Hash = new long[1]; } /// <summary> /// Construct a new ImageStruct from image path. /// </summary> /// <param name="pathToImage">Image location</param> public ImageStruct(String pathToImage) { ImagePath = pathToImage; // Init Hash Hash = new long[1]; } /// <summary> /// ImagePath information. /// </summary> public String ImagePath { get; private set; } /// <summary> /// Hash of the image. Uses longs instead of ulong to be CLS compliant. /// </summary> public long[] Hash { get; set; } } }
using System; using System.Collections.Generic; using System.IO; namespace DupImage { /// <summary> /// Structure for containing image information and hash values. /// </summary> public class ImageStruct { /// <summary> /// Construct a new ImageStruct from FileInfo. /// </summary> /// <param name="file">FileInfo to be used.</param> public ImageStruct(FileInfo file) { if (file == null) throw new ArgumentNullException(nameof(file)); ImagePath = file.FullName; // Init Hash Hash = new long[1]; } /// <summary> /// Construct a new ImageStruct from image path. /// </summary> /// <param name="pathToImage">Image location</param> public ImageStruct(String pathToImage) { ImagePath = pathToImage; // Init Hash Hash = new long[1]; } /// <summary> /// ImagePath information. /// </summary> public String ImagePath { get; private set; } /// <summary> /// Hash of the image. Uses longs instead of ulong to be CLS compliant. /// </summary> public long[] Hash { get; set; } } }
Fix that check not null message didn't contain argument name
namespace Nett.Extensions { using System; internal static class GenericExtensions { public static T CheckNotNull<T>(this T toCheck, string argName) where T : class { if (toCheck == null) { throw new ArgumentNullException(nameof(argName)); } return toCheck; } } }
namespace Nett.Extensions { using System; internal static class GenericExtensions { public static T CheckNotNull<T>(this T toCheck, string argName) where T : class { if (toCheck == null) { throw new ArgumentNullException(argName); } return toCheck; } } }
Fix to the browse images coming up 404.
using ImageResizer.Plugins; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ImageResizer.Sitecore.Plugin { public class SitecoreVirtualImageProviderPlugin : IPlugin, IVirtualImageProvider { public IPlugin Install(global::ImageResizer.Configuration.Config c) { c.Plugins.add_plugin(this); return this; } public bool Uninstall(global::ImageResizer.Configuration.Config c) { c.Plugins.remove_plugin(this); return true; } private string FixVirtualPath(string virtualPath) { var subIndex = virtualPath.LastIndexOf("~"); if (subIndex < 0) { subIndex = virtualPath.LastIndexOf("-"); } if (subIndex > 0) { return virtualPath.Substring(subIndex); } else { return virtualPath; } } public bool FileExists(string virtualPath, NameValueCollection queryString) { virtualPath = FixVirtualPath(virtualPath); DynamicLink dynamicLink; return queryString.Count > 0 && DynamicLink.TryParse(virtualPath, out dynamicLink); } public IVirtualFile GetFile(string virtualPath, NameValueCollection queryString) { virtualPath = FixVirtualPath(virtualPath); return new SitecoreVirtualFile(virtualPath); } } }
using ImageResizer.Plugins; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ImageResizer.Sitecore.Plugin { public class SitecoreVirtualImageProviderPlugin : IPlugin, IVirtualImageProvider { public IPlugin Install(global::ImageResizer.Configuration.Config c) { c.Plugins.add_plugin(this); return this; } public bool Uninstall(global::ImageResizer.Configuration.Config c) { c.Plugins.remove_plugin(this); return true; } private string FixVirtualPath(string virtualPath) { var subIndex = virtualPath.LastIndexOf("~"); if (subIndex < 0) { subIndex = virtualPath.LastIndexOf("-"); } if (subIndex > 0) { return virtualPath.Substring(subIndex); } else { return virtualPath; } } public bool FileExists(string virtualPath, NameValueCollection queryString) { if (virtualPath.StartsWith("/sitecore/shell/-")) { return false; } virtualPath = FixVirtualPath(virtualPath); DynamicLink dynamicLink; return queryString.Count > 0 && DynamicLink.TryParse(virtualPath, out dynamicLink); } public IVirtualFile GetFile(string virtualPath, NameValueCollection queryString) { virtualPath = FixVirtualPath(virtualPath); return new SitecoreVirtualFile(virtualPath); } } }
Use type to find E I
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MemberProperty : MonoBehaviour { public float E, I, length; public int number; }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MemberProperty : MonoBehaviour { public float length; public int number,type; float[] E = { 1 }; float[] I = { 1 }; public float GetI() { return I[type]; } public float GetE() { return E[type]; } }
Add remind_on to insert statement
using System; using Simpler; using Schedules.API.Models; using Dapper; using System.Linq; namespace Schedules.API.Tasks { public class CreateReminder: InOutTask<CreateReminder.Input, CreateReminder.Output> { public FetchReminderType FetchReminderType { get; set; } public class Input { public Reminder Reminder { get; set; } public String ReminderTypeName { get; set; } } public class Output { public Reminder Reminder { get; set; } } public override void Execute() { FetchReminderType.In.ReminderTypeName = In.ReminderTypeName; FetchReminderType.Execute(); In.Reminder.ReminderType = FetchReminderType.Out.ReminderType; Out.Reminder = new Reminder (); using (var connection = Db.Connect ()) { try{ Out.Reminder = connection.Query<Reminder, ReminderType, Reminder>( sql, (reminder, reminderType) => {reminder.ReminderType = reminderType; return reminder;}, In.Reminder).SingleOrDefault(); } catch(Exception ex){ Console.WriteLine (ex); } } } const string sql = @" with insertReminder as ( insert into Reminders(contact, message, verified, address, reminder_type_id) values(@Contact, @Message, @Verified, @Address, @ReminderTypeId) returning * ) select * from insertReminder r left join reminder_types t on t.id = r.reminder_type_id ; "; } }
using System; using Simpler; using Schedules.API.Models; using Dapper; using System.Linq; namespace Schedules.API.Tasks { public class CreateReminder: InOutTask<CreateReminder.Input, CreateReminder.Output> { public FetchReminderType FetchReminderType { get; set; } public class Input { public Reminder Reminder { get; set; } public String ReminderTypeName { get; set; } } public class Output { public Reminder Reminder { get; set; } } public override void Execute() { FetchReminderType.In.ReminderTypeName = In.ReminderTypeName; FetchReminderType.Execute(); In.Reminder.ReminderType = FetchReminderType.Out.ReminderType; Out.Reminder = new Reminder (); using (var connection = Db.Connect ()) { try{ Out.Reminder = connection.Query<Reminder, ReminderType, Reminder>( sql, (reminder, reminderType) => {reminder.ReminderType = reminderType; return reminder;}, In.Reminder).SingleOrDefault(); } catch(Exception ex){ Console.WriteLine (ex); } } } const string sql = @" with insertReminder as ( insert into Reminders(contact, message, remind_on, verified, address, reminder_type_id) values(@Contact, @Message, @RemindOn, @Verified, @Address, @ReminderTypeId) returning * ) select * from insertReminder r left join reminder_types t on t.id = r.reminder_type_id ; "; } }
Add ToString method to empty object
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System.Collections.Generic; using Scriban.Parsing; using Scriban.Syntax; namespace Scriban.Runtime { /// <summary> /// The empty object (unique singleton, cannot be modified, does not contain any properties) /// </summary> public sealed class EmptyScriptObject : IScriptObject { public static readonly EmptyScriptObject Default = new EmptyScriptObject(); private EmptyScriptObject() { } public int Count => 0; public IEnumerable<string> GetMembers() { yield break; } public bool Contains(string member) { return false; } public bool IsReadOnly { get => true; set { } } public bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value) { value = null; return false; } public bool CanWrite(string member) { return false; } public void SetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly) { throw new ScriptRuntimeException(span, "Cannot set a property on the empty object"); } public bool Remove(string member) { return false; } public void SetReadOnly(string member, bool readOnly) { } public IScriptObject Clone(bool deep) { return this; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using Scriban.Parsing; using Scriban.Syntax; namespace Scriban.Runtime { /// <summary> /// The empty object (unique singleton, cannot be modified, does not contain any properties) /// </summary> [DebuggerDisplay("<empty object>")] public sealed class EmptyScriptObject : IScriptObject { public static readonly EmptyScriptObject Default = new EmptyScriptObject(); private EmptyScriptObject() { } public int Count => 0; public IEnumerable<string> GetMembers() { yield break; } public bool Contains(string member) { return false; } public bool IsReadOnly { get => true; set { } } public bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value) { value = null; return false; } public bool CanWrite(string member) { return false; } public void SetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly) { throw new ScriptRuntimeException(span, "Cannot set a property on the empty object"); } public bool Remove(string member) { return false; } public void SetReadOnly(string member, bool readOnly) { } public IScriptObject Clone(bool deep) { return this; } public override string ToString() { return string.Empty; } } }
Add String Argument Extension method
using System; namespace THNETII.Common { public static class ArgumentExtensions { public static T ThrowIfNull<T>(this T instance, string name) where T : class => instance ?? throw new ArgumentNullException(name); } }
using System; namespace THNETII.Common { public static class ArgumentExtensions { public static T ThrowIfNull<T>(this T instance, string name) where T : class => instance ?? throw new ArgumentNullException(name); /// <exception cref="ArgumentException" /> /// <exception cref="ArgumentNullException" /> public static string ThrowIfNullOrWhiteSpace(this string value, string name) { if (string.IsNullOrWhiteSpace(value)) throw value == null ? new ArgumentNullException(nameof(name)) : new ArgumentException("value must neither be empty, nor null, nor whitespace-only.", name); return value; } } }
Remove unnecessary, and wrong, check
using System; public static class ExtensionMethods { public static string Str(this TimeSpan duration) { var hours = Math.Abs((int)duration.TotalHours); var minutes = Math.Abs(duration.Minutes); int seconds = Math.Abs(duration.Seconds); if (Math.Abs(duration.Milliseconds) >= 500) seconds++; if (duration >= TimeSpan.Zero) return string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds); else return string.Format("-{0:00}:{1:00}:{2:00}", hours, minutes, seconds); } }
using System; public static class ExtensionMethods { public static string Str(this TimeSpan duration) { var hours = Math.Abs((int)duration.TotalHours); var minutes = Math.Abs(duration.Minutes); int seconds = Math.Abs(duration.Seconds); if (duration >= TimeSpan.Zero) return string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds); else return string.Format("-{0:00}:{1:00}:{2:00}", hours, minutes, seconds); } }
Add comments and debugger display
using System.Collections.Generic; namespace Octokit { public class OauthToken { public string TokenType { get; set; } public string AccessToken { get; set; } public IReadOnlyCollection<string> Scope { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; namespace Octokit { [DebuggerDisplay("{DebuggerDisplay,nq}")] public class OauthToken { /// <summary> /// The type of OAuth token /// </summary> public string TokenType { get; set; } /// <summary> /// The secret OAuth access token. Use this to authenticate Octokit.net's client. /// </summary> public string AccessToken { get; set; } /// <summary> /// The list of scopes the token includes. /// </summary> public IReadOnlyCollection<string> Scope { get; set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "TokenType: {0}, AccessToken: {1}, Scopes: {2}", TokenType, AccessToken, Scope); } } } }
Fix data bar for min/max
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Spreadsheet; namespace ClosedXML.Excel { internal class XLCFDataBarConverter:IXLCFConverter { public ConditionalFormattingRule Convert(IXLConditionalFormat cf, Int32 priority, XLWorkbook.SaveContext context) { var conditionalFormattingRule = new ConditionalFormattingRule { Type = cf.ConditionalFormatType.ToOpenXml(), Priority = priority }; var dataBar = new DataBar {ShowValue = !cf.ShowBarOnly}; var conditionalFormatValueObject1 = new ConditionalFormatValueObject { Type = cf.ContentTypes[1].ToOpenXml()}; if (cf.Values.Count >= 1) conditionalFormatValueObject1.Val = cf.Values[1].Value; var conditionalFormatValueObject2 = new ConditionalFormatValueObject { Type = cf.ContentTypes[2].ToOpenXml()}; if (cf.Values.Count >= 2) conditionalFormatValueObject2.Val = cf.Values[2].Value; var color = new Color { Rgb = cf.Colors[1].Color.ToHex() }; dataBar.Append(conditionalFormatValueObject1); dataBar.Append(conditionalFormatValueObject2); dataBar.Append(color); conditionalFormattingRule.Append(dataBar); return conditionalFormattingRule; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Spreadsheet; namespace ClosedXML.Excel { internal class XLCFDataBarConverter : IXLCFConverter { public ConditionalFormattingRule Convert(IXLConditionalFormat cf, Int32 priority, XLWorkbook.SaveContext context) { var conditionalFormattingRule = new ConditionalFormattingRule { Type = cf.ConditionalFormatType.ToOpenXml(), Priority = priority }; var dataBar = new DataBar { ShowValue = !cf.ShowBarOnly }; var conditionalFormatValueObject1 = new ConditionalFormatValueObject { Type = cf.ContentTypes[1].ToOpenXml() }; if (cf.Values.Any() && cf.Values[1]?.Value != null) conditionalFormatValueObject1.Val = cf.Values[1].Value; var conditionalFormatValueObject2 = new ConditionalFormatValueObject { Type = cf.ContentTypes[2].ToOpenXml() }; if (cf.Values.Count >= 2 && cf.Values[2]?.Value != null) conditionalFormatValueObject2.Val = cf.Values[2].Value; var color = new Color(); switch (cf.Colors[1].ColorType) { case XLColorType.Color: color.Rgb = cf.Colors[1].Color.ToHex(); break; case XLColorType.Theme: color.Theme = System.Convert.ToUInt32(cf.Colors[1].ThemeColor); break; case XLColorType.Indexed: color.Indexed = System.Convert.ToUInt32(cf.Colors[1].Indexed); break; } dataBar.Append(conditionalFormatValueObject1); dataBar.Append(conditionalFormatValueObject2); dataBar.Append(color); conditionalFormattingRule.Append(dataBar); return conditionalFormattingRule; } } }
Remove redundant code. bugid: 912
@using Csla.Web.Mvc @using ProjectTracker.Library @model IEnumerable<ProjectTracker.Library.ProjectInfo> @{ ViewBag.Title = "Project list"; } <h2>@ViewBag.Message</h2> <p> @Html.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit), Html.ActionLink("Create New", "Create"), string.Empty) @if (Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit))) { @Html.ActionLink("Create New", "Create") } </p> <table> <tr> <th></th> <th> Name </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectEdit), Html.ActionLink("Edit", "Edit", new { id = item.Id }), "Edit") | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectEdit), Html.ActionLink("Delete", "Delete", new { id = item.Id }), "Delete") </td> <td> @item.Name </td> </tr> } </table>
@using Csla.Web.Mvc @using ProjectTracker.Library @model IEnumerable<ProjectTracker.Library.ProjectInfo> @{ ViewBag.Title = "Project list"; } <h2>@ViewBag.Message</h2> <p> @Html.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit), Html.ActionLink("Create New", "Create"), string.Empty) </p> <table> <tr> <th></th> <th> Name </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectEdit), Html.ActionLink("Edit", "Edit", new { id = item.Id }), "Edit") | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectEdit), Html.ActionLink("Delete", "Delete", new { id = item.Id }), "Delete") </td> <td> @item.Name </td> </tr> } </table>
Fix newConnection window is sometimes not displayed
using System; using System.Windows; namespace CupCake.Client { public static class Dispatch { public static void Invoke(Action callback) { Application.Current.Dispatcher.BeginInvoke(callback); } } }
using System; using System.Windows; namespace CupCake.Client { public static class Dispatch { public static void Invoke(Action callback) { Application.Current.Dispatcher.Invoke(callback); } } }
Make constructor of abstract class protected
using System.Linq; using PicklesDoc.Pickles.ObjectModel; namespace PicklesDoc.Pickles.TestFrameworks.XUnit { public abstract class XUnitResultsBase<TSingleResult> : MultipleTestResults where TSingleResult : XUnitSingleResultsBase { public XUnitResultsBase(IConfiguration configuration, ISingleResultLoader singleResultLoader, XUnitExampleSignatureBuilder exampleSignatureBuilder) : base(true, configuration, singleResultLoader) { this.SetExampleSignatureBuilder(exampleSignatureBuilder); } public void SetExampleSignatureBuilder(XUnitExampleSignatureBuilder exampleSignatureBuilder) { foreach (var testResult in TestResults.OfType<TSingleResult>()) { testResult.ExampleSignatureBuilder = exampleSignatureBuilder; } } public override TestResult GetExampleResult(ScenarioOutline scenarioOutline, string[] arguments) { var results = TestResults.OfType<TSingleResult>().Select(tr => tr.GetExampleResult(scenarioOutline, arguments)).ToArray(); return EvaluateTestResults(results); } } }
using System.Linq; using PicklesDoc.Pickles.ObjectModel; namespace PicklesDoc.Pickles.TestFrameworks.XUnit { public abstract class XUnitResultsBase<TSingleResult> : MultipleTestResults where TSingleResult : XUnitSingleResultsBase { protected XUnitResultsBase(IConfiguration configuration, ISingleResultLoader singleResultLoader, XUnitExampleSignatureBuilder exampleSignatureBuilder) : base(true, configuration, singleResultLoader) { this.SetExampleSignatureBuilder(exampleSignatureBuilder); } public void SetExampleSignatureBuilder(XUnitExampleSignatureBuilder exampleSignatureBuilder) { foreach (var testResult in TestResults.OfType<TSingleResult>()) { testResult.ExampleSignatureBuilder = exampleSignatureBuilder; } } public override TestResult GetExampleResult(ScenarioOutline scenarioOutline, string[] arguments) { var results = TestResults.OfType<TSingleResult>().Select(tr => tr.GetExampleResult(scenarioOutline, arguments)).ToArray(); return EvaluateTestResults(results); } } }
Allow audio device selection in settings
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Overlays.Options.Sections.Audio { public class AudioDevicesOptions : OptionsSubsection { protected override string Header => "Devices"; public AudioDevicesOptions() { Children = new[] { new OptionLabel { Text = "Output device: TODO dropdown" } }; } } }
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Graphics; using System.Collections.Generic; using System.Linq; namespace osu.Game.Overlays.Options.Sections.Audio { public class AudioDevicesOptions : OptionsSubsection { protected override string Header => "Devices"; private AudioManager audio; [BackgroundDependencyLoader] private void load(AudioManager audio) { this.audio = audio; } protected override void LoadComplete() { base.LoadComplete(); var deviceItems = new List<KeyValuePair<string, string>>(); deviceItems.Add(new KeyValuePair<string, string>("Standard", "")); deviceItems.AddRange(audio.GetDeviceNames().Select(d => new KeyValuePair<string, string>(d, d))); Children = new Drawable[] { new OptionDropDown<string>() { Items = deviceItems, Bindable = audio.AudioDevice }, }; } } }
Fix linking of follow camera to hero
using UnityEngine; using System.Collections; public class FollowCamera : MonoBehaviour { public GameObject global; public GameObject objectToFollow; // Use this for initialization void Start () { if (global == null) { return; } Global g = global.GetComponent<Global>(); if (g == null) { return; } objectToFollow = g.hero; } // Update is called once per frame (use LateUpdate for cameras) void LateUpdate () { transform.LookAt(objectToFollow.transform); } }
using UnityEngine; using System.Collections; public class FollowCamera : MonoBehaviour { public GameObject global; public GameObject objectToFollow; // Use this for initialization void Start () { if (global == null) { return; } Global g = global.GetComponent<Global>(); if (g == null) { return; } objectToFollow = g.hero; } // Update is called once per frame (use LateUpdate for cameras) void LateUpdate () { if (objectToFollow != null) { transform.LookAt(objectToFollow.transform); } else { Global g = global.GetComponent<Global>(); if (g == null) { return; } objectToFollow = g.hero; } } }
Fix toolbar music button tooltip overflowing off-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 osu.Framework.Allocation; using osu.Framework.Graphics.Sprites; using osu.Game.Input.Bindings; namespace osu.Game.Overlays.Toolbar { public class ToolbarMusicButton : ToolbarOverlayToggleButton { public ToolbarMusicButton() { Icon = FontAwesome.Solid.Music; TooltipMain = "Now playing"; TooltipSub = "Manage the currently playing track"; Hotkey = GlobalAction.ToggleNowPlaying; } [BackgroundDependencyLoader(true)] private void load(NowPlayingOverlay music) { StateContainer = music; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Game.Input.Bindings; namespace osu.Game.Overlays.Toolbar { public class ToolbarMusicButton : ToolbarOverlayToggleButton { protected override Anchor TooltipAnchor => Anchor.TopRight; public ToolbarMusicButton() { Icon = FontAwesome.Solid.Music; TooltipMain = "Now playing"; TooltipSub = "Manage the currently playing track"; Hotkey = GlobalAction.ToggleNowPlaying; } [BackgroundDependencyLoader(true)] private void load(NowPlayingOverlay music) { StateContainer = music; } } }
Handle callback directly if resolve bundle is empty
namespace Miruken.Callback { using System; public class Resolving : Inquiry, IResolveCallback { private bool _handled; public Resolving(object key, object callback) : base(key, true) { if (callback == null) throw new ArgumentNullException(nameof(callback)); Callback = callback; } public object Callback { get; } object IResolveCallback.GetResolveCallback() { return this; } protected override bool IsSatisfied( object resolution, bool greedy, IHandler composer) { if (_handled && !greedy) return true; return _handled = Handler.Dispatch(resolution, Callback, ref greedy, composer) || _handled; } public static object GetDefaultResolvingCallback(object callback) { var dispatch = callback as IDispatchCallback; var policy = dispatch?.Policy ?? HandlesAttribute.Policy; var handlers = policy.GetHandlers(callback); var bundle = new Bundle(false); foreach (var handler in handlers) bundle.Add(h => h.Handle(new Resolving(handler, callback))); bundle.Add(h => h.Handle(callback)); return bundle; } } }
namespace Miruken.Callback { using System; public class Resolving : Inquiry, IResolveCallback { private bool _handled; public Resolving(object key, object callback) : base(key, true) { if (callback == null) throw new ArgumentNullException(nameof(callback)); Callback = callback; } public object Callback { get; } object IResolveCallback.GetResolveCallback() { return this; } protected override bool IsSatisfied( object resolution, bool greedy, IHandler composer) { if (_handled && !greedy) return true; return _handled = Handler.Dispatch( resolution, Callback, ref greedy, composer) || _handled; } public static object GetDefaultResolvingCallback(object callback) { var dispatch = callback as IDispatchCallback; var policy = dispatch?.Policy ?? HandlesAttribute.Policy; var handlers = policy.GetHandlers(callback); var bundle = new Bundle(false); foreach (var handler in handlers) bundle.Add(h => h.Handle(new Resolving(handler, callback))); if (bundle.IsEmpty) bundle.Add(h => h.Handle(callback)); return bundle; } } }
Add positions to db on startup
using System; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; using System.Collections.Generic; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Periods.Any()) { context.Periods.Add(Period.Current); } if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); } if(!context.Users.Any()) { context.Users.Add(new User{ Id = 1, Login = "admin", PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=", Roles = new List<UserRole> { new UserRole { UserId = 1, RoleId = 1 } } }); } context.SaveChanges(); } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }
using System; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; using System.Collections.Generic; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Periods.Any()) { context.Periods.Add(Period.Current); } if (!context.TeachersPositions.Any()) { context.TeachersPositions.AddRange(TeacherPosition.HighTeacher, TeacherPosition.Professor, TeacherPosition.Doctor); } if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); } if(!context.Users.Any()) { context.Users.Add(new User{ Id = 1, Login = "admin", PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=", Roles = new List<UserRole> { new UserRole { UserId = 1, RoleId = 1 } } }); } context.SaveChanges(); } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }
Remove contract count check for protobuf
#region (c) 2010-2011 Lokad CQRS - New BSD License // Copyright (c) Lokad SAS 2010-2011 (http://www.lokad.com) // This code is released as Open Source under the terms of the New BSD Licence // Homepage: http://lokad.github.com/lokad-cqrs/ #endregion using System; using System.Collections.Generic; using ProtoBuf.Meta; namespace Lokad.Cqrs.Core.Serialization { public class DataSerializerWithProtoBuf : AbstractDataSerializer { public DataSerializerWithProtoBuf(ICollection<Type> knownTypes) : base(knownTypes) { if (knownTypes.Count == 0) throw new InvalidOperationException( "ProtoBuf requires some known types to serialize. Have you forgot to supply them?"); } protected override Formatter PrepareFormatter(Type type) { var name = ContractEvil.GetContractReference(type); var formatter = RuntimeTypeModel.Default.CreateFormatter(type); return new Formatter(name, formatter.Deserialize, (o, stream) => formatter.Serialize(stream,o)); } } }
#region (c) 2010-2011 Lokad CQRS - New BSD License // Copyright (c) Lokad SAS 2010-2011 (http://www.lokad.com) // This code is released as Open Source under the terms of the New BSD Licence // Homepage: http://lokad.github.com/lokad-cqrs/ #endregion using System; using System.Collections.Generic; using ProtoBuf.Meta; namespace Lokad.Cqrs.Core.Serialization { public class DataSerializerWithProtoBuf : AbstractDataSerializer { public DataSerializerWithProtoBuf(ICollection<Type> knownTypes) : base(knownTypes) { } protected override Formatter PrepareFormatter(Type type) { var name = ContractEvil.GetContractReference(type); var formatter = RuntimeTypeModel.Default.CreateFormatter(type); return new Formatter(name, formatter.Deserialize, (o, stream) => formatter.Serialize(stream,o)); } } }
Remove private qualifier on version regexes
using NuGet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Squirrel { public static class VersionExtensions { private static readonly Regex _suffixRegex = new Regex(@"(-full|-delta)?\.nupkg$", RegexOptions.Compiled); private static readonly Regex _versionRegex = new Regex(@"\d+(\.\d+){0,3}(-[a-z][0-9a-z-]*)?$", RegexOptions.Compiled); public static SemanticVersion ToSemanticVersion(this IReleasePackage package) { return package.InputPackageFile.ToSemanticVersion(); } public static SemanticVersion ToSemanticVersion(this string fileName) { var name = _suffixRegex.Replace(fileName, ""); var version = _versionRegex.Match(name).Value; return new SemanticVersion(version); } } }
using NuGet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Squirrel { public static class VersionExtensions { static readonly Regex _suffixRegex = new Regex(@"(-full|-delta)?\.nupkg$", RegexOptions.Compiled); static readonly Regex _versionRegex = new Regex(@"\d+(\.\d+){0,3}(-[a-z][0-9a-z-]*)?$", RegexOptions.Compiled); public static SemanticVersion ToSemanticVersion(this IReleasePackage package) { return package.InputPackageFile.ToSemanticVersion(); } public static SemanticVersion ToSemanticVersion(this string fileName) { var name = _suffixRegex.Replace(fileName, ""); var version = _versionRegex.Match(name).Value; return new SemanticVersion(version); } } }
Use AppContext.BaseDirectory for application path
using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Microsoft.Win32; namespace EasySnippets.Utils { [SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "Windows only app")] public class StartUpManager { public static void AddApplicationToCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssembly = Assembly.GetExecutingAssembly(); key?.SetValue(curAssembly.GetName().Name, curAssembly.Location); } public static void RemoveApplicationFromCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssemblyName = Assembly.GetExecutingAssembly().GetName().Name; if (!string.IsNullOrWhiteSpace(curAssemblyName)) { key?.DeleteValue(curAssemblyName, false); } } public static bool IsApplicationAddedToCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssembly = Assembly.GetExecutingAssembly(); var currentValue = key?.GetValue(curAssembly.GetName().Name, null)?.ToString(); return currentValue?.Equals(curAssembly.Location, StringComparison.InvariantCultureIgnoreCase) ?? false; } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Microsoft.Win32; namespace EasySnippets.Utils { [SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "Windows only app")] public class StartUpManager { public static void AddApplicationToCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssembly = Assembly.GetExecutingAssembly(); key?.SetValue(curAssembly.GetName().Name, AppContext.BaseDirectory); } public static void RemoveApplicationFromCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssemblyName = Assembly.GetExecutingAssembly().GetName().Name; if (!string.IsNullOrWhiteSpace(curAssemblyName)) { key?.DeleteValue(curAssemblyName, false); } } public static bool IsApplicationAddedToCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssembly = Assembly.GetExecutingAssembly(); var currentValue = key?.GetValue(curAssembly.GetName().Name, null)?.ToString(); return currentValue?.Equals(AppContext.BaseDirectory, StringComparison.InvariantCultureIgnoreCase) ?? false; } } }
Remove confirmation for exit with no verification
using System; using Abp; using Abp.Collections.Extensions; using Abp.Dependency; using Castle.Facilities.Logging; using Abp.Castle.Logging.Log4Net; namespace AbpCompanyName.AbpProjectName.Migrator { public class Program { private static bool _skipConnVerification = false; public static void Main(string[] args) { ParseArgs(args); using (var bootstrapper = AbpBootstrapper.Create<AbpProjectNameMigratorModule>()) { bootstrapper.IocManager.IocContainer .AddFacility<LoggingFacility>(f => f.UseAbpLog4Net() .WithConfig("log4net.config") ); bootstrapper.Initialize(); using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MultiTenantMigrateExecuter>()) { migrateExecuter.Object.Run(_skipConnVerification); } Console.WriteLine("Press ENTER to exit..."); Console.ReadLine(); } } private static void ParseArgs(string[] args) { if (args.IsNullOrEmpty()) { return; } for (int i = 0; i < args.Length; i++) { var arg = args[i]; switch (arg) { case "-s": _skipConnVerification = true; break; } } } } }
using System; using Abp; using Abp.Collections.Extensions; using Abp.Dependency; using Castle.Facilities.Logging; using Abp.Castle.Logging.Log4Net; namespace AbpCompanyName.AbpProjectName.Migrator { public class Program { private static bool _skipConnVerification = false; public static void Main(string[] args) { ParseArgs(args); using (var bootstrapper = AbpBootstrapper.Create<AbpProjectNameMigratorModule>()) { bootstrapper.IocManager.IocContainer .AddFacility<LoggingFacility>(f => f.UseAbpLog4Net() .WithConfig("log4net.config") ); bootstrapper.Initialize(); using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MultiTenantMigrateExecuter>()) { migrateExecuter.Object.Run(_skipConnVerification); } if (!_skipConnVerification) { Console.WriteLine("Press ENTER to exit..."); Console.ReadLine(); } } } private static void ParseArgs(string[] args) { if (args.IsNullOrEmpty()) { return; } for (int i = 0; i < args.Length; i++) { var arg = args[i]; switch (arg) { case "-s": _skipConnVerification = true; break; } } } } }
Update file version to 3.2.1.0
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 - 2019"; public const string Trademark = ""; public const string Version = "3.2.0.0"; } }
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 - 2019"; public const string Trademark = ""; public const string Version = "3.2.1.0"; } }
Replace literals in order of key length, e.g. most-specific first.
namespace StraightSql { using Npgsql; using System; public class CommandPreparer : ICommandPreparer { public void Prepare(NpgsqlCommand npgsqlCommand, IQuery query) { if (npgsqlCommand == null) throw new ArgumentNullException(nameof(npgsqlCommand)); if (query == null) throw new ArgumentNullException(nameof(query)); var queryText = query.Text; foreach (var literal in query.Literals) { var moniker = $":{literal.Key}"; if (!queryText.Contains(moniker)) throw new LiteralNotFoundException(literal.Key); queryText = queryText.Replace(moniker, literal.Value); } npgsqlCommand.CommandText = queryText; foreach (var queryParameter in query.Parameters) { npgsqlCommand.Parameters.Add(queryParameter); } } } }
namespace StraightSql { using Npgsql; using System; using System.Linq; public class CommandPreparer : ICommandPreparer { public void Prepare(NpgsqlCommand npgsqlCommand, IQuery query) { if (npgsqlCommand == null) throw new ArgumentNullException(nameof(npgsqlCommand)); if (query == null) throw new ArgumentNullException(nameof(query)); var queryText = query.Text; foreach (var literal in query.Literals.OrderByDescending(l => l.Key.Length)) { var moniker = $":{literal.Key}"; if (!queryText.Contains(moniker)) throw new LiteralNotFoundException(literal.Key); queryText = queryText.Replace(moniker, literal.Value); } npgsqlCommand.CommandText = queryText; foreach (var queryParameter in query.Parameters) { npgsqlCommand.Parameters.Add(queryParameter); } } } }
Extend cookie timeout to 1 day
[assembly: Microsoft.Owin.OwinStartup(typeof(BatteryCommander.Web.Startup))] namespace BatteryCommander.Web { using Microsoft.AspNet.Identity; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Owin; using System; public partial class Startup { public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Auth/Login"), LogoutPath = new PathString("/Auth/Logout"), ExpireTimeSpan = TimeSpan.FromHours(1), SlidingExpiration = true, CookieHttpOnly = true, CookieSecure = CookieSecureOption.SameAsRequest // CookieDomain = "", // CookieName = "" }); app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); } } }
[assembly: Microsoft.Owin.OwinStartup(typeof(BatteryCommander.Web.Startup))] namespace BatteryCommander.Web { using Microsoft.AspNet.Identity; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Owin; using System; public partial class Startup { public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Auth/Login"), LogoutPath = new PathString("/Auth/Logout"), ExpireTimeSpan = TimeSpan.FromDays(1), SlidingExpiration = true, CookieHttpOnly = true, CookieSecure = CookieSecureOption.SameAsRequest // CookieDomain = "", // CookieName = "" }); app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); } } }
Adjust max size of contents read from incoming request headers to be 1k
namespace Microsoft.ApplicationInsights.AspNetCore.Common { /// <summary> /// These values are listed to guard against malicious injections by limiting the max size allowed in an HTTP Response. /// These max limits are intentionally exaggerated to allow for unexpected responses, while still guarding against unreasonably large responses. /// Example: While a 32 character response may be expected, 50 characters may be permitted while a 10,000 character response would be unreasonable and malicious. /// </summary> public static class InjectionGuardConstants { /// <summary> /// Max length of AppId allowed in response from Breeze. /// </summary> public const int AppIdMaxLengeth = 50; /// <summary> /// Max length of incoming Request Header value allowed. /// </summary> public const int RequestHeaderMaxLength = 1024; /// <summary> /// Max length of context header key. /// </summary> public const int ContextHeaderKeyMaxLength = 50; /// <summary> /// Max length of context header value. /// </summary> public const int ContextHeaderValueMaxLength = 100; } }
namespace Microsoft.ApplicationInsights.AspNetCore.Common { /// <summary> /// These values are listed to guard against malicious injections by limiting the max size allowed in an HTTP Response. /// These max limits are intentionally exaggerated to allow for unexpected responses, while still guarding against unreasonably large responses. /// Example: While a 32 character response may be expected, 50 characters may be permitted while a 10,000 character response would be unreasonable and malicious. /// </summary> public static class InjectionGuardConstants { /// <summary> /// Max length of AppId allowed in response from Breeze. /// </summary> public const int AppIdMaxLengeth = 50; /// <summary> /// Max length of incoming Request Header value allowed. /// </summary> public const int RequestHeaderMaxLength = 1024; /// <summary> /// Max length of context header key. /// </summary> public const int ContextHeaderKeyMaxLength = 50; /// <summary> /// Max length of context header value. /// </summary> public const int ContextHeaderValueMaxLength = 1024; } }
Fix "Sequence contains no elements" error.
using System; using System.Collections.Concurrent; using System.Linq; using ARSoft.Tools.Net.Dns; namespace DNSAgent { internal class DnsCacheMessageEntry { public DnsCacheMessageEntry(DnsMessage message, int timeToLive) { Message = message; timeToLive = Math.Max(message.AnswerRecords.Concat(message.AuthorityRecords).Min(record => record.TimeToLive), timeToLive); ExpireTime = DateTime.Now.AddSeconds(timeToLive); } public DnsMessage Message { get; set; } public DateTime ExpireTime { get; set; } public bool IsExpired { get { return DateTime.Now > ExpireTime; } } } internal class DnsMessageCache : ConcurrentDictionary<string, ConcurrentDictionary<RecordType, DnsCacheMessageEntry>> { public void Update(DnsQuestion question, DnsMessage message, int timeToLive) { if (!ContainsKey(question.Name)) this[question.Name] = new ConcurrentDictionary<RecordType, DnsCacheMessageEntry>(); this[question.Name][question.RecordType] = new DnsCacheMessageEntry(message, timeToLive); } } }
using System; using System.Collections.Concurrent; using System.Linq; using ARSoft.Tools.Net.Dns; namespace DNSAgent { internal class DnsCacheMessageEntry { public DnsCacheMessageEntry(DnsMessage message, int timeToLive) { Message = message; var records = message.AnswerRecords.Concat(message.AuthorityRecords).ToList(); if (records.Any()) timeToLive = Math.Max(records.Min(record => record.TimeToLive), timeToLive); ExpireTime = DateTime.Now.AddSeconds(timeToLive); } public DnsMessage Message { get; set; } public DateTime ExpireTime { get; set; } public bool IsExpired { get { return DateTime.Now > ExpireTime; } } } internal class DnsMessageCache : ConcurrentDictionary<string, ConcurrentDictionary<RecordType, DnsCacheMessageEntry>> { public void Update(DnsQuestion question, DnsMessage message, int timeToLive) { if (!ContainsKey(question.Name)) this[question.Name] = new ConcurrentDictionary<RecordType, DnsCacheMessageEntry>(); this[question.Name][question.RecordType] = new DnsCacheMessageEntry(message, timeToLive); } } }
Add xmldoc and TODO comment
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; namespace osu.Framework.Utils { public static class ThrowHelper { public static void ThrowInvalidOperationException(string? message) => throw new InvalidOperationException(message); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; namespace osu.Framework.Utils { /// <summary> /// Helper class for throwing exceptions in isolated methods, for cases where method inlining is beneficial. /// As throwing directly in that case causes JIT to disable inlining on the surrounding method. /// </summary> // todo: continue implementation and use where required, see https://github.com/ppy/osu-framework/issues/3470. public static class ThrowHelper { public static void ThrowInvalidOperationException(string? message) => throw new InvalidOperationException(message); } }
Add sumary and remark to class header
using System; namespace Avalonia.Metadata { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class XmlnsPrefixAttribute : Attribute { /// <summary> /// Constructor /// </summary> /// <param name="xmlNamespace">XML namespce</param> /// <param name="prefix">recommended prefix</param> public XmlnsPrefixAttribute(string xmlNamespace, string prefix) { XmlNamespace = xmlNamespace ?? throw new ArgumentNullException(nameof(xmlNamespace)); Prefix = prefix ?? throw new ArgumentNullException(nameof(prefix)); } /// <summary> /// XML Namespace /// </summary> public string XmlNamespace { get; } /// <summary> /// New Xml Namespace /// </summary> public string Prefix { get; } } }
using System; namespace Avalonia.Metadata { /// <summary> /// Use to predefine the prefix associated to an xml namespace in a xaml file /// </summary> /// <remarks> /// example: /// [assembly: XmlnsPrefix("https://github.com/avaloniaui", "av")] /// xaml: /// xmlns:av="https://github.com/avaloniaui" /// </remarks> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class XmlnsPrefixAttribute : Attribute { /// <summary> /// Constructor /// </summary> /// <param name="xmlNamespace">XML namespce</param> /// <param name="prefix">recommended prefix</param> public XmlnsPrefixAttribute(string xmlNamespace, string prefix) { XmlNamespace = xmlNamespace ?? throw new ArgumentNullException(nameof(xmlNamespace)); Prefix = prefix ?? throw new ArgumentNullException(nameof(prefix)); } /// <summary> /// XML Namespace /// </summary> public string XmlNamespace { get; } /// <summary> /// New Xml Namespace /// </summary> public string Prefix { get; } } }
Update assembly version to 4.0.0 (+semver: major)
using System.Reflection; using System.Resources; [assembly: AssemblyCompany( "Carl Zeiss Innovationszentrum für Messtechnik GmbH" )] [assembly: AssemblyProduct( "ZEISS PiWeb Api" )] [assembly: AssemblyCopyright( "Copyright © 2019 Carl Zeiss Innovationszentrum für Messtechnik GmbH" )] [assembly: AssemblyTrademark( "PiWeb" )] [assembly: NeutralResourcesLanguage( "en" )] [assembly: AssemblyVersion( "3.0.0" )] [assembly: AssemblyInformationalVersion("3.0.0")] [assembly: AssemblyFileVersion( "3.0.0" )]
using System.Reflection; using System.Resources; [assembly: AssemblyCompany( "Carl Zeiss Innovationszentrum für Messtechnik GmbH" )] [assembly: AssemblyProduct( "ZEISS PiWeb Api" )] [assembly: AssemblyCopyright( "Copyright © 2019 Carl Zeiss Innovationszentrum für Messtechnik GmbH" )] [assembly: AssemblyTrademark( "PiWeb" )] [assembly: NeutralResourcesLanguage( "en" )] [assembly: AssemblyVersion( "4.0.0" )] [assembly: AssemblyInformationalVersion("4.0.0")] [assembly: AssemblyFileVersion( "4.0.0" )]
Allow specifying metadata for skip reason.
// 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 Xunit.Sdk; namespace Xunit { /// <summary> /// Apply this attribute to your test method to specify this is a platform specific test. /// </summary> [TraitDiscoverer("Xunit.NetCore.Extensions.SkipOnTargetFrameworkDiscoverer", "Xunit.NetCore.Extensions")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] public class SkipOnTargetFrameworkAttribute : Attribute, ITraitAttribute { public SkipOnTargetFrameworkAttribute(TargetFrameworkMonikers platform) { } } }
// 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 Xunit.Sdk; namespace Xunit { /// <summary> /// Apply this attribute to your test method to specify this is a platform specific test. /// </summary> [TraitDiscoverer("Xunit.NetCore.Extensions.SkipOnTargetFrameworkDiscoverer", "Xunit.NetCore.Extensions")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] public class SkipOnTargetFrameworkAttribute : Attribute, ITraitAttribute { public SkipOnTargetFrameworkAttribute(TargetFrameworkMonikers platform, string reason = null) { } } }
Fix link open in browsers
using UnityEngine; public class LinkButton : MonoBehaviour { public void OpenUrl (string url) { Application.OpenURL(url); } }
using UnityEngine; public class LinkButton : MonoBehaviour { public void OpenUrl (string url) { if(Application.platform == RuntimePlatform.WebGLPlayer) { Application.ExternalEval("window.open(\"" + url + "\",\"_blank\")"); } else { Application.OpenURL(url); } } }
Fix crash issue when user didn't install python.
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Python.Runtime; using Wox.Plugin; namespace Wox.PluginLoader { public class PythonPluginLoader : BasePluginLoader { public override List<PluginPair> LoadPlugin() { List<PluginPair> plugins = new List<PluginPair>(); List<PluginMetadata> metadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.Python.ToUpper()).ToList(); foreach (PluginMetadata metadata in metadatas) { PythonPluginWrapper python = new PythonPluginWrapper(metadata); PluginPair pair = new PluginPair() { Plugin = python, Metadata = metadata }; plugins.Add(pair); } return plugins; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Python.Runtime; using Wox.Plugin; using Wox.Helper; namespace Wox.PluginLoader { public class PythonPluginLoader : BasePluginLoader { public override List<PluginPair> LoadPlugin() { if (!CheckPythonEnvironmentInstalled()) return new List<PluginPair>(); List<PluginPair> plugins = new List<PluginPair>(); List<PluginMetadata> metadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.Python.ToUpper()).ToList(); foreach (PluginMetadata metadata in metadatas) { PythonPluginWrapper python = new PythonPluginWrapper(metadata); PluginPair pair = new PluginPair() { Plugin = python, Metadata = metadata }; plugins.Add(pair); } return plugins; } private bool CheckPythonEnvironmentInstalled() { try { PythonEngine.Initialize(); PythonEngine.Shutdown(); } catch { Log.Error("Could't find python environment, all python plugins disabled."); return false; } return true; } } }
Fix test failure After consulting with search team, we can get results needed for this test by searching for "rock,pop" not "rock,pop,2000s"
using System.Linq; using NUnit.Framework; using SevenDigital.Api.Schema; using SevenDigital.Api.Schema.Tags; namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint { [TestFixture] public class ArtistByTagTopTests { [Test] public void Can_hit_endpoint() { ArtistByTagTop tags = Api<ArtistByTagTop>.Create .WithParameter("tags", "rock,pop,2000s") .Please(); Assert.That(tags, Is.Not.Null); Assert.That(tags.TaggedArtists.Count, Is.GreaterThan(0)); Assert.That(tags.Type, Is.EqualTo(ItemType.artist)); Assert.That(tags.TaggedArtists.FirstOrDefault().Artist.Name, Is.Not.Empty); } [Test] public void Can_hit_endpoint_with_paging() { ArtistByTagTop artistBrowse = Api<ArtistByTagTop>.Create .WithParameter("tags", "rock,pop,2000s") .WithParameter("page", "2") .WithParameter("pageSize", "20") .Please(); Assert.That(artistBrowse, Is.Not.Null); Assert.That(artistBrowse.Page, Is.EqualTo(2)); Assert.That(artistBrowse.PageSize, Is.EqualTo(20)); } } }
using System.Linq; using NUnit.Framework; using SevenDigital.Api.Schema; using SevenDigital.Api.Schema.Tags; namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint { [TestFixture] public class ArtistByTagTopTests { private const string Tags = "rock,pop"; [Test] public void Can_hit_endpoint() { ArtistByTagTop tags = Api<ArtistByTagTop>.Create .WithParameter("tags", Tags) .Please(); Assert.That(tags, Is.Not.Null); Assert.That(tags.TaggedArtists.Count, Is.GreaterThan(0)); Assert.That(tags.Type, Is.EqualTo(ItemType.artist)); Assert.That(tags.TaggedArtists.FirstOrDefault().Artist.Name, Is.Not.Empty); } [Test] public void Can_hit_endpoint_with_paging() { ArtistByTagTop artistBrowse = Api<ArtistByTagTop>.Create .WithParameter("tags", Tags) .WithParameter("page", "2") .WithParameter("pageSize", "20") .Please(); Assert.That(artistBrowse, Is.Not.Null); Assert.That(artistBrowse.Page, Is.EqualTo(2)); Assert.That(artistBrowse.PageSize, Is.EqualTo(20)); } } }
Add filter property to most anticipated movies request.
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base.Get; using Objects.Basic; using Objects.Get.Movies.Common; internal class TraktMoviesMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedMovie>, TraktMostAnticipatedMovie> { internal TraktMoviesMostAnticipatedRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "movies/anticipated{?extended,page,limit}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base; using Base.Get; using Objects.Basic; using Objects.Get.Movies.Common; internal class TraktMoviesMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedMovie>, TraktMostAnticipatedMovie> { internal TraktMoviesMostAnticipatedRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "movies/anticipated{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; internal TraktMovieFilter Filter { get; set; } protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
Add DiscogRelease properties: lowest_price and num_for_sale
using System; namespace DiscogsClient.Data.Result { public class DiscogsRelease : DiscogsReleaseBase { public DiscogsReleaseArtist[] extraartists { get; set; } public DiscogsReleaseLabel[] labels { get; set; } public DiscogsReleaseLabel[] companies { get; set; } public DiscogsFormat[] formats { get; set; } public DiscogsIdentifier[] identifiers { get; set; } public DiscogsCommunity community { get; set; } public DiscogsReleaseLabel[] series { get; set; } public string artists_sort { get; set; } public string catno { get; set; } public string country { get; set; } public DateTime date_added { get; set; } public DateTime date_changed { get; set; } public int estimated_weight { get; set; } public int format_quantity { get; set; } public int master_id { get; set; } public string master_url { get; set; } public string notes { get; set; } public string released { get; set; } public string released_formatted { get; set; } public string status { get; set; } public string thumb { get; set; } } }
using System; namespace DiscogsClient.Data.Result { public class DiscogsRelease : DiscogsReleaseBase { public DiscogsReleaseArtist[] extraartists { get; set; } public DiscogsReleaseLabel[] labels { get; set; } public DiscogsReleaseLabel[] companies { get; set; } public DiscogsFormat[] formats { get; set; } public DiscogsIdentifier[] identifiers { get; set; } public DiscogsCommunity community { get; set; } public DiscogsReleaseLabel[] series { get; set; } public string artists_sort { get; set; } public string catno { get; set; } public string country { get; set; } public DateTime date_added { get; set; } public DateTime date_changed { get; set; } /// <remarks>Grams</remarks> public int estimated_weight { get; set; } public int format_quantity { get; set; } public decimal lowest_price { get; set; } public int master_id { get; set; } public string master_url { get; set; } public string notes { get; set; } public int num_for_sale { get; set; } public string released { get; set; } public string released_formatted { get; set; } public string status { get; set; } public string thumb { get; set; } } }
Remove Culture since that causes issues for Workbooks
using System.Reflection; [assembly: AssemblyTitle("Logo en español para Xamarin Workbooks")] [assembly: AssemblyDescription("Aprende a programar con Xamarin Workbooks, C# y la legendaria Tortuga!")] [assembly: AssemblyCulture("es")] // NuGet package metadata [assembly: AssemblyMetadata("id", "Logo.es")] [assembly: AssemblyMetadata("authors", "Daniel Cazzulino")]
using System.Reflection; [assembly: AssemblyTitle("Logo en español para Xamarin Workbooks")] [assembly: AssemblyDescription("Aprende a programar con Xamarin Workbooks, C# y la legendaria Tortuga!")] // NuGet package metadata [assembly: AssemblyMetadata("id", "Logo.es")] [assembly: AssemblyMetadata("authors", "Daniel Cazzulino")]
Update assembly version to 2.2
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyProduct("NuGet")] [assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !FIXED_ASSEMBLY_VERSION [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0")] #endif [assembly: NeutralResourcesLanguage("en-US")]
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyProduct("NuGet")] [assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !FIXED_ASSEMBLY_VERSION [assembly: AssemblyVersion("2.2.0.0")] [assembly: AssemblyInformationalVersion("2.2.0")] #endif [assembly: NeutralResourcesLanguage("en-US")]
Update account balance check, account can have zero balance and still be valid.
using NUnit.Framework; namespace InterFAX.Api.Test.Integration { [TestFixture] public class AccountTests { [Test] public void can_get_balance() { var interfax = new FaxClient(); var actual = interfax.Account.GetBalance().Result; Assert.IsTrue(actual > 0); } } }
using NUnit.Framework; namespace InterFAX.Api.Test.Integration { [TestFixture] public class AccountTests { [Test] public void can_get_balance() { var interfax = new FaxClient(); var actual = interfax.Account.GetBalance().Result; //Assert.IsTrue(actual > 0); } } }
Add additional code gen smoke test cases
using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using IntelliTect.Coalesce; using IntelliTect.Coalesce.DataAnnotations; using IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext; #nullable enable namespace IntelliTect.Coalesce.Tests.TargetClasses { [Coalesce] public class CaseDtoStandalone : IClassDto<Case, TestDbContext.TestDbContext> { [Key] public int CaseId { get; set; } public string? Title { get; set; } public void MapTo(Case obj, IMappingContext context) { obj.Title = Title; } public void MapFrom(Case obj, IMappingContext context, IncludeTree? tree = null) { CaseId = obj.CaseKey; Title = obj.Title; } } public class ExternalTypeWithDtoProp { public CaseDtoStandalone Case { get; set; } } }
using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using IntelliTect.Coalesce; using IntelliTect.Coalesce.DataAnnotations; using IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext; #nullable enable namespace IntelliTect.Coalesce.Tests.TargetClasses { [Coalesce] public class CaseDtoStandalone : IClassDto<Case, TestDbContext.TestDbContext> { [Key] public int CaseId { get; set; } public string? Title { get; set; } public void MapTo(Case obj, IMappingContext context) { obj.Title = Title; } public void MapFrom(Case obj, IMappingContext context, IncludeTree? tree = null) { CaseId = obj.CaseKey; Title = obj.Title; } } public class ExternalTypeWithDtoProp { public CaseDtoStandalone Case { get; set; } public ICollection<CaseDtoStandalone> Cases { get; set; } public List<CaseDtoStandalone> CasesList { get; set; } public CaseDtoStandalone[] CasesArray { get; set; } } }
Update log controller for ow-server-enet
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace HardwareSensorSystem.SensorTechnology.Controllers { public class OwServerEnet2LogController : Controller { [AllowAnonymous] [HttpPost("api/devices/{deviceId}/log")] public async Task<IActionResult> Log([FromRoute]int deviceId) { XDocument file = XDocument.Load(HttpContext.Request.Body); var romIdName = XName.Get("ROMId", file.Root.Name.NamespaceName); var dataSensors = file.Root.Elements().Select(sensor => new { SerialNumber = sensor.Element(romIdName).Value, Data = sensor.Elements().Where(element => element != sensor.Element(romIdName)) }); return Ok(); } } }
using HardwareSensorSystem.SensorTechnology.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace HardwareSensorSystem.SensorTechnology.Controllers { public class OwServerEnet2LogController : Controller { private SensorTechnologyDbContext _context; public OwServerEnet2LogController(SensorTechnologyDbContext context) { _context = context; } [AllowAnonymous] [HttpPost("api/devices/{deviceId}/log/ow-server-enet")] public async Task<IActionResult> Log([FromRoute]int deviceId) { XDocument file = XDocument.Load(HttpContext.Request.Body); var romIdName = XName.Get("ROMId", file.Root.Name.NamespaceName); var dataSensors = file.Root.Elements().Select(sensor => new { SerialNumber = sensor.Element(romIdName).Value, Data = sensor.Elements().Where(element => element != sensor.Element(romIdName)) }); var groupedProperties = await _context.Sensors.Where(sensor => sensor.DeviceId.Equals(deviceId)) .Join(_context.SensorProperties .Where(property => property.Name.Equals("SENSOR_ID")) .Where(property => dataSensors.Any(e => e.SerialNumber.Equals(property.Value))), sensor => sensor.Id, property => property.SensorId, (sensor, _) => sensor) .GroupJoin(_context.SensorProperties, sensor => sensor.Id, property => property.SensorId, (_, properties) => properties) .ToListAsync(); foreach (var properties in groupedProperties) { var serialNumber = properties.Single(property => property.Name.Equals("SENSOR_ID")).Value; try { var data = dataSensors.Single(e => e.SerialNumber.Equals(serialNumber)).Data; } catch { } } return Ok(); } } }
Replace more hard-coded directory separators with "Path.DirectorySeparatorChar"
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ using System; namespace Aerospike.Client { /// <summary> /// Lua static configuration variables. These variables apply to all AerospikeClient instances /// in a single process. /// </summary> public sealed class LuaConfig { /// <summary> /// Directory location which contains user defined Lua source files. /// </summary> public static string PackagePath = "udf/?.lua"; /// <summary> /// Maximum number of Lua runtime instances to cache at any point in time. /// Each query with an aggregation function requires a Lua instance. /// If the number of concurrent queries exceeds the Lua pool size, a new Lua /// instance will still be created, but it will not be returned to the pool. /// </summary> public static int InstancePoolSize = 5; } }
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ using System; using System.IO; namespace Aerospike.Client { /// <summary> /// Lua static configuration variables. These variables apply to all AerospikeClient instances /// in a single process. /// </summary> public sealed class LuaConfig { /// <summary> /// Directory location which contains user defined Lua source files. /// </summary> public static string PackagePath = "udf" + Path.DirectorySeparatorChar + "?.lua"; /// <summary> /// Maximum number of Lua runtime instances to cache at any point in time. /// Each query with an aggregation function requires a Lua instance. /// If the number of concurrent queries exceeds the Lua pool size, a new Lua /// instance will still be created, but it will not be returned to the pool. /// </summary> public static int InstancePoolSize = 5; } }
Add missing field to config
using System.Collections.Generic; using Newtonsoft.Json; namespace TMDbLib.Objects.General { public class ConfigImageTypes { [JsonProperty("base_url")] public string BaseUrl { get; set; } [JsonProperty("secure_base_url")] public string SecureBaseUrl { get; set; } [JsonProperty("poster_sizes")] public List<string> PosterSizes { get; set; } [JsonProperty("backdrop_sizes")] public List<string> BackdropSizes { get; set; } [JsonProperty("profile_sizes")] public List<string> ProfileSizes { get; set; } [JsonProperty("logo_sizes")] public List<string> LogoSizes { get; set; } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace TMDbLib.Objects.General { public class ConfigImageTypes { [JsonProperty("base_url")] public string BaseUrl { get; set; } [JsonProperty("secure_base_url")] public string SecureBaseUrl { get; set; } [JsonProperty("poster_sizes")] public List<string> PosterSizes { get; set; } [JsonProperty("backdrop_sizes")] public List<string> BackdropSizes { get; set; } [JsonProperty("profile_sizes")] public List<string> ProfileSizes { get; set; } [JsonProperty("logo_sizes")] public List<string> LogoSizes { get; set; } [JsonProperty("still_sizes")] public List<string> StillSizes { get; set; } } }
Make a picture unque for every next level
using System; using System.Collections.Generic; namespace MonsterClicker { using Interfaces; using System.Numerics; using System.Windows.Forms; public class Monster : IMonster { private BigInteger health; private static BigInteger startHealth = 10; private BigInteger nextLevelHealth = startHealth; //private List<string> photosPaths; private Random randomGenerator; //TODO: exp and money - every next monster must have more money and exp //TODO: exp must be part of health //TODO: make class Boss //TODO: make homework //TODO: Timer public Monster() { this.Health = startHealth; //this.photosPaths = new List<string>(); this.randomGenerator = new System.Random(); } public BigInteger Health { get { return this.health; } set { this.health = value; } } public void TakeDamage(BigInteger damage) { this.Health -= damage; } public void GenerateHealth() { nextLevelHealth += (nextLevelHealth / 10); this.health = nextLevelHealth; } public int GetRandomNumber() { var number = randomGenerator.Next(0, 5); return number; } } }
using System; using System.Collections.Generic; namespace MonsterClicker { using Interfaces; using System.Numerics; using System.Windows.Forms; public class Monster : IMonster { private BigInteger health; private static BigInteger startHealth = 10; private BigInteger nextLevelHealth = startHealth; //private List<string> photosPaths; private Random randomGenerator; //TODO: exp and money - every next monster must have more money and exp //TODO: exp must be part of health //TODO: make class Boss //TODO: make homework //TODO: Timer public Monster() { this.Health = startHealth; //this.photosPaths = new List<string>(); this.randomGenerator = new System.Random(); } public BigInteger Health { get { return this.health; } set { this.health = value; } } public void TakeDamage(BigInteger damage) { this.Health -= damage; } public void GenerateHealth() { nextLevelHealth += (nextLevelHealth / 10); this.health = nextLevelHealth; } public int GetRandomNumber() { int firstNumber = 0; var number = randomGenerator.Next(0, 5); if (number == firstNumber) { while (number == firstNumber) { number = randomGenerator.Next(0, 5); } } else { firstNumber = number; } return number; } } }
Allow to run build even if git repo informations are not available
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); _versionContext.Git = GitVersion(); return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { var increment = 0; while(increment < 10) { try { var version = VersionContext.BuildVersion; if(increment > 0) version += "-" + increment; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; } } }
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); try { _versionContext.Git = GitVersion(); } catch { _versionContext.Git = new Cake.Common.Tools.GitVersion.GitVersion(); } return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { var increment = 0; while(increment < 10) { try { var version = VersionContext.BuildVersion; if(increment > 0) version += "-" + increment; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; } } }
Fix Mono 5.0 run under Unity 5.5+
using System.Diagnostics; using System.IO; internal class Mono50Compiler : Compiler { public Mono50Compiler(Logger logger, string compilerPath) : base(logger, compilerPath, null) { } public override string Name => "Mono C# 5.0"; protected override Process CreateCompilerProcess(Platform platform, string monoProfileDir, string unityEditorDataDir, string responseFile) { var systemCoreDllPath = Path.Combine(monoProfileDir, "System.Core.dll"); string processArguments; if (platform == Platform.Windows) { processArguments = $"-sdk:2 -debug+ -langversion:Future -r:\"{systemCoreDllPath}\" {responseFile}"; } else { processArguments = $"-sdk:2 -debug+ -langversion:Future {responseFile}"; } var process = new Process(); process.StartInfo = CreateOSDependentStartInfo(platform, ProcessRuntime.CLR40, compilerPath, processArguments, unityEditorDataDir); return process; } }
using System.Diagnostics; using System.IO; using System.Linq; internal class Mono50Compiler : Compiler { public Mono50Compiler(Logger logger, string compilerPath) : base(logger, compilerPath, null) { } public override string Name => "Mono C# 5.0"; protected override Process CreateCompilerProcess(Platform platform, string monoProfileDir, string unityEditorDataDir, string responseFile) { var systemCoreDllPath = Path.Combine(monoProfileDir, "System.Core.dll"); string processArguments; if (platform == Platform.Windows && GetSdkValue(responseFile) == "2.0") { // -sdk:2.0 requires System.Core.dll. but -sdk:unity doesn't. processArguments = $"-r:\"{systemCoreDllPath}\" {responseFile}"; } else { processArguments = responseFile; } var process = new Process(); process.StartInfo = CreateOSDependentStartInfo(platform, ProcessRuntime.CLR40, compilerPath, processArguments, unityEditorDataDir); return process; } private string GetSdkValue(string responseFile) { var lines = File.ReadAllLines(responseFile.Substring(1)); var sdkArg = lines.FirstOrDefault(line => line.StartsWith("-sdk:")); return (sdkArg != null) ? sdkArg.Substring(5) : ""; } }
Fix for email obfuscator of Cloudflare
@model ElmahDashboardHostingApp.Areas.MvcElmahDashboard.Models.Logs.ItemsModel @{ Layout = null; var dateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.Replace("yyyy", "yy").ToUpperInvariant(); } @foreach (var item in Model.Items) { <a id="i@(item.Sequence)" class="hidden" href="@(Url.Action("Details", new { id = item.ErrorId }))" data-href="@(Url.Action("Details", new { id = item.ErrorId }))?application={application}&host={host}&source={source}&type={type}&search={search}">@(item.Sequence)</a> <tr data-forward-click="A#i@(item.Sequence)" style="cursor: pointer;"> <td> @(item.Sequence) <br /><small class="text-muted">@(item.RowNum)</small> </td> <td> <span data-utctime="@(item.TimeUtc.Epoch())" data-format="@(dateFormat) hh:mm:ss"> @(item.TimeUtc.ToString()) (UTC) </span> <br /> <span class="floating-above"><small class="text-muted">@(item.TimeAgoText)</small></span> <br /> </td> <td>@item.Application</td> <td>@item.Host</td> <td>@item.Source</td> <td>@item.Type</td> <td>@item.Message</td> </tr> }
@model ElmahDashboardHostingApp.Areas.MvcElmahDashboard.Models.Logs.ItemsModel @{ Layout = null; var dateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.Replace("yyyy", "yy").ToUpperInvariant(); } @* Disable Email obfuscation by Cloudflare (which is not compatible with this rendering) *@ <!--email_off--> @foreach (var item in Model.Items) { <a id="i@(item.Sequence)" class="hidden" href="@(Url.Action("Details", new { id = item.ErrorId }))" data-href="@(Url.Action("Details", new { id = item.ErrorId }))?application={application}&host={host}&source={source}&type={type}&search={search}">@(item.Sequence)</a> <tr data-forward-click="A#i@(item.Sequence)" style="cursor: pointer;"> <td> @(item.Sequence) <br /><small class="text-muted">@(item.RowNum)</small> </td> <td> <span data-utctime="@(item.TimeUtc.Epoch())" data-format="@(dateFormat) hh:mm:ss"> @(item.TimeUtc.ToString()) (UTC) </span> <br /> <span class="floating-above"><small class="text-muted">@(item.TimeAgoText)</small></span> <br /> </td> <td>@item.Application</td> <td>@item.Host</td> <td>@item.Source</td> <td>@item.Type</td> <td>@item.Message</td> </tr> } <!--/email_off-->
Include a pepper in the hashing algorithm.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Raven.Client.Contrib.MVC.Auth.Interfaces; namespace Raven.Client.Contrib.MVC.Auth.Default { internal class BCryptSecurityEncoder : ISecurityEncoder { /// <summary> /// Generates a unique token. /// </summary> /// <returns>The unique token.</returns> public string GenerateToken() { return new Guid().ToString() .ToLowerInvariant() .Replace("-", ""); } /// <summary> /// Hashes the identifier with the provided salt. /// </summary> /// <param name="identifier">The identifier to hash.</param> /// <returns>The hashed identifier.</returns> public string Hash(string identifier) { return BCrypt.Net.BCrypt.HashPassword(identifier, workFactor: 10); } /// <summary> /// Verifies if the identifier matches the hash. /// </summary> /// <param name="identifier">The identifier to check.</param> /// <param name="hash">The hash to check against.</param> /// <returns>true if the identifiers match, false otherwise.</returns> public bool Verify(string identifier, string hash) { return BCrypt.Net.BCrypt.Verify(identifier, hash); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Raven.Client.Contrib.MVC.Auth.Interfaces; namespace Raven.Client.Contrib.MVC.Auth.Default { internal class BCryptSecurityEncoder : ISecurityEncoder { /// <summary> /// Generates a unique token. /// </summary> /// <returns>The unique token.</returns> public string GenerateToken() { return new Guid().ToString() .ToLowerInvariant() .Replace("-", ""); } /// <summary> /// Hashes the identifier with the provided salt. /// </summary> /// <param name="identifier">The identifier to hash.</param> /// <returns>The hashed identifier.</returns> public string Hash(string identifier) { const string pepper = "BCryptSecurityEncoder"; string salt = BCrypt.Net.BCrypt.GenerateSalt(workFactor: 10); return BCrypt.Net.BCrypt.HashPassword(identifier, salt + pepper); } /// <summary> /// Verifies if the identifier matches the hash. /// </summary> /// <param name="identifier">The identifier to check.</param> /// <param name="hash">The hash to check against.</param> /// <returns>true if the identifiers match, false otherwise.</returns> public bool Verify(string identifier, string hash) { return BCrypt.Net.BCrypt.Verify(identifier, hash); } } }
Decrease allocations in List Serializer
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { internal class ListSerializationDelegateProvider : SerializationDelegateProviderBase { public override bool CanHandle(Type type) { return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>); } private static JsonValue _Encode<T>(List<T> list, JsonSerializer serializer) { var array = new JsonArray(); array.AddRange(list.Select(serializer.Serialize)); return array; } private static List<T> _Decode<T>(JsonValue json, JsonSerializer serializer) { var list = new List<T>(); list.AddRange(json.Array.Select(serializer.Deserialize<T>)); return list; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { internal class ListSerializationDelegateProvider : SerializationDelegateProviderBase { public override bool CanHandle(Type type) { return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>); } private static JsonValue _Encode<T>(List<T> list, JsonSerializer serializer) { var array = new JsonValue[list.Count]; for (int ii = 0; ii < array.Length; ++ii) { array[ii] = serializer.Serialize(list[ii]); } return new JsonArray(array); } private static List<T> _Decode<T>(JsonValue json, JsonSerializer serializer) { var array = json.Array; var list = new List<T>(array.Count); for (int ii = 0; ii < array.Count; ++ii) { list.Add(serializer.Deserialize<T>(array[ii])); } return list; } } }
Add recently used items data
namespace MyStudio.ViewModels { using Catel; using Catel.MVVM; using MyStudio.Models; using MyStudio.Services; public class RibbonViewModel : ViewModelBase { private StudioStateModel model; private ICommandsService commandsService; public RibbonViewModel(StudioStateModel model, ICommandsService commandsService) { Argument.IsNotNull(() => model); Argument.IsNotNull(() => commandsService); this.model = model; this.commandsService = commandsService; } public Command StartCommand { get { return this.commandsService != null ? this.commandsService.StartCommand : null; } } public Command UndoCommand { get { return this.commandsService != null ? this.commandsService.UndoCommand : null; } } public Command RedoCommand { get { return this.commandsService != null ? this.commandsService.RedoCommand : null; } } } }
namespace MyStudio.ViewModels { using System.Collections.Generic; using Catel; using Catel.MVVM; using MyStudio.Models; using MyStudio.Services; using Orchestra.Models; using Orchestra.Services; public class RibbonViewModel : ViewModelBase { private StudioStateModel model; private ICommandsService commandsService; private IRecentlyUsedItemsService recentlyUsedItemsService; public RibbonViewModel(StudioStateModel model, ICommandsService commandsService, IRecentlyUsedItemsService recentlyUsedItemsService) { Argument.IsNotNull(() => model); Argument.IsNotNull(() => commandsService); Argument.IsNotNull(() => recentlyUsedItemsService); this.model = model; this.commandsService = commandsService; this.recentlyUsedItemsService = recentlyUsedItemsService; this.RecentlyUsedItems = new List<RecentlyUsedItem>(this.recentlyUsedItemsService.Items); this.PinnedItems = new List<RecentlyUsedItem>(this.recentlyUsedItemsService.PinnedItems); } public Command StartCommand { get { return this.commandsService != null ? this.commandsService.StartCommand : null; } } public Command UndoCommand { get { return this.commandsService != null ? this.commandsService.UndoCommand : null; } } public Command RedoCommand { get { return this.commandsService != null ? this.commandsService.RedoCommand : null; } } public List<RecentlyUsedItem> RecentlyUsedItems { get; private set; } public List<RecentlyUsedItem> PinnedItems { get; private set; } } }
Fix displayed version in built-in version command
using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Spectre.Console; namespace Spectre.Cli.Internal { [Description("Displays the CLI library version")] [SuppressMessage("Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Injected")] internal sealed class VersionCommand : Command<VersionCommand.Settings> { private readonly IAnsiConsole _writer; public VersionCommand(IConfiguration configuration) { _writer = configuration?.Settings?.Console ?? AnsiConsole.Console; } public sealed class Settings : CommandSettings { } public override int Execute(CommandContext context, Settings settings) { var version = typeof(VersionCommand)?.Assembly?.GetName()?.Version?.ToString(); version ??= "?"; _writer.Write($"Spectre.Cli version {version}"); return 0; } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Spectre.Console; namespace Spectre.Cli.Internal { [Description("Displays the CLI library version")] [SuppressMessage("Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Injected")] internal sealed class VersionCommand : Command<VersionCommand.Settings> { private readonly IAnsiConsole _writer; public VersionCommand(IConfiguration configuration) { _writer = configuration?.Settings?.Console ?? AnsiConsole.Console; } public sealed class Settings : CommandSettings { } public override int Execute(CommandContext context, Settings settings) { _writer.MarkupLine( "[yellow]Spectre.Cli[/] version [aqua]{0}[/]", GetVersion(typeof(VersionCommand)?.Assembly)); _writer.MarkupLine( "[yellow]Spectre.Console[/] version [aqua]{0}[/]", GetVersion(typeof(IAnsiConsole)?.Assembly)); return 0; } [SuppressMessage("Design", "CA1031:Do not catch general exception types")] private static string GetVersion(Assembly? assembly) { if (assembly == null) { return "?"; } try { var info = FileVersionInfo.GetVersionInfo(assembly.Location); return info.ProductVersion ?? "?"; } catch { return "?"; } } } }
Set the version to 1.3 since we're releasing.
using System.Reflection; // 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.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
using System.Reflection; // 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.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")]
Set StateId in DataTokens so ShieldDecode works because StateId was in the data when ShieldEncode was called
using System.Web.Mvc; using System.Web.Routing; namespace Navigation.Mvc { public class RouteConfig { public static void AddStateRoutes() { if (StateInfoConfig.Dialogs == null) return; string controller, action; Route route; using (RouteTable.Routes.GetWriteLock()) { foreach (Dialog dialog in StateInfoConfig.Dialogs) { foreach (State state in dialog.States) { controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty; action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty; if (controller.Length != 0 && action.Length != 0 && state.Route.Length != 0) { state.StateHandler = new MvcStateHandler(); route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route); route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route); route.Defaults["controller"] = controller; route.Defaults["action"] = action; route.RouteHandler = new MvcStateRouteHandler(state); } } } } } } }
using System.Web.Mvc; using System.Web.Routing; namespace Navigation.Mvc { public class RouteConfig { public static void AddStateRoutes() { if (StateInfoConfig.Dialogs == null) return; string controller, action; Route route; using (RouteTable.Routes.GetWriteLock()) { foreach (Dialog dialog in StateInfoConfig.Dialogs) { foreach (State state in dialog.States) { controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty; action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty; if (controller.Length != 0 && action.Length != 0 && state.Route.Length != 0) { state.StateHandler = new MvcStateHandler(); route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route); route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route); route.Defaults["controller"] = controller; route.Defaults["action"] = action; route.DataTokens = new RouteValueDictionary() { { NavigationSettings.Config.StateIdKey, state.Id } }; route.RouteHandler = new MvcStateRouteHandler(state); } } } } } } }
Use auto-version for AssemblyFileVersion in develop builds to facilitate installers
using System.Reflection; [assembly: AssemblyCompany("Picoe Software Solutions Inc.")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.99.0.0")] [assembly: AssemblyFileVersion("1.99.0.0")] [assembly: AssemblyInformationalVersion("1.99.0")]
using System.Reflection; [assembly: AssemblyCompany("Picoe Software Solutions Inc.")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.99.0.0")] [assembly: AssemblyFileVersion("1.99.*")] [assembly: AssemblyInformationalVersion("1.99.0")]
Include missing views AddNews and EditNews in project.
using System.Web; using System.Web.Mvc; namespace SvNaum.Web { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); } } }
using System.Web; using System.Web.Mvc; namespace SvNaum.Web { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
Add support for building from the command line.
namespace C42A { using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static int Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); using (var f = new global::C42A.CAB42.Windows.Forms.CAB42()) { if (args != null && args.Length > 0) { if (args.Length == 1) { f.OpenFileOnShow = args[0]; } } Application.Run(f); } return 0; } } }
namespace C42A { using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; using C42A.CAB42; internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static int Main(string[] args) { if (args.Length > 0 && args[0] == "build") { AllocConsole(); if (args.Length != 2) Console.WriteLine("cab42.exe build PATH"); try { Build(args[1]); } catch (Exception error) { Console.Error.WriteLine(error.ToString()); return 1; } return 0; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); using (var f = new global::C42A.CAB42.Windows.Forms.CAB42()) { if (args != null && args.Length > 0) { if (args.Length == 1) { f.OpenFileOnShow = args[0]; } } Application.Run(f); } return 0; } private static void Build(string file) { var buildProject = ProjectInfo.Open(file); using (var buildContext = new CabwizBuildContext()) { var tasks = buildProject.CreateBuildTasks(); var feedback = new BuildFeedbackBase(Console.Out); buildContext.Build(tasks, feedback); } } [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool AllocConsole(); } }
Update Main to print the graph
using System; using compiler.frontend; namespace Program { class Program { //TODO: adjust main to use the parser when it is complete static void Main(string[] args) { using (Lexer l = new Lexer(@"../../testdata/big.txt")) { Token t; do { t = l.GetNextToken(); Console.WriteLine(TokenHelper.PrintToken(t)); } while (t != Token.EOF); // necessary when testing on windows with visual studio //Console.WriteLine("Press 'enter' to exit ...."); //Console.ReadLine(); } } } }
using System; using compiler.frontend; namespace Program { class Program { //TODO: adjust main to use the parser when it is complete static void Main(string[] args) { // using (Lexer l = new Lexer(@"../../testdata/big.txt")) // { // Token t; // do // { // t = l.GetNextToken(); // Console.WriteLine(TokenHelper.PrintToken(t)); // // } while (t != Token.EOF); // // // necessary when testing on windows with visual studio // //Console.WriteLine("Press 'enter' to exit ...."); // //Console.ReadLine(); // } using (Parser p = new Parser(@"../../testdata/test002.txt")) { p.Parse(); p.FlowCfg.GenerateDOTOutput(); using (System.IO.StreamWriter file = new System.IO.StreamWriter("graph.txt")) { file.WriteLine( p.FlowCfg.DOTOutput); } } } } }
Add HttpResponseMessage.EnsureSuccess that include response content in the exception.
namespace System.Net.Http { using System.Collections.Generic; using System.Diagnostics; using System.Linq; static class HttpHelper { public static string ValidatePath(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path == "" || path == "/") return ""; if (path[0] != '/' || path[path.Length - 1] == '/') throw new ArgumentException(nameof(path)); return path; } public static DelegatingHandler Combine(this IEnumerable<DelegatingHandler> handlers) { var result = handlers.FirstOrDefault(); var last = result; foreach (var handler in handlers.Skip(1)) { last.InnerHandler = handler; last = handler; } return result; } [Conditional("DEBUG")] public static void DumpErrors(HttpResponseMessage message) { if (!message.IsSuccessStatusCode && message.StatusCode != HttpStatusCode.Unauthorized) { var dump = (Action)(async () => { var error = await message.Content.ReadAsStringAsync(); Debug.WriteLine(error); }); dump(); } } public static int TryGetContentLength(HttpResponseMessage response) { int result; IEnumerable<string> value; if (response.Headers.TryGetValues("Content-Length", out value) && value.Any() && int.TryParse(value.First(), out result)) { return result; } return 0; } } }
namespace System.Net.Http { using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; static class HttpHelper { public static string ValidatePath(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path == "" || path == "/") return ""; if (path[0] != '/' || path[path.Length - 1] == '/') throw new ArgumentException(nameof(path)); return path; } public static DelegatingHandler Combine(this IEnumerable<DelegatingHandler> handlers) { var result = handlers.FirstOrDefault(); var last = result; foreach (var handler in handlers.Skip(1)) { last.InnerHandler = handler; last = handler; } return result; } [Conditional("DEBUG")] public static void DumpErrors(HttpResponseMessage message) { if (!message.IsSuccessStatusCode && message.StatusCode != HttpStatusCode.Unauthorized) { var dump = (Action)(async () => { var error = await message.Content.ReadAsStringAsync(); Debug.WriteLine(error); }); dump(); } } public static HttpResponseMessage EnsureSuccess(this HttpResponseMessage message) { if (message.IsSuccessStatusCode) return message; throw new HttpRequestException($"Http {message.StatusCode}: {message.Content.ReadAsStringAsync().Result}"); } public static int TryGetContentLength(HttpResponseMessage response) { int result; IEnumerable<string> value; if (response.Headers.TryGetValues("Content-Length", out value) && value.Any() && int.TryParse(value.First(), out result)) { return result; } return 0; } } }
Add a footer navigation widget.
using System; using System.Collections.Generic; using System.Data; using Orchard.ContentManagement.Drivers; using Orchard.ContentManagement.MetaData; using Orchard.ContentManagement.MetaData.Builders; using Orchard.Core.Contents.Extensions; using Orchard.Data.Migration; using Orchard.Environment.Extensions; namespace LccNetwork.Migrations { [OrchardFeature("fea")] public class NavigationMigrations : DataMigrationImpl { public int Create() { return 1; } public int UpdateFrom1() { return 2; } public int UpdateFrom2() { ContentDefinitionManager.AlterTypeDefinition("SectionMenu", cfg => cfg .WithPart("CommonPart") .WithPart("IdentityPart") .WithPart("WidgetPart") .WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI? .WithSetting("Stereotype", "Widget") ); return 3; } } }
using System; using System.Collections.Generic; using System.Data; using Orchard.ContentManagement.Drivers; using Orchard.ContentManagement.MetaData; using Orchard.ContentManagement.MetaData.Builders; using Orchard.Core.Contents.Extensions; using Orchard.Data.Migration; using Orchard.Environment.Extensions; namespace LccNetwork.Migrations { [OrchardFeature("SectionNavigation")] public class NavigationMigrations : DataMigrationImpl { public int Create() { return 1; } public int UpdateFrom1() { return 2; } public int UpdateFrom2() { ContentDefinitionManager.AlterTypeDefinition("SectionMenu", cfg => cfg .WithPart("CommonPart") .WithPart("IdentityPart") .WithPart("WidgetPart") .WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI? .WithSetting("Stereotype", "Widget") ); return 4; } public int UpdateFrom4() { ContentDefinitionManager.AlterTypeDefinition("FooterMenu", cfg => cfg .WithPart("CommonPart") .WithPart("IdentityPart") .WithPart("WidgetPart") .WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI? .WithSetting("Stereotype", "Widget") ); return 5; } } }
Tweak to use the fact that we now have nanosecond precision in Duration.
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Reflection; namespace NodaTime.Benchmarks.Framework { /// <summary> /// The results of running a single test. /// </summary> internal class BenchmarkResult { private const long TicksPerPicosecond = 100 * 1000L; private const long TicksPerNanosecond = 100; private readonly MethodInfo method; private readonly int iterations; private readonly Duration duration; internal BenchmarkResult(MethodInfo method, int iterations, Duration duration) { this.method = method; this.iterations = iterations; this.duration = duration; } internal MethodInfo Method { get { return method; } } internal long Iterations { get { return iterations; } } internal Duration Duration { get { return duration; } } internal long CallsPerSecond { get { return iterations * NodaConstants.TicksPerSecond / duration.Ticks; } } internal long TicksPerCall { get { return Duration.Ticks / iterations; } } internal long PicosecondsPerCall { get { return (Duration.Ticks * TicksPerPicosecond) / iterations; } } internal long NanosecondsPerCall { get { return (Duration.Ticks * TicksPerNanosecond) / iterations; } } } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Reflection; namespace NodaTime.Benchmarks.Framework { /// <summary> /// The results of running a single test. /// </summary> internal class BenchmarkResult { private const long TicksPerPicosecond = 100 * 1000L; private const long TicksPerNanosecond = 100; private readonly MethodInfo method; private readonly int iterations; private readonly Duration duration; internal BenchmarkResult(MethodInfo method, int iterations, Duration duration) { this.method = method; this.iterations = iterations; this.duration = duration; } internal MethodInfo Method { get { return method; } } internal long Iterations { get { return iterations; } } internal Duration Duration { get { return duration; } } // Use ticks here rather than nanoseconds, as otherwise the multiplication could easily overflow. As an alternative, // we could use decimal arithmetic or BigInteger... internal long CallsPerSecond { get { return iterations * NodaConstants.TicksPerSecond / duration.Ticks; } } internal long NanosecondsPerCall { get { return Duration.ToInt64Nanoseconds() / iterations; } } } }
Make enable method name consistent on TTL field
using Newtonsoft.Json; namespace Nest { [JsonConverter(typeof(ReadAsTypeJsonConverter<TtlField>))] public interface ITtlField : IFieldMapping { [JsonProperty("enabled")] bool? Enabled { get; set; } [JsonProperty("default")] Time Default { get; set; } } public class TtlField : ITtlField { public bool? Enabled { get; set; } public Time Default { get; set; } } public class TtlFieldDescriptor : DescriptorBase<TtlFieldDescriptor, ITtlField>, ITtlField { bool? ITtlField.Enabled { get; set; } Time ITtlField.Default { get; set; } public TtlFieldDescriptor Enable(bool enable = true) => Assign(a => a.Enabled = enable); public TtlFieldDescriptor Default(Time defaultTtl) => Assign(a => a.Default = defaultTtl); } }
using Newtonsoft.Json; namespace Nest { [JsonConverter(typeof(ReadAsTypeJsonConverter<TtlField>))] public interface ITtlField : IFieldMapping { [JsonProperty("enabled")] bool? Enabled { get; set; } [JsonProperty("default")] Time Default { get; set; } } public class TtlField : ITtlField { public bool? Enabled { get; set; } public Time Default { get; set; } } public class TtlFieldDescriptor : DescriptorBase<TtlFieldDescriptor, ITtlField>, ITtlField { bool? ITtlField.Enabled { get; set; } Time ITtlField.Default { get; set; } public TtlFieldDescriptor Enabled(bool enabled = true) => Assign(a => a.Enabled = enabled); public TtlFieldDescriptor Default(Time defaultTtl) => Assign(a => a.Default = defaultTtl); } }
Change test to use new subtract method
using Xunit; namespace PlayerRank.UnitTests { public class PlayerTests { [Fact] public void CanIncreasePlayersScore() { var player = new PlayerScore("Foo"); player.AddPoints(new Points(100)); Assert.Equal(new Points(100), player.Points); Assert.Equal(100, player.Score); } [Fact] public void CanReducePlayersScore() { var player = new PlayerScore("Foo"); player.AddPoints(new Points(-100)); Assert.Equal(new Points(-100), player.Points); Assert.Equal(-100, player.Score); } } }
using Xunit; namespace PlayerRank.UnitTests { public class PlayerTests { [Fact] public void CanIncreasePlayersScore() { var player = new PlayerScore("Foo"); player.AddPoints(new Points(100)); Assert.Equal(new Points(100), player.Points); Assert.Equal(100, player.Score); } [Fact] public void CanReducePlayersScore() { var player = new PlayerScore("Foo"); player.SubtractPoints(new Points(100)); Assert.Equal(new Points(-100), player.Points); Assert.Equal(-100, player.Score); } } }
Stop unwatch from failing on shutdown
using System; using System.Reactive.Linq; using static LanguageExt.Prelude; using static LanguageExt.Process; namespace LanguageExt { internal class ActorDispatchNotExist : IActorDispatch { public readonly ProcessId ProcessId; public ActorDispatchNotExist(ProcessId pid) { ProcessId = pid; } private T Raise<T>() => raise<T>(new ProcessException($"Doesn't exist ({ProcessId})", Self.Path, Sender.Path, null)); public Map<string, ProcessId> GetChildren() => Map.empty<string, ProcessId>(); public IObservable<T> Observe<T>() => Observable.Empty<T>(); public IObservable<T> ObserveState<T>() => Observable.Empty<T>(); public Unit Tell(object message, ProcessId sender, Message.TagSpec tag) => Raise<Unit>(); public Unit TellSystem(SystemMessage message, ProcessId sender) => Raise<Unit>(); public Unit TellUserControl(UserControlMessage message, ProcessId sender) => Raise<Unit>(); public Unit Ask(object message, ProcessId sender) => Raise<Unit>(); public Unit Publish(object message) => Raise<Unit>(); public Unit Kill() => unit; public int GetInboxCount() => 0; public Unit Watch(ProcessId pid) => Raise<Unit>(); public Unit UnWatch(ProcessId pid) => Raise<Unit>(); public Unit DispatchWatch(ProcessId pid) => Raise<Unit>(); public Unit DispatchUnWatch(ProcessId pid) => Raise<Unit>(); } }
using System; using System.Reactive.Linq; using static LanguageExt.Prelude; using static LanguageExt.Process; namespace LanguageExt { internal class ActorDispatchNotExist : IActorDispatch { public readonly ProcessId ProcessId; public ActorDispatchNotExist(ProcessId pid) { ProcessId = pid; } private T Raise<T>() => raise<T>(new ProcessException($"Doesn't exist ({ProcessId})", Self.Path, Sender.Path, null)); public Map<string, ProcessId> GetChildren() => Map.empty<string, ProcessId>(); public IObservable<T> Observe<T>() => Observable.Empty<T>(); public IObservable<T> ObserveState<T>() => Observable.Empty<T>(); public Unit Tell(object message, ProcessId sender, Message.TagSpec tag) => Raise<Unit>(); public Unit TellSystem(SystemMessage message, ProcessId sender) => Raise<Unit>(); public Unit TellUserControl(UserControlMessage message, ProcessId sender) => Raise<Unit>(); public Unit Ask(object message, ProcessId sender) => Raise<Unit>(); public Unit Publish(object message) => Raise<Unit>(); public Unit Kill() => unit; public int GetInboxCount() => 0; public Unit Watch(ProcessId pid) => Raise<Unit>(); public Unit UnWatch(ProcessId pid) => unit; public Unit DispatchWatch(ProcessId pid) => Raise<Unit>(); public Unit DispatchUnWatch(ProcessId pid) => unit; } }