Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Use new "RuntimeDependencies" UBT feature to get our DLLs in place.
using UnrealBuildTool; using System.IO; public class OSVRClientKit : ModuleRules { private string ModulePath { get { return Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); } } public OSVRClientKit(TargetInfo Target) { Type = ModuleType.External; PublicIncludePaths.Add(ModulePath + "/include"); if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.Win32)) { string LibraryPath = ModulePath + "/lib"; if (Target.Platform == UnrealTargetPlatform.Win64) { LibraryPath += "/Win64"; } else if (Target.Platform == UnrealTargetPlatform.Win32) { LibraryPath += "/Win32"; } PublicLibraryPaths.Add(LibraryPath); PublicAdditionalLibraries.Add("osvrClientKit.lib"); PublicDelayLoadDLLs.AddRange( new string[] { "osvrClientKit.dll", "osvrClient.dll", "osvrCommon.dll", "osvrUtil.dll" }); } } }
using UnrealBuildTool; using System.IO; public class OSVRClientKit : ModuleRules { private string ModulePath { get { return Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); } } public OSVRClientKit(TargetInfo Target) { Type = ModuleType.External; PublicIncludePaths.Add(ModulePath + "/include"); if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.Win32)) { string LibraryPath = ModulePath + "/lib"; string DllPath = ModulePath + "/bin"; if (Target.Platform == UnrealTargetPlatform.Win64) { LibraryPath += "/Win64"; DllPath += "/Win64"; } else if (Target.Platform == UnrealTargetPlatform.Win32) { LibraryPath += "/Win32"; DllPath += "/Win32"; } PublicLibraryPaths.Add(LibraryPath); PublicAdditionalLibraries.Add("osvrClientKit.lib"); PublicDelayLoadDLLs.AddRange( new string[] { "osvrClientKit.dll", "osvrClient.dll", "osvrCommon.dll", "osvrUtil.dll" }); DllPath += "/"; foreach (var dll in PublicDelayLoadDLLs) { RuntimeDependencies.Add(new RuntimeDependency(DllPath + dll)); } } } }
Add Initial User API tests
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace Nether.Web.IntegrationTests.Identity { public class UserApiTests : WebTestBase { private HttpClient _client; //[Fact] //public async Task As_a_player_I_get_Forbidden_response_calling_GetUsers() //{ // AsPlayer(); // ResponseForGet("/users", hasStatusCode: HttpStatusCode.Forbidden); //} //private void ResponseForGet(string path, HttpStatusCode hasStatusCode) //{ // _client.GetAsync //} //private void AsPlayer() //{ // _client = GetClient(username:"testuser", isPlayer: true); //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace Nether.Web.IntegrationTests.Identity { public class UserApiTests : WebTestBase { private HttpClient _client; [Fact] public async Task As_a_player_I_get_Forbidden_response_calling_GetUsers() { await AsPlayerAsync(); await ResponseForGetAsync("/api/identity/users", hasStatusCode: HttpStatusCode.Forbidden); } private async Task<HttpResponseMessage> ResponseForGetAsync(string path, HttpStatusCode hasStatusCode) { var response = await _client.GetAsync(path); Assert.Equal(hasStatusCode, response.StatusCode); return response; } private async Task AsPlayerAsync() { _client = await GetClientAsync(username: "testuser", setPlayerGamertag: true); } } }
Set default trivia timeout to match help text.
using CommandLine; using NadekoBot.Core.Common; namespace NadekoBot.Core.Modules.Games.Common.Trivia { public class TriviaOptions : INadekoCommandOptions { [Option('p', "pokemon", Required = false, Default = false, HelpText = "Whether it's 'Who's that pokemon?' trivia.")] public bool IsPokemon { get; set; } = false; [Option("nohint", Required = false, Default = false, HelpText = "Don't show any hints.")] public bool NoHint { get; set; } = false; [Option('w', "win-req", Required = false, Default = 10, HelpText = "Winning requirement. Set 0 for an infinite game. Default 10.")] public int WinRequirement { get; set; } = 10; [Option('q', "question-timer", Required = false, Default = 30, HelpText = "How long until the question ends. Default 30.")] public int QuestionTimer { get; set; } = 30; [Option('t', "timeout", Required = false, Default = 0, HelpText = "Number of questions of inactivity in order stop. Set 0 for never. Default 10.")] public int Timeout { get; set; } = 10; public void NormalizeOptions() { if (WinRequirement < 0) WinRequirement = 10; if (QuestionTimer < 10 || QuestionTimer > 300) QuestionTimer = 30; if (Timeout < 0 || Timeout > 20) Timeout = 10; } } }
using CommandLine; using NadekoBot.Core.Common; namespace NadekoBot.Core.Modules.Games.Common.Trivia { public class TriviaOptions : INadekoCommandOptions { [Option('p', "pokemon", Required = false, Default = false, HelpText = "Whether it's 'Who's that pokemon?' trivia.")] public bool IsPokemon { get; set; } = false; [Option("nohint", Required = false, Default = false, HelpText = "Don't show any hints.")] public bool NoHint { get; set; } = false; [Option('w', "win-req", Required = false, Default = 10, HelpText = "Winning requirement. Set 0 for an infinite game. Default 10.")] public int WinRequirement { get; set; } = 10; [Option('q', "question-timer", Required = false, Default = 30, HelpText = "How long until the question ends. Default 30.")] public int QuestionTimer { get; set; } = 30; [Option('t', "timeout", Required = false, Default = 10, HelpText = "Number of questions of inactivity in order stop. Set 0 for never. Default 10.")] public int Timeout { get; set; } = 10; public void NormalizeOptions() { if (WinRequirement < 0) WinRequirement = 10; if (QuestionTimer < 10 || QuestionTimer > 300) QuestionTimer = 30; if (Timeout < 0 || Timeout > 20) Timeout = 10; } } }
Add support for `confirmation_method` on `PaymentIntent`
namespace Stripe { using System.Collections.Generic; using Newtonsoft.Json; public class PaymentIntentCreateOptions : PaymentIntentSharedOptions { [JsonProperty("capture_method")] public string CaptureMethod { get; set; } [JsonProperty("confirm")] public bool? Confirm { get; set; } [JsonProperty("return_url")] public string ReturnUrl { get; set; } [JsonProperty("statement_descriptor")] public string StatementDescriptor { get; set; } } }
namespace Stripe { using System.Collections.Generic; using Newtonsoft.Json; public class PaymentIntentCreateOptions : PaymentIntentSharedOptions { [JsonProperty("capture_method")] public string CaptureMethod { get; set; } [JsonProperty("confirm")] public bool? Confirm { get; set; } [JsonProperty("confirmation_method")] public string ConfirmationMethod { get; set; } [JsonProperty("return_url")] public string ReturnUrl { get; set; } [JsonProperty("statement_descriptor")] public string StatementDescriptor { get; set; } } }
Fix bug when pre-registered activator is instance
using System; using System.Linq; namespace Orleankka.Cluster { using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; static class ServiceCollectionExtensions { public static void Decorate<T>(this IServiceCollection services, Func<T, T> decorator) where T : class { var registered = services.First(s => s.ServiceType == typeof(T)); var factory = registered.ImplementationFactory; if (factory == null) services.TryAddSingleton(registered.ImplementationType); services.Replace(new ServiceDescriptor(typeof(T), sp => { var inner = factory == null ? sp.GetService(registered.ImplementationType) : factory(sp); return decorator((T) inner); }, registered.Lifetime)); } } }
using System; using System.Linq; namespace Orleankka.Cluster { using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; static class ServiceCollectionExtensions { public static void Decorate<T>(this IServiceCollection services, Func<T, T> decorator) where T : class { var registered = services.First(s => s.ServiceType == typeof(T)); var factory = registered.ImplementationFactory; if (factory == null && registered.ImplementationType != null) services.TryAddSingleton(registered.ImplementationType); services.Replace(new ServiceDescriptor(typeof(T), sp => { var inner = registered.ImplementationInstance; if (inner != null) return decorator((T) inner); inner = factory == null ? sp.GetService(registered.ImplementationType) : factory(sp); return decorator((T) inner); }, registered.Lifetime)); } } }
Expand mania to fit vertical screen bounds
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Game.Rulesets.UI; using osuTK; namespace osu.Game.Rulesets.Mania.UI { public class ManiaPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer { public ManiaPlayfieldAdjustmentContainer() { Anchor = Anchor.Centre; Origin = Anchor.Centre; Size = new Vector2(1, 0.8f); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Mania.UI { public class ManiaPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer { public ManiaPlayfieldAdjustmentContainer() { Anchor = Anchor.Centre; Origin = Anchor.Centre; } } }
Read data from underlying stream in chunks if it does not return everything to us in one go.
using System; using System.Threading; using System.Threading.Tasks; using WebSocket.Portable.Interfaces; namespace WebSocket.Portable.Internal { internal static class DataLayerExtensions { public static Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken) { return layer.ReadAsync(length, cancellationToken, WebSocketErrorCode.CloseInvalidData); } public static async Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken, WebSocketErrorCode errorCode) { var buffer = new byte[length]; var read = await layer.ReadAsync(buffer, 0, buffer.Length, cancellationToken); if (read != buffer.Length) throw new WebSocketException(errorCode); return buffer; } } }
using System.Threading; using System.Threading.Tasks; using WebSocket.Portable.Interfaces; namespace WebSocket.Portable.Internal { internal static class DataLayerExtensions { public static Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken) { return layer.ReadAsync(length, cancellationToken, WebSocketErrorCode.CloseInvalidData); } public static async Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken, WebSocketErrorCode errorCode) { var buffer = new byte[length]; var read = 0; while (read < length && !cancellationToken.IsCancellationRequested) { var chunkOffset = read; var chunkLength = length - chunkOffset; var chunkSize = await layer.ReadAsync(buffer, chunkOffset, chunkLength, cancellationToken); if (chunkSize == 0) { break; } read += chunkSize; } if (read != buffer.Length) throw new WebSocketException(errorCode); return buffer; } } }
Add exec method to js regexp
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> //----------------------------------------------------------------------- #endregion namespace System.Runtime.WootzJs { [Js(Export = false, Name = "RegExp")] public class JsRegExp { public JsRegExp(string s) { } public extern bool test(JsString value); public extern string[] match(JsString value); } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> //----------------------------------------------------------------------- #endregion namespace System.Runtime.WootzJs { [Js(Export = false, Name = "RegExp")] public class JsRegExp { public JsRegExp(string s) { } public extern bool test(JsString value); public extern string[] exec(JsString value); } }
Fix IsMoyaTestRunner to check for correct interface to implement.
namespace Moya.Utility { using System; using Exceptions; using Extensions; using Runners; public class Guard { public static void IsMoyaAttribute(Type type) { if (!Reflection.TypeIsMoyaAttribute(type)) { throw new MoyaException("{0} is not a Moya Attribute.".FormatWith(type)); } } public static void IsMoyaTestRunner(Type type) { if (!typeof(ITestRunner).IsAssignableFrom(type)) { throw new MoyaException("{0} is not a Moya Test Runner.".FormatWith(type)); } } } }
namespace Moya.Utility { using System; using Exceptions; using Extensions; using Runners; public class Guard { public static void IsMoyaAttribute(Type type) { if (!Reflection.TypeIsMoyaAttribute(type)) { throw new MoyaException("{0} is not a Moya Attribute.".FormatWith(type)); } } public static void IsMoyaTestRunner(Type type) { if (!typeof(IMoyaTestRunner).IsAssignableFrom(type)) { throw new MoyaException("{0} is not a Moya Test Runner.".FormatWith(type)); } } } }
Fix scraper to scrape pick a brick facets correctly
using LegoSharp; using System; using System.Threading.Tasks; using System.Collections.Generic; namespace Scraper { class Scraper { static async Task Main(string[] args) { foreach (var entry in await (new FacetScraper<ProductSearchQuery, ProductSearchResult>(new List<ProductSearchQuery> { new ProductSearchQuery() }, new ProductSearchFacetExtractor())).scrapeFacets()) { Console.WriteLine(entry.Key); foreach (var label in entry.Value) { Console.WriteLine(label.name + " " + label.value); } Console.WriteLine(); } Console.WriteLine("\n-----------------------------------------\n"); foreach (var entry in await (new FacetScraper<ProductSearchQuery, ProductSearchResult>(new List<ProductSearchQuery> { new ProductSearchQuery() }, new ProductSearchFacetExtractor())).scrapeFacets()) { Console.WriteLine(entry.Key); foreach (var label in entry.Value) { Console.WriteLine(label.name + " " + label.value); } Console.WriteLine(); } } } }
using LegoSharp; using System; using System.Threading.Tasks; using System.Collections.Generic; namespace Scraper { class Scraper { static async Task Main(string[] args) { foreach (var entry in await (new FacetScraper<ProductSearchQuery, ProductSearchResult>(new List<ProductSearchQuery> { new ProductSearchQuery() }, new ProductSearchFacetExtractor())).scrapeFacets()) { Console.WriteLine(entry.Key); foreach (var label in entry.Value) { Console.WriteLine(label.name + " " + label.value); } Console.WriteLine(); } Console.WriteLine("\n-----------------------------------------\n"); foreach (var entry in await (new FacetScraper<PickABrickQuery, PickABrickResult>(new List<PickABrickQuery> { new PickABrickQuery() }, new PickABrickFacetExtractor())).scrapeFacets()) { Console.WriteLine(entry.Key); foreach (var label in entry.Value) { Console.WriteLine(label.name + " " + label.value); } Console.WriteLine(); } } } }
Add background to rankings header
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Bindables; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets; using osu.Game.Users; namespace osu.Game.Overlays.Rankings { public class RankingsOverlayHeader : TabControlOverlayHeader<RankingsScope> { public readonly Bindable<RulesetInfo> Ruleset = new Bindable<RulesetInfo>(); public readonly Bindable<Country> Country = new Bindable<Country>(); protected override ScreenTitle CreateTitle() => new RankingsTitle { Scope = { BindTarget = Current } }; protected override Drawable CreateTitleContent() => new OverlayRulesetSelector { Current = Ruleset }; protected override Drawable CreateContent() => new CountryFilter { Current = Country }; private class RankingsTitle : ScreenTitle { public readonly Bindable<RankingsScope> Scope = new Bindable<RankingsScope>(); public RankingsTitle() { Title = "ranking"; } protected override void LoadComplete() { base.LoadComplete(); Scope.BindValueChanged(scope => Section = scope.NewValue.ToString().ToLowerInvariant(), true); } protected override Drawable CreateIcon() => new ScreenTitleTextureIcon(@"Icons/rankings"); } } public enum RankingsScope { Performance, Spotlights, Score, Country } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Bindables; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets; using osu.Game.Users; namespace osu.Game.Overlays.Rankings { public class RankingsOverlayHeader : TabControlOverlayHeader<RankingsScope> { public readonly Bindable<RulesetInfo> Ruleset = new Bindable<RulesetInfo>(); public readonly Bindable<Country> Country = new Bindable<Country>(); protected override ScreenTitle CreateTitle() => new RankingsTitle { Scope = { BindTarget = Current } }; protected override Drawable CreateTitleContent() => new OverlayRulesetSelector { Current = Ruleset }; protected override Drawable CreateContent() => new CountryFilter { Current = Country }; protected override Drawable CreateBackground() => new OverlayHeaderBackground(@"Headers/rankings"); private class RankingsTitle : ScreenTitle { public readonly Bindable<RankingsScope> Scope = new Bindable<RankingsScope>(); public RankingsTitle() { Title = "ranking"; } protected override void LoadComplete() { base.LoadComplete(); Scope.BindValueChanged(scope => Section = scope.NewValue.ToString().ToLowerInvariant(), true); } protected override Drawable CreateIcon() => new ScreenTitleTextureIcon(@"Icons/rankings"); } } public enum RankingsScope { Performance, Spotlights, Score, Country } }
Fix compile error by commenting out offending code.
using System.Collections.Concurrent; using LunaClient.Base; using LunaClient.Base.Interface; using LunaCommon.Message.Data.Vessel; using LunaCommon.Message.Interface; namespace LunaClient.Systems.VesselFlightStateSys { public class VesselFlightStateMessageHandler : SubSystem<VesselFlightStateSystem>, IMessageHandler { public ConcurrentQueue<IMessageData> IncomingMessages { get; set; } = new ConcurrentQueue<IMessageData>(); public void HandleMessage(IMessageData messageData) { var msgData = messageData as VesselFlightStateMsgData; if (msgData == null) return; var flightState = new FlightCtrlState { mainThrottle = msgData.MainThrottle, wheelThrottleTrim = msgData.WheelThrottleTrim, X = msgData.X, Y = msgData.Y, Z = msgData.Z, killRot = msgData.KillRot, gearUp = msgData.GearUp, gearDown = msgData.GearDown, headlight = msgData.Headlight, wheelThrottle = msgData.WheelThrottle, roll = msgData.Roll, yaw = msgData.Yaw, pitch = msgData.Pitch, rollTrim = msgData.RollTrim, yawTrim = msgData.YawTrim, pitchTrim = msgData.PitchTrim, wheelSteer = msgData.WheelSteer, wheelSteerTrim = msgData.WheelSteerTrim }; System.FlightState = flightState; } } }
using System.Collections.Concurrent; using LunaClient.Base; using LunaClient.Base.Interface; using LunaCommon.Message.Data.Vessel; using LunaCommon.Message.Interface; namespace LunaClient.Systems.VesselFlightStateSys { public class VesselFlightStateMessageHandler : SubSystem<VesselFlightStateSystem>, IMessageHandler { public ConcurrentQueue<IMessageData> IncomingMessages { get; set; } = new ConcurrentQueue<IMessageData>(); public void HandleMessage(IMessageData messageData) { var msgData = messageData as VesselFlightStateMsgData; if (msgData == null) return; var flightState = new FlightCtrlState { mainThrottle = msgData.MainThrottle, wheelThrottleTrim = msgData.WheelThrottleTrim, X = msgData.X, Y = msgData.Y, Z = msgData.Z, killRot = msgData.KillRot, gearUp = msgData.GearUp, gearDown = msgData.GearDown, headlight = msgData.Headlight, wheelThrottle = msgData.WheelThrottle, roll = msgData.Roll, yaw = msgData.Yaw, pitch = msgData.Pitch, rollTrim = msgData.RollTrim, yawTrim = msgData.YawTrim, pitchTrim = msgData.PitchTrim, wheelSteer = msgData.WheelSteer, wheelSteerTrim = msgData.WheelSteerTrim }; //System.FlightState = flightState; } } }
Delete unused experiment names added in merge.
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { public bool ReturnValue = false; [ImportingConstructor] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => ReturnValue; } internal static class WellKnownExperimentNames { public const string RoslynOOP64bit = nameof(RoslynOOP64bit); public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string RoslynToggleBlockComment = "Roslyn.ToggleBlockComment"; public const string RoslynToggleLineComment = "Roslyn.ToggleLineComment"; public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport"; public const string RoslynInlineRenameFile = "Roslyn.FileRename"; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { public bool ReturnValue = false; [ImportingConstructor] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => ReturnValue; } internal static class WellKnownExperimentNames { public const string RoslynOOP64bit = nameof(RoslynOOP64bit); public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport"; public const string RoslynInlineRenameFile = "Roslyn.FileRename"; } }
Use uint instead of Uint32 for consistency (even though they're exactly the same)
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; namespace CefSharp { [Flags] public enum DragOperationsMask : uint { None = 0, Copy = 1, Link = 2, Generic = 4, Private = 8, Move = 16, Delete = 32, Every = UInt32.MaxValue } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; namespace CefSharp { [Flags] public enum DragOperationsMask : uint { None = 0, Copy = 1, Link = 2, Generic = 4, Private = 8, Move = 16, Delete = 32, Every = uint.MaxValue } }
Add NotNull to Predicate setter.
// Copyright (c) Microsoft Open Technologies, Inc. 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.Threading.Tasks; using Microsoft.AspNet.Http; namespace Microsoft.AspNet.Builder.Extensions { /// <summary> /// Options for the MapWhen middleware /// </summary> public class MapWhenOptions { /// <summary> /// The user callback that determines if the branch should be taken /// </summary> public Func<HttpContext, bool> Predicate { get; set; } /// <summary> /// The branch taken for a positive match /// </summary> public RequestDelegate Branch { get; set; } } }
// Copyright (c) Microsoft Open Technologies, Inc. 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.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Builder.Extensions { /// <summary> /// Options for the MapWhen middleware /// </summary> public class MapWhenOptions { /// <summary> /// The user callback that determines if the branch should be taken /// </summary> public Func<HttpContext, bool> Predicate { get; [param: NotNull] set; } /// <summary> /// The branch taken for a positive match /// </summary> public RequestDelegate Branch { get; set; } } }
Add Admin user in Seed method
namespace StudentSystem.Data.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; public sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; } protected override void Seed(ApplicationDbContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
namespace StudentSystem.Data.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using StudentSystem.Models; public sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; } protected override void Seed(ApplicationDbContext context) { if (!context.Roles.Any()) { const string adminUsername = "admin@admin.com"; const string adminPass = "administrator"; const string roleName = "Administrator"; var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var role = new IdentityRole { Name = roleName }; roleManager.Create(role); var userStore = new UserStore<User>(context); var userManager = new UserManager<User>(userStore); var admin = new User { Email = adminUsername }; userManager.Create(admin, adminPass); userManager.AddToRole(admin.Id, roleName); } } } }
Test for default plex path before checking for registry key.
using System; using Microsoft.Win32; namespace PlexServiceCommon { public static class PlexDirHelper { /// <summary> /// Returns the full path and filename of the plex media server executable /// </summary> /// <returns></returns> public static string GetPlexDataDir() { var result = string.Empty; //work out the os type (32 or 64) and set the registry view to suit. this is only a reliable check when this project is compiled to x86. var is64Bit = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432")); var architecture = RegistryView.Registry32; if (is64Bit) { architecture = RegistryView.Registry64; } using var pmsDataKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, architecture).OpenSubKey(@"Software\Plex, Inc.\Plex Media Server"); if (pmsDataKey == null) { return result; } var path = (string) pmsDataKey.GetValue("LocalAppdataPath"); result = path; return result; } } }
using System; using System.IO; using Microsoft.Win32; namespace PlexServiceCommon { public static class PlexDirHelper { /// <summary> /// Returns the full path and filename of the plex media server executable /// </summary> /// <returns></returns> public static string GetPlexDataDir() { var result = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var path = Path.Combine(result, "Plex Media Server"); if (Directory.Exists(path)) { return path; } result = String.Empty; //work out the os type (32 or 64) and set the registry view to suit. this is only a reliable check when this project is compiled to x86. var is64Bit = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432")); var architecture = RegistryView.Registry32; if (is64Bit) { architecture = RegistryView.Registry64; } using var pmsDataKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, architecture).OpenSubKey(@"Software\Plex, Inc.\Plex Media Server"); if (pmsDataKey == null) { return result; } path = (string) pmsDataKey.GetValue("LocalAppdataPath"); result = path; return result; } } }
Add Join extension for strings
using System.Globalization; namespace GoldenAnvil.Utility { public static class StringUtility { public static string FormatInvariant(this string format, params object[] args) { return string.Format(CultureInfo.InvariantCulture, format, args); } } }
using System.Collections.Generic; using System.Globalization; using System.Text; namespace GoldenAnvil.Utility { public static class StringUtility { public static string FormatInvariant(this string format, params object[] args) { return string.Format(CultureInfo.InvariantCulture, format, args); } public static string Join(this IEnumerable<string> parts, string joinText) { var builder = new StringBuilder(); foreach (var part in parts) { if (builder.Length != 0) builder.Append(joinText); builder.Append(part); } return builder.ToString(); } } }
Enable UpnEndpointIdentity tests on UWP
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ServiceModel; using Infrastructure.Common; using Xunit; public static class UpnEndpointIdentityTest { #if FULLXUNIT_NOTSUPPORTED [Theory] #endif [WcfTheory] [InlineData("")] [InlineData("test@wcf.example.com")] [Issue(1454, Framework = FrameworkID.NetNative)] public static void Ctor_UpnName(string upn) { UpnEndpointIdentity upnEndpointEntity = new UpnEndpointIdentity(upn); } #if FULLXUNIT_NOTSUPPORTED [Fact] #endif [WcfFact] public static void Ctor_NullUpn() { string upnName = null; Assert.Throws<ArgumentNullException>("upnName", () => { UpnEndpointIdentity upnEndpointEntity = new UpnEndpointIdentity(upnName); }); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ServiceModel; using Infrastructure.Common; using Xunit; public static class UpnEndpointIdentityTest { #if FULLXUNIT_NOTSUPPORTED [Theory] #endif [WcfTheory] [InlineData("")] [InlineData("test@wcf.example.com")] public static void Ctor_UpnName(string upn) { UpnEndpointIdentity upnEndpointEntity = new UpnEndpointIdentity(upn); } #if FULLXUNIT_NOTSUPPORTED [Fact] #endif [WcfFact] public static void Ctor_NullUpn() { string upnName = null; Assert.Throws<ArgumentNullException>("upnName", () => { UpnEndpointIdentity upnEndpointEntity = new UpnEndpointIdentity(upnName); }); } }
Add note about action type
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Input.Bindings { /// <summary> /// A binding of a <see cref="Bindings.KeyCombination"/> to an action. /// </summary> public interface IKeyBinding { /// <summary> /// The combination of keys which will trigger this binding. /// </summary> KeyCombination KeyCombination { get; set; } /// <summary> /// The resultant action which is triggered by this binding. /// </summary> object Action { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Input.Bindings { /// <summary> /// A binding of a <see cref="Bindings.KeyCombination"/> to an action. /// </summary> public interface IKeyBinding { /// <summary> /// The combination of keys which will trigger this binding. /// </summary> KeyCombination KeyCombination { get; set; } /// <summary> /// The resultant action which is triggered by this binding. /// Generally an enum type, but may also be an int representing an enum (converted via <see cref="KeyBindingExtensions.GetAction{T}"/> /// </summary> object Action { get; set; } } }
Fix issue with readonly RedirectUri
using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Provider; namespace Auth0.Owin { /// <summary> /// Context passed when the redirect_uri is generated during the token exchange. /// </summary> public class Auth0CustomizeTokenExchangeRedirectUriContext : BaseContext<Auth0AuthenticationOptions> { /// <summary> /// Creates a new context object. /// </summary> /// <param name="context">The OWIN request context</param> /// <param name="options">The Auth0 middleware options</param> /// <param name="properties">The authenticaiton properties of the challenge</param> /// <param name="redirectUri">The initial redirect URI</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#", Justification = "Represents header value")] public Auth0CustomizeTokenExchangeRedirectUriContext(IOwinContext context, Auth0AuthenticationOptions options, AuthenticationProperties properties, string redirectUri) : base(context, options) { RedirectUri = redirectUri; Properties = properties; } /// <summary> /// Gets the URI used for the redirect operation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Represents header value")] public string RedirectUri { get; private set; } /// <summary> /// Gets the authenticaiton properties of the challenge /// </summary> public AuthenticationProperties Properties { get; private set; } } }
using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Provider; namespace Auth0.Owin { /// <summary> /// Context passed when the redirect_uri is generated during the token exchange. /// </summary> public class Auth0CustomizeTokenExchangeRedirectUriContext : BaseContext<Auth0AuthenticationOptions> { /// <summary> /// Creates a new context object. /// </summary> /// <param name="context">The OWIN request context</param> /// <param name="options">The Auth0 middleware options</param> /// <param name="properties">The authenticaiton properties of the challenge</param> /// <param name="redirectUri">The initial redirect URI</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#", Justification = "Represents header value")] public Auth0CustomizeTokenExchangeRedirectUriContext(IOwinContext context, Auth0AuthenticationOptions options, AuthenticationProperties properties, string redirectUri) : base(context, options) { RedirectUri = redirectUri; Properties = properties; } /// <summary> /// Gets the URI used for the redirect operation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Represents header value")] public string RedirectUri { get; set; } /// <summary> /// Gets the authenticaiton properties of the challenge /// </summary> public AuthenticationProperties Properties { get; private set; } } }
Add unit tests for PEHeaderBuilder factory methods
// 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 Xunit; namespace System.Reflection.PortableExecutable.Tests { public class PEHeaderBuilderTests { [Fact] public void Ctor_Errors() { Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 512, fileAlignment: 1024)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 513)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 513)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 64*1024*2)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: int.MaxValue)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: int.MinValue)); } } }
// 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 Xunit; namespace System.Reflection.PortableExecutable.Tests { public class PEHeaderBuilderTests { [Fact] public void Ctor_Errors() { Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 512, fileAlignment: 1024)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 513)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 513)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 64*1024*2)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: int.MaxValue)); Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: int.MinValue)); } [Fact] public void ValidateFactoryMethods() { var peHeaderExe = PEHeaderBuilder.CreateExecutableHeader(); Assert.NotNull(peHeaderExe); Assert.True((peHeaderExe.ImageCharacteristics & Characteristics.ExecutableImage) != 0); var peHeaderLib = PEHeaderBuilder.CreateLibraryHeader(); Assert.NotNull(peHeaderLib); Assert.True((peHeaderLib.ImageCharacteristics & Characteristics.ExecutableImage) != 0); Assert.True((peHeaderLib.ImageCharacteristics & Characteristics.Dll) != 0); } } }
Make components of IRequestContext independently injectable.
using Dolstagis.Web.Auth; using Dolstagis.Web.Lifecycle; using Dolstagis.Web.Lifecycle.ResultProcessors; using Dolstagis.Web.Sessions; using Dolstagis.Web.Static; using Dolstagis.Web.Views; namespace Dolstagis.Web { internal class CoreServices : Feature { public CoreServices() { Container.Setup.Application(c => { c.Use<IExceptionHandler, ExceptionHandler>(Scope.Request); c.Use<ISessionStore, InMemorySessionStore>(Scope.Application); c.Use<IAuthenticator, SessionAuthenticator>(Scope.Application); c.Use<ILoginHandler, LoginHandler>(Scope.Request); c.Add<IResultProcessor, StaticResultProcessor>(Scope.Transient); c.Add<IResultProcessor, ViewResultProcessor>(Scope.Transient); c.Add<IResultProcessor>(JsonResultProcessor.Instance); c.Add<IResultProcessor>(ContentResultProcessor.Instance); c.Add<IResultProcessor>(HeadResultProcessor.Instance); c.Use<ViewRegistry, ViewRegistry>(Scope.Request); }); } } }
using Dolstagis.Web.Auth; using Dolstagis.Web.Http; using Dolstagis.Web.Lifecycle; using Dolstagis.Web.Lifecycle.ResultProcessors; using Dolstagis.Web.Sessions; using Dolstagis.Web.Static; using Dolstagis.Web.Views; namespace Dolstagis.Web { internal class CoreServices : Feature { public CoreServices() { Container.Setup.Application(c => { c.Use<IExceptionHandler, ExceptionHandler>(Scope.Request); c.Use<ISessionStore, InMemorySessionStore>(Scope.Application); c.Use<IAuthenticator, SessionAuthenticator>(Scope.Application); c.Use<ILoginHandler, LoginHandler>(Scope.Request); c.Add<IResultProcessor, StaticResultProcessor>(Scope.Transient); c.Add<IResultProcessor, ViewResultProcessor>(Scope.Transient); c.Add<IResultProcessor>(JsonResultProcessor.Instance); c.Add<IResultProcessor>(ContentResultProcessor.Instance); c.Add<IResultProcessor>(HeadResultProcessor.Instance); c.Use<ViewRegistry, ViewRegistry>(Scope.Request); c.Use<IRequest>(ctx => ctx.GetService<IRequestContext>().Request, Scope.Request); c.Use<IResponse>(ctx => ctx.GetService<IRequestContext>().Response, Scope.Request); c.Use<IUser>(ctx => ctx.GetService<IRequestContext>().User, Scope.Request); c.Use<ISession>(ctx => ctx.GetService<IRequestContext>().Session, Scope.Request); }) .Setup.Request(c => { }); } } }
Fix test broken by e771e78
using System.Linq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Web.UI.JavaScript; namespace Umbraco.Tests.Web.AngularIntegration { [TestFixture] public class JsInitializationTests { [Test] public void Get_Default_Init() { var init = JsInitialization.GetDefaultInitialization(); Assert.IsTrue(init.Any()); } [Test] public void Parse_Main() { var result = JsInitialization.WriteScript("[World]", "Hello", "Blah"); Assert.AreEqual(@"LazyLoad.js([World], function () { //we need to set the legacy UmbClientMgr path UmbClientMgr.setUmbracoPath('Hello'); jQuery(document).ready(function () { angular.bootstrap(document, ['Blah']); }); });".StripWhitespace(), result.StripWhitespace()); } } }
using System.Linq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Web.UI.JavaScript; namespace Umbraco.Tests.Web.AngularIntegration { [TestFixture] public class JsInitializationTests { [Test] public void Get_Default_Init() { var init = JsInitialization.GetDefaultInitialization(); Assert.IsTrue(init.Any()); } [Test] public void Parse_Main() { var result = JsInitialization.WriteScript("[World]", "Hello", "Blah"); Assert.AreEqual(@"LazyLoad.js([World], function () { //we need to set the legacy UmbClientMgr path if ((typeof UmbClientMgr) !== ""undefined"") { UmbClientMgr.setUmbracoPath('Hello'); } jQuery(document).ready(function () { angular.bootstrap(document, ['Blah']); }); });".StripWhitespace(), result.StripWhitespace()); } } }
Allow mixed path references and url transforms
using System.Web; using System.Web.Optimization; using wwwplatform.Models; using wwwplatform.Models.Support; namespace wwwplatform { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { var settings = Settings.Create(new HttpContextWrapper(HttpContext.Current)); string skin = settings.SkinDefinitionFile ?? "~/App_Data/Skins/Default/skin.json"; SkinDefinition skindef = SkinDefinition.Load(HttpContext.Current.Server.MapPath(skin)); HttpContext.Current.Application["Layout"] = skindef.layout; foreach (var script in skindef.scripts.Keys) { bundles.Add(new ScriptBundle(script).Include(skindef.scripts[script].ToArray())); } foreach (var css in skindef.css.Keys) { bundles.Add(new StyleBundle(css).Include(skindef.css[css].ToArray())); } } } }
using System.Web; using System.Web.Optimization; using wwwplatform.Models; using wwwplatform.Models.Support; namespace wwwplatform { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { var settings = Settings.Create(new HttpContextWrapper(HttpContext.Current)); string skin = settings.SkinDefinitionFile ?? "~/App_Data/Skins/Default/skin.json"; SkinDefinition skindef = SkinDefinition.Load(HttpContext.Current.Server.MapPath(skin)); HttpContext.Current.Application["Layout"] = skindef.layout; foreach (var script in skindef.scripts.Keys) { bundles.Add(new ScriptBundle(script).Include(skindef.scripts[script].ToArray())); } foreach (var css in skindef.css.Keys) { StyleBundle bundle = new StyleBundle(css); foreach(string file in skindef.css[css]) { bundle.Include(file, new CssRewriteUrlTransform()); } bundles.Add(bundle); } } } }
Add test coverage of animation restarting
// 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.Framework.Graphics.Textures; using osu.Game.Graphics; using osuTK; namespace osu.Game.Tests.Visual.Gameplay { [TestFixture] public class TestSceneParticleExplosion : OsuTestScene { [BackgroundDependencyLoader] private void load(TextureStore textures) { AddRepeatStep(@"display", () => { Child = new ParticleExplosion(textures.Get("Cursor/cursortrail"), 150, 1200) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(400) }; }, 10); } } }
// 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.Framework.Graphics.Textures; using osu.Game.Graphics; using osuTK; namespace osu.Game.Tests.Visual.Gameplay { [TestFixture] public class TestSceneParticleExplosion : OsuTestScene { private ParticleExplosion explosion; [BackgroundDependencyLoader] private void load(TextureStore textures) { AddStep("create initial", () => { Child = explosion = new ParticleExplosion(textures.Get("Cursor/cursortrail"), 150, 1200) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(400) }; }); AddWaitStep("wait for playback", 5); AddRepeatStep(@"restart animation", () => { explosion.Restart(); }, 10); } } }
Fix for missing correlationId preventing startup of EAS
using System; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Dapper; using SFA.DAS.EAS.Domain.Configuration; using SFA.DAS.EAS.Domain.Data.Repositories; using SFA.DAS.EAS.Domain.Models.UserProfile; using SFA.DAS.Sql.Client; using SFA.DAS.NLog.Logger; namespace SFA.DAS.EAS.Infrastructure.Data { public class UserRepository : BaseRepository, IUserRepository { private readonly Lazy<EmployerAccountsDbContext> _db; public UserRepository(EmployerApprenticeshipsServiceConfiguration configuration, ILog logger, Lazy<EmployerAccountsDbContext> db) : base(configuration.DatabaseConnectionString, logger) { _db = db; } public Task Upsert(User user) { return WithConnection(c => { var parameters = new DynamicParameters(); parameters.Add("@email", user.Email, DbType.String); parameters.Add("@userRef", new Guid(user.UserRef), DbType.Guid); parameters.Add("@firstName", user.FirstName, DbType.String); parameters.Add("@lastName", user.LastName, DbType.String); return c.ExecuteAsync( sql: "[employer_account].[UpsertUser] @userRef, @email, @firstName, @lastName", param: parameters, commandType: CommandType.Text); }); } } }
using System; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Dapper; using SFA.DAS.EAS.Domain.Configuration; using SFA.DAS.EAS.Domain.Data.Repositories; using SFA.DAS.EAS.Domain.Models.UserProfile; using SFA.DAS.Sql.Client; using SFA.DAS.NLog.Logger; namespace SFA.DAS.EAS.Infrastructure.Data { public class UserRepository : BaseRepository, IUserRepository { private readonly Lazy<EmployerAccountsDbContext> _db; public UserRepository(EmployerApprenticeshipsServiceConfiguration configuration, ILog logger, Lazy<EmployerAccountsDbContext> db) : base(configuration.DatabaseConnectionString, logger) { _db = db; } public Task Upsert(User user) { return WithConnection(c => { var parameters = new DynamicParameters(); parameters.Add("@email", user.Email, DbType.String); parameters.Add("@userRef", new Guid(user.UserRef), DbType.Guid); parameters.Add("@firstName", user.FirstName, DbType.String); parameters.Add("@lastName", user.LastName, DbType.String); parameters.Add("@correlationId", null, DbType.String); return c.ExecuteAsync( sql: "[employer_account].[UpsertUser] @userRef, @email, @firstName, @lastName, @correlationId", param: parameters, commandType: CommandType.Text); }); } } }
Add received timestamp and basic xmldoc for header class
// 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; using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; namespace osu.Game.Online.Spectator { [Serializable] public class FrameHeader { public int Combo { get; set; } public int MaxCombo { get; set; } public Dictionary<HitResult, int> Statistics { get; set; } /// <summary> /// Construct header summary information from a point-in-time reference to a score which is actively being played. /// </summary> /// <param name="score">The score for reference.</param> public FrameHeader(ScoreInfo score) { Combo = score.Combo; MaxCombo = score.MaxCombo; // copy for safety Statistics = new Dictionary<HitResult, int>(score.Statistics); } [JsonConstructor] public FrameHeader(int combo, int maxCombo, Dictionary<HitResult, int> statistics) { Combo = combo; MaxCombo = maxCombo; Statistics = statistics; } } }
// 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; using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; namespace osu.Game.Online.Spectator { [Serializable] public class FrameHeader { /// <summary> /// The current combo of the score. /// </summary> public int Combo { get; set; } /// <summary> /// The maximum combo achieved up to the current point in time. /// </summary> public int MaxCombo { get; set; } /// <summary> /// Cumulative hit statistics. /// </summary> public Dictionary<HitResult, int> Statistics { get; set; } /// <summary> /// The time at which this frame was received by the server. /// </summary> public DateTimeOffset ReceivedTime { get; set; } /// <summary> /// Construct header summary information from a point-in-time reference to a score which is actively being played. /// </summary> /// <param name="score">The score for reference.</param> public FrameHeader(ScoreInfo score) { Combo = score.Combo; MaxCombo = score.MaxCombo; // copy for safety Statistics = new Dictionary<HitResult, int>(score.Statistics); } [JsonConstructor] public FrameHeader(int combo, int maxCombo, Dictionary<HitResult, int> statistics, DateTimeOffset receivedTime) { Combo = combo; MaxCombo = maxCombo; Statistics = statistics; ReceivedTime = receivedTime; } } }
Use version parser instead of string.split
using System; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.System; namespace EarTrumpet.Services { public static class WhatsNewDisplayService { internal static void ShowIfAppropriate() { if (App.HasIdentity()) { var currentVersion = PackageVersionToReadableString(Package.Current.Id.Version); var hasShownFirstRun = false; var lastVersion = Windows.Storage.ApplicationData.Current.LocalSettings.Values[nameof(currentVersion)]; if ((lastVersion != null && currentVersion == (string)lastVersion)) { return; } Windows.Storage.ApplicationData.Current.LocalSettings.Values[nameof(currentVersion)] = currentVersion; var versionArray = lastVersion?.ToString().Split('.'); if (versionArray?.Length > 2 && (versionArray[0] == Package.Current.Id.Version.Major.ToString() && versionArray[1] == Package.Current.Id.Version.Minor.ToString())) { return; } if (!Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey(nameof(hasShownFirstRun))) { return; } try { System.Diagnostics.Process.Start("eartrumpet:"); } catch { } } } private static string PackageVersionToReadableString(PackageVersion packageVersion) { return $"{packageVersion.Major}.{packageVersion.Minor}.{packageVersion.Build}.{packageVersion.Revision}"; } } }
using System; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.System; namespace EarTrumpet.Services { public static class WhatsNewDisplayService { internal static void ShowIfAppropriate() { if (App.HasIdentity()) { var currentVersion = PackageVersionToReadableString(Package.Current.Id.Version); var hasShownFirstRun = false; var lastVersion = Windows.Storage.ApplicationData.Current.LocalSettings.Values[nameof(currentVersion)]; if ((lastVersion != null && currentVersion == (string)lastVersion)) { return; } Windows.Storage.ApplicationData.Current.LocalSettings.Values[nameof(currentVersion)] = currentVersion; Version.TryParse(lastVersion?.ToString(), out var oldVersion); if (oldVersion?.Major == Package.Current.Id.Version.Major && oldVersion?.Minor == Package.Current.Id.Version.Minor) { return; } if (!Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey(nameof(hasShownFirstRun))) { return; } try { System.Diagnostics.Process.Start("eartrumpet:"); } catch { } } } private static string PackageVersionToReadableString(PackageVersion packageVersion) { return $"{packageVersion.Major}.{packageVersion.Minor}.{packageVersion.Build}.{packageVersion.Revision}"; } } }
Remove CIV.Ccs reference from CIV.Hml
using System; using System.Collections.Generic; using System.Linq; using CIV.Ccs; using CIV.Common; namespace CIV.Hml { class BoxFormula : HmlLabelFormula { protected override string BuildRepr() => $"[{String.Join(",", Label)}]{Inner}"; protected override bool CheckStrategy(IEnumerable<IProcess> processes) => processes.All(Inner.Check); protected override IEnumerable<Transition> TransitionStrategy(IProcess process) { return process.GetTransitions(); } public override bool Check(IProcess process) { var grouped = MatchedTransitions(process).GroupBy(x => x.Label); return grouped.All(procs => procs.All(p => Inner.Check(p.Process))); } } }
using System; using System.Collections.Generic; using System.Linq; using CIV.Common; namespace CIV.Hml { class BoxFormula : HmlLabelFormula { protected override string BuildRepr() => $"[{String.Join(",", Label)}]{Inner}"; protected override bool CheckStrategy(IEnumerable<IProcess> processes) => processes.All(Inner.Check); protected override IEnumerable<Transition> TransitionStrategy(IProcess process) { return process.GetTransitions(); } public override bool Check(IProcess process) { var grouped = MatchedTransitions(process).GroupBy(x => x.Label); return grouped.All(procs => procs.All(p => Inner.Check(p.Process))); } } }
Use a fix that's closer to the Mongo 2.0 driver's way of doing things
using System; namespace RightpointLabs.Pourcast.Infrastructure.Persistence.Repositories { using System.Collections.Generic; using System.Linq; using RightpointLabs.Pourcast.Domain.Models; using RightpointLabs.Pourcast.Domain.Repositories; using RightpointLabs.Pourcast.Infrastructure.Persistence.Collections; public class UserRepository : EntityRepository<User>, IUserRepository { public UserRepository(UserCollectionDefinition userCollectionDefinition) : base(userCollectionDefinition) { } public User GetByUsername(string username) { // TODO: use a Regex so we can drop the ToList() and push the work to Mongo return Queryable.ToList().SingleOrDefault(x => string.Equals(x.Username, username, StringComparison.InvariantCultureIgnoreCase)); } public IEnumerable<User> GetUsersInRole(string id) { return Queryable.Where(x => x.RoleIds.Contains(id)); } } }
using System; namespace RightpointLabs.Pourcast.Infrastructure.Persistence.Repositories { using System.Collections.Generic; using System.Linq; using RightpointLabs.Pourcast.Domain.Models; using RightpointLabs.Pourcast.Domain.Repositories; using RightpointLabs.Pourcast.Infrastructure.Persistence.Collections; public class UserRepository : EntityRepository<User>, IUserRepository { public UserRepository(UserCollectionDefinition userCollectionDefinition) : base(userCollectionDefinition) { } public User GetByUsername(string username) { // TODO: Update to Mongo 2.0 so we can drop the .ToList() and push the work to Mongo return Queryable.ToList().SingleOrDefault(x => x.Username.Equals(username, StringComparison.InvariantCultureIgnoreCase)); } public IEnumerable<User> GetUsersInRole(string id) { return Queryable.Where(x => x.RoleIds.Contains(id)); } } }
Add pictures count of category
@model PagedList.IPagedList<AstroPhotoGallery.Models.Category> @using PagedList.Mvc; @using System.Linq; @{ ViewBag.Title = "List"; } <link href="~/Content/PagedList.css" rel="stylesheet" /> <div class="container"> <h2 class="text-center">Browse by categories</h2> <br/> @foreach (var category in Model) { <div class="col-sm-4"> <div class="thumbnail "> @if (category.Pictures.Any(p => p.CategoryId == category.Id)) { <img src="@Url.Content(category.Pictures.Where(p => p.CategoryId == category.Id).FirstOrDefault().ImagePath)" style="height:190px;width:350px"> } else { <img src="~/Content/images/default-gallery-image.jpg" style="height:190px;width:350px" /> } <div class="caption text-center "> <h4> @Html.ActionLink(string.Format($"{category.Name}"), "ListPictures", "Home", new { @categoryId = category.Id }, null) </h4> </div> </div> </div> } </div> Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount @Html.PagedListPager(Model, page => Url.Action("ListCategories", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
@model PagedList.IPagedList<AstroPhotoGallery.Models.Category> @using PagedList.Mvc; @using System.Linq; @{ ViewBag.Title = "List"; } <link href="~/Content/PagedList.css" rel="stylesheet" /> <div class="container"> <h2 class="text-center">Browse by categories</h2> <br/> @foreach (var category in Model) { <div class="col-sm-4"> <div class="thumbnail "> @if (category.Pictures.Any(p => p.CategoryId == category.Id)) { <img src="@Url.Content(category.Pictures.Where(p => p.CategoryId == category.Id).FirstOrDefault().ImagePath)" style="height:190px;width:350px"> } else { <img src="~/Content/images/default-gallery-image.jpg" style="height:190px;width:350px" /> } <div class="caption text-center "> <h4> @Html.ActionLink(string.Format($"{category.Name}({category.Pictures.Count})"), "ListPictures", "Home", new { @categoryId = category.Id }, null) </h4> </div> </div> </div> } </div> Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount @Html.PagedListPager(Model, page => Url.Action("ListCategories", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
Update test methods for DbContextFactory
using System; using Aliencube.EntityContextLibrary.Interfaces; using FluentAssertions; using NUnit.Framework; namespace Aliencube.EntityContextLibrary.Tests { [TestFixture] public class DbContextFactoryTest { private IDbContextFactory _factory; [SetUp] public void Init() { AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory()); this._factory = new DbContextFactory<ProductContext>(); } [TearDown] public void Cleanup() { if (this._factory != null) { this._factory.Dispose(); } } [Test] [TestCase(typeof(ProductContext))] public void GetContext_GivenDetails_ReturnContext(Type expectedType) { var context = this._factory.Context; context.Should().NotBeNull(); context.Should().BeOfType(expectedType); } } }
using System; using Aliencube.EntityContextLibrary.Interfaces; using FluentAssertions; using NUnit.Framework; namespace Aliencube.EntityContextLibrary.Tests { /// <summary> /// This represents the test entity for the <see cref="DbContextFactory{TContext}" /> class. /// </summary> [TestFixture] public class DbContextFactoryTest { private IDbContextFactory _factory; /// <summary> /// Initialises all resources for tests. /// </summary> [SetUp] public void Init() { AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory()); this._factory = new DbContextFactory<ProductContext>(); } /// <summary> /// Release all resources after tests. /// </summary> [TearDown] public void Cleanup() { if (this._factory != null) { this._factory.Dispose(); } } /// <summary> /// Tests whether the context factory returns DbContext with given type or not. /// </summary> /// <param name="expectedType"> /// The expected type. /// </param> [Test] [TestCase(typeof(ProductContext))] public void ContextFactory_Should_Return_Context_Of_Given_Type(Type expectedType) { var context = this._factory.Context; context.Should().NotBeNull(); context.Should().BeOfType(expectedType); } } }
Check we have a message as well when checking the flashmessage view model
@using SFA.DAS.EmployerApprenticeshipsService.Web @using SFA.DAS.EmployerApprenticeshipsService.Web.Models @model dynamic @{ var viewModel = Model as OrchestratorResponse; } @if (viewModel?.FlashMessage != null) { <div class="grid-row"> <div class="column-full"> <div class="@viewModel.FlashMessage.SeverityCssClass"> @if (!string.IsNullOrWhiteSpace(viewModel.FlashMessage.Headline)) { <h1 class="bold-large">@viewModel.FlashMessage.Headline</h1> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.Message)) { <p>@viewModel.FlashMessage.Message</p> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.SubMessage)) { <p>@viewModel.FlashMessage.SubMessage</p> } </div> </div> </div> }
@using SFA.DAS.EmployerApprenticeshipsService.Web @using SFA.DAS.EmployerApprenticeshipsService.Web.Models @model dynamic @{ var viewModel = Model as OrchestratorResponse; } @if (!string.IsNullOrEmpty(viewModel?.FlashMessage?.Message)) { <div class="grid-row"> <div class="column-full"> <div class="@viewModel.FlashMessage.SeverityCssClass"> @if (!string.IsNullOrWhiteSpace(viewModel.FlashMessage.Headline)) { <h1 class="bold-large">@viewModel.FlashMessage.Headline</h1> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.Message)) { <p>@viewModel.FlashMessage.Message</p> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.SubMessage)) { <p>@viewModel.FlashMessage.SubMessage</p> } </div> </div> </div> }
Simplify the Expression<Func<>> specimen building
namespace Ploeh.AutoFixture { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Kernel; public class LambdaExpressionGenerator : ISpecimenBuilder { public object Create(object request, ISpecimenContext context) { var requestType = request as Type; if (requestType == null) { return new NoSpecimen(); } if (requestType.BaseType != typeof(LambdaExpression)) { return new NoSpecimen(); } var delegateType = requestType.GetGenericArguments().Single(); var genericArguments = delegateType.GetGenericArguments().Select(Expression.Parameter).ToList(); if (delegateType.Name.StartsWith( "Action")) { return Expression.Lambda(Expression.Empty(), genericArguments); } var body = genericArguments.Last(); var parameters = new List<ParameterExpression>(); if (genericArguments.Count > 1) { parameters = genericArguments.Take(genericArguments.Count - 1).ToList(); } return Expression.Lambda(body, parameters); } } }
namespace Ploeh.AutoFixture { using System; using System.Linq; using System.Linq.Expressions; using Kernel; public class LambdaExpressionGenerator : ISpecimenBuilder { public object Create(object request, ISpecimenContext context) { var requestType = request as Type; if (requestType == null) { return new NoSpecimen(); } if (requestType.BaseType != typeof(LambdaExpression)) { return new NoSpecimen(); } var delegateType = requestType.GetGenericArguments().Single(); var genericArguments = delegateType.GetGenericArguments().Select(Expression.Parameter).ToList(); if (delegateType.Name.StartsWith("Action")) { return Expression.Lambda(Expression.Empty(), genericArguments); } var body = genericArguments.Last(); var parameters = genericArguments.Except(new[] { body }); return Expression.Lambda(body, parameters); } } }
Add image for a hovered state in image button
using System; using System.Drawing; using MonoHaven.Graphics; using MonoHaven.Utils; using OpenTK.Input; namespace MonoHaven.UI { public class ImageButton : Widget { private bool isPressed; public ImageButton(Widget parent) : base(parent) { IsFocusable = true; } public event EventHandler Clicked; public Drawable Image { get; set; } public Drawable PressedImage { get; set; } protected override void OnDraw(DrawingContext dc) { var tex = isPressed ? PressedImage : Image; if (tex != null) dc.Draw(tex, 0, 0); } protected override void OnMouseButtonDown(MouseButtonEventArgs e) { Host.GrabMouse(this); isPressed = true; } protected override void OnMouseButtonUp(MouseButtonEventArgs e) { Host.ReleaseMouse(); isPressed = false; // button released outside of borders? var p = PointToWidget(e.Position); if (Rectangle.FromLTRB(0, 0, Width, Height).Contains(p)) Clicked.Raise(this, EventArgs.Empty); } } }
using System; using System.Drawing; using MonoHaven.Graphics; using MonoHaven.Utils; using OpenTK.Input; namespace MonoHaven.UI { public class ImageButton : Widget { private bool isPressed; public ImageButton(Widget parent) : base(parent) { IsFocusable = true; } public event EventHandler Clicked; public Drawable Image { get; set; } public Drawable PressedImage { get; set; } public Drawable HoveredImage { get; set; } protected override void OnDraw(DrawingContext dc) { Drawable image = null; if (isPressed && PressedImage != null) image = PressedImage; else if (IsHovered && HoveredImage != null) image = HoveredImage; else image = Image; if (image != null) dc.Draw(image, 0, 0); } protected override void OnMouseButtonDown(MouseButtonEventArgs e) { Host.GrabMouse(this); isPressed = true; } protected override void OnMouseButtonUp(MouseButtonEventArgs e) { Host.ReleaseMouse(); isPressed = false; // button released outside of borders? var p = PointToWidget(e.Position); if (Rectangle.FromLTRB(0, 0, Width, Height).Contains(p)) Clicked.Raise(this, EventArgs.Empty); } } }
Change source code as Nintendo updates SplatNet (bug fix).
using System.Threading.Tasks; using Mntone.NintendoNetworkHelper; using Mntone.SplatoonClient.Internal; namespace Mntone.SplatoonClient { public static class SplatoonContextFactory { public static async Task<SplatoonContext> GetContextAsync(string username, string password) { var authorizer = new NintendoNetworkAuthorizer(); var requestToken = await authorizer.GetRequestTokenAsync(SplatoonConstantValues.AUTH_FORWARD_URI).ConfigureAwait(false); var accessToken = await authorizer.Authorize(requestToken, new AuthenticationToken(username, password), SplatoonHelper.GetSessionValue).ConfigureAwait(false); var requestToken2 = await authorizer.GetRequestTokenAsync(SplatoonConstantValues.AUTH_FORWARD_URI).ConfigureAwait(false); var accessToken2 = await authorizer.Authorize(requestToken2, new AuthenticationToken(username, password), SplatoonHelper.GetSessionValue).ConfigureAwait(false); authorizer.Dispose(); return new SplatoonContext(accessToken2); } } }
using System.Threading.Tasks; using Mntone.NintendoNetworkHelper; using Mntone.SplatoonClient.Internal; namespace Mntone.SplatoonClient { public static class SplatoonContextFactory { public static async Task<SplatoonContext> GetContextAsync(string username, string password) { var authorizer = new NintendoNetworkAuthorizer(); var requestToken = await authorizer.GetRequestTokenAsync(SplatoonConstantValues.AUTH_FORWARD_URI).ConfigureAwait(false); var accessToken = await authorizer.Authorize(requestToken, new AuthenticationToken(username, password), SplatoonHelper.GetSessionValue).ConfigureAwait(false); authorizer.Dispose(); return new SplatoonContext(accessToken); } } }
Check that it can work with nullables too.
using System; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH1119 { [TestFixture] public class Fixture : BugTestCase { public override string BugNumber { get { return "NH1119"; } } [Test] public void SelectMinFromEmptyTable() { using (ISession s = OpenSession()) { DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>(); Assert.AreEqual(default(DateTime), dt); } } } }
using System; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH1119 { [TestFixture] public class Fixture : BugTestCase { public override string BugNumber { get { return "NH1119"; } } [Test] public void SelectMinFromEmptyTable() { using (ISession s = OpenSession()) { DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>(); Assert.AreEqual(default(DateTime), dt); DateTime? dtn = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime?>(); Assert.IsFalse(dtn.HasValue); } } } }
Remove [AllowAnonymous] since added by default
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.RazorPages; using BlogTemplate.Models; using Microsoft.AspNetCore.Mvc; using System.Xml; using System.Xml.Linq; using Microsoft.AspNetCore.Authorization; namespace BlogTemplate.Pages { public class PostModel : PageModel { private Blog _blog; private BlogDataStore _dataStore; public PostModel(Blog blog, BlogDataStore dataStore) { _blog = blog; _dataStore = dataStore; } [BindProperty] public Comment Comment { get; set; } public Post Post { get; set; } [AllowAnonymous] public void OnGet() { InitializePost(); } private void InitializePost() { string slug = RouteData.Values["slug"].ToString(); Post = _dataStore.GetPost(slug); if (Post == null) { RedirectToPage("/Index"); } } [AllowAnonymous] public IActionResult OnPostPublishComment() { string slug = RouteData.Values["slug"].ToString(); Post = _dataStore.GetPost(slug); if (Post == null) { RedirectToPage("/Index"); } else if (ModelState.IsValid) { Comment.IsPublic = true; Comment.UniqueId = Guid.NewGuid(); Post.Comments.Add(Comment); _dataStore.SavePost(Post); } return Page(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.RazorPages; using BlogTemplate.Models; using Microsoft.AspNetCore.Mvc; using System.Xml; using System.Xml.Linq; using Microsoft.AspNetCore.Authorization; namespace BlogTemplate.Pages { public class PostModel : PageModel { private Blog _blog; private BlogDataStore _dataStore; public PostModel(Blog blog, BlogDataStore dataStore) { _blog = blog; _dataStore = dataStore; } [BindProperty] public Comment Comment { get; set; } public Post Post { get; set; } public void OnGet() { InitializePost(); } private void InitializePost() { string slug = RouteData.Values["slug"].ToString(); Post = _dataStore.GetPost(slug); if (Post == null) { RedirectToPage("/Index"); } } public IActionResult OnPostPublishComment() { string slug = RouteData.Values["slug"].ToString(); Post = _dataStore.GetPost(slug); if (Post == null) { RedirectToPage("/Index"); } else if (ModelState.IsValid) { Comment.IsPublic = true; Comment.UniqueId = Guid.NewGuid(); Post.Comments.Add(Comment); _dataStore.SavePost(Post); } return Page(); } } }
Fix all violations of SA1127
namespace Tvl.VisualStudio.InheritanceMargin { using System.ComponentModel.Composition; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using IOutputWindowService = Tvl.VisualStudio.OutputWindow.Interfaces.IOutputWindowService; using TaskScheduler = System.Threading.Tasks.TaskScheduler; [Name("CSharp Inheritance Tagger Provider")] [TagType(typeof(IInheritanceTag))] [Export(typeof(ITaggerProvider))] [ContentType("CSharp")] internal class CSharpInheritanceTaggerProvider : ITaggerProvider { public CSharpInheritanceTaggerProvider() { TaskScheduler = TaskScheduler.Default; } ////[Import(PredefinedTaskSchedulers.BackgroundIntelliSense)] public TaskScheduler TaskScheduler { get; private set; } [Import] public ITextDocumentFactoryService TextDocumentFactoryService { get; private set; } [Import] public IOutputWindowService OutputWindowService { get; private set; } [Import] public SVsServiceProvider GlobalServiceProvider { get; private set; } public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag { if (buffer != null) return CSharpInheritanceTagger.CreateInstance(this, buffer) as ITagger<T>; return null; } } }
namespace Tvl.VisualStudio.InheritanceMargin { using System.ComponentModel.Composition; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using IOutputWindowService = Tvl.VisualStudio.OutputWindow.Interfaces.IOutputWindowService; using TaskScheduler = System.Threading.Tasks.TaskScheduler; [Name("CSharp Inheritance Tagger Provider")] [TagType(typeof(IInheritanceTag))] [Export(typeof(ITaggerProvider))] [ContentType("CSharp")] internal class CSharpInheritanceTaggerProvider : ITaggerProvider { public CSharpInheritanceTaggerProvider() { TaskScheduler = TaskScheduler.Default; } ////[Import(PredefinedTaskSchedulers.BackgroundIntelliSense)] public TaskScheduler TaskScheduler { get; private set; } [Import] public ITextDocumentFactoryService TextDocumentFactoryService { get; private set; } [Import] public IOutputWindowService OutputWindowService { get; private set; } [Import] public SVsServiceProvider GlobalServiceProvider { get; private set; } public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag { if (buffer != null) return CSharpInheritanceTagger.CreateInstance(this, buffer) as ITagger<T>; return null; } } }
Improve the test in regards to \r\n
using System.Linq; using System.Text; using NUnit.Framework; namespace ValveKeyValue.Test { class CommentOnEndOfTheLine { [Test] public void CanHandleCommentOnEndOfTheLine() { var text = new StringBuilder(); text.AppendLine(@"""test_kv"""); text.AppendLine("{"); text.AppendLine("//"); text.AppendLine(@"""test"" ""hello"""); text.AppendLine("}"); var data = KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize(text.ToString()); Assert.Multiple(() => { Assert.That(data.Children.Count(), Is.EqualTo(1)); Assert.That((string)data["test"], Is.EqualTo("hello")); }); } } }
using System.Linq; using System.Text; using NUnit.Framework; namespace ValveKeyValue.Test { class CommentOnEndOfTheLine { [Test] public void CanHandleCommentOnEndOfTheLine() { var text = new StringBuilder(); text.Append(@"""test_kv""" + "\n"); text.Append("{" + "\n"); text.Append("//" + "\n"); text.Append(@"""test"" ""hello""" + "\n"); text.Append("}" + "\n"); var data = KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize(text.ToString()); Assert.Multiple(() => { Assert.That(data.Children.Count(), Is.EqualTo(1)); Assert.That((string)data["test"], Is.EqualTo("hello")); }); } } }
Revert "Fix up for 16.11"
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.PickMembers; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PickMembers; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Internal.PickMembers { [Shared] [ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host)] internal class OmniSharpPickMembersService : IPickMembersService { private readonly IOmniSharpPickMembersService _omniSharpPickMembersService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OmniSharpPickMembersService(IOmniSharpPickMembersService omniSharpPickMembersService) { _omniSharpPickMembersService = omniSharpPickMembersService; } public PickMembersResult PickMembers(string title, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options = default) { var result = _omniSharpPickMembersService.PickMembers(title, members, options.SelectAsArray(o => new OmniSharpPickMembersOption(o)), selectAll: true); return new(result.Members, result.Options.SelectAsArray(o => o.PickMembersOptionInternal)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.PickMembers; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PickMembers; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Internal.PickMembers { [Shared] [ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host)] internal class OmniSharpPickMembersService : IPickMembersService { private readonly IOmniSharpPickMembersService _omniSharpPickMembersService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OmniSharpPickMembersService(IOmniSharpPickMembersService omniSharpPickMembersService) { _omniSharpPickMembersService = omniSharpPickMembersService; } public PickMembersResult PickMembers(string title, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options = default, bool selectAll = true) { var result = _omniSharpPickMembersService.PickMembers(title, members, options.SelectAsArray(o => new OmniSharpPickMembersOption(o)), selectAll); return new(result.Members, result.Options.SelectAsArray(o => o.PickMembersOptionInternal), result.SelectedAll); } } }
Fix order of route registration.
using System.Net.Http.Formatting; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using WebApiContrib.Formatting.Jsonp; using WebContribContrib.Formatting.Jsonp.SampleWebHost.App_Start; namespace WebContribContrib.Formatting.Jsonp.SampleWebHost { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); BundleConfig.RegisterBundles(BundleTable.Bundles); RouteConfig.RegisterRoutes(RouteTable.Routes); GlobalConfiguration.Configure(config => { config.MapHttpAttributeRoutes(); FormatterConfig.RegisterFormatters(config.Formatters); }); } } }
using System.Net.Http.Formatting; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using WebApiContrib.Formatting.Jsonp; using WebContribContrib.Formatting.Jsonp.SampleWebHost.App_Start; namespace WebContribContrib.Formatting.Jsonp.SampleWebHost { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(config => { config.MapHttpAttributeRoutes(); FormatterConfig.RegisterFormatters(config.Formatters); }); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); BundleConfig.RegisterBundles(BundleTable.Bundles); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
Tweak in Console VS Project Template.
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ConsoleAbstraction.cs" company="Naos Project"> // Copyright (c) Naos Project 2019. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace [PROJECT_NAME] { using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using CLAP; using Naos.Bootstrapper; /// <inheritdoc /> public class ConsoleAbstraction : ConsoleAbstractionBase { /// <summary> /// Does some work. /// </summary> /// <param name="debug">Optional value indicating whether to launch the debugger from inside the application (default is false).</param> /// <param name="requiredParameter">A required parameter to the operation.</param> [Verb(Aliases = "do", IsDefault = false, Description = "Does some work.")] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = ObcSuppressBecause.CA1811_AvoidUncalledPrivateCode_MethodIsWiredIntoClapAsVerb)] public static void DoSomeWork( [Aliases("")] [Description("Launches the debugger.")] [DefaultValue(false)] bool debug, [Aliases("")] [Required] [Description("A required parameter to the operation.")] string requiredParameter) { if (debug) { Debugger.Launch(); } System.Console.WriteLine(requiredParameter); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ConsoleAbstraction.cs" company="Naos Project"> // Copyright (c) Naos Project 2019. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace [PROJECT_NAME] { using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using CLAP; using Naos.Bootstrapper; using Naos.Build.Analyzers; /// <inheritdoc /> public class ConsoleAbstraction : ConsoleAbstractionBase { /// <summary> /// Does some work. /// </summary> /// <param name="debug">Optional value indicating whether to launch the debugger from inside the application (default is false).</param> /// <param name="requiredParameter">A required parameter to the operation.</param> [Verb(Aliases = "do", IsDefault = false, Description = "Does some work.")] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = NaosSuppressBecause.CA1811_AvoidUncalledPrivateCode_MethodIsWiredIntoClapAsVerb)] public static void DoSomeWork( [Aliases("")] [Description("Launches the debugger.")] [DefaultValue(false)] bool debug, [Aliases("")] [Required] [Description("A required parameter to the operation.")] string requiredParameter) { if (debug) { Debugger.Launch(); } System.Console.WriteLine(requiredParameter); } } }
Sort usings in gotodef exports.
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.ComponentModel.Composition; using Microsoft.VisualStudio.LiveShare.LanguageServices; using Microsoft.CodeAnalysis.Editor; using Microsoft.VisualStudio.LanguageServer.Protocol; using System; namespace Microsoft.VisualStudio.LanguageServices.LiveShare { [ExportLspRequestHandler(LiveShareConstants.RoslynContractName, Methods.TextDocumentDefinitionName)] [Obsolete("Used for backwards compatibility with old liveshare clients.")] internal class RoslynGoToDefinitionHandler : AbstractGoToDefinitionWithFarHandler { [ImportingConstructor] public RoslynGoToDefinitionHandler([Import(AllowDefault = true)] IMetadataAsSourceFileService metadataAsSourceService) : base(metadataAsSourceService) { } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentDefinitionName)] internal class TypeScriptGoToDefinitionHandler : AbstractGoToDefinitionWithFarHandler { [ImportingConstructor] public TypeScriptGoToDefinitionHandler() : base(null) { } } }
// Copyright (c) Microsoft. 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LiveShare.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.LiveShare { [ExportLspRequestHandler(LiveShareConstants.RoslynContractName, Methods.TextDocumentDefinitionName)] [Obsolete("Used for backwards compatibility with old liveshare clients.")] internal class RoslynGoToDefinitionHandler : AbstractGoToDefinitionWithFarHandler { [ImportingConstructor] public RoslynGoToDefinitionHandler([Import(AllowDefault = true)] IMetadataAsSourceFileService metadataAsSourceService) : base(metadataAsSourceService) { } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentDefinitionName)] internal class TypeScriptGoToDefinitionHandler : AbstractGoToDefinitionWithFarHandler { [ImportingConstructor] public TypeScriptGoToDefinitionHandler() : base(null) { } } }
Include a codebase for System.IO.FileSystem
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Shell; using Roslyn.VisualStudio.Setup; [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.Scripting.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.Scripting.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.Scripting.VisualBasic.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.InteractiveEditorFeatures.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.InteractiveEditorFeatures.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.VisualBasic.InteractiveEditorFeatures.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.InteractiveFeatures.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.InteractiveServices.dll")] [assembly: ProvideRoslynBindingRedirection("InteractiveHost.exe")]
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Shell; using Roslyn.VisualStudio.Setup; [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.Scripting.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.Scripting.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.Scripting.VisualBasic.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.InteractiveEditorFeatures.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.InteractiveEditorFeatures.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.VisualBasic.InteractiveEditorFeatures.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.InteractiveFeatures.dll")] [assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.InteractiveServices.dll")] [assembly: ProvideRoslynBindingRedirection("InteractiveHost.exe")] [assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.IO.FileSystem.dll")]
Check if using SelectedItem pattern first
namespace Winium.Desktop.Driver.CommandExecutors { #region using using System.Windows.Automation; using Winium.Cruciatus.Exceptions; using Winium.Cruciatus.Extensions; using Winium.StoreApps.Common; #endregion internal class IsElementSelectedExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var element = this.Automator.Elements.GetRegisteredElement(registeredKey); var isSelected = false; try { var isTogglePattrenAvailable = element.GetAutomationPropertyValue<bool>(AutomationElement.IsTogglePatternAvailableProperty); if (isTogglePattrenAvailable) { var toggleStateProperty = TogglePattern.ToggleStateProperty; var toggleState = element.GetAutomationPropertyValue<ToggleState>(toggleStateProperty); isSelected = toggleState == ToggleState.On; } } catch (CruciatusException) { var selectionItemProperty = SelectionItemPattern.IsSelectedProperty; isSelected = element.GetAutomationPropertyValue<bool>(selectionItemProperty); } return this.JsonResponse(ResponseStatus.Success, isSelected); } #endregion } }
namespace Winium.Desktop.Driver.CommandExecutors { #region using using System.Windows.Automation; using Winium.Cruciatus.Exceptions; using Winium.Cruciatus.Extensions; using Winium.StoreApps.Common; #endregion internal class IsElementSelectedExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var element = this.Automator.Elements.GetRegisteredElement(registeredKey); var isSelected = false; try { var isSelectedItemPattrenAvailable = element.GetAutomationPropertyValue<bool>(AutomationElement.IsSelectionItemPatternAvailableProperty); if (isSelectedItemPattrenAvailable) { var selectionItemProperty = SelectionItemPattern.IsSelectedProperty; isSelected = element.GetAutomationPropertyValue<bool>(selectionItemProperty); } } catch (CruciatusException) { var toggleStateProperty = TogglePattern.ToggleStateProperty; var toggleState = element.GetAutomationPropertyValue<ToggleState>(toggleStateProperty); isSelected = toggleState == ToggleState.On; } return this.JsonResponse(ResponseStatus.Success, isSelected); } #endregion } }
Update Metatogger default install path
#r "C:\Program Files (x86)\Luminescence Software\Metatogger 5.8\Metatogger.exe" using System.Collections.Generic; using Metatogger.Data; IEnumerable<AudioFile> files = new List<AudioFile>(); // list of checked audio files in the workspace
#r "C:\Program Files (x86)\Luminescence Software\Metatogger 5.9\Metatogger.exe" using System.Collections.Generic; using Metatogger.Data; IEnumerable<AudioFile> files = new List<AudioFile>(); // list of checked audio files in the workspace
Fix bug: Searching too fast in dialog returns no results when enter is pressed Work items: 598
using System; using System.Linq; using Microsoft.VisualStudio.ExtensionsExplorer; namespace NuGet.Dialog.Providers { internal class PackagesSearchNode : PackagesTreeNodeBase { private string _searchText; private readonly PackagesTreeNodeBase _baseNode; public PackagesTreeNodeBase BaseNode { get { return _baseNode; } } public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) : base(parent, provider) { if (baseNode == null) { throw new ArgumentNullException("baseNode"); } _searchText = searchText; _baseNode = baseNode; // Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer IsSearchResultsNode = true; } public override string Name { get { return Resources.Dialog_RootNodeSearch; } } public void SetSearchText(string newSearchText) { if (newSearchText == null) { throw new ArgumentNullException("newSearchText"); } if (_searchText != newSearchText) { _searchText = newSearchText; if (IsSelected) { ResetQuery(); LoadPage(1); } } } public override IQueryable<IPackage> GetPackages() { return _baseNode.GetPackages().Find(_searchText); } } }
using System; using System.Linq; using Microsoft.VisualStudio.ExtensionsExplorer; namespace NuGet.Dialog.Providers { internal class PackagesSearchNode : PackagesTreeNodeBase { private string _searchText; private readonly PackagesTreeNodeBase _baseNode; public PackagesTreeNodeBase BaseNode { get { return _baseNode; } } public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) : base(parent, provider) { if (baseNode == null) { throw new ArgumentNullException("baseNode"); } _searchText = searchText; _baseNode = baseNode; // Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer IsSearchResultsNode = true; } public override string Name { get { return Resources.Dialog_RootNodeSearch; } } public void SetSearchText(string newSearchText) { if (newSearchText == null) { throw new ArgumentNullException("newSearchText"); } _searchText = newSearchText; if (IsSelected) { ResetQuery(); LoadPage(1); } } public override IQueryable<IPackage> GetPackages() { return _baseNode.GetPackages().Find(_searchText); } } }
Make generic for local and production
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Configuration; namespace Microsoft.Azure.WebJobs { /// <summary> /// Abstraction to provide storage accounts from the connection names. /// This gets the storage account name via the binding attribute's <see cref="IConnectionProvider.Connection"/> /// property. /// If the connection is not specified on the attribute, it uses a default account. /// </summary> public class StorageAccountProvider { private readonly IConfiguration _configuration; public StorageAccountProvider(IConfiguration configuration) { _configuration = configuration; } public StorageAccount Get(string name, INameResolver resolver) { var resolvedName = resolver.ResolveWholeString(name); return this.Get(resolvedName); } public virtual StorageAccount Get(string name) { if (string.IsNullOrWhiteSpace(name)) { name = ConnectionStringNames.Storage; // default } // $$$ Where does validation happen? string connectionString = _configuration.GetWebJobsConnectionString(name); if (connectionString == null) { // Not found throw new InvalidOperationException($"Storage account connection string '{name}' does not exist. Make sure that it is defined in application settings."); } return StorageAccount.NewFromConnectionString(connectionString); } /// <summary> /// The host account is for internal storage mechanisms like load balancer queuing. /// </summary> /// <returns></returns> public virtual StorageAccount GetHost() { return this.Get(null); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Configuration; namespace Microsoft.Azure.WebJobs { /// <summary> /// Abstraction to provide storage accounts from the connection names. /// This gets the storage account name via the binding attribute's <see cref="IConnectionProvider.Connection"/> /// property. /// If the connection is not specified on the attribute, it uses a default account. /// </summary> public class StorageAccountProvider { private readonly IConfiguration _configuration; public StorageAccountProvider(IConfiguration configuration) { _configuration = configuration; } public StorageAccount Get(string name, INameResolver resolver) { var resolvedName = resolver.ResolveWholeString(name); return this.Get(resolvedName); } public virtual StorageAccount Get(string name) { if (string.IsNullOrWhiteSpace(name)) { name = ConnectionStringNames.Storage; // default } // $$$ Where does validation happen? string connectionString = _configuration.GetWebJobsConnectionString(name); if (connectionString == null) { // Not found throw new InvalidOperationException($"Storage account connection string '{name}' does not exist. Make sure that it a defined App Setting."); } return StorageAccount.NewFromConnectionString(connectionString); } /// <summary> /// The host account is for internal storage mechanisms like load balancer queuing. /// </summary> /// <returns></returns> public virtual StorageAccount GetHost() { return this.Get(null); } } }
Allow PlatformSpecific 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 this is a platform specific test. /// </summary> [TraitDiscoverer("Xunit.NetCore.Extensions.PlatformSpecificDiscoverer", "Xunit.NetCore.Extensions")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class PlatformSpecificAttribute : Attribute, ITraitAttribute { public PlatformSpecificAttribute(PlatformID platform) { } } }
// 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 this is a platform specific test. /// </summary> [TraitDiscoverer("Xunit.NetCore.Extensions.PlatformSpecificDiscoverer", "Xunit.NetCore.Extensions")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] public class PlatformSpecificAttribute : Attribute, ITraitAttribute { public PlatformSpecificAttribute(PlatformID platform) { } } }
Apply rendering code, now need to test
using UnityEngine; using UniRx; namespace Reduxity.Example.PlayerMovementLook { [RequireComponent(typeof(Camera))] public class MoveCamera : MonoBehaviour { private Camera camera_; private void Awake() { camera_ = GetComponent<Camera>(); } void Start() { RenderLook(); } void RenderLook() { // Debug.Log($"App.Store: {App.Store}"); App.Store .Subscribe(state => { // Debug.Log($"going to move character by: {distance}"); // camera_.transform.localRotation = state.Look.lookRotation; }) .AddTo(this); } // Ripped straight out of the Standard Assets MouseLook script. (This should really be a standard function...) private Quaternion ClampRotationAroundXAxis(Quaternion q, float minAngle, float maxAngle) { q.x /= q.w; q.y /= q.w; q.z /= q.w; q.w = 1.0f; float angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan(q.x); angleX = Mathf.Clamp(angleX, minAngle, maxAngle); q.x = Mathf.Tan(0.5f * Mathf.Deg2Rad * angleX); return q; } } }
using UnityEngine; using UniRx; namespace Reduxity.Example.PlayerMovementLook { [RequireComponent(typeof(Camera))] public class MoveCamera : MonoBehaviour { private Camera camera_; private void Awake() { camera_ = GetComponent<Camera>(); } void Start() { RenderLook(); } void RenderLook() { // Debug.Log($"App.Store: {App.Store}"); App.Store .Subscribe(state => { Debug.Log($"looking by rotation: {state.Camera.transform.localRotation}"); camera_.transform.localRotation = state.Camera.transform.localRotation; }) .AddTo(this); } } }
Revert "Added ability to have more than one dynamic placeholder in the same rendering"
using System.Linq; using Sitecore.Mvc.Helpers; using Sitecore.Mvc.Presentation; using System.Collections.Generic; using System.Web; namespace DynamicPlaceholders.Mvc.Extensions { public static class SitecoreHelperExtensions { public static List<string> DynamicPlaceholders = new List<string>(); public static HtmlString DynamicPlaceholder(this SitecoreHelper helper, string placeholderName) { var placeholder = string.Format("{0}_{1}", placeholderName, RenderingContext.Current.Rendering.UniqueId); var count = 0; if ((count = DynamicPlaceholders.Count(dp => dp.StartsWith(placeholder))) > 0) { placeholder = string.Format("{0}_{1}", placeholder, count); DynamicPlaceholders.Add(placeholder); } return helper.Placeholder(placeholder); } } }
using Sitecore.Mvc.Helpers; using Sitecore.Mvc.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace DynamicPlaceholders.Mvc.Extensions { public static class SitecoreHelperExtensions { public static HtmlString DynamicPlaceholder(this SitecoreHelper helper, string placeholderName) { var currentRenderingId = RenderingContext.Current.Rendering.UniqueId; return helper.Placeholder(string.Format("{0}_{1}", placeholderName, currentRenderingId)); } } }
Add test owner to FqdnTag test
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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 Microsoft.Azure.ServiceManagemenet.Common.Models; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Xunit; using Xunit.Abstractions; namespace Commands.Network.Test.ScenarioTests { public class AzureFirewallFqdnTagTests : Microsoft.WindowsAzure.Commands.Test.Utilities.Common.RMTestBase { public XunitTracingInterceptor _logger; public AzureFirewallFqdnTagTests(ITestOutputHelper output) { _logger = new XunitTracingInterceptor(output); XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output)); } [Fact(Skip = "Need to re-record test after changes are deployed in Gateway Manager.")] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAzureFirewallFqdnTagList() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-AzureFirewallFqdnTagList"); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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 Microsoft.Azure.ServiceManagemenet.Common.Models; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Xunit; using Xunit.Abstractions; namespace Commands.Network.Test.ScenarioTests { public class AzureFirewallFqdnTagTests : Microsoft.WindowsAzure.Commands.Test.Utilities.Common.RMTestBase { public XunitTracingInterceptor _logger; public AzureFirewallFqdnTagTests(ITestOutputHelper output) { _logger = new XunitTracingInterceptor(output); XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output)); } [Fact(Skip = "Need to re-record test after changes are deployed in Gateway Manager.")] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, "azurefirewall")] public void TestAzureFirewallFqdnTagList() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-AzureFirewallFqdnTagList"); } } }
Fix ordering of views so the ordering is the same as v8
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.Extensions.Options; namespace Umbraco.Cms.Web.Website.ViewEngines { /// <summary> /// Configure view engine locations for front-end rendering /// </summary> public class RenderRazorViewEngineOptionsSetup : IConfigureOptions<RazorViewEngineOptions> { /// <inheritdoc/> public void Configure(RazorViewEngineOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } options.ViewLocationExpanders.Add(new ViewLocationExpander()); } /// <summary> /// Expands the default view locations /// </summary> private class ViewLocationExpander : IViewLocationExpander { public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { string[] umbViewLocations = new string[] { "/Views/Partials/{0}.cshtml", "/Views/MacroPartials/{0}.cshtml", "/Views/{0}.cshtml" }; viewLocations = umbViewLocations.Concat(viewLocations); return viewLocations; } // not a dynamic expander public void PopulateValues(ViewLocationExpanderContext context) { } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.Extensions.Options; namespace Umbraco.Cms.Web.Website.ViewEngines { /// <summary> /// Configure view engine locations for front-end rendering /// </summary> public class RenderRazorViewEngineOptionsSetup : IConfigureOptions<RazorViewEngineOptions> { /// <inheritdoc/> public void Configure(RazorViewEngineOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } options.ViewLocationExpanders.Add(new ViewLocationExpander()); } /// <summary> /// Expands the default view locations /// </summary> private class ViewLocationExpander : IViewLocationExpander { public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { string[] umbViewLocations = new string[] { "/Views/{0}.cshtml", "/Views/Shared/{0}.cshtml", "/Views/Partials/{0}.cshtml", "/Views/MacroPartials/{0}.cshtml", }; viewLocations = umbViewLocations.Concat(viewLocations); return viewLocations; } // not a dynamic expander public void PopulateValues(ViewLocationExpanderContext context) { } } } }
Add material mappings to eth1.
// This script is executed on the server $MAP_ROOT = "ethernet/maps/eth1/"; $sgLightEditor::lightDBPath = $MAP_ROOT @ "lights/"; $sgLightEditor::filterDBPath = $MAP_ROOT @ "filters/"; sgLoadDataBlocks($sgLightEditor::lightDBPath); sgLoadDataBlocks($sgLightEditor::filterDBPath); //exec("./difs/propertymap.cs"); //exec("./scripts/env.cs");
// This script is executed on the server $MAP_ROOT = "ethernet/maps/eth1/"; $sgLightEditor::lightDBPath = $MAP_ROOT @ "lights/"; $sgLightEditor::filterDBPath = $MAP_ROOT @ "filters/"; sgLoadDataBlocks($sgLightEditor::lightDBPath); sgLoadDataBlocks($sgLightEditor::filterDBPath); //------------------------------------------------------------------------------ // Material mappings //------------------------------------------------------------------------------ %mapping = createMaterialMapping("gray3"); %mapping.sound = $MaterialMapping::Sound::Hard; %mapping.color = "0.3 0.3 0.3 0.4 0.0"; %mapping = createMaterialMapping("grass2"); %mapping.sound = $MaterialMapping::Sound::Soft; %mapping.color = "0.3 0.3 0.3 0.4 0.0"; %mapping = createMaterialMapping("rock"); %mapping.sound = $MaterialMapping::Sound::Hard; %mapping.color = "0.3 0.3 0.3 0.4 0.0"; %mapping = createMaterialMapping("stone"); %mapping.sound = $MaterialMapping::Sound::Hard; %mapping.color = "0.3 0.3 0.3 0.4 0.0";
Update device creation to just return the raw token
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using RightpointLabs.ConferenceRoom.Domain.Models; using RightpointLabs.ConferenceRoom.Domain.Models.Entities; using RightpointLabs.ConferenceRoom.Domain.Repositories; using RightpointLabs.ConferenceRoom.Infrastructure.Services; namespace RightpointLabs.ConferenceRoom.Services.Controllers { [RoutePrefix("api/devices")] public class DeviceController : ApiController { private readonly IOrganizationRepository _organizationRepository; private readonly IDeviceRepository _deviceRepository; private readonly ITokenService _tokenService; public DeviceController(IOrganizationRepository organizationRepository, IDeviceRepository deviceRepository, ITokenService tokenService) { _organizationRepository = organizationRepository; _deviceRepository = deviceRepository; _tokenService = tokenService; } [Route("create")] public object PostCreate(string organizationId, string joinKey) { var org = _organizationRepository.Get(organizationId); if (null == org || org.JoinKey != joinKey) { return new HttpResponseMessage(HttpStatusCode.Forbidden); } var device = _deviceRepository.Create(new DeviceEntity() { OrganizationId = org.Id }); var token = CreateToken(device); return token; } private string CreateToken(DeviceEntity device) { return _tokenService.CreateDeviceToken(device.Id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http; using RightpointLabs.ConferenceRoom.Domain.Models; using RightpointLabs.ConferenceRoom.Domain.Models.Entities; using RightpointLabs.ConferenceRoom.Domain.Repositories; using RightpointLabs.ConferenceRoom.Infrastructure.Services; namespace RightpointLabs.ConferenceRoom.Services.Controllers { [RoutePrefix("api/devices")] public class DeviceController : ApiController { private readonly IOrganizationRepository _organizationRepository; private readonly IDeviceRepository _deviceRepository; private readonly ITokenService _tokenService; public DeviceController(IOrganizationRepository organizationRepository, IDeviceRepository deviceRepository, ITokenService tokenService) { _organizationRepository = organizationRepository; _deviceRepository = deviceRepository; _tokenService = tokenService; } [Route("create")] public HttpResponseMessage PostCreate(string organizationId, string joinKey) { var org = _organizationRepository.Get(organizationId); if (null == org || org.JoinKey != joinKey) { return new HttpResponseMessage(HttpStatusCode.Forbidden); } var device = _deviceRepository.Create(new DeviceEntity() { OrganizationId = org.Id }); var token = _tokenService.CreateDeviceToken(device.Id); return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(token, Encoding.UTF8) }; } } }
Create mapping from NotificationOption to EditorConfig severity string.
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis.CodeStyle { internal static class NotificationOptionExtensions { public static string ToEditorConfigString(this NotificationOption notificationOption) { if (notificationOption == NotificationOption.Silent) { return nameof(NotificationOption.Silent).ToLowerInvariant(); } else { return notificationOption.ToString().ToLowerInvariant(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeStyle { internal static class NotificationOptionExtensions { public static string ToEditorConfigString(this NotificationOption notificationOption) { return notificationOption.Severity switch { ReportDiagnostic.Suppress => EditorConfigSeverityStrings.None, ReportDiagnostic.Hidden => EditorConfigSeverityStrings.Silent, ReportDiagnostic.Info => EditorConfigSeverityStrings.Suggestion, ReportDiagnostic.Warn => EditorConfigSeverityStrings.Warning, ReportDiagnostic.Error => EditorConfigSeverityStrings.Error, _ => throw ExceptionUtilities.Unreachable }; } } }
Support visual debugging of enum masks.
using System; using Entitas; using UnityEditor; namespace Entitas.Unity.VisualDebugging { public class EnumTypeDrawer : ITypeDrawer { public bool HandlesType(Type type) { return type.IsEnum; } public object DrawAndGetNewValue(Type memberType, string memberName, object value, Entity entity, int index, IComponent component) { return EditorGUILayout.EnumPopup(memberName, (Enum)value); } } }
using System; using Entitas; using UnityEditor; namespace Entitas.Unity.VisualDebugging { public class EnumTypeDrawer : ITypeDrawer { public bool HandlesType(Type type) { return type.IsEnum; } public object DrawAndGetNewValue(Type memberType, string memberName, object value, Entity entity, int index, IComponent component) { if (memberType.IsDefined(typeof(FlagsAttribute), false)) { return EditorGUILayout.EnumMaskField(memberName, (Enum)value); } return EditorGUILayout.EnumPopup(memberName, (Enum)value); } } }
Make sure the departure airport gets filled correctly.
using System; using System.Collections.Generic; using System.Linq; using OpenQA.Selenium; namespace Diskordia.Columbus.Bots.Host.Services.SingaporeAirlines.PageObjects { public class FareDealsSectionComponent { private readonly IWebDriver driver; private readonly IWebElement element; public FareDealsSectionComponent(IWebDriver driver, IWebElement element) { if (driver == null) { throw new ArgumentNullException(nameof(driver)); } if (element == null) { throw new ArgumentNullException(nameof(element)); } this.driver = driver; this.element = element; } public string DepartureAirport { get { return this.driver.FindElement(By.ClassName("select__text")).Text; } } public IEnumerable<FareDealsListItemComponent> FareDeals { get { return this.driver.FindElements(By.CssSelector(".fare-deals-list li")) .Where(e => !string.IsNullOrWhiteSpace(e.FindElement(By.ClassName("link")).Text)) .Select(e => new FareDealsListItemComponent(this.driver, e)); } } } }
using System; using System.Collections.Generic; using System.Linq; using OpenQA.Selenium; namespace Diskordia.Columbus.Bots.Host.Services.SingaporeAirlines.PageObjects { public class FareDealsSectionComponent { private readonly IWebDriver driver; private readonly IWebElement element; public FareDealsSectionComponent(IWebDriver driver, IWebElement element) { if (driver == null) { throw new ArgumentNullException(nameof(driver)); } if (element == null) { throw new ArgumentNullException(nameof(element)); } this.driver = driver; this.element = element; } public string DepartureAirport { get { return this.element.FindElement(By.ClassName("select__text")).Text; } } public IEnumerable<FareDealsListItemComponent> FareDeals { get { return this.element.FindElements(By.CssSelector(".fare-deals-list li")) .Where(e => !string.IsNullOrWhiteSpace(e.FindElement(By.ClassName("link")).Text)) .Select(e => new FareDealsListItemComponent(this.driver, e)); } } } }
Throw on null syntax or errors.
#region License /********************************************************************************* * RootJsonSyntax.cs * * Copyright (c) 2004-2019 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion using System.Collections.Generic; namespace Eutherion.Text.Json { /// <summary> /// Contains the syntax tree and list of parse errors which are the result of parsing json. /// </summary> public sealed class RootJsonSyntax { public JsonMultiValueSyntax Syntax { get; } public List<JsonErrorInfo> Errors { get; } public RootJsonSyntax(JsonMultiValueSyntax syntax, List<JsonErrorInfo> errors) { Syntax = syntax; Errors = errors; } } }
#region License /********************************************************************************* * RootJsonSyntax.cs * * Copyright (c) 2004-2019 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; namespace Eutherion.Text.Json { /// <summary> /// Contains the syntax tree and list of parse errors which are the result of parsing json. /// </summary> public sealed class RootJsonSyntax { public JsonMultiValueSyntax Syntax { get; } public List<JsonErrorInfo> Errors { get; } public RootJsonSyntax(JsonMultiValueSyntax syntax, List<JsonErrorInfo> errors) { Syntax = syntax ?? throw new ArgumentNullException(nameof(syntax)); Errors = errors ?? throw new ArgumentNullException(nameof(errors)); } } }
Tweak to use typed GetCustomAttributes from field
using System; using System.ComponentModel.DataAnnotations; using System.Reflection; namespace CertiPay.Common { public static class ExtensionMethods { /// <summary> /// Trims the string of any whitestace and leaves null if there is no content. /// </summary> public static String TrimToNull(this String s) { return String.IsNullOrWhiteSpace(s) ? null : s.Trim(); } /// <summary> /// Returns the display name from the display attribute on the enumeration, if available. /// Otherwise returns the ToString() value. /// </summary> public static string DisplayName(this Enum val) { return val.Display(e => e.GetName()); } /// <summary> /// Returns the short name from the display attribute on the enumeration, if available. /// Otherwise returns the ToString() value. /// </summary> public static string ShortName(this Enum val) { return val.Display(e => e.GetShortName()); } /// <summary> /// Returns the description from the display attribute on the enumeration, if available. /// Otherwise returns the ToString() value. /// </summary> public static string Description(this Enum val) { return val.Display(e => e.GetDescription()); } private static String Display(this Enum val, Func<DisplayAttribute, String> selector) { FieldInfo fi = val.GetType().GetField(val.ToString()); DisplayAttribute[] attributes = (DisplayAttribute[])fi.GetCustomAttributes(typeof(DisplayAttribute), false); if (attributes != null && attributes.Length > 0) { return selector.Invoke(attributes[0]); } return val.ToString(); } } }
using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; namespace CertiPay.Common { public static class ExtensionMethods { /// <summary> /// Trims the string of any whitestace and leaves null if there is no content. /// </summary> public static String TrimToNull(this String s) { return String.IsNullOrWhiteSpace(s) ? null : s.Trim(); } /// <summary> /// Returns the display name from the display attribute on the enumeration, if available. /// Otherwise returns the ToString() value. /// </summary> public static string DisplayName(this Enum val) { return val.Display(e => e.GetName()); } /// <summary> /// Returns the short name from the display attribute on the enumeration, if available. /// Otherwise returns the ToString() value. /// </summary> public static string ShortName(this Enum val) { return val.Display(e => e.GetShortName()); } /// <summary> /// Returns the description from the display attribute on the enumeration, if available. /// Otherwise returns the ToString() value. /// </summary> public static string Description(this Enum val) { return val.Display(e => e.GetDescription()); } private static String Display(this Enum val, Func<DisplayAttribute, String> selector) { FieldInfo fi = val.GetType().GetField(val.ToString()); var attributes = fi.GetCustomAttributes<DisplayAttribute>(); if (attributes != null && attributes.Any()) { return selector.Invoke(attributes.First()); } return val.ToString(); } } }
Allow .mustache extension as well for Nustache views
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using global::Nustache.Core; namespace Dolstagis.Web.Views.Nustache { public class NustacheViewEngine : ViewEngineBase { private static readonly string[] _extensions = new[] { "nustache" }; public override IEnumerable<string> Extensions { get { return _extensions; } } protected override IView CreateView(VirtualPath pathToView, Static.IResourceLocator locator) { var resource = locator.GetResource(pathToView); if (resource == null || !resource.Exists) { throw new ViewNotFoundException("There is no view at " + pathToView.ToString()); } return new NustacheView(this, pathToView, resource); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using global::Nustache.Core; namespace Dolstagis.Web.Views.Nustache { public class NustacheViewEngine : ViewEngineBase { private static readonly string[] _extensions = new[] { "mustache", "nustache" }; public override IEnumerable<string> Extensions { get { return _extensions; } } protected override IView CreateView(VirtualPath pathToView, Static.IResourceLocator locator) { var resource = locator.GetResource(pathToView); if (resource == null || !resource.Exists) { throw new ViewNotFoundException("There is no view at " + pathToView.ToString()); } return new NustacheView(this, pathToView, resource); } } }
Add string based YAML tasks.
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.IO; using System.Linq; using JetBrains.Annotations; using Nuke.Common.IO; using Nuke.Core.Execution; using Nuke.Core.Tooling; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; [assembly: IconClass(typeof(YamlTasks), "file-empty2")] namespace Nuke.Common.IO { [PublicAPI] public class YamlTasks { public static void YamlSerialize<T> (T obj, string path, Configure<SerializerBuilder> configurator = null) { var builder = new SerializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()); builder = configurator.InvokeSafe(builder); var serializer = builder.Build(); var content = serializer.Serialize(obj); File.WriteAllText(path, content); } [Pure] public static T YamlDeserialize<T> (string path, Configure<DeserializerBuilder> configurator = null) { var builder = new DeserializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()); builder = configurator.InvokeSafe(builder); var content = File.ReadAllText(path); var deserializer = builder.Build(); return deserializer.Deserialize<T>(content); } } }
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.IO; using System.Linq; using JetBrains.Annotations; using Nuke.Common.IO; using Nuke.Core.Execution; using Nuke.Core.Tooling; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; [assembly: IconClass(typeof(YamlTasks), "file-empty2")] namespace Nuke.Common.IO { [PublicAPI] public class YamlTasks { public static void YamlSerializeToFile (object obj, string path, Configure<SerializerBuilder> configurator = null) { File.WriteAllText(path, YamlSerialize(obj, configurator)); } [Pure] public static T YamlDeserializeFromFile<T> (string path, Configure<DeserializerBuilder> configurator = null) { return YamlDeserialize<T>(File.ReadAllText(path), configurator); } [Pure] public static string YamlSerialize (object obj, Configure<SerializerBuilder> configurator = null) { var builder = new SerializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()); builder = configurator.InvokeSafe(builder); var serializer = builder.Build(); return serializer.Serialize(obj); } [Pure] public static T YamlDeserialize<T> (string content, Configure<DeserializerBuilder> configurator = null) { var builder = new DeserializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()); builder = configurator.InvokeSafe(builder); var deserializer = builder.Build(); return deserializer.Deserialize<T>(content); } } }
Change ASP.NET tool version to reflect project format.
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DotNet.ProjectJsonMigration { internal class ConstantPackageVersions { public const string AspNetToolsVersion = "1.0.0-rc1-final"; public const string TestSdkPackageVersion = "15.0.0-preview-20161024-02"; public const string XUnitPackageVersion = "2.2.0-beta3-build3402"; public const string XUnitRunnerPackageVersion = "2.2.0-beta4-build1188"; public const string MstestTestAdapterVersion = "1.1.3-preview"; public const string MstestTestFrameworkVersion = "1.0.4-preview"; } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DotNet.ProjectJsonMigration { internal class ConstantPackageVersions { public const string AspNetToolsVersion = "1.0.0-msbuild1-final"; public const string TestSdkPackageVersion = "15.0.0-preview-20161024-02"; public const string XUnitPackageVersion = "2.2.0-beta3-build3402"; public const string XUnitRunnerPackageVersion = "2.2.0-beta4-build1188"; public const string MstestTestAdapterVersion = "1.1.3-preview"; public const string MstestTestFrameworkVersion = "1.0.4-preview"; } }
Add unit test for analyzing class without imported namespace.
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestHelper; namespace DebuggerStepThroughRemover.Test { [TestClass] public class AnalyzerTests : DiagnosticVerifier { [TestMethod] public void WithEmptySourceFile_ShouldNotFindAnything() { var test = @""; VerifyCSharpDiagnostic(test); } [TestMethod] public void Analyzer_WithImportedNameSpace_ShouldReportAttribute() { var test = @" using System.Diagnostics; namespace ConsoleApplication1 { [DebuggerStepThrough] class TypeName { } }"; var expected = new DiagnosticResult { Id = "DebuggerStepThroughRemover", Message = $"Type 'TypeName' is decorated with DebuggerStepThrough attribute", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 6, 5) } }; VerifyCSharpDiagnostic(test, expected); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new DebuggerStepThroughRemoverAnalyzer(); } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestHelper; namespace DebuggerStepThroughRemover.Test { [TestClass] public class AnalyzerTests : DiagnosticVerifier { [TestMethod] public void WithEmptySourceFile_ShouldNotFindAnything() { var test = @""; VerifyCSharpDiagnostic(test); } [TestMethod] public void Analyzer_WithImportedNameSpace_ShouldReportAttribute() { var test = @" using System.Diagnostics; namespace ConsoleApplication1 { [DebuggerStepThrough] class TypeName { } }"; var expected = new DiagnosticResult { Id = "DebuggerStepThroughRemover", Message = $"Type 'TypeName' is decorated with DebuggerStepThrough attribute", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 6, 5) } }; VerifyCSharpDiagnostic(test, expected); } [TestMethod] public void Analyzer_WithoutImportedNameSpace_ShouldReportAttribute() { var test = @" namespace ConsoleApplication1 { [System.Diagnostics.DebuggerStepThrough] class TypeName { } }"; var expected = new DiagnosticResult { Id = "DebuggerStepThroughRemover", Message = $"Type 'TypeName' is decorated with DebuggerStepThrough attribute", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 4, 5) } }; VerifyCSharpDiagnostic(test, expected); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new DebuggerStepThroughRemoverAnalyzer(); } } }
Remove code to trigger expiry of funds processing until fix has been implemented for the calculation
using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ExpireFundsJob { private readonly IMessageSession _messageSession; public ExpireFundsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 0 28 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ExpireFundsCommand()); } } }
using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ExpireFundsJob { private readonly IMessageSession _messageSession; public ExpireFundsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run( [TimerTrigger("0 0 0 28 * *")] TimerInfo timer, ILogger logger) { return Task.FromResult(0); // return _messageSession.Send(new ExpireFundsCommand()); } } }
Fix peer up port decoding bug
using System; using System.Net; using BmpListener.Bgp; using System.Linq; using BmpListener.MiscUtil.Conversion; namespace BmpListener.Bmp { public class PeerUpNotification : BmpMessage { public IPAddress LocalAddress { get; private set; } public int LocalPort { get; private set; } public int RemotePort { get; private set; } public BgpOpenMessage SentOpenMessage { get; private set; } public BgpOpenMessage ReceivedOpenMessage { get; private set; } public override void Decode(byte[] data, int offset) { if (((PeerHeader.Flags & (1 << 7)) != 0)) { var ipBytes = new byte[16]; Array.Copy(data, offset, ipBytes, 0, 4); LocalAddress = new IPAddress(ipBytes); } else { var ipBytes = new byte[4]; Array.Copy(data, offset + 12, ipBytes, 0, 4); LocalAddress = new IPAddress(ipBytes); } LocalPort = EndianBitConverter.Big.ToUInt16(data, 16); RemotePort = EndianBitConverter.Big.ToUInt16(data, 18); offset += 20; SentOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage; offset += SentOpenMessage.Header.Length; ReceivedOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage; } } }
using System; using System.Net; using BmpListener.Bgp; using System.Linq; using BmpListener.MiscUtil.Conversion; namespace BmpListener.Bmp { public class PeerUpNotification : BmpMessage { public IPAddress LocalAddress { get; private set; } public int LocalPort { get; private set; } public int RemotePort { get; private set; } public BgpOpenMessage SentOpenMessage { get; private set; } public BgpOpenMessage ReceivedOpenMessage { get; private set; } public override void Decode(byte[] data, int offset) { if (((PeerHeader.Flags & (1 << 7)) != 0)) { var ipBytes = new byte[16]; Array.Copy(data, offset, ipBytes, 0, 4); LocalAddress = new IPAddress(ipBytes); offset += 4; } else { var ipBytes = new byte[4]; Array.Copy(data, offset + 12, ipBytes, 0, 4); LocalAddress = new IPAddress(ipBytes); offset += 16; } LocalPort = EndianBitConverter.Big.ToUInt16(data, offset); offset += 2; RemotePort = EndianBitConverter.Big.ToUInt16(data, offset); offset += 2; SentOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage; offset += SentOpenMessage.Header.Length; ReceivedOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage; } } }
Test coverage for validation of the --report command line option.
namespace Fixie.Tests.Execution { using System; using Fixie.Cli; using Fixie.Execution; public class OptionsTests { public void DemandsAssemblyPathProvided() { var options = new Options(null); Action validate = options.Validate; validate.ShouldThrow<CommandLineException>( "Missing required test assembly path."); } public void DemandsAssemblyPathExistsOnDisk() { var options = new Options("foo.dll"); Action validate = options.Validate; validate.ShouldThrow<CommandLineException>( "Specified test assembly does not exist: foo.dll"); } public void DemandsAssemblyPathDirectoryContainsFixie() { var mscorlib = typeof(string).Assembly.Location; var options = new Options(mscorlib); Action validate = options.Validate; validate.ShouldThrow<CommandLineException>( $"Specified assembly {mscorlib} does not appear to be a test assembly. Ensure that it references Fixie.dll and try again."); } public void AcceptsExistingTestAssemblyPath() { var assemblyPath = typeof(OptionsTests).Assembly.Location; var options = new Options(assemblyPath); options.Validate(); } } }
namespace Fixie.Tests.Execution { using System; using Fixie.Cli; using Fixie.Execution; public class OptionsTests { public void DemandsAssemblyPathProvided() { var options = new Options(null); Action validate = options.Validate; validate.ShouldThrow<CommandLineException>( "Missing required test assembly path."); } public void DemandsAssemblyPathExistsOnDisk() { var options = new Options("foo.dll"); Action validate = options.Validate; validate.ShouldThrow<CommandLineException>( "Specified test assembly does not exist: foo.dll"); } public void DemandsAssemblyPathDirectoryContainsFixie() { var mscorlib = typeof(string).Assembly.Location; var options = new Options(mscorlib); Action validate = options.Validate; validate.ShouldThrow<CommandLineException>( $"Specified assembly {mscorlib} does not appear to be a test assembly. Ensure that it references Fixie.dll and try again."); } public void AcceptsExistingTestAssemblyPath() { var assemblyPath = typeof(OptionsTests).Assembly.Location; var options = new Options(assemblyPath); options.Validate(); } public void DemandsValidReportFileNameWhenProvided() { var assemblyPath = typeof(OptionsTests).Assembly.Location; var options = new Options(assemblyPath); Action validate = options.Validate; options.Report = "Report.xml"; validate(); options.Report = "\t"; validate.ShouldThrow<CommandLineException>( "Specified report name is invalid: \t"); } } }
Use Crockford Base32 by default.
using System.Security.Cryptography; using DeviceId.Encoders; using DeviceId.Formatters; namespace DeviceId { /// <summary> /// Provides access to some of the default formatters. /// </summary> public static class DeviceIdFormatters { /// <summary> /// Returns the default formatter used in version 5 of the DeviceId library. /// </summary> public static IDeviceIdFormatter DefaultV5 { get; } = new HashDeviceIdFormatter(() => SHA256.Create(), new Base64UrlByteArrayEncoder()); /// <summary> /// Returns the default formatter used in version 4 of the DeviceId library. /// </summary> public static IDeviceIdFormatter DefaultV6 { get; } = new HashDeviceIdFormatter(() => SHA256.Create(), new Base32ByteArrayEncoder()); } }
using System.Security.Cryptography; using DeviceId.Encoders; using DeviceId.Formatters; namespace DeviceId { /// <summary> /// Provides access to some of the default formatters. /// </summary> public static class DeviceIdFormatters { /// <summary> /// Returns the default formatter used in version 5 of the DeviceId library. /// </summary> public static IDeviceIdFormatter DefaultV5 { get; } = new HashDeviceIdFormatter(() => SHA256.Create(), new Base64UrlByteArrayEncoder()); /// <summary> /// Returns the default formatter used in version 4 of the DeviceId library. /// </summary> public static IDeviceIdFormatter DefaultV6 { get; } = new HashDeviceIdFormatter(() => SHA256.Create(), new Base32ByteArrayEncoder(Base32ByteArrayEncoder.CrockfordAlphabet)); } }
Add Needed Vm properties and cmds
using System; using System.Collections.Generic; using System.Text; using GalaSoft.MvvmLight.Views; using ToxRt.Helpers; using ToxRt.Model; using ToxRt.NavigationService; namespace ToxRt.ViewModel { public class LoadProfileViewModel : NavigableViewModelBase { #region Fields #endregion #region Properties #endregion #region Commands #endregion #region Ctors and Methods public LoadProfileViewModel(INavigationService navigationService, IDataService dataService, IMessagesNavigationService innerNavigationService) : base(navigationService,dataService, innerNavigationService) { } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Views; using ToxRt.Helpers; using ToxRt.Model; using ToxRt.NavigationService; namespace ToxRt.ViewModel { public class LoadProfileViewModel : NavigableViewModelBase { #region Fields private ObservableCollection<Profile> _listProfiles; private Profile _selectedProfile; #endregion #region Properties public ObservableCollection<Profile> ListProfilesNames { get { return _listProfiles; } set { if (_listProfiles == value) { return; } _listProfiles = value; RaisePropertyChanged(); } } public Profile SelectedProfile { get { return _selectedProfile; } set { if (_selectedProfile == value) { return; } _selectedProfile = value; RaisePropertyChanged(); } } #endregion #region Commands private RelayCommand _loadProfielCommand; public RelayCommand LoadProfileCommand { get { return _loadProfielCommand ?? (_loadProfielCommand = new RelayCommand( () => { })); } } private RelayCommand _setDefaultProfileCommand; public RelayCommand SetDefaultProfileCommand { get { return _setDefaultProfileCommand ?? (_setDefaultProfileCommand = new RelayCommand( () => { })); } } #endregion #region Ctors and Methods public LoadProfileViewModel(INavigationService navigationService, IDataService dataService, IMessagesNavigationService innerNavigationService) : base(navigationService,dataService, innerNavigationService) { } #endregion } }
Update to consume framework fixes
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Specialized; using System.Linq; using osu.Framework.Bindables; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts { /// <summary> /// The part of the timeline that displays the control points. /// </summary> public class ControlPointPart : TimelinePart<GroupVisualisation> { private BindableList<ControlPointGroup> controlPointGroups; protected override void LoadBeatmap(WorkingBeatmap beatmap) { base.LoadBeatmap(beatmap); controlPointGroups = (BindableList<ControlPointGroup>)beatmap.Beatmap.ControlPointInfo.Groups.GetBoundCopy(); controlPointGroups.BindCollectionChanged((sender, args) => { switch (args.Action) { case NotifyCollectionChangedAction.Reset: Clear(); break; case NotifyCollectionChangedAction.Add: foreach (var group in args.NewItems.OfType<ControlPointGroup>()) Add(new GroupVisualisation(group)); break; case NotifyCollectionChangedAction.Remove: foreach (var group in args.OldItems.OfType<ControlPointGroup>()) { var matching = Children.SingleOrDefault(gv => gv.Group == group); matching?.Expire(); } break; } }, true); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Specialized; using System.Linq; using osu.Framework.Bindables; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts { /// <summary> /// The part of the timeline that displays the control points. /// </summary> public class ControlPointPart : TimelinePart<GroupVisualisation> { private IBindableList<ControlPointGroup> controlPointGroups; protected override void LoadBeatmap(WorkingBeatmap beatmap) { base.LoadBeatmap(beatmap); controlPointGroups = beatmap.Beatmap.ControlPointInfo.Groups.GetBoundCopy(); controlPointGroups.BindCollectionChanged((sender, args) => { switch (args.Action) { case NotifyCollectionChangedAction.Reset: Clear(); break; case NotifyCollectionChangedAction.Add: foreach (var group in args.NewItems.OfType<ControlPointGroup>()) Add(new GroupVisualisation(group)); break; case NotifyCollectionChangedAction.Remove: foreach (var group in args.OldItems.OfType<ControlPointGroup>()) { var matching = Children.SingleOrDefault(gv => gv.Group == group); matching?.Expire(); } break; } }, true); } } }
Make GetAllStubs return a List<string> instead of immediately writing the output to console
using System; using System.Collections.Generic; using System.Reflection; using JAGBE.Attributes; namespace JAGBE.Stats { internal static class AttributeReflector { /// <summary> /// Gets the methods of <paramref name="type"/> with the <see cref="Attribute"/> of type /// <paramref name="attribute"/>. /// </summary> /// <param name="type">The type.</param> /// <param name="attribute">The attribute.</param> /// <param name="parentList">The parent list.</param> public static void GetMethodsOfTypeWithAttribute(Type type, Type attribute, ICollection<string> parentList) { foreach (MethodInfo info in type.GetMethods( BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public)) { Attribute a = info.GetCustomAttribute(attribute); if (a != null) { parentList.Add(type.FullName + "." + info.Name); } } } /// <summary> /// Writes all method stubs to the console. /// </summary> public static void GetAllStubs() { // Reflection doesn't seem to grab this method. List<string> strs = new List<string>(0); foreach (Type t in typeof(AttributeReflector).Assembly.GetTypes()) { GetMethodsOfTypeWithAttribute(t, typeof(StubAttribute), strs); } strs.Sort(); // TODO: sort by namespace, then class, then method (by length then by 0-9A-Za-z) foreach (string str in strs) { Console.WriteLine(str); } } } }
using System; using System.Collections.Generic; using System.Reflection; using JAGBE.Attributes; namespace JAGBE.Stats { internal static class AttributeReflector { /// <summary> /// Gets the methods of <paramref name="type"/> with the <see cref="Attribute"/> of type /// <paramref name="attribute"/>. /// </summary> /// <param name="type">The type.</param> /// <param name="attribute">The attribute.</param> /// <param name="parentList">The parent list.</param> public static void GetMethodsOfTypeWithAttribute(Type type, Type attribute, ICollection<string> parentList) { foreach (MethodInfo info in type.GetMethods( BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public)) { Attribute a = info.GetCustomAttribute(attribute); if (a != null) { parentList.Add(type.FullName + "." + info.Name); } } } /// <summary> /// Writes all method stubs to the console. /// </summary> public static List<string> GetAllStubs() { // Reflection doesn't seem to grab this method. List<string> strs = new List<string>(0); foreach (Type t in typeof(AttributeReflector).Assembly.GetTypes()) { GetMethodsOfTypeWithAttribute(t, typeof(StubAttribute), strs); } return strs; } } }
Add source of script and remove unnecessary usings
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StretchScript : MonoBehaviour { public float orthographicSize = 4; public float aspect = 0.6f; void Start() { Camera.main.projectionMatrix = Matrix4x4.Ortho( -orthographicSize * aspect, orthographicSize * aspect, -orthographicSize, orthographicSize, Camera.main.nearClipPlane, Camera.main.farClipPlane); } }
using UnityEngine; // Source: http://answers.unity3d.com/questions/464487/windowed-game-to-fullscreen.html public class StretchScript : MonoBehaviour { public float orthographicSize = 4; public float aspect = 0.6f; void Start() { Camera.main.projectionMatrix = Matrix4x4.Ortho( -orthographicSize * aspect, orthographicSize * aspect, -orthographicSize, orthographicSize, Camera.main.nearClipPlane, Camera.main.farClipPlane); } }
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34003 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.2.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Mef 3.0.2")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.2.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Mef 3.0.2")]
Fix for stringize when values contain single quotes.
using System; using System.Web; namespace VersionOne.SDK.APIClient { internal class ValueStringizer { private readonly string valueWrapper; public ValueStringizer(string valueWrapper = "'") { this.valueWrapper = valueWrapper; } public string Stringize(object value) { var valueString = value != null ? Format(value).Replace("'", "''") : null; valueString = HttpUtility.UrlEncode(valueString); return string.Format("{0}{1}{0}", valueWrapper, valueString); } private static string Format(object value) { if(value is DateTime) { var date = (DateTime) value; return date.ToString("yyyy-MM-ddTHH:mm:ss.fff"); } return value.ToString(); } } }
using System; using System.Web; namespace VersionOne.SDK.APIClient { internal class ValueStringizer { private readonly string valueWrapper; public ValueStringizer(string valueWrapper = "'") { this.valueWrapper = valueWrapper; } public string Stringize(object value) { string valueString = value == null ? null : HttpUtility.UrlEncode(value.ToString()); return string.Format("{0}{1}{0}", valueWrapper, valueString); } private static string Format(object value) { if(value is DateTime) { var date = (DateTime) value; return date.ToString("yyyy-MM-ddTHH:mm:ss.fff"); } return value.ToString(); } } }
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34003 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.2.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.DynamicProxy2 3.0.2")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.2.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.DynamicProxy2 3.0.2")]
Add drone to the right og 10x
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; public class Team : MonoBehaviour { //public List<Drone> team = new List<Drone>(); public ArrayList team = new ArrayList(); public GameObject DronePrefab; public void addDrone(Drone drone){ team.Add(drone); } public void getDronesGameObjects(){ Debug.Log ("DronesGameObject"+team.Count); int i = 1; foreach (Drone drone in team) { string imageName = "Drone" + i.ToString (); string spriteName = drone.eveId.ToString (); GameObject droneClone = (GameObject)Instantiate (DronePrefab, transform.position, transform.rotation); droneClone.BroadcastMessage ("set", drone.raw); Sprite droneImg = (Sprite)Resources.Load("sprites/drones/"+spriteName, typeof(Sprite)); GameObject image = GameObject.Find (imageName); image.GetComponent<Image> ().overrideSprite= droneImg; i = i + 1; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; public class Team : MonoBehaviour { //public List<Drone> team = new List<Drone>(); public ArrayList team = new ArrayList(); public GameObject DronePrefab; public void addDrone(Drone drone){ team.Add(drone); } public void getDronesGameObjects(){ Debug.Log ("DronesGameObject"+team.Count); int i = 1; foreach (Drone drone in team) { string imageName = "Drone" + i.ToString (); string spriteName = drone.eveId.ToString (); GameObject droneClone = (GameObject)Instantiate (DronePrefab, transform.position, transform.rotation); droneClone.transform.position = new Vector3(droneClone.transform.position.x + 10 *i, droneClone.transform.position.y, droneClone.transform.position.z); droneClone.BroadcastMessage ("set", drone.raw); Sprite droneImg = (Sprite)Resources.Load("sprites/drones/"+spriteName, typeof(Sprite)); GameObject image = GameObject.Find (imageName); image.GetComponent<Image> ().overrideSprite= droneImg; i = i + 1; } } }
Add some new map code
using UnityEngine; using System.Collections; namespace ecorealms.map { public class MapPresenter : MonoBehaviour { private int sizeX; private int sizeY; private GameObject rootObject; private Transform root; public Mesh mesh; public Material material; public void Setup(int sizeX, int sizeY) { this.sizeX = sizeX; this.sizeY = sizeY; rootObject = new GameObject("MapRoot"); root = rootObject.transform; rootObject.AddComponent<MeshFilter>().mesh = mesh; rootObject.AddComponent<MeshRenderer>().material = material; } } }
using UnityEngine; using System.Collections; namespace ecorealms.map { public class MapPresenter : MonoBehaviour { private int sizeX; private int sizeY; private GameObject rootObject; private Transform root; public Mesh mesh; public Material material; private Tile[] tiles; public void Setup(int sizeX, int sizeY) { this.sizeX = sizeX; this.sizeY = sizeY; tiles = new Tile[sizeX * sizeY]; rootObject = new GameObject("MapRoot"); rootObject.AddComponent<MeshFilter>().mesh = mesh; rootObject.AddComponent<MeshRenderer>().material = material; root = rootObject.transform; StartCoroutine(DelayedFunction()); } private IEnumerator DelayedFunction () { //TDOD do something yield return new WaitForSeconds(0.5f); } private void CreateQuad(){ //Vector3.one; } } public class Tile { } }
Remove obsolete chain to base ctor
using MyCouch.Extensions; using Newtonsoft.Json.Serialization; namespace MyCouch.Serialization { public class SerializationContractResolver : DefaultContractResolver { public SerializationContractResolver() : base(true) { } protected override string ResolvePropertyName(string propertyName) { return base.ResolvePropertyName(propertyName.ToCamelCase()); } } }
using MyCouch.Extensions; using Newtonsoft.Json.Serialization; namespace MyCouch.Serialization { public class SerializationContractResolver : DefaultContractResolver { protected override string ResolvePropertyName(string propertyName) { return base.ResolvePropertyName(propertyName.ToCamelCase()); } } }
Update IActionViewMessage message to remove verb
using System.Collections.Generic; namespace Glimpse.Agent.AspNet.Mvc.Messages { public interface IActionViewFoundMessage { string ActionId { get; set; } string ViewName { get; set; } bool DidFind { get; set; } ViewResult ViewData { get; set; } } }
using System.Collections.Generic; namespace Glimpse.Agent.AspNet.Mvc.Messages { public interface IActionViewMessage { string ActionId { get; set; } string ViewName { get; set; } bool DidFind { get; set; } ViewResult ViewData { get; set; } } }
Improve readability of previous implementation.
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using System.IO; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Input.Events; using osu.Framework.Extensions.EnumExtensions; namespace osu.Framework.Graphics.UserInterface { public abstract class DirectorySelectorDirectory : DirectorySelectorItem { protected readonly DirectoryInfo Directory; protected override string FallbackName => Directory.Name; [Resolved] private Bindable<DirectoryInfo> currentDirectory { get; set; } protected DirectorySelectorDirectory(DirectoryInfo directory, string displayName = null) : base(displayName) { Directory = directory; try { if (directory?.Attributes.HasFlagFast(FileAttributes.System) == true) { } else if (directory?.Attributes.HasFlagFast(FileAttributes.Hidden) == true) ApplyHiddenState(); } catch (UnauthorizedAccessException) { // checking attributes on access-controlled directories will throw an error so we handle it here to prevent a crash } } protected override bool OnClick(ClickEvent e) { currentDirectory.Value = Directory; return true; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using System.IO; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Input.Events; using osu.Framework.Extensions.EnumExtensions; namespace osu.Framework.Graphics.UserInterface { public abstract class DirectorySelectorDirectory : DirectorySelectorItem { protected readonly DirectoryInfo Directory; protected override string FallbackName => Directory.Name; [Resolved] private Bindable<DirectoryInfo> currentDirectory { get; set; } protected DirectorySelectorDirectory(DirectoryInfo directory, string displayName = null) : base(displayName) { Directory = directory; try { bool isHidden = directory?.Attributes.HasFlagFast(FileAttributes.Hidden) == true; // System drives show up as `System | Hidden | Directory` but shouldn't be shown in a hidden state. bool isSystem = directory?.Attributes.HasFlagFast(FileAttributes.System) == true; if (isHidden && !isSystem) ApplyHiddenState(); } catch (UnauthorizedAccessException) { // checking attributes on access-controlled directories will throw an error so we handle it here to prevent a crash } } protected override bool OnClick(ClickEvent e) { currentDirectory.Value = Directory; return true; } } }
Fix console color staying red after unrecognized game error.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TextPet.Commands { /// <summary> /// A command line interface command that sets the current active game. /// </summary> internal class GameCommand : CliCommand { public override string Name => "game"; public override string RunString => "Initializing game..."; private const string nameArg = "name"; public GameCommand(CommandLineInterface cli, TextPetCore core) : base(cli, core, new string[] { nameArg, }) { } protected override void RunImplementation() { string gameCode = GetRequiredValue(nameArg); if (!this.Core.SetActiveGame(gameCode)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ERROR: Unrecognized game name \"" + gameCode + "\"."); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TextPet.Commands { /// <summary> /// A command line interface command that sets the current active game. /// </summary> internal class GameCommand : CliCommand { public override string Name => "game"; public override string RunString => "Initializing game..."; private const string nameArg = "name"; public GameCommand(CommandLineInterface cli, TextPetCore core) : base(cli, core, new string[] { nameArg, }) { } protected override void RunImplementation() { string gameCode = GetRequiredValue(nameArg); if (!this.Core.SetActiveGame(gameCode)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ERROR: Unrecognized game name \"" + gameCode + "\"."); Console.ResetColor(); } } } }
Add an extra catch to handle incorrect paths
using System; using System.IO; using System.Xml; using System.Xml.Linq; namespace IvionSoft { public abstract class XmlConfig { public XElement Config { get; private set; } public XmlConfig(string file) { try { Config = XElement.Load(file); Console.WriteLine("-> Loaded config from " + file); } catch (FileNotFoundException) { Config = DefaultConfig(); Config.Save(file); Console.WriteLine("-> Created default config at " + file); } catch (XmlException ex) { Console.WriteLine("!! XML Exception: " + ex.Message); Console.WriteLine("-> Loading default config."); Config = DefaultConfig(); } try { LoadConfig(); } catch (Exception ex) { if (ex is FormatException || ex is NullReferenceException) { Console.WriteLine(" ! Error(s) in loading values from {0}. ({1})", file, ex.Message); Console.WriteLine("-> Loading default config."); Config = DefaultConfig(); LoadConfig(); } else throw; } } public abstract void LoadConfig(); public abstract XElement DefaultConfig(); } }
using System; using System.IO; using System.Xml; using System.Xml.Linq; namespace IvionSoft { public abstract class XmlConfig { public XElement Config { get; private set; } public XmlConfig(string file) { try { Config = XElement.Load(file); Console.WriteLine("-> Loaded config from " + file); } catch (FileNotFoundException) { Config = DefaultConfig(); Config.Save(file); Console.WriteLine("-> Created default config at " + file); } catch (DirectoryNotFoundException) { Console.WriteLine(" ! Directory not found: " + file); Console.WriteLine("-> Loading default config."); Config = DefaultConfig(); } catch (XmlException ex) { Console.WriteLine("!! XML Exception: " + ex.Message); Console.WriteLine("-> Loading default config."); Config = DefaultConfig(); } try { LoadConfig(); } catch (Exception ex) { if (ex is FormatException || ex is NullReferenceException) { Console.WriteLine(" ! Error(s) in loading values from {0}. ({1})", file, ex.Message); Console.WriteLine("-> Loading default config."); Config = DefaultConfig(); LoadConfig(); } else throw; } } public abstract void LoadConfig(); public abstract XElement DefaultConfig(); } }
Add comment to execution options class
using System; namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution { public enum ExecutionPriority { Normal, Next, } public record ExecutionOptions { public static ExecutionOptions Default = new() { Priority = ExecutionPriority.Normal, MustRunInForeground = false, InterruptCurrentForeground = false, }; public ExecutionPriority Priority { get; init; } public bool MustRunInForeground { get; init; } public bool InterruptCurrentForeground { get; init; } } public record PowerShellExecutionOptions : ExecutionOptions { public static new PowerShellExecutionOptions Default = new() { Priority = ExecutionPriority.Normal, MustRunInForeground = false, InterruptCurrentForeground = false, WriteOutputToHost = false, WriteInputToHost = false, ThrowOnError = true, AddToHistory = false, }; public bool WriteOutputToHost { get; init; } public bool WriteInputToHost { get; init; } public bool ThrowOnError { get; init; } public bool AddToHistory { get; init; } } }
using System; namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution { public enum ExecutionPriority { Normal, Next, } // Some of the fields of this class are not orthogonal, // so it's possible to construct self-contradictory execution options. // We should see if it's possible to rework this class to make the options less misconfigurable. // Generally the executor will do the right thing though; some options just priority over others. public record ExecutionOptions { public static ExecutionOptions Default = new() { Priority = ExecutionPriority.Normal, MustRunInForeground = false, InterruptCurrentForeground = false, }; public ExecutionPriority Priority { get; init; } public bool MustRunInForeground { get; init; } public bool InterruptCurrentForeground { get; init; } } public record PowerShellExecutionOptions : ExecutionOptions { public static new PowerShellExecutionOptions Default = new() { Priority = ExecutionPriority.Normal, MustRunInForeground = false, InterruptCurrentForeground = false, WriteOutputToHost = false, WriteInputToHost = false, ThrowOnError = true, AddToHistory = false, }; public bool WriteOutputToHost { get; init; } public bool WriteInputToHost { get; init; } public bool ThrowOnError { get; init; } public bool AddToHistory { get; init; } } }
Tweak eval due email for thru and last update dates
@model IEnumerable<BatteryCommander.Web.Models.Evaluation> <h1>Past Due and Upcoming Evaluations</h1> <table border="1"> <thead> <tr> <th>Ratee</th> <th>Rater</th> <th>Senior Rater</th> <th>Due Date</th> <th>Status</th> <th>Last Update</th> </tr> </thead> <tbody> @foreach (var eval in Model) { var style = eval.LastUpdated < DateTime.Now.AddDays(-30) ? "background-color:red" : ""; <tr style="@style"> <td>@eval.Ratee</td> <td>@eval.Rater</td> <td>@eval.SeniorRater</td> <td>@eval.ThruDate.ToString("yyyy-MM-dd")</td> <td>@eval.Status</td> <td>@eval.LastUpdatedHumanized</td> </tr> } </tbody> </table> <a href="https://bc.redleg.app/Evaluations">Evaluation Tracker</a>
@model IEnumerable<BatteryCommander.Web.Models.Evaluation> <h1>Past Due and Upcoming Evaluations</h1> <table border="1"> <thead> <tr> <th>Ratee</th> <th>Rater</th> <th>Senior Rater</th> <th>Due Date</th> <th>Status</th> <th>Last Update</th> </tr> </thead> <tbody> @foreach (var eval in Model) { var last_update_style = eval.LastUpdated < DateTime.Now.AddDays(-30) ? "background-color:red" : ""; var thru_date_style = eval.ThruDate < DateTime.Now.AddDays(-60) ? "background-color:red" : ""; <tr> <td>@eval.Ratee</td> <td>@eval.Rater</td> <td>@eval.SeniorRater</td> <td style="@thru_date_style">@eval.ThruDate.ToString("yyyy-MM-dd")</td> <td>@eval.Status</td> <td style="@last_update_style">@eval.LastUpdatedHumanized</td> </tr> } </tbody> </table> <a href="https://bc.redleg.app/Evaluations">Evaluation Tracker</a>
Correct broken test - wrong exception
using MVVM.HTML.Core.V8JavascriptObject; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MVVM.HTML.Core.Infra; using MVVM.HTML.Core.Exceptions; namespace MVVM.HTML.Core.Binding { public static class IJavascriptObjectFactory_CreateEnum_extesion { public static IJavascriptObject CreateEnum(this IJavascriptObjectFactory @this, Enum ienum) { IJavascriptObject res = @this.CreateObject(string.Format("new Enum('{0}',{1},'{2}','{3}')", ienum.GetType().Name, Convert.ToInt32(ienum), ienum.ToString(), ienum.GetDescription())); if ((res==null) || (!res.IsObject)) throw ExceptionHelper.NoKoExtension(); return res; } } }
using MVVM.HTML.Core.V8JavascriptObject; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MVVM.HTML.Core.Infra; using MVVM.HTML.Core.Exceptions; namespace MVVM.HTML.Core.Binding { public static class IJavascriptObjectFactory_CreateEnum_extesion { public static IJavascriptObject CreateEnum(this IJavascriptObjectFactory @this, Enum ienum) { try { IJavascriptObject res = @this.CreateObject(string.Format("new Enum('{0}',{1},'{2}','{3}')", ienum.GetType().Name, Convert.ToInt32(ienum), ienum.ToString(), ienum.GetDescription())); if ((res == null) || (!res.IsObject)) throw ExceptionHelper.NoKoExtension(); return res; } catch { throw ExceptionHelper.NoKoExtension(); } } } }
Trim search strings in deskapp.
using Chalmers.ILL.Members; using Chalmers.ILL.Models.Page; using Chalmers.ILL.OrderItems; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Mvc; using Umbraco.Web.Models; using Umbraco.Web.Mvc; namespace Chalmers.ILL.Controllers.SurfaceControllers.Page { public class ChalmersILLDiskPageController : RenderMvcController { IMemberInfoManager _memberInfoManager; IOrderItemSearcher _searcher; public ChalmersILLDiskPageController(IMemberInfoManager memberInfoManager, IOrderItemSearcher searcher) { _memberInfoManager = memberInfoManager; _searcher = searcher; } public override ActionResult Index(RenderModel model) { var customModel = new ChalmersILLDiskPageModel(); _memberInfoManager.PopulateModelWithMemberData(Request, Response, customModel); if (!String.IsNullOrEmpty(Request.QueryString["query"])) { customModel.OrderItems = _searcher.Search("\"" + Request.Params["query"] + "\""); } return CurrentTemplate(customModel); } } }
using Chalmers.ILL.Members; using Chalmers.ILL.Models.Page; using Chalmers.ILL.OrderItems; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Mvc; using Umbraco.Web.Models; using Umbraco.Web.Mvc; namespace Chalmers.ILL.Controllers.SurfaceControllers.Page { public class ChalmersILLDiskPageController : RenderMvcController { IMemberInfoManager _memberInfoManager; IOrderItemSearcher _searcher; public ChalmersILLDiskPageController(IMemberInfoManager memberInfoManager, IOrderItemSearcher searcher) { _memberInfoManager = memberInfoManager; _searcher = searcher; } public override ActionResult Index(RenderModel model) { var customModel = new ChalmersILLDiskPageModel(); _memberInfoManager.PopulateModelWithMemberData(Request, Response, customModel); if (!String.IsNullOrEmpty(Request.QueryString["query"])) { customModel.OrderItems = _searcher.Search("\"" + Request.Params["query"].Trim() + "\""); } return CurrentTemplate(customModel); } } }
Include Förlorad and Förlorad? in disk page.
using Chalmers.ILL.Members; using Chalmers.ILL.Models.Page; using Chalmers.ILL.OrderItems; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Mvc; using Umbraco.Web.Models; using Umbraco.Web.Mvc; namespace Chalmers.ILL.Controllers.SurfaceControllers.Page { public class ChalmersILLDiskPageController : RenderMvcController { IMemberInfoManager _memberInfoManager; IOrderItemSearcher _searcher; public ChalmersILLDiskPageController(IMemberInfoManager memberInfoManager, IOrderItemSearcher searcher) { _memberInfoManager = memberInfoManager; _searcher = searcher; } public override ActionResult Index(RenderModel model) { var customModel = new ChalmersILLDiskPageModel(); _memberInfoManager.PopulateModelWithMemberData(Request, Response, customModel); if (!String.IsNullOrEmpty(Request.QueryString["query"])) { customModel.OrderItems = _searcher.Search("((type:Bok AND status:(Infodisk OR Utlånad OR Transport OR Krävd)) OR (type:Artikel AND status:Transport)) AND " + "\"" + Request.Params["query"].Trim() + "\""); } return CurrentTemplate(customModel); } } }
using Chalmers.ILL.Members; using Chalmers.ILL.Models.Page; using Chalmers.ILL.OrderItems; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Mvc; using Umbraco.Web.Models; using Umbraco.Web.Mvc; namespace Chalmers.ILL.Controllers.SurfaceControllers.Page { public class ChalmersILLDiskPageController : RenderMvcController { IMemberInfoManager _memberInfoManager; IOrderItemSearcher _searcher; public ChalmersILLDiskPageController(IMemberInfoManager memberInfoManager, IOrderItemSearcher searcher) { _memberInfoManager = memberInfoManager; _searcher = searcher; } public override ActionResult Index(RenderModel model) { var customModel = new ChalmersILLDiskPageModel(); _memberInfoManager.PopulateModelWithMemberData(Request, Response, customModel); if (!String.IsNullOrEmpty(Request.QueryString["query"])) { customModel.OrderItems = _searcher.Search("((type:Bok AND status:(Infodisk OR Utlånad OR Transport OR Krävd OR Förlorad OR Förlorad\?)) OR (type:Artikel AND status:Transport)) AND " + "\"" + Request.Params["query"].Trim() + "\""); } return CurrentTemplate(customModel); } } }
Initialize TextInfo's m_textInfoName in stubbed out globalization
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.Contracts; using System.Text; namespace System.Globalization { public partial class TextInfo { ////////////////////////////////////////////////////////////////////////// //// //// TextInfo Constructors //// //// Implements CultureInfo.TextInfo. //// ////////////////////////////////////////////////////////////////////////// internal unsafe TextInfo(CultureData cultureData) { // TODO: Implement this fully. } private unsafe string ChangeCase(string s, bool toUpper) { Contract.Assert(s != null); // TODO: Implement this fully. StringBuilder sb = new StringBuilder(s.Length); for (int i = 0; i < s.Length; i++) { sb.Append(ChangeCaseAscii(s[i], toUpper)); } return sb.ToString(); } private unsafe char ChangeCase(char c, bool toUpper) { // TODO: Implement this fully. return ChangeCaseAscii(c, toUpper); } // PAL Methods end here. internal static char ChangeCaseAscii(char c, bool toUpper = true) { if (toUpper && c >= 'a' && c <= 'z') { return (char)('A' + (c - 'a')); } else if (!toUpper && c >= 'A' && c <= 'Z') { return (char)('a' + (c - 'A')); } return c; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.Contracts; using System.Text; namespace System.Globalization { public partial class TextInfo { ////////////////////////////////////////////////////////////////////////// //// //// TextInfo Constructors //// //// Implements CultureInfo.TextInfo. //// ////////////////////////////////////////////////////////////////////////// internal unsafe TextInfo(CultureData cultureData) { // TODO: Implement this fully. this.m_cultureData = cultureData; this.m_cultureName = this.m_cultureData.CultureName; this.m_textInfoName = this.m_cultureData.STEXTINFO; } private unsafe string ChangeCase(string s, bool toUpper) { Contract.Assert(s != null); // TODO: Implement this fully. StringBuilder sb = new StringBuilder(s.Length); for (int i = 0; i < s.Length; i++) { sb.Append(ChangeCaseAscii(s[i], toUpper)); } return sb.ToString(); } private unsafe char ChangeCase(char c, bool toUpper) { // TODO: Implement this fully. return ChangeCaseAscii(c, toUpper); } // PAL Methods end here. internal static char ChangeCaseAscii(char c, bool toUpper = true) { if (toUpper && c >= 'a' && c <= 'z') { return (char)('A' + (c - 'a')); } else if (!toUpper && c >= 'A' && c <= 'Z') { return (char)('a' + (c - 'A')); } return c; } } }
Fix handling empty values collection
using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using VanillaTransformer.Core.Utility; namespace VanillaTransformer.Core.ValuesProviders { public class XmlInlineConfigurationValuesProvider:IValuesProvider { private readonly XElement inlineValues; public XmlInlineConfigurationValuesProvider(XElement inlineValues) { this.inlineValues = inlineValues; } public IDictionary<string, string> GetValues() { var result = inlineValues.Elements() .Where(x => x.NodeType == XmlNodeType.Element) .ToDictionary(el => { var keyAttributeValue = el.Attribute("key")?.Value; var valueName = el.Name.LocalName; if ((valueName == "add" || valueName == "value") && string.IsNullOrWhiteSpace(keyAttributeValue) == false) { return keyAttributeValue; } return valueName; }, el => el.GetInnerXmlAsText()); return result; } } }
using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using VanillaTransformer.Core.Utility; namespace VanillaTransformer.Core.ValuesProviders { public class XmlInlineConfigurationValuesProvider:IValuesProvider { private readonly XElement inlineValues; public XmlInlineConfigurationValuesProvider(XElement inlineValues) { this.inlineValues = inlineValues; } public IDictionary<string, string> GetValues() { if (inlineValues == null) { return new Dictionary<string, string>(); } var result = inlineValues.Elements() .Where(x => x.NodeType == XmlNodeType.Element) .ToDictionary(el => { var keyAttributeValue = el.Attribute("key")?.Value; var valueName = el.Name.LocalName; if ((valueName == "add" || valueName == "value") && string.IsNullOrWhiteSpace(keyAttributeValue) == false) { return keyAttributeValue; } return valueName; }, el => el.GetInnerXmlAsText()); return result; } } }
Remove currently not used signal r documentation
namespace NuGet.Lucene.Web.Extension.Controllers { #region Usings using AspNet.WebApi.HtmlMicrodataFormatter; using NuGet.Lucene.Web.DataServices; using NuGet.Lucene.Web.Hubs; #endregion /// <summary> /// Provides documentation and semantic information about various /// resources and actions configured for use in this application. /// </summary> public class NuGetMultiRepositoryDocumentationController : DocumentationController { #region Public Properties [Ninject.Inject] public NuGetMultiRepositoryWebApiRouteMapper NuGetWebApiRouteMapper { get; set; } #endregion #region Public Methods and Operators /// <summary> /// Probably the document you are reading now. /// </summary> public override SimpleApiDocumentation GetApiDocumentation() { var docs = base.GetApiDocumentation(); docs.Add( "Packages", new SimpleApiDescription(this.Request, "OData", this.NuGetWebApiRouteMapper.ODataRoutePath) { Documentation = this .DocumentationProvider .GetDocumentation ( typeof ( PackageDataService )) }); docs.Add( "Indexing", new SimpleApiDescription(this.Request, "Hub", this.NuGetWebApiRouteMapper.SignalrRoutePath) { Documentation = this .DocumentationProvider .GetDocumentation ( typeof ( StatusHub )) }); return docs; } #endregion } }
namespace NuGet.Lucene.Web.Extension.Controllers { #region Usings using AspNet.WebApi.HtmlMicrodataFormatter; using NuGet.Lucene.Web.DataServices; using NuGet.Lucene.Web.Hubs; #endregion /// <summary> /// Provides documentation and semantic information about various /// resources and actions configured for use in this application. /// </summary> public class NuGetMultiRepositoryDocumentationController : DocumentationController { #region Public Properties [Ninject.Inject] public NuGetMultiRepositoryWebApiRouteMapper NuGetWebApiRouteMapper { get; set; } #endregion #region Public Methods and Operators /// <summary> /// Probably the document you are reading now. /// </summary> public override SimpleApiDocumentation GetApiDocumentation() { var docs = base.GetApiDocumentation(); docs.Add( "Packages", new SimpleApiDescription(this.Request, "OData", this.NuGetWebApiRouteMapper.ODataRoutePath) { Documentation = this .DocumentationProvider .GetDocumentation ( typeof ( PackageDataService )) }); return docs; } #endregion } }
Fix screen breadcrumb control updating on click
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Screens; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A <see cref="BreadcrumbControl{IScreen}"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack. /// </summary> public class ScreenBreadcrumbControl : BreadcrumbControl<IScreen> { public ScreenBreadcrumbControl(ScreenStack stack) { stack.ScreenPushed += onPushed; stack.ScreenExited += onExited; if (stack.CurrentScreen != null) onPushed(null, stack.CurrentScreen); Current.ValueChanged += current => current.NewValue.MakeCurrent(); } private void onPushed(IScreen lastScreen, IScreen newScreen) { AddItem(newScreen); Current.Value = newScreen; } private void onExited(IScreen lastScreen, IScreen newScreen) { if (newScreen != null) Current.Value = newScreen; Items.ToList().SkipWhile(s => s != Current.Value).Skip(1).ForEach(RemoveItem); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics.UserInterface; using osu.Framework.Screens; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A <see cref="BreadcrumbControl{IScreen}"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack. /// </summary> public class ScreenBreadcrumbControl : BreadcrumbControl<IScreen> { public ScreenBreadcrumbControl(ScreenStack stack) { stack.ScreenPushed += onPushed; stack.ScreenExited += onExited; if (stack.CurrentScreen != null) onPushed(null, stack.CurrentScreen); } protected override void SelectTab(TabItem<IScreen> tab) { // override base method to prevent current item from being changed on click. // depend on screen push/exit to change current item instead. tab.Value.MakeCurrent(); } private void onPushed(IScreen lastScreen, IScreen newScreen) { AddItem(newScreen); Current.Value = newScreen; } private void onExited(IScreen lastScreen, IScreen newScreen) { if (newScreen != null) Current.Value = newScreen; Items.ToList().SkipWhile(s => s != Current.Value).Skip(1).ForEach(RemoveItem); } } }
Rearrange values in numeric order.
using System; namespace MySql.Data.MySqlClient { public enum MySqlDbType { Decimal, Byte, Int16, Int24 = 9, Int32 = 3, Int64 = 8, Float = 4, Double, Timestamp = 7, Date = 10, Time, DateTime, [Obsolete("The Datetime enum value is obsolete. Please use DateTime.")] Datetime = 12, Year, Newdate, VarString, Bit, JSON = 245, NewDecimal, Enum, Set, TinyBlob, MediumBlob, LongBlob, Blob, VarChar, String, Geometry, UByte = 501, UInt16, UInt24 = 509, UInt32 = 503, UInt64 = 508, Binary = 600, VarBinary, TinyText = 749, MediumText, LongText, Text, Guid = 800 } }
using System; namespace MySql.Data.MySqlClient { public enum MySqlDbType { Decimal, Byte, Int16, Int32, Float, Double, Timestamp = 7, Int64, Int24, Date, Time, DateTime, [Obsolete("The Datetime enum value is obsolete. Please use DateTime.")] Datetime = 12, Year, Newdate, VarString, Bit, JSON = 245, NewDecimal, Enum, Set, TinyBlob, MediumBlob, LongBlob, Blob, VarChar, String, Geometry, UByte = 501, UInt16, UInt32, UInt64 = 508, UInt24, Binary = 600, VarBinary, TinyText = 749, MediumText, LongText, Text, Guid = 800 } }
Remove votes when changing poll type
using System; using System.Linq; using System.Net; using System.Web.Http; using VotingApplication.Data.Context; using VotingApplication.Data.Model; using VotingApplication.Web.Api.Models.DBViewModels; namespace VotingApplication.Web.Api.Controllers { public class ManagePollTypeController : WebApiController { public ManagePollTypeController() : base() { } public ManagePollTypeController(IContextFactory contextFactory) : base(contextFactory) { } [HttpPut] public void Put(Guid manageId, ManagePollTypeRequest updateRequest) { using (var context = _contextFactory.CreateContext()) { Poll poll = context.Polls.Where(p => p.ManageId == manageId).SingleOrDefault(); if (poll == null) { ThrowError(HttpStatusCode.NotFound, string.Format("Poll for manage id {0} not found", manageId)); } if (!ModelState.IsValid) { ThrowError(HttpStatusCode.BadRequest, ModelState); } poll.PollType = (PollType)Enum.Parse(typeof(PollType), updateRequest.PollType, true); poll.MaxPerVote = updateRequest.MaxPerVote; poll.MaxPoints = updateRequest.MaxPoints; poll.LastUpdated = DateTime.Now; context.SaveChanges(); } } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Net; using System.Web.Http; using VotingApplication.Data.Context; using VotingApplication.Data.Model; using VotingApplication.Web.Api.Models.DBViewModels; namespace VotingApplication.Web.Api.Controllers { public class ManagePollTypeController : WebApiController { public ManagePollTypeController() : base() { } public ManagePollTypeController(IContextFactory contextFactory) : base(contextFactory) { } [HttpPut] public void Put(Guid manageId, ManagePollTypeRequest updateRequest) { using (var context = _contextFactory.CreateContext()) { Poll poll = context.Polls.Where(p => p.ManageId == manageId).SingleOrDefault(); if (poll == null) { ThrowError(HttpStatusCode.NotFound, string.Format("Poll for manage id {0} not found", manageId)); } if (!ModelState.IsValid) { ThrowError(HttpStatusCode.BadRequest, ModelState); } if (updateRequest.PollType.ToLower() != poll.PollType.ToString().ToLower()) { List<Vote> removedVotes = context.Votes.Include(v => v.Poll) .Where(v => v.Poll.UUID == poll.UUID) .ToList(); foreach (Vote oldVote in removedVotes) { context.Votes.Remove(oldVote); } poll.PollType = (PollType)Enum.Parse(typeof(PollType), updateRequest.PollType, true); poll.MaxPerVote = updateRequest.MaxPerVote; } poll.MaxPoints = updateRequest.MaxPoints; poll.LastUpdated = DateTime.Now; context.SaveChanges(); } } } }
Clean up type scanner and remove lazy initialization of assembly types
using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Conventional { public class TypeScanner : ITypeScanner { private readonly ITypeSource _typeSource; private readonly IList<IConvention> _conventions = new List<IConvention>(); public TypeScanner(ITypeSource typeSource) { _typeSource = typeSource; } public void AddConvention(IConvention convention) { _conventions.Add(convention); } internal void Run(Func<Type, Action<Type>> installers) { var types = _typeSource.GetTypes().ToList(); foreach (var convention in _conventions) foreach (var type in types) if (convention.Matches(type)) installers(convention.GetType())(type); } internal IEnumerable<Registration> GetRegistrations() { var types = new Lazy<IEnumerable<Type>>(() => _typeSource.GetTypes().ToList(), LazyThreadSafetyMode.ExecutionAndPublication); return from c in _conventions.AsParallel().AsOrdered() let ct = c.GetType() from t in types.Value where c.Matches(t) select new Registration(ct, t); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Conventional { public class TypeScanner : ITypeScanner { private readonly ITypeSource _typeSource; private readonly IList<IConvention> _conventions = new List<IConvention>(); public TypeScanner(ITypeSource typeSource) { _typeSource = typeSource; } public void AddConvention(IConvention convention) { _conventions.Add(convention); } internal IEnumerable<Registration> GetRegistrations() { var types = _typeSource.GetTypes().ToList(); return from c in _conventions.AsParallel().AsOrdered() let ct = c.GetType() from t in types where c.Matches(t) select new Registration(ct, t); } } }
Fix navigation to Overview after deleting LocalClient.
using Neptuo.Observables.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebCamImageCollector.RemoteControl.Services; using WebCamImageCollector.RemoteControl.Views; namespace WebCamImageCollector.RemoteControl.ViewModels.Commands { public class DeleteLocalCommand : NavigateCommand { public DeleteLocalCommand() : base(typeof(Overview)) { } public override bool CanExecute() { return true; } public override void Execute() { ClientRepository repository = new ClientRepository(); repository.DeleteLocal(); } } }
using Neptuo.Observables.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebCamImageCollector.RemoteControl.Services; using WebCamImageCollector.RemoteControl.Views; namespace WebCamImageCollector.RemoteControl.ViewModels.Commands { public class DeleteLocalCommand : NavigateCommand { public DeleteLocalCommand() : base(typeof(Overview)) { } public override bool CanExecute() { return true; } public override void Execute() { ClientRepository repository = new ClientRepository(); repository.DeleteLocal(); base.Execute(); } } }
Use MainAsync instead of Main
namespace Sandbox { public class Program { public static void Main() { } } }
using System.Threading.Tasks; namespace Sandbox { public class Program { public static void Main() => new Program().MainAsync().GetAwaiter().GetResult(); private async Task MainAsync() { } } }
Fix bug in the StringCollection converter when DataServicePackage.Authors is a simple string.
using System; using System.Collections.Generic; using System.Windows.Data; namespace NuPack.Dialog.PackageManagerUI { public class StringCollectionsToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType == typeof(string)) { IEnumerable<string> parts = (IEnumerable<string>)value; return String.Join(", ", parts); } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Windows.Data; namespace NuPack.Dialog.PackageManagerUI { public class StringCollectionsToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType == typeof(string)) { string stringValue = value as string; if (stringValue != null) { return stringValue; } else { IEnumerable<string> parts = (IEnumerable<string>)value; return String.Join(", ", parts); } } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
Add method to add paragraph to section
using System.Collections.Generic; using System.Runtime.CompilerServices; namespace SharpLayout { public class Section { public PageSettings PageSettings { get; } public List<Table> Tables { get; } = new List<Table>(); public Section(PageSettings pageSettings) { PageSettings = pageSettings; } public Table AddTable([CallerLineNumber] int line = 0) { var table = new Table(line); Tables.Add(table); return table; } } }
using System.Collections.Generic; using System.Runtime.CompilerServices; namespace SharpLayout { public class Section { public PageSettings PageSettings { get; } public List<Table> Tables { get; } = new List<Table>(); public Section(PageSettings pageSettings) { PageSettings = pageSettings; } public Table AddTable([CallerLineNumber] int line = 0) { var table = new Table(line); Tables.Add(table); return table; } public Section Add(Paragraph paragraph, [CallerLineNumber] int line = 0, [CallerFilePath] string filePath = "") { var table = AddTable(); var c1 = table.AddColumn(PageSettings.PageWidthWithoutMargins); var r1 = table.AddRow(); r1[c1, line, filePath].Add(paragraph); return this; } } }