Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Return File() result (file on the server).
using System.Web.Mvc; namespace OdeToFood.Controllers { public class CuisineController : Controller { // // GET: /Cuisine/ // Including parameter named "name" causes MVC framework to try to // find a parameter named "name" in ANY of the web request (routing // data, query string or posted form data). public ActionResult Search(string name = "french") { // HtmlEncode prevents cross-site scripting attack. (Razor will // prevent this but a call to Content() assumes you know what // you are doing. You have been warned! var encodedName = Server.HtmlEncode(name); return RedirectToRoute("Default", new {controller = "Home", action = "About"}); } } }
using System.Net; using System.Web.Mvc; namespace OdeToFood.Controllers { public class CuisineController : Controller { // // GET: /Cuisine/ // Including parameter named "name" causes MVC framework to try to // find a parameter named "name" in ANY of the web request (routing // data, query string or posted form data). public ActionResult Search(string name = "french") { // Server.MapPath() converts from virtual path to actual path on // the **server** filesystem. The symbol ~ identifies the // application root (OdeToFood). var encodedName = Server.HtmlEncode(name); return File(Server.MapPath("~/Content/Site.css"), "text/css"); } } }
Add more reporters by default
using System; using System.Collections.Generic; using Assent.Reporters.DiffPrograms; namespace Assent.Reporters { public class DiffReporter : IReporter { #if NET45 internal static readonly bool IsWindows = Environment.OSVersion.Platform == PlatformID.Win32NT; #else internal static readonly bool IsWindows = System.Runtime.InteropServices.RuntimeInformation .IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows); #endif static DiffReporter() { DefaultDiffPrograms = IsWindows ? new IDiffProgram[] { new BeyondCompareDiffProgram(), new KDiff3DiffProgram(), new XdiffDiffProgram() } : new IDiffProgram[] { new VsCodeDiffProgram(), }; } public static readonly IReadOnlyList<IDiffProgram> DefaultDiffPrograms; private readonly IReadOnlyList<IDiffProgram> _diffPrograms; public DiffReporter() : this(DefaultDiffPrograms) { } public DiffReporter(IReadOnlyList<IDiffProgram> diffPrograms) { _diffPrograms = diffPrograms; } public void Report(string receivedFile, string approvedFile) { foreach (var program in _diffPrograms) if (program.Launch(receivedFile, approvedFile)) return; throw new Exception("Could not find a diff program to use"); } } }
using System; using System.Collections.Generic; using Assent.Reporters.DiffPrograms; namespace Assent.Reporters { public class DiffReporter : IReporter { #if NET45 internal static readonly bool IsWindows = Environment.OSVersion.Platform == PlatformID.Win32NT; #else internal static readonly bool IsWindows = System.Runtime.InteropServices.RuntimeInformation .IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows); #endif static DiffReporter() { DefaultDiffPrograms = IsWindows ? new IDiffProgram[] { new BeyondCompareDiffProgram(), new KDiff3DiffProgram(), new XdiffDiffProgram(), new P4MergeDiffProgram(), new VsCodeDiffProgram() } : new IDiffProgram[] { new VsCodeDiffProgram() }; } public static readonly IReadOnlyList<IDiffProgram> DefaultDiffPrograms; private readonly IReadOnlyList<IDiffProgram> _diffPrograms; public DiffReporter() : this(DefaultDiffPrograms) { } public DiffReporter(IReadOnlyList<IDiffProgram> diffPrograms) { _diffPrograms = diffPrograms; } public void Report(string receivedFile, string approvedFile) { foreach (var program in _diffPrograms) if (program.Launch(receivedFile, approvedFile)) return; throw new Exception("Could not find a diff program to use"); } } }
Put Squirrel updater behind conditional compilation flag
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.ResourceDownloading; using Squirrel; using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Threading; using System.Xml; namespace OpenLiveWriter.PostEditor.Updates { public class UpdateManager { public static DateTime Expires = DateTime.MaxValue; public static void CheckforUpdates(bool forceCheck = false) { var checkNow = forceCheck || UpdateSettings.AutoUpdate; var downloadUrl = UpdateSettings.CheckForBetaUpdates ? UpdateSettings.BetaUpdateDownloadUrl : UpdateSettings.UpdateDownloadUrl; // Schedule Open Live Writer 10 seconds after the launch var delayUpdate = new DelayUpdateHelper(UpdateOpenLiveWriter(downloadUrl, checkNow), UPDATELAUNCHDELAY); delayUpdate.StartBackgroundUpdate("Background OpenLiveWriter application update"); } private static ThreadStart UpdateOpenLiveWriter(string downloadUrl, bool checkNow) { return async () => { if (checkNow) { try { using (var manager = new Squirrel.UpdateManager(downloadUrl)) { await manager.UpdateApp(); } } catch (Exception ex) { Trace.WriteLine("Unexpected error while updating Open Live Writer. " + ex); } } }; } private const int UPDATELAUNCHDELAY = 10000; } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.ResourceDownloading; using Squirrel; using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Threading; using System.Xml; namespace OpenLiveWriter.PostEditor.Updates { public class UpdateManager { public static DateTime Expires = DateTime.MaxValue; public static void CheckforUpdates(bool forceCheck = false) { #if !DesktopUWP // Update using Squirrel if not a Desktop UWP package var checkNow = forceCheck || UpdateSettings.AutoUpdate; var downloadUrl = UpdateSettings.CheckForBetaUpdates ? UpdateSettings.BetaUpdateDownloadUrl : UpdateSettings.UpdateDownloadUrl; // Schedule Open Live Writer 10 seconds after the launch var delayUpdate = new DelayUpdateHelper(UpdateOpenLiveWriter(downloadUrl, checkNow), UPDATELAUNCHDELAY); delayUpdate.StartBackgroundUpdate("Background OpenLiveWriter application update"); #endif } private static ThreadStart UpdateOpenLiveWriter(string downloadUrl, bool checkNow) { return async () => { if (checkNow) { try { using (var manager = new Squirrel.UpdateManager(downloadUrl)) { await manager.UpdateApp(); } } catch (Exception ex) { Trace.WriteLine("Unexpected error while updating Open Live Writer. " + ex); } } }; } private const int UPDATELAUNCHDELAY = 10000; } }
Stop using [Timeout] so that there should be no thread abort on the test thread
#if !NETSTANDARD1_3 && !NETSTANDARD1_6 using System.Runtime.InteropServices; using System.Threading; namespace NUnit.Framework.Internal { [TestFixture] public class ThreadUtilityTests { [Platform("Win")] [Timeout(1000)] [TestCase(false, TestName = "Abort")] [TestCase(true, TestName = "Kill")] public void AbortOrKillThreadWithMessagePump(bool kill) { using (var isThreadAboutToWait = new ManualResetEvent(false)) { var nativeId = 0; var thread = new Thread(() => { nativeId = ThreadUtility.GetCurrentThreadNativeId(); isThreadAboutToWait.Set(); while (true) WaitMessage(); }); thread.Start(); isThreadAboutToWait.WaitOne(); Thread.Sleep(1); if (kill) ThreadUtility.Kill(thread, nativeId); else ThreadUtility.Abort(thread, nativeId); thread.Join(); } } [DllImport("user32.dll")] private static extern bool WaitMessage(); } } #endif
#if !NETSTANDARD1_3 && !NETSTANDARD1_6 using System.Runtime.InteropServices; using System.Threading; namespace NUnit.Framework.Internal { [TestFixture] public class ThreadUtilityTests { [Platform("Win")] [TestCase(false, TestName = "Abort")] [TestCase(true, TestName = "Kill")] public void AbortOrKillThreadWithMessagePump(bool kill) { using (var isThreadAboutToWait = new ManualResetEvent(false)) { var nativeId = 0; var thread = new Thread(() => { nativeId = ThreadUtility.GetCurrentThreadNativeId(); isThreadAboutToWait.Set(); while (true) WaitMessage(); }); thread.Start(); isThreadAboutToWait.WaitOne(); Thread.Sleep(1); if (kill) ThreadUtility.Kill(thread, nativeId); else ThreadUtility.Abort(thread, nativeId); Assert.That(thread.Join(1000), "Native message pump was not able to be interrupted to enable a managed thread abort."); } } [DllImport("user32.dll")] private static extern bool WaitMessage(); } } #endif
Disable local hover in cloud env
// 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo { [ContentType(ContentTypeNames.RoslynContentType)] [Export(typeof(IAsyncQuickInfoSourceProvider))] [Name("RoslynQuickInfoProvider")] internal partial class QuickInfoSourceProvider : IAsyncQuickInfoSourceProvider { private readonly IThreadingContext _threadingContext; private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public QuickInfoSourceProvider( IThreadingContext threadingContext, Lazy<IStreamingFindUsagesPresenter> streamingPresenter) { _threadingContext = threadingContext; _streamingPresenter = streamingPresenter; } public IAsyncQuickInfoSource TryCreateQuickInfoSource(ITextBuffer textBuffer) => new QuickInfoSource(textBuffer, _threadingContext, _streamingPresenter); } }
// 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo { [ContentType(ContentTypeNames.RoslynContentType)] [Export(typeof(IAsyncQuickInfoSourceProvider))] [Name("RoslynQuickInfoProvider")] internal partial class QuickInfoSourceProvider : IAsyncQuickInfoSourceProvider { private readonly IThreadingContext _threadingContext; private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public QuickInfoSourceProvider( IThreadingContext threadingContext, Lazy<IStreamingFindUsagesPresenter> streamingPresenter) { _threadingContext = threadingContext; _streamingPresenter = streamingPresenter; } public IAsyncQuickInfoSource TryCreateQuickInfoSource(ITextBuffer textBuffer) { if (textBuffer.IsInCloudEnvironmentClientContext()) { return null; } return new QuickInfoSource(textBuffer, _threadingContext, _streamingPresenter); } } }
Fix chainedresult to actually chain the results if there are more than 2
using LogicalShift.Reason.Api; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LogicalShift.Reason.Solvers { /// <summary> /// A query result where the next result is retrieved by a function /// </summary> public class ChainedResult : IQueryResult { /// <summary> /// A query result that stores the results for this query /// </summary> private readonly IQueryResult _basicResult; /// <summary> /// A function that retrieves the next query result /// </summary> private readonly Func<Task<IQueryResult>> _nextResult; public ChainedResult(IQueryResult basicResult, Func<Task<IQueryResult>> nextResult) { if (basicResult == null) throw new ArgumentNullException("basicResult"); if (nextResult == null) throw new ArgumentNullException("nextResult"); _basicResult = basicResult; _nextResult = nextResult; } public bool Success { get { return _basicResult.Success; } } public IBindings Bindings { get { return _basicResult.Bindings; } } public Task<IQueryResult> Next() { return _nextResult(); } } }
using LogicalShift.Reason.Api; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LogicalShift.Reason.Solvers { /// <summary> /// A query result where the next result is retrieved by a function /// </summary> public class ChainedResult : IQueryResult { /// <summary> /// A query result that stores the results for this query /// </summary> private readonly IQueryResult _basicResult; /// <summary> /// A function that retrieves the next query result /// </summary> private readonly Func<Task<IQueryResult>> _nextResult; public ChainedResult(IQueryResult basicResult, Func<Task<IQueryResult>> nextResult) { if (basicResult == null) throw new ArgumentNullException("basicResult"); if (nextResult == null) throw new ArgumentNullException("nextResult"); _basicResult = basicResult; _nextResult = nextResult; } public bool Success { get { return _basicResult.Success; } } public IBindings Bindings { get { return _basicResult.Bindings; } } public async Task<IQueryResult> Next() { return new ChainedResult(await _nextResult(), _nextResult); } } }
Update comment about when a section view can't be removed
using System; using System.Reactive.Disposables; using SolidWorks.Interop.sldworks; namespace SolidworksAddinFramework { public static class ModelViewManagerExtensions { public static IDisposable CreateSectionView(this IModelViewManager modelViewManager, Action<SectionViewData> config) { var data = modelViewManager.CreateSectionViewData(); config(data); if (!modelViewManager.CreateSectionView(data)) { throw new Exception("Error while creating section view."); } // TODO `modelViewManager.RemoveSectionView` always returns `false` and doesn't remove the section view // In 2011 this seems to have worked (see https://forum.solidworks.com/thread/47641) return Disposable.Create(() => modelViewManager.RemoveSectionView()); } } }
using System; using System.Reactive.Disposables; using SolidWorks.Interop.sldworks; namespace SolidworksAddinFramework { public static class ModelViewManagerExtensions { public static IDisposable CreateSectionView(this IModelViewManager modelViewManager, Action<SectionViewData> config) { var data = modelViewManager.CreateSectionViewData(); config(data); if (!modelViewManager.CreateSectionView(data)) { throw new Exception("Error while creating section view."); } // TODO `modelViewManager.RemoveSectionView` returns `false` and doesn't remove the section view // when `SectionViewData::GraphicsOnlySection` is `true` return Disposable.Create(() => modelViewManager.RemoveSectionView()); } } }
Fix Typo in Unix Lock/Unlock PAL
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { internal enum LockType : short { F_UNLCK = 2, // unlock F_WRLCK = 3 // exclusive or write lock } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LockFileRegion", SetLastError=true)] internal static extern int LockFileRegion(SafeHandle fd, long offset, long length, LockType lockType); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { internal enum LockType : short { F_WRLCK = 1, // exclusive or write lock F_UNLCK = 2 // unlock } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LockFileRegion", SetLastError=true)] internal static extern int LockFileRegion(SafeHandle fd, long offset, long length, LockType lockType); } }
Allow redirectUrl and custom layout on home page
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using wwwplatform.Extensions; using wwwplatform.Models; namespace wwwplatform.Controllers { public class HomeController : BaseController { public ActionResult Index() { var page = SitePage.GetAvailablePages(db, User, UserManager, RoleManager, true, false, false).Where(p => p.HomePage == true).FirstOrDefault(); if (page == null) { if (db.ActiveSitePages.Where(p => p.HomePage == true).Any()) { return new HttpUnauthorizedResult("Access Denied"); } return RedirectToAction("Setup"); } return View(page); } public ActionResult Setup() { return View(); } public ActionResult Upgrade() { ApplicationDbContext.Upgrade(); return RedirectToAction("Index"); } public ActionResult Uninstall() { if (Request.IsLocal) { var config = new Migrations.Configuration(); config.Uninstall(db); } return RedirectToAction("Index"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using wwwplatform.Extensions; using wwwplatform.Models; namespace wwwplatform.Controllers { public class HomeController : BaseController { public ActionResult Index() { var page = SitePage.GetAvailablePages(db, User, UserManager, RoleManager, true, false, false).Where(p => p.HomePage == true).FirstOrDefault(); if (page == null) { if (db.ActiveSitePages.Where(p => p.HomePage == true).Any()) { return new HttpUnauthorizedResult("Access Denied"); } return RedirectToAction("Setup"); } if (!string.IsNullOrEmpty(page.RedirectUrl)) { return Redirect(page.RedirectUrl); } ViewBag.Layout = page.Layout; return View(page); } public ActionResult Setup() { return View(); } public ActionResult Upgrade() { ApplicationDbContext.Upgrade(); return RedirectToAction("Index"); } public ActionResult Uninstall() { if (Request.IsLocal) { var config = new Migrations.Configuration(); config.Uninstall(db); } return RedirectToAction("Index"); } } }
Handle null id for Cars/Details action
using CarFuel.Models; using CarFuel.Services; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using CarFuel.DataAccess; namespace CarFuel.Controllers { public class CarsController : Controller { //private static List<Car> cars = new List<Car>(); private ICarDb db; private CarService carService; public CarsController() { db = new CarDb(); carService = new CarService(db); } [Authorize] public ActionResult Index() { var userId = new Guid(User.Identity.GetUserId()); IEnumerable<Car> cars = carService.GetCarsByMember(userId); return View(cars); } [Authorize] public ActionResult Create() { return View(); } [HttpPost] [Authorize] public ActionResult Create(Car item) { var userId = new Guid(User.Identity.GetUserId()); try { carService.AddCar(item, userId); } catch (OverQuotaException ex) { TempData["error"] = ex.Message; } return RedirectToAction("Index"); } public ActionResult Details(Guid Id) { var userId = new Guid(User.Identity.GetUserId()); var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == Id); return View(c); } } }
using CarFuel.Models; using CarFuel.Services; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using CarFuel.DataAccess; using System.Net; namespace CarFuel.Controllers { public class CarsController : Controller { //private static List<Car> cars = new List<Car>(); private ICarDb db; private CarService carService; public CarsController() { db = new CarDb(); carService = new CarService(db); } [Authorize] public ActionResult Index() { var userId = new Guid(User.Identity.GetUserId()); IEnumerable<Car> cars = carService.GetCarsByMember(userId); return View(cars); } [Authorize] public ActionResult Create() { return View(); } [HttpPost] [Authorize] public ActionResult Create(Car item) { var userId = new Guid(User.Identity.GetUserId()); try { carService.AddCar(item, userId); } catch (OverQuotaException ex) { TempData["error"] = ex.Message; } return RedirectToAction("Index"); } public ActionResult Details(Guid? Id) { if (Id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadGateway); } var userId = new Guid(User.Identity.GetUserId()); var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == Id); return View(c); } } }
Add integration test for same.
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Box.V2.Models; using System.Threading.Tasks; namespace Box.V2.Test.Integration { [TestClass] public class BoxUsersManagerTestIntegration : BoxResourceManagerTestIntegration { [TestMethod] public async Task UsersInformation_LiveSession_ValidResponse() { BoxUser user = await _client.UsersManager.GetCurrentUserInformationAsync(); Assert.AreEqual("215917383", user.Id); Assert.AreEqual("Box Windows", user.Name); Assert.AreEqual("boxwinintegration@gmail.com", user.Login, true); } } }
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Box.V2.Models; using System.Threading.Tasks; namespace Box.V2.Test.Integration { [TestClass] public class BoxUsersManagerTestIntegration : BoxResourceManagerTestIntegration { [TestMethod] public async Task UsersInformation_LiveSession_ValidResponse() { BoxUser user = await _client.UsersManager.GetCurrentUserInformationAsync(); Assert.AreEqual("215917383", user.Id); Assert.AreEqual("Box Windows", user.Name); Assert.AreEqual("boxwinintegration@gmail.com", user.Login, true); } [TestMethod] public async Task EnterpriseUsersInformation_LiveSession_ValidResponse() { BoxCollection<BoxUser> users = await _client.UsersManager.GetEnterpriseUsersAsync("jhoerr"); Assert.AreEqual(users.TotalCount, 1); Assert.AreEqual(users.Entries.First().Name, "John Hoerr"); Assert.AreEqual(users.Entries.First().Login, "jhoerr@iu.edu"); } } }
Fix editor crashing when loading a beatmap for an unsupported ruleset
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Edit; using osu.Game.Screens.Edit.Compose.Components.Timeline; using osu.Game.Skinning; namespace osu.Game.Screens.Edit.Compose { public class ComposeScreen : EditorScreenWithTimeline { private HitObjectComposer composer; protected override Drawable CreateMainContent() { var ruleset = Beatmap.Value.BeatmapInfo.Ruleset?.CreateInstance(); composer = ruleset?.CreateHitObjectComposer(); if (ruleset == null || composer == null) return new ScreenWhiteBox.UnderConstructionMessage(ruleset == null ? "This beatmap" : $"{ruleset.Description}'s composer"); var beatmapSkinProvider = new BeatmapSkinProvidingContainer(Beatmap.Value.Skin); // the beatmapSkinProvider is used as the fallback source here to allow the ruleset-specific skin implementation // full access to all skin sources. var rulesetSkinProvider = new SkinProvidingContainer(ruleset.CreateLegacySkinProvider(beatmapSkinProvider)); // load the skinning hierarchy first. // this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources. return beatmapSkinProvider.WithChild(rulesetSkinProvider.WithChild(composer)); } protected override Drawable CreateTimelineContent() => new TimelineHitObjectDisplay(composer.EditorBeatmap); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Edit; using osu.Game.Screens.Edit.Compose.Components.Timeline; using osu.Game.Skinning; namespace osu.Game.Screens.Edit.Compose { public class ComposeScreen : EditorScreenWithTimeline { private HitObjectComposer composer; protected override Drawable CreateMainContent() { var ruleset = Beatmap.Value.BeatmapInfo.Ruleset?.CreateInstance(); composer = ruleset?.CreateHitObjectComposer(); if (ruleset == null || composer == null) return new ScreenWhiteBox.UnderConstructionMessage(ruleset == null ? "This beatmap" : $"{ruleset.Description}'s composer"); var beatmapSkinProvider = new BeatmapSkinProvidingContainer(Beatmap.Value.Skin); // the beatmapSkinProvider is used as the fallback source here to allow the ruleset-specific skin implementation // full access to all skin sources. var rulesetSkinProvider = new SkinProvidingContainer(ruleset.CreateLegacySkinProvider(beatmapSkinProvider)); // load the skinning hierarchy first. // this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources. return beatmapSkinProvider.WithChild(rulesetSkinProvider.WithChild(composer)); } protected override Drawable CreateTimelineContent() => composer == null ? base.CreateTimelineContent() : new TimelineHitObjectDisplay(composer.EditorBeatmap); } }
Make Master/Detail sample not rely on WPF magic
using System; namespace Stylet.Samples.MasterDetail { public class EmployeeModel { public string Name { get; set; } } }
using System; namespace Stylet.Samples.MasterDetail { public class EmployeeModel : PropertyChangedBase { private string _name; public string Name { get { return this._name; } set { this.SetAndNotify(ref this._name, value); } } } }
Handle case where no facts are published.
using System.Threading.Tasks; using System.Web.Mvc; using DancingGoat.Models; using System.Collections.Generic; namespace DancingGoat.Controllers { public class AboutController : ControllerBase { public async Task<ActionResult> Index() { var response = await client.GetItemAsync<AboutUs>("about_us"); var viewModel = new AboutUsViewModel { FactViewModels = new List<FactAboutUsViewModel>() }; int i = 0; foreach (var fact in response.Item?.Facts) { var factViewModel = new FactAboutUsViewModel { Fact = (FactAboutUs)fact }; if (i++ % 2 == 0) { factViewModel.Odd = true; } viewModel.FactViewModels.Add(factViewModel); } return View(viewModel); } } }
using System.Threading.Tasks; using System.Web.Mvc; using DancingGoat.Models; using System.Collections.Generic; using KenticoCloud.Delivery; namespace DancingGoat.Controllers { public class AboutController : ControllerBase { public async Task<ActionResult> Index() { var response = await client.GetItemAsync<AboutUs>("about_us"); var viewModel = new AboutUsViewModel { FactViewModels = MapFactsAboutUs(response) }; return View(viewModel); } private IList<FactAboutUsViewModel> MapFactsAboutUs(DeliveryItemResponse<AboutUs> response) { var facts = new List<FactAboutUsViewModel>(); if (response.Item == null) { return facts; } int i = 0; foreach (var fact in response.Item.Facts) { var factViewModel = new FactAboutUsViewModel { Fact = (FactAboutUs)fact }; if (i++ % 2 == 0) { factViewModel.Odd = true; } facts.Add(factViewModel); } return facts; } } }
Set Version Numer for 3.0.3.1
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SiteWarmer.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SiteWarmer.Core")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f28abe61-e729-4553-b910-8604c9046a97")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.0.4.0")] [assembly: AssemblyFileVersion("3.0.4.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SiteWarmer.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SiteWarmer.Core")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f28abe61-e729-4553-b910-8604c9046a97")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.0.3.1")] [assembly: AssemblyFileVersion("3.0.3.1")]
Make way for future improvements
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2015, MPL Ali Taheri Moghaddar ali.taheri.m@gmail.com */ namespace Pablo.Graphics { /// <summary> /// Determines the pattern of a line. /// </summary> public enum StrokeType { /// <summary> /// This produces a solid continuous line. /// </summary> Solid, /// <summary> /// This produces a dashed line. /// </summary> Dashed, /// <summary> /// This produces a dash-dotted line. /// </summary> DashDot, } }
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2015, MPL Ali Taheri Moghaddar ali.taheri.m@gmail.com */ namespace Pablo.Graphics { /// <summary> /// Determines the pattern of a line. /// </summary> public enum StrokeType { /// <summary> /// This produces a solid continuous line. /// </summary> Solid, /// <summary> /// This produces a dashed line. /// </summary> Dashed, /// <summary> /// This produces a zigzag line. /// </summary> Zigzag, } }
Set Default-LogLevel to Debug since Trace isn't really logged onto the console.
using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace ExRam.Gremlinq.Providers.WebSocket { public readonly struct QueryLoggingOptions { public static readonly QueryLoggingOptions Default = new QueryLoggingOptions(LogLevel.Trace, QueryLoggingVerbosity.QueryOnly, Formatting.None); public QueryLoggingOptions(LogLevel logLevel, QueryLoggingVerbosity verbosity, Formatting formatting) { LogLevel = logLevel; Verbosity = verbosity; Formatting = formatting; } public QueryLoggingOptions SetLogLevel(LogLevel logLevel) { return new QueryLoggingOptions(logLevel, Verbosity, Formatting); } public QueryLoggingOptions SetQueryLoggingVerbosity(QueryLoggingVerbosity verbosity) { return new QueryLoggingOptions(LogLevel, verbosity, Formatting); } public QueryLoggingOptions SetFormatting(Formatting formatting) { return new QueryLoggingOptions(LogLevel, Verbosity, formatting); } public LogLevel LogLevel { get; } public Formatting Formatting { get; } public QueryLoggingVerbosity Verbosity { get; } } }
using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace ExRam.Gremlinq.Providers.WebSocket { public readonly struct QueryLoggingOptions { public static readonly QueryLoggingOptions Default = new QueryLoggingOptions(LogLevel.Debug, QueryLoggingVerbosity.QueryOnly, Formatting.None); public QueryLoggingOptions(LogLevel logLevel, QueryLoggingVerbosity verbosity, Formatting formatting) { LogLevel = logLevel; Verbosity = verbosity; Formatting = formatting; } public QueryLoggingOptions SetLogLevel(LogLevel logLevel) { return new QueryLoggingOptions(logLevel, Verbosity, Formatting); } public QueryLoggingOptions SetQueryLoggingVerbosity(QueryLoggingVerbosity verbosity) { return new QueryLoggingOptions(LogLevel, verbosity, Formatting); } public QueryLoggingOptions SetFormatting(Formatting formatting) { return new QueryLoggingOptions(LogLevel, Verbosity, formatting); } public LogLevel LogLevel { get; } public Formatting Formatting { get; } public QueryLoggingVerbosity Verbosity { get; } } }
Fix tournament POST not wrapping return value in an object.
using System; using System.Linq; using System.Web.Http; using Peregrine.Data; namespace Peregrine.Web.Controllers { [RoutePrefix("api/tournaments")] public class TournamentsController : ApiController { [Route] public IHttpActionResult Get() { using(var dataContext = new DataContext()) { var tournamentKeys = dataContext .Tournaments .Select(tournament => tournament.Key) .ToArray(); return Ok(new { keys = tournamentKeys, }); } } [Route] public IHttpActionResult Post() { using(var dataContext = new DataContext()) { var tournament = dataContext .Tournaments .Add(new Tournament { Key = Guid.NewGuid(), }); dataContext.SaveChanges(); return CreatedAtRoute( "tournament-get", new { tournamentKey = tournament.Key }, new { key = tournament.Key }); } } } }
using System; using System.Linq; using System.Web.Http; using Peregrine.Data; namespace Peregrine.Web.Controllers { [RoutePrefix("api/tournaments")] public class TournamentsController : ApiController { [Route] public IHttpActionResult Get() { using(var dataContext = new DataContext()) { var tournamentKeys = dataContext .Tournaments .Select(tournament => tournament.Key) .ToArray(); return Ok(new { keys = tournamentKeys, }); } } [Route] public IHttpActionResult Post() { using(var dataContext = new DataContext()) { var tournament = dataContext .Tournaments .Add(new Tournament { Key = Guid.NewGuid(), }); dataContext.SaveChanges(); return CreatedAtRoute( "tournament-get", new { tournamentKey = tournament.Key }, new { tournament = new { key = tournament.Key, } }); } } } }
Update the TryGetJointPose docs to accurately describe the set of inputs it can take.
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; namespace Microsoft.MixedReality.Toolkit.Input { public static class HandJointUtils { /// <summary> /// Try to find the first matching hand controller and return the pose of the requested joint for that hand. /// </summary> public static bool TryGetJointPose(TrackedHandJoint joint, Handedness handedness, out MixedRealityPose pose) { IMixedRealityHand hand = FindHand(handedness); if (hand != null) { return hand.TryGetJoint(joint, out pose); } pose = MixedRealityPose.ZeroIdentity; return false; } /// <summary> /// Find the first detected hand controller with matching handedness. /// </summary> public static IMixedRealityHand FindHand(Handedness handedness) { foreach (var detectedController in MixedRealityToolkit.InputSystem.DetectedControllers) { var hand = detectedController as IMixedRealityHand; if (hand != null) { if (detectedController.ControllerHandedness == handedness) { return hand; } } } return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; namespace Microsoft.MixedReality.Toolkit.Input { public static class HandJointUtils { /// <summary> /// Tries to get the the pose of the requested joint for the first controller with the specified handedness. /// </summary> /// <param name="joint">The requested joint</param> /// <param name="handedness">The specific hand of interest. This should be either Handedness.Left or Handedness.Right</param> /// <param name="pose">The output pose data</param> public static bool TryGetJointPose(TrackedHandJoint joint, Handedness handedness, out MixedRealityPose pose) { IMixedRealityHand hand = FindHand(handedness); if (hand != null) { return hand.TryGetJoint(joint, out pose); } pose = MixedRealityPose.ZeroIdentity; return false; } /// <summary> /// Find the first detected hand controller with matching handedness. /// </summary> /// <remarks> /// The given handeness should be either Handedness.Left or Handedness.Right. /// </remarks> public static IMixedRealityHand FindHand(Handedness handedness) { foreach (var detectedController in MixedRealityToolkit.InputSystem.DetectedControllers) { var hand = detectedController as IMixedRealityHand; if (hand != null) { if (detectedController.ControllerHandedness == handedness) { return hand; } } } return null; } } }
Move call to UseFluentActions before UseMvc in hello world sample project
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace HelloWorld { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddFluentActions(); } public void Configure(IApplicationBuilder app) { app.UseMvc(); app.UseFluentActions(actions => { actions.RouteGet("/").To(() => "Hello World!"); }); } } }
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace HelloWorld { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddFluentActions(); } public void Configure(IApplicationBuilder app) { app.UseFluentActions(actions => { actions.RouteGet("/").To(() => "Hello World!"); }); app.UseMvc(); } } }
Load fonts over https if using https
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Vaskelista</title> @Styles.Render("~/Content/css") @Mvc.RazorTools.BundleManager.Styles.Render() @Styles.Render("~/Content/less") @Scripts.Render("~/bundles/modernizr") <link href='http://fonts.googleapis.com/css?family=Patrick+Hand+SC|Schoolbell' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Roboto:400,100,700' rel='stylesheet' type='text/css' /> <link rel="shortcut icon" href="../favicon.ico" /> </head> <body> <main class="main container body-content"> @RenderBody() </main> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Vaskelista</title> @Styles.Render("~/Content/css") @Mvc.RazorTools.BundleManager.Styles.Render() @Styles.Render("~/Content/less") @Scripts.Render("~/bundles/modernizr") <link href='//fonts.googleapis.com/css?family=Patrick+Hand+SC|Schoolbell' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Roboto:400,100,700' rel='stylesheet' type='text/css' /> <link rel="shortcut icon" href="../favicon.ico" /> </head> <body> <main class="main container body-content"> @RenderBody() </main> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
Add description in test case.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Game.Overlays; using osu.Game.Users; namespace osu.Desktop.VisualTests.Tests { internal class TestCaseUserProfile : TestCase { public override void Reset() { base.Reset(); var userpage = new UserProfile(new User { Username = @"peppy", Id = 2, Country = new Country { FlagName = @"AU" }, CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg" }) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Width = 800, Height = 500 }; Add(userpage); AddStep("Toggle", userpage.ToggleVisibility); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Game.Overlays; using osu.Game.Users; namespace osu.Desktop.VisualTests.Tests { internal class TestCaseUserProfile : TestCase { public override string Description => "Tests user's profile page."; public override void Reset() { base.Reset(); var userpage = new UserProfile(new User { Username = @"peppy", Id = 2, Country = new Country { FlagName = @"AU" }, CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg" }) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Width = 800, Height = 500 }; Add(userpage); AddStep("Toggle", userpage.ToggleVisibility); } } }
Rollback now uses the changes field of the change collection instead of traverse flat.
using System; using System.Linq; using System.Transactions; using NMF.Expressions; using NMF.Models.Evolution; using NMF.Models.Repository; namespace NMF.Models { class NMFTransaction : IDisposable { private bool _committed; private readonly ExecutionEngine _engine = ExecutionEngine.Current; private readonly ModelChangeRecorder _recorder = new ModelChangeRecorder(); private IModelRepository _repository; //private TransactionScope _scope; public NMFTransaction(IModelElement rootElement) { if (rootElement == null) throw new ArgumentNullException(nameof(rootElement)); _repository = rootElement.Model.Repository; _recorder.Start(rootElement); //_scope = new TransactionScope(); _engine.BeginTransaction(); } public void Commit() { //if (_scope == null) throw new InvalidOperationException(); _engine.CommitTransaction(); _committed = true; //_scope.Complete(); } public void Rollback() { var modelChanges = _recorder.GetModelChanges().TraverseFlat().Reverse(); _recorder.Stop(); foreach (var change in modelChanges) change.Invert(_repository); _engine.RollbackTransaction(); } public void Dispose() { if (!_committed) Rollback(); //if (_scope != null) //{ // _scope.Dispose(); // _scope = null; //} } } }
using System; using System.Linq; using System.Transactions; using NMF.Expressions; using NMF.Models.Evolution; using NMF.Models.Repository; namespace NMF.Models { class NMFTransaction : IDisposable { private bool _committed; private readonly ExecutionEngine _engine = ExecutionEngine.Current; private readonly ModelChangeRecorder _recorder = new ModelChangeRecorder(); private IModelRepository _repository; //private TransactionScope _scope; public NMFTransaction(IModelElement rootElement) { if (rootElement == null) throw new ArgumentNullException(nameof(rootElement)); _repository = rootElement.Model.Repository; _recorder.Start(rootElement); //_scope = new TransactionScope(); _engine.BeginTransaction(); } public void Commit() { //if (_scope == null) throw new InvalidOperationException(); _engine.CommitTransaction(); _committed = true; //_scope.Complete(); } public void Rollback() { var modelChanges = _recorder.GetModelChanges().Changes; _recorder.Stop(); modelChanges.Reverse(); foreach (var change in modelChanges) change.Invert(_repository); _engine.RollbackTransaction(); } public void Dispose() { if (!_committed) Rollback(); //if (_scope != null) //{ // _scope.Dispose(); // _scope = null; //} } } }
Switch to ImmutableArray to prevent accidental mutation
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Globalization; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class ArityUtilities { private const string GenericTypeNameManglingString = "`"; private static readonly string[] s_aritySuffixesOneToNine = { "`1", "`2", "`3", "`4", "`5", "`6", "`7", "`8", "`9" }; public static string GetMetadataAritySuffix(int arity) { Debug.Assert(arity > 0); return (arity <= s_aritySuffixesOneToNine.Length) ? s_aritySuffixesOneToNine[arity - 1] : string.Concat(GenericTypeNameManglingString, arity.ToString(CultureInfo.InvariantCulture)); } } }
// 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.Collections.Immutable; using System.Diagnostics; using System.Globalization; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class ArityUtilities { private const string GenericTypeNameManglingString = "`"; private static readonly ImmutableArray<string> s_aritySuffixesOneToNine = ImmutableArray.Create("`1", "`2", "`3", "`4", "`5", "`6", "`7", "`8", "`9"); public static string GetMetadataAritySuffix(int arity) { Debug.Assert(arity > 0); return (arity <= s_aritySuffixesOneToNine.Length) ? s_aritySuffixesOneToNine[arity - 1] : string.Concat(GenericTypeNameManglingString, arity.ToString(CultureInfo.InvariantCulture)); } } }
Enable all kernel tests again.
using System; namespace Cosmos.TestRunner.Core { public static class DefaultEngineConfiguration { public static void Apply(Engine engine) { if (engine == null) { throw new ArgumentNullException("engine"); } engine.AddKernel(typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel).Assembly.Location); //engine.AddKernel(typeof(SimpleStructsAndArraysTest.Kernel).Assembly.Location); //engine.AddKernel(typeof(VGACompilerCrash.Kernel).Assembly.Location); // known bugs, therefor disabled for now: } } }
using System; namespace Cosmos.TestRunner.Core { public static class DefaultEngineConfiguration { public static void Apply(Engine engine) { if (engine == null) { throw new ArgumentNullException("engine"); } engine.AddKernel(typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel).Assembly.Location); engine.AddKernel(typeof(SimpleStructsAndArraysTest.Kernel).Assembly.Location); engine.AddKernel(typeof(VGACompilerCrash.Kernel).Assembly.Location); // known bugs, therefor disabled for now: } } }
Fix string.ToUpper/ToLower to use the computed result
// 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 s.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. } 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 wrong class hierarchy in Abstract class test cases
namespace Serilog.Tests.Support { public abstract class DummyAbstractClass { } public class DummyConcreteClassWithDefaultConstructor { // ReSharper disable once UnusedParameter.Local public DummyConcreteClassWithDefaultConstructor(string param = "") { } } public class DummyConcreteClassWithoutDefaultConstructor { // ReSharper disable once UnusedParameter.Local public DummyConcreteClassWithoutDefaultConstructor(string param) { } } }
namespace Serilog.Tests.Support { public abstract class DummyAbstractClass { } public class DummyConcreteClassWithDefaultConstructor : DummyAbstractClass { // ReSharper disable once UnusedParameter.Local public DummyConcreteClassWithDefaultConstructor(string param = "") { } } public class DummyConcreteClassWithoutDefaultConstructor : DummyAbstractClass { // ReSharper disable once UnusedParameter.Local public DummyConcreteClassWithoutDefaultConstructor(string param) { } } }
Change string to int for mark
namespace CloudantDotNet.Models { public class ToDoItem { public string id { get; set; } public string rev { get; set; } public string text { get; set; } } public class VREntryItem { public string id { get; set; } public string rev { get; set; } public string caseName { get; set; } public string mark { get; set; } public string comment { get; set; } } }
namespace CloudantDotNet.Models { public class ToDoItem { public string id { get; set; } public string rev { get; set; } public string text { get; set; } } public class VREntryItem { public string id { get; set; } public string rev { get; set; } public string caseName { get; set; } public int mark { get; set; } public string comment { get; set; } } }
Fix StructureMap missing default convention for React.Config
using System; using StructureMap; namespace Reactive.Config.StructureMap { public static class ContainerExtensions { public static void ReactiveConfig(this ConfigurationExpression config, Action<IReactiveConfigRegistry> action) { config.For<IKeyPathProvider>().Use<NamespaceKeyPathProvider>(); config.For<IConfigurationResultStore>().Singleton().Use<ConfigurationResultStore>(); var configRegsitry = new ReactiveConfigRegsitry(config); action(configRegsitry); config.For<IConfigurationProvider>().Use<ConfigurationProvider>(); } } }
using System; using StructureMap; namespace Reactive.Config.StructureMap { public static class ContainerExtensions { public static void ReactiveConfig(this ConfigurationExpression config, Action<IReactiveConfigRegistry> action) { config.Scan(s => { s.AssemblyContainingType<IConfigured>(); s.WithDefaultConventions(); }); config.For<IConfigurationResultStore>().Singleton().Use<ConfigurationResultStore>(); config.For<IKeyPathProvider>().Use<NamespaceKeyPathProvider>(); var configRegsitry = new ReactiveConfigRegsitry(config); action(configRegsitry); config.For<IConfigurationProvider>().Use<ConfigurationProvider>(); } } }
Support computing navigation bar items for source generated files
// 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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.NavigationBar; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteNavigationBarItemService : BrokeredServiceBase, IRemoteNavigationBarItemService { internal sealed class Factory : FactoryBase<IRemoteNavigationBarItemService> { protected override IRemoteNavigationBarItemService CreateService(in ServiceConstructionArguments arguments) => new RemoteNavigationBarItemService(arguments); } public RemoteNavigationBarItemService(in ServiceConstructionArguments arguments) : base(arguments) { } public ValueTask<ImmutableArray<SerializableNavigationBarItem>> GetItemsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, bool supportsCodeGeneration, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetRequiredDocument(documentId); var navigationBarService = document.GetRequiredLanguageService<INavigationBarItemService>(); var result = await navigationBarService.GetItemsAsync(document, supportsCodeGeneration, cancellationToken).ConfigureAwait(false); return SerializableNavigationBarItem.Dehydrate(result); }, cancellationToken); } } }
// 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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.NavigationBar; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteNavigationBarItemService : BrokeredServiceBase, IRemoteNavigationBarItemService { internal sealed class Factory : FactoryBase<IRemoteNavigationBarItemService> { protected override IRemoteNavigationBarItemService CreateService(in ServiceConstructionArguments arguments) => new RemoteNavigationBarItemService(arguments); } public RemoteNavigationBarItemService(in ServiceConstructionArguments arguments) : base(arguments) { } public ValueTask<ImmutableArray<SerializableNavigationBarItem>> GetItemsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, bool supportsCodeGeneration, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(document); var navigationBarService = document.GetRequiredLanguageService<INavigationBarItemService>(); var result = await navigationBarService.GetItemsAsync(document, supportsCodeGeneration, cancellationToken).ConfigureAwait(false); return SerializableNavigationBarItem.Dehydrate(result); }, cancellationToken); } } }
Update class name to reflect additional test
using NUnit.Framework; using FluentMigrator.Infrastructure; namespace FluentMigrator.Tests.Unit { using System.Collections.ObjectModel; using System.Linq; using FluentMigrator.Expressions; using Moq; [TestFixture] public class AutoReversingMigrationTests { private Mock<IMigrationContext> context; [SetUp] public void SetUp() { context = new Mock<IMigrationContext>(); context.SetupAllProperties(); } [Test] public void CreateTableUpAutoReversingMigrationGivesDeleteTableDown() { var autoReversibleMigration = new TestAutoReversingMigrationCreateTable(); context.Object.Expressions = new Collection<IMigrationExpression>(); autoReversibleMigration.GetDownExpressions(context.Object); Assert.True(context.Object.Expressions.Any(me => me is DeleteTableExpression && ((DeleteTableExpression)me).TableName == "Foo")); } [Test] public void DownMigrationsAreInReverseOrderOfUpMigrations() { var autoReversibleMigration = new TestAutoReversingMigrationCreateTable(); context.Object.Expressions = new Collection<IMigrationExpression>(); autoReversibleMigration.GetDownExpressions(context.Object); Assert.IsAssignableFrom(typeof(RenameTableExpression), context.Object.Expressions.ToList()[0]); Assert.IsAssignableFrom(typeof(DeleteTableExpression), context.Object.Expressions.ToList()[1]); } } internal class TestAutoReversingMigrationCreateTable : AutoReversingMigration { public override void Up() { Create.Table("Foo"); Rename.Table("Foo").InSchema("FooSchema").To("Bar"); } } }
using NUnit.Framework; using FluentMigrator.Infrastructure; namespace FluentMigrator.Tests.Unit { using System.Collections.ObjectModel; using System.Linq; using FluentMigrator.Expressions; using Moq; [TestFixture] public class AutoReversingMigrationTests { private Mock<IMigrationContext> context; [SetUp] public void SetUp() { context = new Mock<IMigrationContext>(); context.SetupAllProperties(); } [Test] public void CreateTableUpAutoReversingMigrationGivesDeleteTableDown() { var autoReversibleMigration = new TestAutoReversingMigration(); context.Object.Expressions = new Collection<IMigrationExpression>(); autoReversibleMigration.GetDownExpressions(context.Object); Assert.True(context.Object.Expressions.Any(me => me is DeleteTableExpression && ((DeleteTableExpression)me).TableName == "Foo")); } [Test] public void DownMigrationsAreInReverseOrderOfUpMigrations() { var autoReversibleMigration = new TestAutoReversingMigration(); context.Object.Expressions = new Collection<IMigrationExpression>(); autoReversibleMigration.GetDownExpressions(context.Object); Assert.IsAssignableFrom(typeof(RenameTableExpression), context.Object.Expressions.ToList()[0]); Assert.IsAssignableFrom(typeof(DeleteTableExpression), context.Object.Expressions.ToList()[1]); } } internal class TestAutoReversingMigration : AutoReversingMigration { public override void Up() { Create.Table("Foo"); Rename.Table("Foo").InSchema("FooSchema").To("Bar"); } } }
Change RedisSubscriberConnection externally owned in Autofac registration
using Autofac; using BookSleeve; using Compilify.Web.Services; namespace Compilify.Web.Infrastructure.DependencyInjection { public class RedisModule : Module { protected override void Load(ContainerBuilder builder) { builder.Register(x => RedisConnectionGateway.Current) .SingleInstance() .AsSelf(); builder.Register(x => x.Resolve<RedisConnectionGateway>().GetConnection()) .ExternallyOwned() .AsSelf(); builder.Register(x => x.Resolve<RedisConnection>().GetOpenSubscriberChannel()) .SingleInstance() .AsSelf(); } } }
using Autofac; using BookSleeve; using Compilify.Web.Services; namespace Compilify.Web.Infrastructure.DependencyInjection { public class RedisModule : Module { protected override void Load(ContainerBuilder builder) { builder.Register(x => RedisConnectionGateway.Current) .SingleInstance() .AsSelf(); builder.Register(x => x.Resolve<RedisConnectionGateway>().GetConnection()) .ExternallyOwned() .AsSelf(); builder.Register(x => x.Resolve<RedisConnection>().GetOpenSubscriberChannel()) .ExternallyOwned() .AsSelf(); } } }
Fix Uap TFM to include Aot
// 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; namespace Xunit { [Flags] public enum TargetFrameworkMonikers { Net45 = 0x1, Net451 = 0x2, Net452 = 0x4, Net46 = 0x8, Net461 = 0x10, Net462 = 0x20, Net463 = 0x40, Netcore50 = 0x80, Netcore50aot = 0x100, Netcoreapp1_0 = 0x200, Netcoreapp1_1 = 0x400, NetFramework = 0x800, Netcoreapp = 0x1000, Uap = 0x2000, UapAot = 0x4000, NetcoreCoreRT = 0x8000 } }
// 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; namespace Xunit { [Flags] public enum TargetFrameworkMonikers { Net45 = 0x1, Net451 = 0x2, Net452 = 0x4, Net46 = 0x8, Net461 = 0x10, Net462 = 0x20, Net463 = 0x40, Netcore50 = 0x80, Netcore50aot = 0x100, Netcoreapp1_0 = 0x200, Netcoreapp1_1 = 0x400, NetFramework = 0x800, Netcoreapp = 0x1000, Uap = UapAot | 0x2000, UapAot = 0x4000, NetcoreCoreRT = 0x8000 } }
Support params usage as input for tests
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.AdventOfCode.Puzzles { using Xunit; /// <summary> /// A class containing methods for helping to test puzzles. This class cannot be inherited. /// </summary> internal static class PuzzleTestHelpers { /// <summary> /// Solves the specified puzzle type. /// </summary> /// <typeparam name="T">The type of the puzzle to solve.</typeparam> /// <returns> /// The solved puzzle of the type specified by <typeparamref name="T"/>. /// </returns> internal static T SolvePuzzle<T>() where T : IPuzzle, new() { return SolvePuzzle<T>(new string[0]); } /// <summary> /// Solves the specified puzzle type with the specified arguments. /// </summary> /// <typeparam name="T">The type of the puzzle to solve.</typeparam> /// <param name="args">The arguments to pass to the puzzle.</param> /// <returns> /// The solved puzzle of the type specified by <typeparamref name="T"/>. /// </returns> internal static T SolvePuzzle<T>(string[] args) where T : IPuzzle, new() { // Arrange T puzzle = new T(); // Act int result = puzzle.Solve(args); // Assert Assert.Equal(0, result); return puzzle; } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.AdventOfCode.Puzzles { using Xunit; /// <summary> /// A class containing methods for helping to test puzzles. This class cannot be inherited. /// </summary> internal static class PuzzleTestHelpers { /// <summary> /// Solves the specified puzzle type. /// </summary> /// <typeparam name="T">The type of the puzzle to solve.</typeparam> /// <returns> /// The solved puzzle of the type specified by <typeparamref name="T"/>. /// </returns> internal static T SolvePuzzle<T>() where T : IPuzzle, new() { return SolvePuzzle<T>(new string[0]); } /// <summary> /// Solves the specified puzzle type with the specified arguments. /// </summary> /// <typeparam name="T">The type of the puzzle to solve.</typeparam> /// <param name="args">The arguments to pass to the puzzle.</param> /// <returns> /// The solved puzzle of the type specified by <typeparamref name="T"/>. /// </returns> internal static T SolvePuzzle<T>(params string[] args) where T : IPuzzle, new() { // Arrange T puzzle = new T(); // Act int result = puzzle.Solve(args); // Assert Assert.Equal(0, result); return puzzle; } } }
Test Commit for Slack Integration
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AIController : MonoBehaviour { public UnityEngine.AI.NavMeshAgent agent { get; private set; } // the navmesh agent required for the path finding public Transform target; // target to aim for public Transform head; private void Start() { // get the components on the object we need ( should not be null due to require component so no need to check ) agent = GetComponentInChildren<UnityEngine.AI.NavMeshAgent>(); agent.updateRotation = false; agent.updatePosition = true; } private void Update() { if (target != null) { agent.SetDestination(target.position); } head.LookAt(target); } public void SetTarget(Transform target) { this.target = target; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AIController : MonoBehaviour { public UnityEngine.AI.NavMeshAgent agent { get; private set; } // the navmesh agent required for the path finding public Transform target; // target to aim for public Transform head; private void Start() { // get the components on the object we need ( should not be null due to require component so no need to check ) //testing agent = GetComponentInChildren<UnityEngine.AI.NavMeshAgent>(); agent.updateRotation = false; agent.updatePosition = true; } private void Update() { if (target != null) { agent.SetDestination(target.position); } head.LookAt(target); } public void SetTarget(Transform target) { this.target = target; } }
Fix an issue with assembly binding which prevents the tests from running by removing the AssemblyCulture.
// Copyright (c) Timm Krause. All rights reserved. See LICENSE file in the project root for license information. using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("AspNet.Identity.OracleProvider")] [assembly: AssemblyDescription("ASP.NET Identity provider for Oracle databases.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AspNet.Identity.OracleProvider")] [assembly: AssemblyCopyright("Copyright © Timm Krause 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("en-US")] [assembly: ComVisible(false)] [assembly: Guid("051142e2-9936-4eb4-9a92-83a1d1ad63f6")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0-alpha1")] [assembly: SuppressMessage("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant", Justification = "Needless.")]
// Copyright (c) Timm Krause. All rights reserved. See LICENSE file in the project root for license information. using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("AspNet.Identity.OracleProvider")] [assembly: AssemblyDescription("ASP.NET Identity provider for Oracle databases.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AspNet.Identity.OracleProvider")] [assembly: AssemblyCopyright("Copyright © Timm Krause 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("051142e2-9936-4eb4-9a92-83a1d1ad63f6")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0-alpha1")] [assembly: SuppressMessage("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant", Justification = "Needless.")]
Update model project to minor version 11
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Propeller.Mvc.Model")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Propeller.Mvc.Model")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("479a5641-1614-4d2a-aeab-afa79884e207")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.10")] [assembly: AssemblyFileVersion("1.1.0.10")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Propeller.Mvc.Model")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Propeller.Mvc.Model")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("479a5641-1614-4d2a-aeab-afa79884e207")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.11")] [assembly: AssemblyFileVersion("1.1.0.11")]
Change load event of UI component to from Awake to Start
using System.Collections; using PatchKit.Api; using UnityEngine; namespace PatchKit.Unity.UI { public abstract class UIApiComponent : MonoBehaviour { private Coroutine _loadCoroutine; private bool _isDirty; private ApiConnection _apiConnection; public bool LoadOnAwake = true; protected ApiConnection ApiConnection { get { return _apiConnection; } } [ContextMenu("Reload")] public void SetDirty() { _isDirty = true; } protected abstract IEnumerator LoadCoroutine(); private void Load() { try { if (_loadCoroutine != null) { StopCoroutine(_loadCoroutine); } _loadCoroutine = StartCoroutine(LoadCoroutine()); } finally { _isDirty = false; } } protected virtual void Awake() { _apiConnection = new ApiConnection(Settings.GetApiConnectionSettings()); if (LoadOnAwake) { Load(); } } protected virtual void Update() { if (_isDirty) { Load(); } } } }
using System.Collections; using PatchKit.Api; using UnityEngine; namespace PatchKit.Unity.UI { public abstract class UIApiComponent : MonoBehaviour { private Coroutine _loadCoroutine; private bool _isDirty; private ApiConnection _apiConnection; public bool LoadOnStart = true; protected ApiConnection ApiConnection { get { return _apiConnection; } } [ContextMenu("Reload")] public void SetDirty() { _isDirty = true; } protected abstract IEnumerator LoadCoroutine(); private void Load() { try { if (_loadCoroutine != null) { StopCoroutine(_loadCoroutine); } _loadCoroutine = StartCoroutine(LoadCoroutine()); } finally { _isDirty = false; } } protected virtual void Awake() { _apiConnection = new ApiConnection(Settings.GetApiConnectionSettings()); } protected virtual void Start() { if (LoadOnStart) { Load(); } } protected virtual void Update() { if (_isDirty) { Load(); } } } }
Add nullability for helper extensions
using System; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; namespace Telegram.Bot.Helpers { /// <summary> /// Extension Methods /// </summary> internal static class Extensions { static string EncodeUtf8(this string value) => new(Encoding.UTF8.GetBytes(value).Select(Convert.ToChar).ToArray()); internal static void AddStreamContent( this MultipartFormDataContent multipartContent, Stream content, string name, string fileName = default) { fileName ??= name; var contentDisposition = $@"form-data; name=""{name}""; filename=""{fileName}""".EncodeUtf8(); HttpContent mediaPartContent = new StreamContent(content) { Headers = { {"Content-Type", "application/octet-stream"}, {"Content-Disposition", contentDisposition} } }; multipartContent.Add(mediaPartContent, name, fileName); } internal static void AddContentIfInputFileStream( this MultipartFormDataContent multipartContent, params IInputMedia[] inputMedia) { foreach (var input in inputMedia) { if (input.Media.FileType == FileType.Stream) { multipartContent.AddStreamContent(input.Media.Content, input.Media.FileName); } var mediaThumb = (input as IInputMediaThumb)?.Thumb; if (mediaThumb?.FileType == FileType.Stream) { multipartContent.AddStreamContent(mediaThumb.Content, mediaThumb.FileName); } } } } }
using System; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; namespace Telegram.Bot.Helpers { /// <summary> /// Extension Methods /// </summary> internal static class Extensions { static string EncodeUtf8(this string value) => new(Encoding.UTF8.GetBytes(value).Select(c => Convert.ToChar(c)).ToArray()); internal static void AddStreamContent(this MultipartFormDataContent multipartContent, Stream content, string name, string? fileName = default) { fileName ??= name; var contentDisposition = $@"form-data; name=""{name}""; filename=""{fileName}""".EncodeUtf8(); HttpContent mediaPartContent = new StreamContent(content) { Headers = { {"Content-Type", "application/octet-stream"}, {"Content-Disposition", contentDisposition} } }; multipartContent.Add(mediaPartContent, name, fileName); } internal static void AddContentIfInputFileStream(this MultipartFormDataContent multipartContent, params IInputMedia[] inputMedia) { foreach (var input in inputMedia) { if (input.Media.FileType == FileType.Stream) { multipartContent.AddStreamContent(input.Media.Content, input.Media.FileName); } var mediaThumb = (input as IInputMediaThumb)?.Thumb; if (mediaThumb?.FileType == FileType.Stream) { multipartContent.AddStreamContent(mediaThumb.Content, mediaThumb.FileName); } } } } }
Add necessary assembly info to project.
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Junle Li"> // Copyright (c) Junle Li. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Vsxmd")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Vsxmd")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("1911d778-b05f-4eac-8fc8-4c2a8fd456ce")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Junle Li"> // Copyright (c) Junle Li. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Vsxmd")] [assembly: AssemblyDescription("VS XML documentation -> Markdown syntax.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Junle Li")] [assembly: AssemblyProduct("Vsxmd")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("1911d778-b05f-4eac-8fc8-4c2a8fd456ce")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
Change code to use async defer call for Google Maps
@using System.Web.Mvc.Html @inherits Umbraco.Web.Mvc.UmbracoViewPage<dynamic> @if (Model.value != null) { string value = Model.value.ToString(); var id = Guid.NewGuid().ToString() + "_map"; var js_id = id.Replace('-', '_'); <div class="map gridmaps" id="@id" style="width:100%;"></div> <script type="text/javascript"> var settings = @Html.Raw(value); var mapCenter = new google.maps.LatLng(settings.latitude, settings.longitude); var mapElement = document.getElementById('@id'); mapElement.style.height = settings.height + "px"; var mapOptions = { zoom: settings.zoom, center: mapCenter, mapTypeId: google.maps.MapTypeId[settings.mapType] }; var panoramaOptions = { position: mapCenter }; map = new google.maps.Map(mapElement, mapOptions); if (settings.streetView) { var panorama = new google.maps.StreetViewPanorama(mapElement, panoramaOptions); map.setStreetView(panorama); } marker = new google.maps.Marker({ map: map, position: new google.maps.LatLng(settings.latitude, settings.longitude), draggable: true }); marker.setMap(map); </script> }
@inherits Umbraco.Web.Mvc.UmbracoViewPage<dynamic> @if (Model.value != null) { string value = Model.value.ToString(); var id = string.Format("{0}_map", Guid.NewGuid()); <div class="map gridmaps" id="@id" style="width:100%;"></div> <script type="text/javascript"> function initializeMap() { var mapElement = document.getElementById('@id'); var settings = @Html.Raw(value); var mapCenter = new google.maps.LatLng(settings.latitude, settings.longitude); mapElement.style.height = settings.height + "px"; var mapOptions = { zoom: settings.zoom, center: mapCenter, mapTypeId: google.maps.MapTypeId[settings.mapType] }; var map = new google.maps.Map(mapElement, mapOptions); var marker = new google.maps.Marker({ map: map, position: new google.maps.LatLng(settings.latitude, settings.longitude), draggable: true }); marker.setMap(map); } </script> }
Fix unit test by specifying the font in the test image.
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Threading.Tasks; using Avalonia.Controls; using Avalonia.Layout; using Avalonia.Media; using Xunit; #if AVALONIA_SKIA namespace Avalonia.Skia.RenderTests #else namespace Avalonia.Direct2D1.RenderTests.Controls #endif { public class TextBlockTests : TestBase { public TextBlockTests() : base(@"Controls\TextBlock") { } [Fact] public async Task Wrapping_NoWrap() { Decorator target = new Decorator { Padding = new Thickness(8), Width = 200, Height = 200, Child = new TextBlock { Background = Brushes.Red, FontSize = 12, Foreground = Brushes.Black, Text = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit", VerticalAlignment = VerticalAlignment.Top, TextWrapping = TextWrapping.NoWrap, } }; await RenderToFile(target); CompareImages(); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Threading.Tasks; using Avalonia.Controls; using Avalonia.Layout; using Avalonia.Media; using Xunit; #if AVALONIA_SKIA namespace Avalonia.Skia.RenderTests #else namespace Avalonia.Direct2D1.RenderTests.Controls #endif { public class TextBlockTests : TestBase { public TextBlockTests() : base(@"Controls\TextBlock") { } [Fact] public async Task Wrapping_NoWrap() { Decorator target = new Decorator { FontFamily = new FontFamily("Courier New"), Padding = new Thickness(8), Width = 200, Height = 200, Child = new TextBlock { Background = Brushes.Red, FontSize = 12, Foreground = Brushes.Black, Text = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit", VerticalAlignment = VerticalAlignment.Top, TextWrapping = TextWrapping.NoWrap, } }; await RenderToFile(target); CompareImages(); } } }
Delete corrupted downloads after an error
using System; using System.ComponentModel; using System.IO; using System.Net; namespace TweetLib.Core.Utils{ public static class WebUtils{ private static bool HasMicrosoftBeenBroughtTo2008Yet; private static void EnsureTLS12(){ if (!HasMicrosoftBeenBroughtTo2008Yet){ ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; ServicePointManager.SecurityProtocol &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11); HasMicrosoftBeenBroughtTo2008Yet = true; } } public static WebClient NewClient(string userAgent){ EnsureTLS12(); WebClient client = new WebClient{ Proxy = null }; client.Headers[HttpRequestHeader.UserAgent] = userAgent; return client; } public static AsyncCompletedEventHandler FileDownloadCallback(string file, Action? onSuccess, Action<Exception>? onFailure){ return (sender, args) => { if (args.Cancelled){ try{ File.Delete(file); }catch{ // didn't want it deleted anyways } } else if (args.Error != null){ onFailure?.Invoke(args.Error); } else{ onSuccess?.Invoke(); } }; } } }
using System; using System.ComponentModel; using System.IO; using System.Net; namespace TweetLib.Core.Utils{ public static class WebUtils{ private static bool HasMicrosoftBeenBroughtTo2008Yet; private static void EnsureTLS12(){ if (!HasMicrosoftBeenBroughtTo2008Yet){ ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; ServicePointManager.SecurityProtocol &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11); HasMicrosoftBeenBroughtTo2008Yet = true; } } public static WebClient NewClient(string userAgent){ EnsureTLS12(); WebClient client = new WebClient{ Proxy = null }; client.Headers[HttpRequestHeader.UserAgent] = userAgent; return client; } public static AsyncCompletedEventHandler FileDownloadCallback(string file, Action? onSuccess, Action<Exception>? onFailure){ return (sender, args) => { if (args.Cancelled){ TryDeleteFile(file); } else if (args.Error != null){ TryDeleteFile(file); onFailure?.Invoke(args.Error); } else{ onSuccess?.Invoke(); } }; } private static void TryDeleteFile(string file){ try{ File.Delete(file); }catch{ // didn't want it deleted anyways } } } }
Remove meta charset from fortunes in ASP.NET
@model IEnumerable<Benchmarks.AspNet.Models.Fortune> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Fortunes</title> </head> <body> <table> <tr> <th>id</th> <th>message</th> </tr> @foreach (var fortune in Model) { <tr> <td>@fortune.ID</td> <td>@fortune.Message</td> </tr> } </table> </body> </html>
@model IEnumerable<Benchmarks.AspNet.Models.Fortune> <!DOCTYPE html> <html> <head> <title>Fortunes</title> </head> <body> <table> <tr> <th>id</th> <th>message</th> </tr> @foreach (var fortune in Model) { <tr> <td>@fortune.ID</td> <td>@fortune.Message</td> </tr> } </table> </body> </html>
Change variable name per review request
using MQTTnet.Client.Connecting; using MQTTnet.Exceptions; namespace MQTTnet.Adapter { public class MqttConnectingFailedException : MqttCommunicationException { public MqttConnectingFailedException(MqttClientAuthenticateResult resultCode) : base($"Connecting with MQTT server failed ({resultCode.ResultCode.ToString()}).") { Result = resultCode; } public MqttClientAuthenticateResult Result { get; } public MqttClientConnectResultCode ResultCode => Result.ResultCode; } }
using MQTTnet.Client.Connecting; using MQTTnet.Exceptions; namespace MQTTnet.Adapter { public class MqttConnectingFailedException : MqttCommunicationException { public MqttConnectingFailedException(MqttClientAuthenticateResult result) : base($"Connecting with MQTT server failed ({result.ResultCode.ToString()}).") { Result = result; } public MqttClientAuthenticateResult Result { get; } public MqttClientConnectResultCode ResultCode => Result.ResultCode; } }
Update accessor constructor used for tests
using System; using System.Threading.Tasks; using BlogApp.Common.Contracts.Accessors; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using StackExchange.Redis; namespace BlogApp.Accessors { public sealed class BlogCacheAccessor : ICacheAccessor { #region Constructor and private members private readonly IConfiguration _config; private readonly IConnectionMultiplexer _connectionMultiplexer; public BlogCacheAccessor(IConfiguration config) { _config = config ?? throw new ArgumentNullException(nameof(config)); _connectionMultiplexer = ConnectionMultiplexer.Connect(_config["redis:endpoint"]); } public BlogCacheAccessor(IConfiguration config, IConnectionMultiplexer multiplexer) { _config = config ?? throw new ArgumentNullException(nameof(config)); _connectionMultiplexer = multiplexer ?? throw new ArgumentNullException(nameof(multiplexer)); } #endregion public async Task<TEntity> GetEnt<TEntity>(string key) where TEntity : class { var db = _connectionMultiplexer.GetDatabase(); var text = await db.StringGetAsync(key); return string.IsNullOrEmpty(text) ? null : JsonConvert.DeserializeObject<TEntity>(text); } public async Task CacheEnt<TEntity>(string key, TEntity ent, TimeSpan? ttl = null) { if (ttl == null) ttl = TimeSpan.FromMilliseconds(double.Parse(_config["redis:ttlMsDefault"])); var db = _connectionMultiplexer.GetDatabase(); await db.StringSetAsync(key, JsonConvert.SerializeObject(ent), ttl, When.Always, CommandFlags.FireAndForget); } } }
using System; using System.Threading.Tasks; using BlogApp.Common.Contracts.Accessors; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using StackExchange.Redis; namespace BlogApp.Accessors { public sealed class BlogCacheAccessor : ICacheAccessor { #region Constructor and private members private readonly IConfiguration _config; private readonly IConnectionMultiplexer _connectionMultiplexer; public BlogCacheAccessor(IConfiguration config) { _config = config ?? throw new ArgumentNullException(nameof(config)); _connectionMultiplexer = ConnectionMultiplexer.Connect(_config["redis:endpoint"]); } internal BlogCacheAccessor(IConfiguration config, IConnectionMultiplexer multiplexer) { _config = config ?? throw new ArgumentNullException(nameof(config)); _connectionMultiplexer = multiplexer ?? throw new ArgumentNullException(nameof(multiplexer)); } #endregion public async Task<TEntity> GetEnt<TEntity>(string key) where TEntity : class { var db = _connectionMultiplexer.GetDatabase(); var text = await db.StringGetAsync(key); return string.IsNullOrEmpty(text) ? null : JsonConvert.DeserializeObject<TEntity>(text); } public async Task CacheEnt<TEntity>(string key, TEntity ent, TimeSpan? ttl = null) { if (ttl == null) ttl = TimeSpan.FromMilliseconds(double.Parse(_config["redis:ttlMsDefault"])); var db = _connectionMultiplexer.GetDatabase(); await db.StringSetAsync(key, JsonConvert.SerializeObject(ent), ttl, When.Always, CommandFlags.FireAndForget); } } }
Comment should be // not ///
#if LESSTHAN_NET471 || LESSTHAN_NETCOREAPP20 || LESSTHAN_NETSTANDARD21 // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This attribute should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.All, Inherited = false)] public sealed class IsReadOnlyAttribute : Attribute { /// Empty } } #endif
#if LESSTHAN_NET471 || LESSTHAN_NETCOREAPP20 || LESSTHAN_NETSTANDARD21 // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This attribute should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.All, Inherited = false)] public sealed class IsReadOnlyAttribute : Attribute { // Empty } } #endif
Test coverage for simple void blocks with a variable
namespace AgileObjects.ReadableExpressions.UnitTests { using System; using System.Linq.Expressions; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class WhenTranslatingBlockExpressions { [TestMethod] public void ShouldTranslateANoVariableNoReturnValueBlock() { Expression<Action> writeLine = () => Console.WriteLine(); Expression<Func<int>> read = () => Console.Read(); Expression<Action> beep = () => Console.Beep(); var consoleBlock = Expression.Block(writeLine.Body, read.Body, beep.Body); var translated = consoleBlock.ToReadableString(); const string EXPECTED = @" Console.WriteLine(); Console.Read(); Console.Beep();"; Assert.AreEqual(EXPECTED.TrimStart(), translated); } [TestMethod] public void ShouldTranslateANoVariableBlockWithAReturnValue() { Expression<Action> writeLine = () => Console.WriteLine(); Expression<Func<int>> read = () => Console.Read(); var consoleBlock = Expression.Block(writeLine.Body, read.Body); var translated = consoleBlock.ToReadableString(); const string EXPECTED = @" Console.WriteLine(); return Console.Read();"; Assert.AreEqual(EXPECTED.TrimStart(), translated); } } }
namespace AgileObjects.ReadableExpressions.UnitTests { using System; using System.Linq.Expressions; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class WhenTranslatingBlockExpressions { [TestMethod] public void ShouldTranslateANoVariableBlockWithNoReturnValue() { Expression<Action> writeLine = () => Console.WriteLine(); Expression<Func<int>> read = () => Console.Read(); Expression<Action> beep = () => Console.Beep(); var consoleBlock = Expression.Block(writeLine.Body, read.Body, beep.Body); var translated = consoleBlock.ToReadableString(); const string EXPECTED = @" Console.WriteLine(); Console.Read(); Console.Beep();"; Assert.AreEqual(EXPECTED.TrimStart(), translated); } [TestMethod] public void ShouldTranslateANoVariableBlockWithAReturnValue() { Expression<Action> writeLine = () => Console.WriteLine(); Expression<Func<int>> read = () => Console.Read(); var consoleBlock = Expression.Block(writeLine.Body, read.Body); var translated = consoleBlock.ToReadableString(); const string EXPECTED = @" Console.WriteLine(); return Console.Read();"; Assert.AreEqual(EXPECTED.TrimStart(), translated); } [TestMethod] public void ShouldTranslateAVariableBlockWithNoReturnValue() { var countVariable = Expression.Variable(typeof(int), "count"); var countEqualsZero = Expression.Assign(countVariable, Expression.Constant(0)); var incrementCount = Expression.Increment(countVariable); var noReturnValue = Expression.Default(typeof(void)); var consoleBlock = Expression.Block( new[] { countVariable }, countEqualsZero, incrementCount, noReturnValue); var translated = consoleBlock.ToReadableString(); const string EXPECTED = @" var count = 0; ++count;"; Assert.AreEqual(EXPECTED.TrimStart(), translated); } } }
Remove redundant call to SatisfyImportsOnce
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Windows; using GitHub.Exports; using GitHub.Services; using GitHub.ViewModels; namespace GitHub.Factories { /// <summary> /// Factory for creating views and view models. /// </summary> [Export(typeof(IViewViewModelFactory))] [PartCreationPolicy(CreationPolicy.Shared)] public class ViewViewModelFactory : IViewViewModelFactory { readonly IGitHubServiceProvider serviceProvider; [ImportingConstructor] public ViewViewModelFactory( IGitHubServiceProvider serviceProvider, ICompositionService cc) { this.serviceProvider = serviceProvider; cc.SatisfyImportsOnce(this); } [ImportMany(AllowRecomposition = true)] IEnumerable<ExportFactory<FrameworkElement, IViewModelMetadata>> Views { get; set; } /// <inheritdoc/> public TViewModel CreateViewModel<TViewModel>() where TViewModel : IViewModel { return serviceProvider.ExportProvider.GetExport<TViewModel>().Value; } /// <inheritdoc/> public FrameworkElement CreateView<TViewModel>() where TViewModel : IViewModel { return CreateView(typeof(TViewModel)); } /// <inheritdoc/> public FrameworkElement CreateView(Type viewModel) { var f = Views.FirstOrDefault(x => x.Metadata.ViewModelType.Contains(viewModel)); return f?.CreateExport().Value; } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Windows; using GitHub.Exports; using GitHub.Services; using GitHub.ViewModels; namespace GitHub.Factories { /// <summary> /// Factory for creating views and view models. /// </summary> [Export(typeof(IViewViewModelFactory))] [PartCreationPolicy(CreationPolicy.Shared)] public class ViewViewModelFactory : IViewViewModelFactory { readonly IGitHubServiceProvider serviceProvider; [ImportingConstructor] public ViewViewModelFactory( IGitHubServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } [ImportMany(AllowRecomposition = true)] IEnumerable<ExportFactory<FrameworkElement, IViewModelMetadata>> Views { get; set; } /// <inheritdoc/> public TViewModel CreateViewModel<TViewModel>() where TViewModel : IViewModel { return serviceProvider.ExportProvider.GetExport<TViewModel>().Value; } /// <inheritdoc/> public FrameworkElement CreateView<TViewModel>() where TViewModel : IViewModel { return CreateView(typeof(TViewModel)); } /// <inheritdoc/> public FrameworkElement CreateView(Type viewModel) { var f = Views.FirstOrDefault(x => x.Metadata.ViewModelType.Contains(viewModel)); return f?.CreateExport().Value; } } }
Fix osu!mania failing due to 0 hp.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Mania.Judgements; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Mania.Scoring { internal class ManiaScoreProcessor : ScoreProcessor<ManiaHitObject, ManiaJudgement> { public ManiaScoreProcessor() { } public ManiaScoreProcessor(HitRenderer<ManiaHitObject, ManiaJudgement> hitRenderer) : base(hitRenderer) { } protected override void OnNewJudgement(ManiaJudgement judgement) { } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Mania.Judgements; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Mania.Scoring { internal class ManiaScoreProcessor : ScoreProcessor<ManiaHitObject, ManiaJudgement> { public ManiaScoreProcessor() { } public ManiaScoreProcessor(HitRenderer<ManiaHitObject, ManiaJudgement> hitRenderer) : base(hitRenderer) { } protected override void OnNewJudgement(ManiaJudgement judgement) { } protected override void Reset() { base.Reset(); Health.Value = 1; } } }
Update information about valid archive types
using CommandLine; namespace Arkivverket.Arkade.CLI { public abstract class ArchiveProcessingOptions : OutputOptions { [Option('t', "type", HelpText = "Optional. Archive type, valid values: noark3, noark5 or fagsystem")] public string ArchiveType { get; set; } [Option('a', "archive", HelpText = "Archive directory or file (.tar) to process.", Required = true)] public string Archive { get; set; } [Option('p', "processing-area", HelpText = "Directory to place temporary files and logs.", Required = true)] public string ProcessingArea { get; set; } } }
using CommandLine; namespace Arkivverket.Arkade.CLI { public abstract class ArchiveProcessingOptions : OutputOptions { [Option('t', "type", HelpText = "Optional. Archive type, valid values: noark3, noark4, noark5 or fagsystem")] public string ArchiveType { get; set; } [Option('a', "archive", HelpText = "Archive directory or file (.tar) to process.", Required = true)] public string Archive { get; set; } [Option('p', "processing-area", HelpText = "Directory to place temporary files and logs.", Required = true)] public string ProcessingArea { get; set; } } }
Normalize newlines in json test.
using System.Linq; using System.Text; using AsmResolver.DotNet.Bundles; using AsmResolver.PE.DotNet.Metadata.Strings; using AsmResolver.PE.DotNet.Metadata.Tables; using AsmResolver.PE.DotNet.Metadata.Tables.Rows; using Xunit; namespace AsmResolver.DotNet.Tests.Bundles { public class BundleFileTest { [Fact] public void ReadUncompressedStringContents() { var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6); var file = manifest.Files.First(f => f.Type == BundleFileType.RuntimeConfigJson); string contents = Encoding.UTF8.GetString(file.GetData()); Assert.Equal(@"{ ""runtimeOptions"": { ""tfm"": ""net6.0"", ""framework"": { ""name"": ""Microsoft.NETCore.App"", ""version"": ""6.0.0"" }, ""configProperties"": { ""System.Reflection.Metadata.MetadataUpdater.IsSupported"": false } } }", contents); } [Fact] public void ReadUncompressedAssemblyContents() { var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6); var bundleFile = manifest.Files.First(f => f.RelativePath == "HelloWorld.dll"); var embeddedImage = ModuleDefinition.FromBytes(bundleFile.GetData()); Assert.Equal("HelloWorld.dll", embeddedImage.Name); } } }
using System.Linq; using System.Text; using AsmResolver.DotNet.Bundles; using AsmResolver.PE.DotNet.Metadata.Strings; using AsmResolver.PE.DotNet.Metadata.Tables; using AsmResolver.PE.DotNet.Metadata.Tables.Rows; using Xunit; namespace AsmResolver.DotNet.Tests.Bundles { public class BundleFileTest { [Fact] public void ReadUncompressedStringContents() { var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6); var file = manifest.Files.First(f => f.Type == BundleFileType.RuntimeConfigJson); string contents = Encoding.UTF8.GetString(file.GetData()).Replace("\r", ""); Assert.Equal(@"{ ""runtimeOptions"": { ""tfm"": ""net6.0"", ""framework"": { ""name"": ""Microsoft.NETCore.App"", ""version"": ""6.0.0"" }, ""configProperties"": { ""System.Reflection.Metadata.MetadataUpdater.IsSupported"": false } } }".Replace("\r", ""), contents); } [Fact] public void ReadUncompressedAssemblyContents() { var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6); var bundleFile = manifest.Files.First(f => f.RelativePath == "HelloWorld.dll"); var embeddedImage = ModuleDefinition.FromBytes(bundleFile.GetData()); Assert.Equal("HelloWorld.dll", embeddedImage.Name); } } }
Update to Castle Rock header text
@using CkanDotNet.Web.Models.Helpers <p>As part of an initiative to improve the accessibility, transparency, and accountability of the Town of Castle Rock, this catalog provides open access to City-managed data. </p> @if (SettingsHelper.GetUserVoiceEnabled()) { <p>We invite you to actively participate in shaping the future of this data catalog by <a href="javascript:UserVoice.showPopupWidget();" title="Suggest additional datasets">suggesting additional datasets</a> or building applications with the available data.</p> } <p><span class="header-package-count">@Html.Action("PackageCount", "Widget") registered datasets are available.</span></p>
@using CkanDotNet.Web.Models.Helpers <p>As part of an initiative to improve the accessibility, transparency, and accountability of the Town of Castle Rock, this catalog provides open access to town-managed data. </p> @if (SettingsHelper.GetUserVoiceEnabled()) { <p>We invite you to actively participate in shaping the future of this data catalog by <a href="javascript:UserVoice.showPopupWidget();" title="Suggest additional datasets">suggesting additional datasets</a> or building applications with the available data.</p> } <p><span class="header-package-count">@Html.Action("PackageCount", "Widget") registered datasets are available.</span></p>
Change default HttpTimeout to 120 seconds
using System.IO; using System.Reflection; namespace Tiver.Fowl.Drivers.Configuration { public class DriversConfiguration { /// <summary> /// Location for binaries to be saved /// Defaults to assembly location /// </summary> public string DownloadLocation { get; set; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); /// <summary> /// Configured driver instances /// </summary> public DriverElement[] Drivers { get; set; } = {}; /// <summary> /// Timeout to be used for HTTP requests /// Value in seconds /// </summary> public int HttpTimeout { get; set; } = 100; } }
using System.IO; using System.Reflection; namespace Tiver.Fowl.Drivers.Configuration { public class DriversConfiguration { /// <summary> /// Location for binaries to be saved /// Defaults to assembly location /// </summary> public string DownloadLocation { get; set; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); /// <summary> /// Configured driver instances /// </summary> public DriverElement[] Drivers { get; set; } = {}; /// <summary> /// Timeout to be used for HTTP requests /// Value in seconds /// </summary> public int HttpTimeout { get; set; } = 120; } }
Support complex field- and record separators
using System; using System.Collections.Generic; using Arkivverket.Arkade.Util; namespace Arkivverket.Arkade.Core.Addml.Definitions { public class Separator { private static readonly Dictionary<string, string> SpecialSeparators = new Dictionary<string, string> { {"CRLF", "\r\n"}, {"LF", "\n"} }; public static readonly Separator CRLF = new Separator("CRLF"); private readonly string _name; private readonly string _separator; public Separator(string separator) { Assert.AssertNotNullOrEmpty("separator", separator); _name = separator; _separator = Convert(separator); } public string Get() { return _separator; } public override string ToString() { return _name; } protected bool Equals(Separator other) { return string.Equals(_name, other._name); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Separator) obj); } public override int GetHashCode() { return _name?.GetHashCode() ?? 0; } private string Convert(string s) { return SpecialSeparators.ContainsKey(s) ? SpecialSeparators[s] : s; } internal int GetLength() { return _separator.Length; } } }
using System; using System.Collections.Generic; using Arkivverket.Arkade.Util; namespace Arkivverket.Arkade.Core.Addml.Definitions { public class Separator { private static readonly Dictionary<string, string> SpecialSeparators = new Dictionary<string, string> { {"CRLF", "\r\n"}, {"LF", "\n"} }; public static readonly Separator CRLF = new Separator("CRLF"); private readonly string _name; private readonly string _separator; public Separator(string separator) { Assert.AssertNotNullOrEmpty("separator", separator); _name = separator; _separator = Convert(separator); } public string Get() { return _separator; } public override string ToString() { return _name; } protected bool Equals(Separator other) { return string.Equals(_name, other._name); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Separator) obj); } public override int GetHashCode() { return _name?.GetHashCode() ?? 0; } private static string Convert(string separator) { foreach (string key in SpecialSeparators.Keys) if (separator.Contains(key)) separator = separator.Replace(key, SpecialSeparators[key]); return separator; } internal int GetLength() { return _separator.Length; } } }
Use of UnityWebRequest for default http client.
using System; using System.Collections.Generic; using System.IO; using UnityEngine; namespace CotcSdk { /** @cond private */ [Serializable] public class CotcSettings : ScriptableObject { public const string AssetPath = "Assets/Resources/CotcSettings.asset"; public static CotcSettings Instance { get { if (instance == null) { instance = Resources.Load(Path.GetFileNameWithoutExtension(AssetPath)) as CotcSettings; } return instance; } } private static CotcSettings instance; [Serializable] public class Environment { [SerializeField] public string Name; [SerializeField] public string ApiKey; [SerializeField] public string ApiSecret; [SerializeField] public string ServerUrl; [SerializeField] public int LbCount = 1; [SerializeField] public bool HttpVerbose = true; [SerializeField] public int HttpTimeout = 60; [SerializeField] public int HttpClientType = 0; } [SerializeField] public int FileVersion = 2; [SerializeField] public List<Environment> Environments = new List<Environment>(); [SerializeField] public int SelectedEnvironment = 0; } /** @endcond */ }
using System; using System.Collections.Generic; using System.IO; using UnityEngine; namespace CotcSdk { /** @cond private */ [Serializable] public class CotcSettings : ScriptableObject { public const string AssetPath = "Assets/Resources/CotcSettings.asset"; public static CotcSettings Instance { get { if (instance == null) { instance = Resources.Load(Path.GetFileNameWithoutExtension(AssetPath)) as CotcSettings; } return instance; } } private static CotcSettings instance; [Serializable] public class Environment { [SerializeField] public string Name; [SerializeField] public string ApiKey; [SerializeField] public string ApiSecret; [SerializeField] public string ServerUrl; [SerializeField] public int LbCount = 1; [SerializeField] public bool HttpVerbose = true; [SerializeField] public int HttpTimeout = 60; [SerializeField] public int HttpClientType = 1; } [SerializeField] public int FileVersion = 2; [SerializeField] public List<Environment> Environments = new List<Environment>(); [SerializeField] public int SelectedEnvironment = 0; } /** @endcond */ }
Add basePath and baseUrl parameters at AddPiranhaFileStorage extension method.
/* * Copyright (c) 2018 Håkan Edling * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using Microsoft.Extensions.DependencyInjection; using Piranha; using Piranha.Local; public static class FileStorageExtensions { /// <summary> /// Adds the services for the local FileStorage service. /// </summary> /// <param name="services">The current service collection</param> /// <param name="scope">The optional service scope</param> /// <returns>The service collection</returns> public static IServiceCollection AddPiranhaFileStorage(this IServiceCollection services, ServiceLifetime scope = ServiceLifetime.Singleton) { services.Add(new ServiceDescriptor(typeof(IStorage), typeof(FileStorage), scope)); return services; } }
/* * Copyright (c) 2018 Håkan Edling * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using Microsoft.Extensions.DependencyInjection; using Piranha; using Piranha.Local; public static class FileStorageExtensions { /// <summary> /// Adds the services for the local FileStorage service. /// </summary> /// <param name="services">The current service collection</param> /// <param name="scope">The optional service scope</param> /// <returns>The service collection</returns> public static IServiceCollection AddPiranhaFileStorage(this IServiceCollection services, ServiceLifetime scope = ServiceLifetime.Singleton, string basePath = null, string baseUrl = null) { services.Add(new ServiceDescriptor(typeof(IStorage), sp => new FileStorage(basePath, baseUrl), scope)); return services; } }
Allow only http/https schemes, and href attribute to contain an uri.
using Ganss.XSS; namespace CollAction.Helpers { public static class InputSanitizer { public static string Sanitize(string input) { var saniziter = new HtmlSanitizer( allowedTags: new[] { "p", "br", "strong", "em", "i", "u", "a", "ol", "ul", "li" }, allowedAttributes: new[] { "href", "target" }, allowedCssClasses: new string[] {}, allowedCssProperties: new string[] {} ); return saniziter.Sanitize(input); } } }
using Ganss.XSS; namespace CollAction.Helpers { public static class InputSanitizer { public static string Sanitize(string input) { var saniziter = new HtmlSanitizer( allowedTags: new[] { "p", "br", "strong", "em", "i", "u", "a", "ol", "ul", "li" }, allowedSchemes: new string[] { "http", "https"}, allowedAttributes: new[] { "target" }, uriAttributes: new[] { "href" }, allowedCssProperties: new string[] {}, allowedCssClasses: new string[] {} ); return saniziter.Sanitize(input); } } }
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); } } }
Use camelCase for new widgets
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace OpenOrderFramework.Controllers { public class JsonNetResult : JsonResult { public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); var response = context.HttpContext.Response; response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; // If you need special handling, you can call another form of SerializeObject below // var serializedObject = JsonConvert.SerializeObject(Data, new JsonSerializerSettings{ ContractResolver = new CamelCasePropertyNamesContractResolver() }); var serializedObject = JsonConvert.SerializeObject(Data, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() }); response.Write(serializedObject); } } public class JsonHandlerAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { var jsonResult = filterContext.Result as JsonResult; if (jsonResult != null) { filterContext.Result = new JsonNetResult { ContentEncoding = jsonResult.ContentEncoding, ContentType = jsonResult.ContentType, Data = jsonResult.Data, JsonRequestBehavior = jsonResult.JsonRequestBehavior }; } base.OnActionExecuted(filterContext); } } }
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace OpenOrderFramework.Controllers { public class JsonNetResult : JsonResult { public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); var response = context.HttpContext.Response; response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; // If you need special handling, you can call another form of SerializeObject below var serializedObject = JsonConvert.SerializeObject(Data, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); //var serializedObject = JsonConvert.SerializeObject(Data, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() }); response.Write(serializedObject); } } public class JsonHandlerAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { var jsonResult = filterContext.Result as JsonResult; if (jsonResult != null) { filterContext.Result = new JsonNetResult { ContentEncoding = jsonResult.ContentEncoding, ContentType = jsonResult.ContentType, Data = jsonResult.Data, JsonRequestBehavior = jsonResult.JsonRequestBehavior }; } base.OnActionExecuted(filterContext); } } }
Break failing test into working & non-working parts
using System; using System.Threading.Tasks; using FluentAssertions; using Xunit; using Auth0.Tests.Shared; namespace Auth0.ManagementApi.IntegrationTests { public class StatsTests : TestBase { [Fact(Skip = "Inactivity causes these to fail")] public async Task Test_stats_sequence() { string token = await GenerateManagementApiToken(); using (var apiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"))) { // Get stats for the past 10 days var dailyStats = await apiClient.Stats.GetDailyStatsAsync(DateTime.Now.AddDays(-100), DateTime.Now); dailyStats.Should().NotBeNull(); dailyStats.Count.Should().BeGreaterOrEqualTo(1); // Get the active users var activeUsers = await apiClient.Stats.GetActiveUsersAsync(); activeUsers.Should().BeGreaterOrEqualTo(1); // These integration tests themselves trigger non-zero values } } } }
using System; using System.Threading.Tasks; using FluentAssertions; using Xunit; using Auth0.Tests.Shared; using System.Linq; namespace Auth0.ManagementApi.IntegrationTests { public class StatsTests : TestBase { [Fact] public async Task Daily_Stats_Returns_Values() { string token = await GenerateManagementApiToken(); using (var apiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"))) { var dailyStats = await apiClient.Stats.GetDailyStatsAsync(DateTime.Now.AddDays(-100), DateTime.Now); dailyStats.Should().NotBeNull(); dailyStats.Count.Should().BeGreaterOrEqualTo(1); dailyStats.Max(d => d.Logins).Should().BeGreaterThan(0); } } [Fact(Skip = "Inactivity causes these to fail")] public async Task Active_Users_Returns_Values() { string token = await GenerateManagementApiToken(); using (var apiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"))) { var activeUsers = await apiClient.Stats.GetActiveUsersAsync(); activeUsers.Should().BeGreaterThan(0); } } } }
Revert "Navigate up many parents"
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Gibe.DittoProcessors.Processors { public class ParentAttribute : TestableDittoProcessorAttribute { private readonly uint _parentDepth; public ParentAttribute(uint parentDepth = 1) { _parentDepth = parentDepth; } public override object ProcessValue() { var content = Context.Content; for (var i = 0; i < _parentDepth; i++) { content = content.Parent; } return content; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Gibe.DittoProcessors.Processors { public class ParentAttribute : TestableDittoProcessorAttribute { public override object ProcessValue() { return Context.Content.Parent; } } }
Add attributes that can't be easily tested due to being public in the current target framework
using System.Collections.Generic; namespace PublicApiGenerator { partial class AttributeFilter { private static readonly HashSet<string> RequiredAttributeNames = new HashSet<string> { "System.Diagnostics.CodeAnalysis.AllowNullAttribute", "System.Diagnostics.CodeAnalysis.DisallowNullAttribute", "System.Diagnostics.CodeAnalysis.DoesNotReturnAttribute", "System.Diagnostics.CodeAnalysis.DoesNotReturnIfAttribute", "System.Diagnostics.CodeAnalysis.MaybeNullAttribute", "System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute", "System.Diagnostics.CodeAnalysis.NotNullAttribute", "System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute", "System.Diagnostics.CodeAnalysis.NotNullWhenAttribute" }; } }
using System.Collections.Generic; namespace PublicApiGenerator { partial class AttributeFilter { private static readonly HashSet<string> RequiredAttributeNames = new HashSet<string> { "System.Diagnostics.CodeAnalysis.AllowNullAttribute", "System.Diagnostics.CodeAnalysis.DisallowNullAttribute", "System.Diagnostics.CodeAnalysis.DoesNotReturnAttribute", "System.Diagnostics.CodeAnalysis.DoesNotReturnIfAttribute", "System.Diagnostics.CodeAnalysis.MaybeNullAttribute", "System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute", "System.Diagnostics.CodeAnalysis.NotNullAttribute", "System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute", "System.Diagnostics.CodeAnalysis.NotNullWhenAttribute", "System.SerializableAttribute", "System.Runtime.CompilerServices.CallerArgumentExpressionAttribute", "System.Runtime.CompilerServices.CallerFilePath", "System.Runtime.CompilerServices.CallerLineNumberAttribute", "System.Runtime.CompilerServices.CallerMemberName", "System.Runtime.CompilerServices.ReferenceAssemblyAttribute" }; } }
Update production endpoint to new version
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online { public class ProductionEndpointConfiguration : EndpointConfiguration { public ProductionEndpointConfiguration() { WebsiteRootUrl = APIEndpointUrl = @"https://osu.ppy.sh"; APIClientSecret = @"FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk"; APIClientID = "5"; SpectatorEndpointUrl = "https://spectator.ppy.sh/spectator"; MultiplayerEndpointUrl = "https://spectator.ppy.sh/multiplayer"; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online { public class ProductionEndpointConfiguration : EndpointConfiguration { public ProductionEndpointConfiguration() { WebsiteRootUrl = APIEndpointUrl = @"https://osu.ppy.sh"; APIClientSecret = @"FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk"; APIClientID = "5"; SpectatorEndpointUrl = "https://spectator2.ppy.sh/spectator"; MultiplayerEndpointUrl = "https://spectator2.ppy.sh/multiplayer"; } } }
Make default version table meta data virtual
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // // 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 namespace FluentMigrator.VersionTableInfo { public class DefaultVersionTableMetaData : IVersionTableMetaData { public string SchemaName { get { return string.Empty; } } public string TableName { get { return "VersionInfo"; } } public string ColumnName { get { return "Version"; } } public string UniqueIndexName { get { return "UC_Version"; } } } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // // 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 namespace FluentMigrator.VersionTableInfo { public class DefaultVersionTableMetaData : IVersionTableMetaData { public virtual string SchemaName { get { return string.Empty; } } public virtual string TableName { get { return "VersionInfo"; } } public virtual string ColumnName { get { return "Version"; } } public virtual string UniqueIndexName { get { return "UC_Version"; } } } }
Move conditional compilation around namespace.
namespace Cassette.Views { #if NET35 public interface IHtmlString { string ToHtmlString(); } public class HtmlString : IHtmlString { string _htmlString; public HtmlString(string htmlString) { this._htmlString = htmlString; } public string ToHtmlString() { return _htmlString; } public override string ToString() { return this._htmlString; } } #endif }
#if NET35 namespace Cassette.Views { public interface IHtmlString { string ToHtmlString(); } public class HtmlString : IHtmlString { string _htmlString; public HtmlString(string htmlString) { this._htmlString = htmlString; } public string ToHtmlString() { return _htmlString; } public override string ToString() { return this._htmlString; } } } #endif
Test for converting an empty NameValueCollection
using System; using System.Collections.Generic; using System.Collections.Specialized; using ExtraLinq; using FluentAssertions; using NUnit.Framework; namespace ExtraLINQ.Tests { [TestFixture] public class ToDictionaryTests { [ExpectedException(typeof(ArgumentNullException))] [Test] public void ThrowsArgumentNullExceptionWhenCollectionIsNull() { NameValueCollection collection = null; Dictionary<string, string> dictionary = collection.ToDictionary(); } [Test] public void ReturnedDictionaryContainsExactlyTheElementsFromTheNameValueCollection() { var collection = new NameValueCollection { { "a", "1" }, { "b", "2" }, { "c", "3" } }; Dictionary<string, string> dictionary = collection.ToDictionary(); dictionary.Should().Equal(new Dictionary<string, string> { { "a", "1" }, { "b", "2" }, { "c", "3" } }); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using ExtraLinq; using FluentAssertions; using NUnit.Framework; namespace ExtraLINQ.Tests { [TestFixture] public class ToDictionaryTests { [ExpectedException(typeof(ArgumentNullException))] [Test] public void ThrowsArgumentNullExceptionWhenCollectionIsNull() { NameValueCollection collection = null; Dictionary<string, string> dictionary = collection.ToDictionary(); } [Test] public void ReturnedDictionaryContainsExactlyTheElementsFromTheNameValueCollection() { var collection = new NameValueCollection { { "a", "1" }, { "b", "2" }, { "c", "3" } }; Dictionary<string, string> dictionary = collection.ToDictionary(); dictionary.Should().Equal(new Dictionary<string, string> { { "a", "1" }, { "b", "2" }, { "c", "3" } }); } [Test] public void ReturnsAnEmptyDictionaryForAnEmptyNameValueCollection() { var emptyCollection = new NameValueCollection(); Dictionary<string, string> dictionary = emptyCollection.ToDictionary(); dictionary.Should().HaveCount(0); } } }
Make PR status visible when GitSccProvider is loaded
using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.ComponentModelHost; using GitHub.VisualStudio; using GitHub.InlineReviews.Services; namespace GitHub.InlineReviews { [PackageRegistration(UseManagedResourcesOnly = true)] [Guid(Guids.PullRequestStatusPackageId)] [ProvideAutoLoad(UIContextGuids80.SolutionExists)] public class PullRequestStatusPackage : Package { protected override void Initialize() { var componentModel = (IComponentModel)GetService(typeof(SComponentModel)); var exportProvider = componentModel.DefaultExportProvider; var pullRequestStatusManager = exportProvider.GetExportedValue<IPullRequestStatusManager>(); pullRequestStatusManager.Initialize(); } } }
using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.ComponentModelHost; using GitHub.VisualStudio; using GitHub.InlineReviews.Services; namespace GitHub.InlineReviews { [PackageRegistration(UseManagedResourcesOnly = true)] [Guid(Guids.PullRequestStatusPackageId)] [ProvideAutoLoad(Guids.GitSccProviderId)] public class PullRequestStatusPackage : Package { protected override void Initialize() { var componentModel = (IComponentModel)GetService(typeof(SComponentModel)); var exportProvider = componentModel.DefaultExportProvider; var pullRequestStatusManager = exportProvider.GetExportedValue<IPullRequestStatusManager>(); pullRequestStatusManager.Initialize(); } } }
Adjust osu!mania scroll speed defaults to be more sane
// 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.Configuration.Tracking; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Mania.UI; namespace osu.Game.Rulesets.Mania.Configuration { public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting> { public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null) : base(settings, ruleset, variant) { } protected override void InitialiseDefaults() { base.InitialiseDefaults(); Set(ManiaRulesetSetting.ScrollTime, 2250.0, 50.0, 10000.0, 50.0); Set(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down); } public override TrackedSettings CreateTrackedSettings() => new TrackedSettings { new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms")) }; } public enum ManiaRulesetSetting { ScrollTime, ScrollDirection } }
// 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.Configuration.Tracking; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Mania.UI; namespace osu.Game.Rulesets.Mania.Configuration { public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting> { public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null) : base(settings, ruleset, variant) { } protected override void InitialiseDefaults() { base.InitialiseDefaults(); Set(ManiaRulesetSetting.ScrollTime, 1500.0, 50.0, 5000.0, 50.0); Set(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down); } public override TrackedSettings CreateTrackedSettings() => new TrackedSettings { new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms")) }; } public enum ManiaRulesetSetting { ScrollTime, ScrollDirection } }
Remove star creation debug printing
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SuikaShakeSparkleSpawner : MonoBehaviour { [SerializeField] private float spanwStartTime = .05f; [SerializeField] private float spawnFrequency = .25f; [SerializeField] private GameObject sparklePrefab; [SerializeField] private SuikaShakeSpriteFinder spriteCollection; [SerializeField] private BoxCollider2D spawnCollider; void Update () { InvokeRepeating("createSparkle", spanwStartTime, spawnFrequency); enabled = false; } void createSparkle() { var newSparkle = Instantiate(sparklePrefab, transform); newSparkle.transform.localScale = new Vector3(Random.Range(0, 2) == 0 ? -1f : 1f, 1f, 1f); newSparkle.transform.eulerAngles = Vector3.forward * Random.Range(0f, 360f); var chosenSprite = spriteCollection.sprites[Random.Range(0, spriteCollection.sprites.Length)]; var spriteRenderers = newSparkle.GetComponentsInChildren<SpriteRenderer>(); foreach (var sparkleRenderer in spriteRenderers) { sparkleRenderer.sprite = chosenSprite; } float xOffset = spawnCollider.bounds.extents.x; float yOffset = spawnCollider.bounds.extents.y; print(newSparkle.transform.position); newSparkle.transform.position += (Vector3)spawnCollider.offset + new Vector3(Random.Range(-xOffset, xOffset), Random.Range(-yOffset, yOffset), 0f); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SuikaShakeSparkleSpawner : MonoBehaviour { [SerializeField] private float spanwStartTime = .05f; [SerializeField] private float spawnFrequency = .25f; [SerializeField] private GameObject sparklePrefab; [SerializeField] private SuikaShakeSpriteFinder spriteCollection; [SerializeField] private BoxCollider2D spawnCollider; void Update () { InvokeRepeating("createSparkle", spanwStartTime, spawnFrequency); enabled = false; } void createSparkle() { var newSparkle = Instantiate(sparklePrefab, transform); newSparkle.transform.localScale = new Vector3(Random.Range(0, 2) == 0 ? -1f : 1f, 1f, 1f); newSparkle.transform.eulerAngles = Vector3.forward * Random.Range(0f, 360f); var chosenSprite = spriteCollection.sprites[Random.Range(0, spriteCollection.sprites.Length)]; var spriteRenderers = newSparkle.GetComponentsInChildren<SpriteRenderer>(); foreach (var sparkleRenderer in spriteRenderers) { sparkleRenderer.sprite = chosenSprite; } float xOffset = spawnCollider.bounds.extents.x; float yOffset = spawnCollider.bounds.extents.y; newSparkle.transform.position += (Vector3)spawnCollider.offset + new Vector3(Random.Range(-xOffset, xOffset), Random.Range(-yOffset, yOffset), 0f); } }
Handle Kayak framwork's Invoking event - here we can catch the total number of requests made, as well as do some basic authentication.
using System; using Kayak; using Kayak.Framework; namespace csharp_github_api.IntegrationTests { public abstract class IntegrationTestBase : IDisposable { protected readonly KayakServer WebServer = new KayakServer(); protected string BaseUrl = "http://localhost:8080"; protected IntegrationTestBase() { WebServer.UseFramework(); WebServer.Start(); } public void Dispose() { WebServer.Stop(); } } }
using System; using System.Linq; using System.Text; using Kayak; using Kayak.Framework; namespace csharp_github_api.IntegrationTests { public abstract class IntegrationTestBase : IDisposable { protected readonly KayakServer WebServer = new KayakServer(); protected string BaseUrl = "http://localhost:8080"; protected int RequestCount; protected IntegrationTestBase() { var framework = WebServer.UseFramework(); framework.Invoking += framework_Invoking; WebServer.Start(); } void framework_Invoking(object sender, InvokingEventArgs e) { RequestCount++; var header = e.Invocation.Context.Request.Headers["Authorization"]; if (!string.IsNullOrEmpty(header)) { var parts = Encoding.ASCII.GetString(Convert.FromBase64String(header.Substring("Basic ".Length))).Split(':'); if (parts.Count() == 2) { // Purely an aid to unit testing. e.Invocation.Context.Response.Headers.Add("Authenticated", "true"); // We don't want to write anything here because it will interfere with our json response from the Services //e.Invocation.Context.Response.Write(string.Join("|", parts)); } } } public void Dispose() { WebServer.Stop(); } } }
Remove old logging line. Causes an exception if the directory doesn't exist.
using System; using System.Configuration; using System.IO; using System.Net; using System.ServiceProcess; using System.Timers; using NLog; namespace ZBuildLightsUpdater { public partial class ZBuildLightsUpdaterService : ServiceBase { private static readonly Logger Log = LogManager.GetCurrentClassLogger(); private Timer _timer; private string _triggerUrl; public ZBuildLightsUpdaterService() { InitializeComponent(); } protected override void OnStart(string[] args) { File.AppendAllLines(@"c:\var\ZBuildLights\_logs\servicelog.txt", new[] {"Service starting..."}); Log.Info("ZBuildLights Updater Service Starting..."); _timer = new Timer(); var updateSeconds = Int32.Parse(ConfigurationManager.AppSettings["UpdateIntervalSeconds"]); _timer.Interval = TimeSpan.FromSeconds(updateSeconds).TotalMilliseconds; _timer.Elapsed += OnTimerElapsed; _timer.Start(); _triggerUrl = ConfigurationManager.AppSettings["TriggerUrl"]; Log.Info("ZBuildLights Updater Service Startup Complete."); } private void OnTimerElapsed(object sender, ElapsedEventArgs e) { Log.Debug("Initiating status refresh..."); var request = WebRequest.Create(_triggerUrl); request.GetResponse(); Log.Debug("Status refresh complete."); } protected override void OnStop() { Log.Info("ZBuildLights Updater Service Stopping."); } } }
using System; using System.Configuration; using System.Net; using System.ServiceProcess; using System.Timers; using NLog; namespace ZBuildLightsUpdater { public partial class ZBuildLightsUpdaterService : ServiceBase { private static readonly Logger Log = LogManager.GetCurrentClassLogger(); private Timer _timer; private string _triggerUrl; public ZBuildLightsUpdaterService() { InitializeComponent(); } protected override void OnStart(string[] args) { Log.Info("ZBuildLights Updater Service Starting..."); _timer = new Timer(); var updateSeconds = Int32.Parse(ConfigurationManager.AppSettings["UpdateIntervalSeconds"]); _timer.Interval = TimeSpan.FromSeconds(updateSeconds).TotalMilliseconds; _timer.Elapsed += OnTimerElapsed; _timer.Start(); _triggerUrl = ConfigurationManager.AppSettings["TriggerUrl"]; Log.Info("ZBuildLights Updater Service Startup Complete."); } private void OnTimerElapsed(object sender, ElapsedEventArgs e) { Log.Debug("Initiating status refresh..."); var request = WebRequest.Create(_triggerUrl); request.GetResponse(); Log.Debug("Status refresh complete."); } protected override void OnStop() { Log.Info("ZBuildLights Updater Service Stopping."); } } }
Fix getmentions tests and add missing TestMethod attribute
using System.Linq; using Microsoft.Bot.Connector; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Bot.Builder.Tests { [TestClass] public class ActivityExTests { [TestMethod] public void HasContent_Test() { IMessageActivity activity = DialogTestBase.MakeTestMessage(); Assert.IsFalse(activity.HasContent()); activity.Text = "test"; Assert.IsTrue(activity.HasContent()); } public void GetMentions_Test() { IMessageActivity activity = DialogTestBase.MakeTestMessage(); Assert.IsFalse(activity.GetMentions().Any()); activity.Entities.Add(new Mention() { Text = "testMention" }); Assert.IsTrue(activity.GetMentions().Any()); Assert.AreEqual("testMention", activity.GetMentions()[0].Text); } } }
using System.Collections.Generic; using System.Linq; using Microsoft.Bot.Connector; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; namespace Microsoft.Bot.Builder.Tests { [TestClass] public class ActivityExTests { [TestMethod] public void HasContent_Test() { IMessageActivity activity = DialogTestBase.MakeTestMessage(); Assert.IsFalse(activity.HasContent()); activity.Text = "test"; Assert.IsTrue(activity.HasContent()); } [TestMethod] public void GetMentions_Test() { IMessageActivity activity = DialogTestBase.MakeTestMessage(); Assert.IsFalse(activity.GetMentions().Any()); activity.Entities = new List<Entity> { new Mention() { Text = "testMention" } }; // Cloning activity to resemble the incoming activity to bot var clonedActivity = JsonConvert.DeserializeObject<Activity>(JsonConvert.SerializeObject(activity)); Assert.IsTrue(clonedActivity.GetMentions().Any()); Assert.AreEqual("testMention", clonedActivity.GetMentions()[0].Text); } } }
Tweak to one of the demo programs
using System; using System.Collections.Generic; using System.Linq; using MonadLib; namespace ReaderHaskellDocsExample1 { using Bindings = IDictionary<string, int>; internal class Program { private static void Main() { var sampleBindings = new Dictionary<string, int> { {"count", 3}, {"1", 1}, {"b", 2} }; Console.Write("Count is correct for bindings " + FormatBindings(sampleBindings) + ": "); Console.WriteLine(IsCountCorrect(sampleBindings)); } private static bool IsCountCorrect(Bindings bindings) { return CalcIsCountCorrect().RunReader(bindings); } private static Reader<Bindings, bool> CalcIsCountCorrect() { Func<Bindings, int> lookupVarPartiallyApplied = bindings => LookupVar("count", bindings); return Reader.Asks(lookupVarPartiallyApplied).Bind( count => Reader<Bindings>.Ask().Bind( bindings => Reader<Bindings>.Return( count == bindings.Count))); } private static int LookupVar(string name, Bindings bindings) { return bindings.GetValue(name).FromJust; } private static string FormatBindings(Bindings bindings) { Func<KeyValuePair<string, int>, string> formatBinding = kvp => string.Format("(\"{0}\",{1})", kvp.Key, kvp.Value); return string.Format("[{0}]", string.Join(",", bindings.Select(formatBinding))); } } }
using System; using System.Collections.Generic; using System.Linq; using MonadLib; namespace ReaderHaskellDocsExample1 { using Bindings = IDictionary<string, int>; internal class Program { private static void Main() { var sampleBindings = new Dictionary<string, int> { {"count", 3}, {"1", 1}, {"b", 2} }; Console.Write("Count is correct for bindings " + FormatBindings(sampleBindings) + ": "); Console.WriteLine(IsCountCorrect(sampleBindings)); } private static bool IsCountCorrect(Bindings bindings) { return CalcIsCountCorrect().RunReader(bindings); } private static Reader<Bindings, bool> CalcIsCountCorrect() { Func<string, Func<Bindings, int>> partiallyAppliedLookupVar = name => bindings => LookupVar(name, bindings); return Reader.Asks(partiallyAppliedLookupVar("count")).Bind( count => Reader<Bindings>.Ask().Bind( bindings => Reader<Bindings>.Return( count == bindings.Count))); } private static int LookupVar(string name, Bindings bindings) { return bindings.GetValue(name).FromJust; } private static string FormatBindings(Bindings bindings) { Func<KeyValuePair<string, int>, string> formatBinding = kvp => string.Format("(\"{0}\",{1})", kvp.Key, kvp.Value); return string.Format("[{0}]", string.Join(",", bindings.Select(formatBinding))); } } }
Fix running on < iOS 6.0
using System; using MonoTouch.Foundation; using MonoTouch.UIKit; using Eto.Platform.iOS.Forms; using Eto.Forms; namespace Eto.Platform.iOS { [MonoTouch.Foundation.Register("EtoAppDelegate")] public class EtoAppDelegate : UIApplicationDelegate { public EtoAppDelegate () { } public override bool WillFinishLaunching (UIApplication application, NSDictionary launchOptions) { ApplicationHandler.Instance.Initialize(this); return true; } } }
using System; using MonoTouch.Foundation; using MonoTouch.UIKit; using Eto.Platform.iOS.Forms; using Eto.Forms; namespace Eto.Platform.iOS { [MonoTouch.Foundation.Register("EtoAppDelegate")] public class EtoAppDelegate : UIApplicationDelegate { public EtoAppDelegate () { } public override bool FinishedLaunching (UIApplication application, NSDictionary launcOptions) { ApplicationHandler.Instance.Initialize(this); return true; } } }
Fix the problem that the web request is displayed twice when -Verbosity is set to detailed.
 namespace NuGet.Common { public class CommandLineRepositoryFactory : PackageRepositoryFactory { public static readonly string UserAgent = "NuGet Command Line"; private readonly IConsole _console; public CommandLineRepositoryFactory(IConsole console) { _console = console; } public override IPackageRepository CreateRepository(string packageSource) { var repository = base.CreateRepository(packageSource); var httpClientEvents = repository as IHttpClientEvents; if (httpClientEvents != null) { httpClientEvents.SendingRequest += (sender, args) => { if (_console.Verbosity == Verbosity.Detailed) { _console.WriteLine( System.ConsoleColor.Green, "{0} {1}", args.Request.Method, args.Request.RequestUri); } string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent); HttpUtility.SetUserAgent(args.Request, userAgent); }; } return repository; } } }
 using System.Windows; namespace NuGet.Common { public class CommandLineRepositoryFactory : PackageRepositoryFactory, IWeakEventListener { public static readonly string UserAgent = "NuGet Command Line"; private readonly IConsole _console; public CommandLineRepositoryFactory(IConsole console) { _console = console; } public override IPackageRepository CreateRepository(string packageSource) { var repository = base.CreateRepository(packageSource); var httpClientEvents = repository as IHttpClientEvents; if (httpClientEvents != null) { SendingRequestEventManager.AddListener(httpClientEvents, this); } return repository; } public bool ReceiveWeakEvent(System.Type managerType, object sender, System.EventArgs e) { if (managerType == typeof(SendingRequestEventManager)) { var args = (WebRequestEventArgs)e; if (_console.Verbosity == Verbosity.Detailed) { _console.WriteLine( System.ConsoleColor.Green, "{0} {1}", args.Request.Method, args.Request.RequestUri); } string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent); HttpUtility.SetUserAgent(args.Request, userAgent); return true; } else { return false; } } } }
Use bitwise operator (review by Clive)
namespace DependencyInjection.Console { internal class OddEvenPatternGenerator : IPatternGenerator { public Pattern Generate(int width, int height) { var generate = new Pattern(width, height); var squares = generate.Squares; for (var i = 0; i < squares.GetLength(0); ++i) { for (var j = 0; j < squares.GetLength(1); ++j) { squares[i, j] = (i ^ j) % 2 == 0 ? Square.White : Square.Black; } } return generate; } } }
namespace DependencyInjection.Console { internal class OddEvenPatternGenerator : IPatternGenerator { public Pattern Generate(int width, int height) { var generate = new Pattern(width, height); var squares = generate.Squares; for (var i = 0; i < squares.GetLength(0); ++i) { for (var j = 0; j < squares.GetLength(1); ++j) { squares[i, j] = ((i ^ j) & 1) == 0 ? Square.White : Square.Black; } } return generate; } } }
Update player loader screen mouse disable text to use localised version
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Configuration; namespace osu.Game.Screens.Play.PlayerSettings { public class InputSettings : PlayerSettingsGroup { private readonly PlayerCheckbox mouseButtonsCheckbox; public InputSettings() : base("Input Settings") { Children = new Drawable[] { mouseButtonsCheckbox = new PlayerCheckbox { LabelText = "Disable mouse buttons" } }; } [BackgroundDependencyLoader] private void load(OsuConfigManager config) => mouseButtonsCheckbox.Current = config.GetBindable<bool>(OsuSetting.MouseDisableButtons); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Configuration; using osu.Game.Localisation; namespace osu.Game.Screens.Play.PlayerSettings { public class InputSettings : PlayerSettingsGroup { private readonly PlayerCheckbox mouseButtonsCheckbox; public InputSettings() : base("Input Settings") { Children = new Drawable[] { mouseButtonsCheckbox = new PlayerCheckbox { LabelText = MouseSettingsStrings.DisableMouseButtons } }; } [BackgroundDependencyLoader] private void load(OsuConfigManager config) => mouseButtonsCheckbox.Current = config.GetBindable<bool>(OsuSetting.MouseDisableButtons); } }
Update automatic reservations flag to match what has been implemented
using System.Collections.Generic; using System.Linq; namespace SFA.DAS.Reservations.Api.Types { public class ReservationAllocationStatusResult { public bool AutoReservations { get; set; } } }
namespace SFA.DAS.Reservations.Api.Types { public class ReservationAllocationStatusResult { public bool CanAutoCreateReservations { get; set; } } }
Print out the response as a string when the exception is not JSON
using System; using System.Net; using System.Net.Http; namespace Kudu.Client { public static class HttpResponseMessageExtensions { /// <summary> /// Determines if the HttpResponse is successful, throws otherwise. /// </summary> public static HttpResponseMessage EnsureSuccessful(this HttpResponseMessage httpResponseMessage) { if (httpResponseMessage.StatusCode == HttpStatusCode.InternalServerError) { // For 500, we serialize the exception message on the server. var exceptionMessage = httpResponseMessage.Content.ReadAsAsync<HttpExceptionMessage>().Result; exceptionMessage.StatusCode = httpResponseMessage.StatusCode; exceptionMessage.ReasonPhrase = httpResponseMessage.ReasonPhrase; throw new HttpUnsuccessfulRequestException(exceptionMessage); } return httpResponseMessage.EnsureSuccessStatusCode(); } } public class HttpExceptionMessage { public HttpStatusCode StatusCode { get; set; } public string ReasonPhrase { get; set; } public string ExceptionMessage { get; set; } public string ExceptionType { get; set; } } public class HttpUnsuccessfulRequestException : HttpRequestException { public HttpUnsuccessfulRequestException() : this(null) { } public HttpUnsuccessfulRequestException(HttpExceptionMessage responseMessage) : base( responseMessage != null ? String.Format("{0}: {1}\nStatus Code: {2}", responseMessage.ReasonPhrase, responseMessage.ExceptionMessage, responseMessage.StatusCode) : null) { ResponseMessage = responseMessage; } public HttpExceptionMessage ResponseMessage { get; private set; } } }
using System; using System.Net; using System.Net.Http; namespace Kudu.Client { public static class HttpResponseMessageExtensions { /// <summary> /// Determines if the HttpResponse is successful, throws otherwise. /// </summary> public static HttpResponseMessage EnsureSuccessful(this HttpResponseMessage httpResponseMessage) { if (httpResponseMessage.StatusCode == HttpStatusCode.InternalServerError) { // For 500, we serialize the exception message on the server. HttpExceptionMessage exceptionMessage; try { exceptionMessage = httpResponseMessage.Content.ReadAsAsync<HttpExceptionMessage>().Result; } catch (InvalidOperationException ex) { // This would happen if the response type is not a Json object. throw new HttpRequestException(httpResponseMessage.Content.ReadAsStringAsync().Result, ex); } exceptionMessage.StatusCode = httpResponseMessage.StatusCode; exceptionMessage.ReasonPhrase = httpResponseMessage.ReasonPhrase; throw new HttpUnsuccessfulRequestException(exceptionMessage); } return httpResponseMessage.EnsureSuccessStatusCode(); } } public class HttpExceptionMessage { public HttpStatusCode StatusCode { get; set; } public string ReasonPhrase { get; set; } public string ExceptionMessage { get; set; } public string ExceptionType { get; set; } } public class HttpUnsuccessfulRequestException : HttpRequestException { public HttpUnsuccessfulRequestException() : this(null) { } public HttpUnsuccessfulRequestException(HttpExceptionMessage responseMessage) : base( responseMessage != null ? String.Format("{0}: {1}\nStatus Code: {2}", responseMessage.ReasonPhrase, responseMessage.ExceptionMessage, responseMessage.StatusCode) : null) { ResponseMessage = responseMessage; } public HttpExceptionMessage ResponseMessage { get; private set; } } }
Update server side API for single multiple answer question
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model /// </summary> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
Make the two extra ByRef value-type equality comparer methods static
using System; using System.Collections.Generic; namespace Equality { public struct StructEqualityComparer<T> : IEqualityComparer<T> where T : struct { public static StructEqualityComparer<T> Default = new StructEqualityComparer<T>(); public Boolean Equals(T x, T y) => Struct.Equals(ref x, ref y); public Int32 GetHashCode(T x) => Struct.GetHashCode(ref x); public Boolean Equals(ref T x, ref T y) => Struct.Equals(ref x, ref y); public Int32 GetHashCode(ref T x) => Struct.GetHashCode(ref x); } }
using System; using System.Collections.Generic; namespace Equality { public struct StructEqualityComparer<T> : IEqualityComparer<T> where T : struct { public static StructEqualityComparer<T> Default = new StructEqualityComparer<T>(); public Boolean Equals(T x, T y) => Struct.Equals(ref x, ref y); public Int32 GetHashCode(T x) => Struct.GetHashCode(ref x); public static Boolean Equals(ref T x, ref T y) => Struct.Equals(ref x, ref y); public static Int32 GetHashCode(ref T x) => Struct.GetHashCode(ref x); } }
Add ability to change the flie extension of API download requests
// 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.IO; using osu.Framework.IO.Network; namespace osu.Game.Online.API { public abstract class APIDownloadRequest : APIRequest { private string filename; protected override WebRequest CreateWebRequest() { var request = new FileWebRequest(filename = Path.GetTempFileName(), Uri); request.DownloadProgress += request_Progress; return request; } private void request_Progress(long current, long total) => API.Schedule(() => Progressed?.Invoke(current, total)); protected APIDownloadRequest() { base.Success += onSuccess; } private void onSuccess() { Success?.Invoke(filename); } public event APIProgressHandler Progressed; public new event APISuccessHandler<string> Success; } }
// 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.IO; using osu.Framework.IO.Network; namespace osu.Game.Online.API { public abstract class APIDownloadRequest : APIRequest { private string filename; /// <summary> /// Sets the extension of the file outputted by this request. /// </summary> protected virtual string FileExtension { get; } = @".tmp"; protected override WebRequest CreateWebRequest() { var file = Path.GetTempFileName(); File.Move(file, filename = Path.ChangeExtension(file, FileExtension)); var request = new FileWebRequest(filename, Uri); request.DownloadProgress += request_Progress; return request; } private void request_Progress(long current, long total) => API.Schedule(() => Progressed?.Invoke(current, total)); protected APIDownloadRequest() { base.Success += onSuccess; } private void onSuccess() { Success?.Invoke(filename); } public event APIProgressHandler Progressed; public new event APISuccessHandler<string> Success; } }
Improve reliability of test by using semaphores
// 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.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new AudioCollectionManager<AdjustableAudioComponent>(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a seperate thread start processing the queue new Thread(() => manager.Update()).Start(); // wait a little for beginning of the update to start Thread.Sleep(4); Assert.DoesNotThrow(() => manager.Dispose()); } private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } } }
// 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.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new TestAudioCollectionManager(); var threadExecutionFinished = new ManualResetEventSlim(); var updateLoopStarted = new ManualResetEventSlim(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a separate thread start processing the queue var thread = new Thread(() => { while (!manager.IsDisposed) { manager.Update(); updateLoopStarted.Set(); } threadExecutionFinished.Set(); }); thread.Start(); Assert.IsTrue(updateLoopStarted.Wait(1000)); Assert.DoesNotThrow(() => manager.Dispose()); Assert.IsTrue(threadExecutionFinished.Wait(1000)); } private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent> { public new bool IsDisposed => base.IsDisposed; } private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } } }
Make node root path variable and add debugger display
using System; using System.Collections.Generic; namespace Additio.Configuration { public class Node { public const string IncludeFolderPath = @"App_Config\Include"; public string FilePath { get; set; } public string RelativePath => FilePath.Remove(0, FilePath.IndexOf(IncludeFolderPath, StringComparison.OrdinalIgnoreCase) + 19); public List<Node> Dependencies { get; } = new List<Node>(); } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Additio.Configuration { [DebuggerDisplay("{RelativePath}")] public class Node { private string Root { get; } public Node(string root) { if (!root.EndsWith("\\")) root += "\\"; Root = root; } public string FilePath { get; set; } public string RelativePath => FilePath.Replace(Root, ""); public List<Node> Dependencies { get; } = new List<Node>(); } }
Replace SerialPort construction with factory invocation
using System; using System.IO.Ports; using MYCroes.ATCommands; using MYCroes.ATCommands.Forwarding; namespace SupportManager.Control { public class ATHelper : IDisposable { private readonly SerialPort serialPort; public ATHelper(string port) { serialPort = new SerialPort(port); serialPort.Open(); } public void ForwardTo(string phoneNumberWithInternationalAccessCode) { var cmd = ForwardingStatus.Set(ForwardingReason.Unconditional, ForwardingMode.Registration, phoneNumberWithInternationalAccessCode, ForwardingPhoneNumberType.WithInternationalAccessCode, ForwardingClass.Voice); Execute(cmd); } public string GetForwardedPhoneNumber() { var cmd = ForwardingStatus.Query(ForwardingReason.Unconditional); var res = Execute(cmd); return ForwardingStatus.Parse(res[0]).Number; } private string[] Execute(ATCommand command) { var stream = serialPort.BaseStream; stream.ReadTimeout = 10000; stream.WriteTimeout = 10000; return command.Execute(stream); } public void Dispose() { if (serialPort.IsOpen) serialPort.Close(); serialPort.Dispose(); } } }
using System; using System.IO.Ports; using MYCroes.ATCommands; using MYCroes.ATCommands.Forwarding; namespace SupportManager.Control { public class ATHelper : IDisposable { private readonly SerialPort serialPort; public ATHelper(string portConnectionString) { serialPort = SerialPortFactory.CreateFromConnectionString(portConnectionString); serialPort.Open(); } public ATHelper(SerialPort port) { serialPort = port; port.Open(); } public void ForwardTo(string phoneNumberWithInternationalAccessCode) { var cmd = ForwardingStatus.Set(ForwardingReason.Unconditional, ForwardingMode.Registration, phoneNumberWithInternationalAccessCode, ForwardingPhoneNumberType.WithInternationalAccessCode, ForwardingClass.Voice); Execute(cmd); } public string GetForwardedPhoneNumber() { var cmd = ForwardingStatus.Query(ForwardingReason.Unconditional); var res = Execute(cmd); return ForwardingStatus.Parse(res[0]).Number; } private string[] Execute(ATCommand command) { var stream = serialPort.BaseStream; stream.ReadTimeout = 10000; stream.WriteTimeout = 10000; return command.Execute(stream); } public void Dispose() { if (serialPort.IsOpen) serialPort.Close(); serialPort.Dispose(); } } }
Add installer_patcher get controller method
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace EndlessAges.LauncherService.Controllers { /// <summary> /// Emulated controller ContentManager.aspx from the Endless Ages backend. /// </summary> [Route("ContentManager.aspx")] public class ContentManager : Controller { } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace EndlessAges.LauncherService.Controllers { /// <summary> /// Emulated controller ContentManager.aspx from the Endless Ages backend. /// </summary> [Route("ContentManager.aspx")] public class ContentManager : Controller { //ContentManager.aspx?installer_patcher=ENDLESS [HttpGet] public IActionResult Get([FromQuery]string installer_patcher) { //If no valid parameter was provided in the query then return an error code //This should only happen if someone is spoofing //422 (Unprocessable Entity) if (string.IsNullOrWhiteSpace(installer_patcher)) return StatusCode(422); //TODO: What exactly should the backend return? EACentral returns a broken url return Content($"{@"http://game1.endlessagesonline./ENDLESSINSTALL.cab"}\n{@"ENDLESSINSTALL.cab"}"); } } }
Split out `base` call from `switch` statement
// 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 Markdig.Extensions.Yaml; using Markdig.Syntax; using Markdig.Syntax.Inlines; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Graphics.Containers.Markdown; namespace osu.Game.Overlays.Wiki.Markdown { public class WikiMarkdownContainer : OsuMarkdownContainer { public string CurrentPath { set => Schedule(() => DocumentUrl += $"wiki/{value}"); } protected override void AddMarkdownComponent(IMarkdownObject markdownObject, FillFlowContainer container, int level) { switch (markdownObject) { case YamlFrontMatterBlock yamlFrontMatterBlock: container.Add(CreateNotice(yamlFrontMatterBlock)); break; default: base.AddMarkdownComponent(markdownObject, container, level); break; } } public override MarkdownTextFlowContainer CreateTextFlow() => new WikiMarkdownTextFlowContainer(); protected override MarkdownParagraph CreateParagraph(ParagraphBlock paragraphBlock, int level) => new WikiMarkdownParagraph(paragraphBlock); protected virtual FillFlowContainer CreateNotice(YamlFrontMatterBlock yamlFrontMatterBlock) => new WikiNoticeContainer(yamlFrontMatterBlock); private class WikiMarkdownTextFlowContainer : OsuMarkdownTextFlowContainer { protected override void AddImage(LinkInline linkInline) => AddDrawable(new WikiMarkdownImage(linkInline)); } } }
// 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 Markdig.Extensions.Yaml; using Markdig.Syntax; using Markdig.Syntax.Inlines; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Graphics.Containers.Markdown; namespace osu.Game.Overlays.Wiki.Markdown { public class WikiMarkdownContainer : OsuMarkdownContainer { public string CurrentPath { set => Schedule(() => DocumentUrl += $"wiki/{value}"); } protected override void AddMarkdownComponent(IMarkdownObject markdownObject, FillFlowContainer container, int level) { switch (markdownObject) { case YamlFrontMatterBlock yamlFrontMatterBlock: container.Add(CreateNotice(yamlFrontMatterBlock)); return; } base.AddMarkdownComponent(markdownObject, container, level); } public override MarkdownTextFlowContainer CreateTextFlow() => new WikiMarkdownTextFlowContainer(); protected override MarkdownParagraph CreateParagraph(ParagraphBlock paragraphBlock, int level) => new WikiMarkdownParagraph(paragraphBlock); protected virtual FillFlowContainer CreateNotice(YamlFrontMatterBlock yamlFrontMatterBlock) => new WikiNoticeContainer(yamlFrontMatterBlock); private class WikiMarkdownTextFlowContainer : OsuMarkdownTextFlowContainer { protected override void AddImage(LinkInline linkInline) => AddDrawable(new WikiMarkdownImage(linkInline)); } } }
Add ignore attribute to test which for some reason fails when it is run together with other tests
using NUnit.Framework; using System.Web.Mvc; using System.Web.Routing; using Zk.Helpers; namespace Zk.Tests { [TestFixture] public class UrlHelperExtensionTest { [Test] public void UrlHelper_CreatePartialViewName() { // ARRANGE var httpContext = MvcMockHelpers.MockHttpContext(); var routeData = new RouteData(); var requestContext = new RequestContext(httpContext, routeData); var urlHelper = new UrlHelper(requestContext); // ACT var expected = "~/Views/Controller/_PartialView.cshtml"; var actual = urlHelper.View("_PartialView", "Controller"); // ASSERT Assert.AreEqual(expected, actual, "The UrlpHelper View extension should return the path to the partial view."); } } }
using NUnit.Framework; using System.Web.Mvc; using System.Web.Routing; using Zk.Helpers; namespace Zk.Tests { [Ignore] [TestFixture] public class UrlHelperExtensionTest { [Test] public void UrlHelper_CreatePartialViewName() { // ARRANGE var httpContext = MvcMockHelpers.MockHttpContext(); var routeData = new RouteData(); var requestContext = new RequestContext(httpContext, routeData); var urlHelper = new UrlHelper(requestContext); // ACT var expected = "~/Views/Controller/_PartialView.cshtml"; var actual = urlHelper.View("_PartialView", "Controller"); // ASSERT Assert.AreEqual(expected, actual, "The UrlpHelper View extension should return the path to the partial view."); } } }
Use MirroringPackageRepository to auto-mirror packages in OData lookup.
using System.Linq; using System.Web.Http; using System.Web.Http.OData; using NuGet.Lucene.Web.Models; using NuGet.Lucene.Web.Util; namespace NuGet.Lucene.Web.Controllers { /// <summary> /// OData provider for Lucene based NuGet package repository. /// </summary> public class PackagesODataController : ODataController { public ILucenePackageRepository Repository { get; set; } [Queryable] public IQueryable<ODataPackage> Get() { return Repository.LucenePackages.Select(p => p.AsDataServicePackage()).AsQueryable(); } public object Get([FromODataUri] string id, [FromODataUri] string version) { SemanticVersion semanticVersion; if (!SemanticVersion.TryParse(version, out semanticVersion)) { return BadRequest("Invalid version"); } if (string.IsNullOrWhiteSpace(id)) { return BadRequest("Invalid package id"); } var package = Repository.FindPackage(id, semanticVersion); return package == null ? (object)NotFound() : package.AsDataServicePackage(); } } }
using System.Linq; using System.Web.Http; using System.Web.Http.OData; using NuGet.Lucene.Web.Models; using NuGet.Lucene.Web.Util; namespace NuGet.Lucene.Web.Controllers { /// <summary> /// OData provider for Lucene based NuGet package repository. /// </summary> public class PackagesODataController : ODataController { public ILucenePackageRepository Repository { get; set; } public IMirroringPackageRepository MirroringRepository { get; set; } [Queryable] public IQueryable<ODataPackage> Get() { return Repository.LucenePackages.Select(p => p.AsDataServicePackage()).AsQueryable(); } public object Get([FromODataUri] string id, [FromODataUri] string version) { SemanticVersion semanticVersion; if (!SemanticVersion.TryParse(version, out semanticVersion)) { return BadRequest("Invalid version"); } if (string.IsNullOrWhiteSpace(id)) { return BadRequest("Invalid package id"); } var package = MirroringRepository.FindPackage(id, semanticVersion); return package == null ? (object)NotFound() : package.AsDataServicePackage(); } } }
Add [Fact] attribute to a test that was missing it, regaining coverage.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace MalApi.IntegrationTests { public class GetRecentOnlineUsersTest { public void GetRecentOnlineUsers() { using (MyAnimeListApi api = new MyAnimeListApi()) { RecentUsersResults results = api.GetRecentOnlineUsers(); Assert.NotEmpty(results.RecentUsers); } } } } /* Copyright 2017 Greg Najda Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace MalApi.IntegrationTests { public class GetRecentOnlineUsersTest { [Fact] public void GetRecentOnlineUsers() { using (MyAnimeListApi api = new MyAnimeListApi()) { RecentUsersResults results = api.GetRecentOnlineUsers(); Assert.NotEmpty(results.RecentUsers); } } } } /* Copyright 2017 Greg Najda 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. */
Add support for MSDIA140 to DIA-based CoreRT/.NETNative StackTraceGenerator on Windows
// 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.Diagnostics; using System.Collections.Generic; namespace Internal.StackGenerator.Dia { internal static class Guids { public static readonly IEnumerable<Guid> DiaSource_CLSIDs = new Guid[] { new Guid("3BFCEA48-620F-4B6B-81F7-B9AF75454C7D"), // msdia120.dll new Guid("761D3BCD-1304-41D5-94E8-EAC54E4AC172"), // msdia110.dll }; public static readonly Guid IID_IDiaDataSource = new Guid("79F1BB5F-B66E-48E5-B6A9-1545C323CA3D"); } }
// 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.Diagnostics; using System.Collections.Generic; namespace Internal.StackGenerator.Dia { internal static class Guids { public static readonly IEnumerable<Guid> DiaSource_CLSIDs = new Guid[] { new Guid("E6756135-1E65-4D17-8576-610761398C3C"), // msdia140.dll new Guid("3BFCEA48-620F-4B6B-81F7-B9AF75454C7D"), // msdia120.dll }; public static readonly Guid IID_IDiaDataSource = new Guid("79F1BB5F-B66E-48E5-B6A9-1545C323CA3D"); } }
Use SingleOrDefault as we may not know all WhatMine.com algorithms
using MultiMiner.CoinApi.Data; using MultiMiner.Xgminer.Data; using Newtonsoft.Json.Linq; using System.Linq; namespace MultiMiner.WhatMine.Extensions { public static class CoinInformationExtensions { public static void PopulateFromJson(this CoinInformation coinInformation, JToken jToken) { coinInformation.Symbol = jToken.Value<string>("market_code"); coinInformation.Name = jToken.Value<string>("name"); string algorithm = jToken.Value<string>("algorithm"); coinInformation.Algorithm = FixAlgorithmName(algorithm); coinInformation.CurrentBlocks = jToken.Value<int>("height"); coinInformation.Difficulty = jToken.Value<double>("difficulty"); coinInformation.Reward = jToken.Value<double>("reward"); coinInformation.Exchange = jToken.Value<string>("exchange_name"); coinInformation.Income = jToken.Value<double>("btc_per_day"); if (coinInformation.Symbol.Equals("BTC", System.StringComparison.OrdinalIgnoreCase)) coinInformation.Price = 1; else coinInformation.Price = jToken.Value<double>("exchange_rate"); } private static string FixAlgorithmName(string algorithm) { string result = algorithm; if (algorithm.Equals(ApiContext.ScryptNFactor, System.StringComparison.OrdinalIgnoreCase)) result = AlgorithmFullNames.ScryptN; else { var knownAlgorithm = KnownAlgorithms.Algorithms.Single(a => a.Name.Equals(algorithm, System.StringComparison.OrdinalIgnoreCase)); result = knownAlgorithm.FullName; } return result; } } }
using MultiMiner.CoinApi.Data; using MultiMiner.Xgminer.Data; using Newtonsoft.Json.Linq; using System; using System.Linq; namespace MultiMiner.WhatMine.Extensions { public static class CoinInformationExtensions { public static void PopulateFromJson(this CoinInformation coinInformation, JToken jToken) { coinInformation.Symbol = jToken.Value<string>("market_code"); coinInformation.Name = jToken.Value<string>("name"); string algorithm = jToken.Value<string>("algorithm"); coinInformation.Algorithm = FixAlgorithmName(algorithm); coinInformation.CurrentBlocks = jToken.Value<int>("height"); coinInformation.Difficulty = jToken.Value<double>("difficulty"); coinInformation.Reward = jToken.Value<double>("reward"); coinInformation.Exchange = jToken.Value<string>("exchange_name"); coinInformation.Income = jToken.Value<double>("btc_per_day"); if (coinInformation.Symbol.Equals("BTC", System.StringComparison.OrdinalIgnoreCase)) coinInformation.Price = 1; else coinInformation.Price = jToken.Value<double>("exchange_rate"); } private static string FixAlgorithmName(string algorithm) { string result = algorithm; if (algorithm.Equals(ApiContext.ScryptNFactor, StringComparison.OrdinalIgnoreCase)) result = AlgorithmFullNames.ScryptN; else { KnownAlgorithm knownAlgorithm = KnownAlgorithms.Algorithms.SingleOrDefault(a => a.Name.Equals(algorithm, StringComparison.OrdinalIgnoreCase)); if (knownAlgorithm != null) result = knownAlgorithm.FullName; } return result; } } }
Fix example notification timer breaking on skip (forward mouse button or Enter)
using System.Windows.Forms; using TweetDuck.Core.Controls; using TweetDuck.Plugins; using TweetDuck.Resources; namespace TweetDuck.Core.Notification.Example{ sealed class FormNotificationExample : FormNotificationMain{ public override bool RequiresResize => true; protected override bool CanDragWindow => Program.UserConfig.NotificationPosition == TweetNotification.Position.Custom; protected override FormBorderStyle NotificationBorderStyle{ get{ if (Program.UserConfig.NotificationSize == TweetNotification.Size.Custom){ switch(base.NotificationBorderStyle){ case FormBorderStyle.FixedSingle: return FormBorderStyle.Sizable; case FormBorderStyle.FixedToolWindow: return FormBorderStyle.SizableToolWindow; } } return base.NotificationBorderStyle; } } private readonly TweetNotification exampleNotification; public FormNotificationExample(FormBrowser owner, PluginManager pluginManager) : base(owner, pluginManager, false){ string exampleTweetHTML = ScriptLoader.LoadResource("pages/example.html", true).Replace("{avatar}", TweetNotification.AppLogoLink); #if DEBUG exampleTweetHTML = exampleTweetHTML.Replace("</p>", @"</p><div style='margin-top:256px'>Scrollbar test padding...</div>"); #endif exampleNotification = TweetNotification.Example(exampleTweetHTML, 176); } public override void HideNotification(){ Location = ControlExtensions.InvisibleLocation; } public void ShowExampleNotification(bool reset){ if (reset){ LoadTweet(exampleNotification); } else{ PrepareAndDisplayWindow(); } UpdateTitle(); } } }
using System.Windows.Forms; using TweetDuck.Core.Controls; using TweetDuck.Plugins; using TweetDuck.Resources; namespace TweetDuck.Core.Notification.Example{ sealed class FormNotificationExample : FormNotificationMain{ public override bool RequiresResize => true; protected override bool CanDragWindow => Program.UserConfig.NotificationPosition == TweetNotification.Position.Custom; protected override FormBorderStyle NotificationBorderStyle{ get{ if (Program.UserConfig.NotificationSize == TweetNotification.Size.Custom){ switch(base.NotificationBorderStyle){ case FormBorderStyle.FixedSingle: return FormBorderStyle.Sizable; case FormBorderStyle.FixedToolWindow: return FormBorderStyle.SizableToolWindow; } } return base.NotificationBorderStyle; } } private readonly TweetNotification exampleNotification; public FormNotificationExample(FormBrowser owner, PluginManager pluginManager) : base(owner, pluginManager, false){ string exampleTweetHTML = ScriptLoader.LoadResource("pages/example.html", true).Replace("{avatar}", TweetNotification.AppLogoLink); #if DEBUG exampleTweetHTML = exampleTweetHTML.Replace("</p>", @"</p><div style='margin-top:256px'>Scrollbar test padding...</div>"); #endif exampleNotification = TweetNotification.Example(exampleTweetHTML, 176); } public override void HideNotification(){ Location = ControlExtensions.InvisibleLocation; } public override void FinishCurrentNotification(){} public void ShowExampleNotification(bool reset){ if (reset){ LoadTweet(exampleNotification); } else{ PrepareAndDisplayWindow(); } UpdateTitle(); } } }
Revert "Fix threading issue on initialisation"
using System; using EPiServer.Framework.Localization; using EPiServer.ServiceLocation; using EPiServer.Web; namespace AlloyDemoKit.Business.Channels { /// <summary> /// Base class for all resolution definitions /// </summary> public abstract class DisplayResolutionBase : IDisplayResolution { private Injected<LocalizationService> LocalizationService { get; set; } private static object syncLock = new Object(); protected DisplayResolutionBase(string name, int width, int height) { Id = GetType().FullName; Name = Translate(name); Width = width; Height = height; } /// <summary> /// Gets the unique ID for this resolution /// </summary> public string Id { get; protected set; } /// <summary> /// Gets the name of resolution /// </summary> public string Name { get; protected set; } /// <summary> /// Gets the resolution width in pixels /// </summary> public int Width { get; protected set; } /// <summary> /// Gets the resolution height in pixels /// </summary> public int Height { get; protected set; } private string Translate(string resurceKey) { string value; lock (syncLock) { if (!LocalizationService.Service.TryGetString(resurceKey, out value)) { value = resurceKey; } } return value; } } }
using EPiServer.Framework.Localization; using EPiServer.ServiceLocation; using EPiServer.Web; namespace AlloyDemoKit.Business.Channels { /// <summary> /// Base class for all resolution definitions /// </summary> public abstract class DisplayResolutionBase : IDisplayResolution { private Injected<LocalizationService> LocalizationService { get; set; } protected DisplayResolutionBase(string name, int width, int height) { Id = GetType().FullName; Name = Translate(name); Width = width; Height = height; } /// <summary> /// Gets the unique ID for this resolution /// </summary> public string Id { get; protected set; } /// <summary> /// Gets the name of resolution /// </summary> public string Name { get; protected set; } /// <summary> /// Gets the resolution width in pixels /// </summary> public int Width { get; protected set; } /// <summary> /// Gets the resolution height in pixels /// </summary> public int Height { get; protected set; } private string Translate(string resurceKey) { string value; if(!LocalizationService.Service.TryGetString(resurceKey, out value)) { value = resurceKey; } return value; } } }
Mark System.Collections HashCollisionScenario test as OuterLoop
// 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.Collections.Generic; using Xunit; namespace System.Collections.Tests { public class InternalHashCodeTests { /// <summary> /// Given a byte array, copies it to the string, without messing with any encoding. This issue was hit on a x64 machine /// </summary> private static string GetString(byte[] bytes) { var chars = new char[bytes.Length / sizeof(char)]; Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); } [Fact] public static void OutOfBoundsRegression() { var dictionary = new Dictionary<string, string>(); foreach (var item in TestData.GetData()) { var operation = item.Item1; var keyBase64 = item.Item2; var key = keyBase64.Length > 0 ? GetString(Convert.FromBase64String(keyBase64)) : string.Empty; if (operation == InputAction.Add) dictionary[key] = key; else if (operation == InputAction.Delete) dictionary.Remove(key); } } } }
// 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.Collections.Generic; using Xunit; namespace System.Collections.Tests { public class InternalHashCodeTests { /// <summary> /// Given a byte array, copies it to the string, without messing with any encoding. This issue was hit on a x64 machine /// </summary> private static string GetString(byte[] bytes) { var chars = new char[bytes.Length / sizeof(char)]; Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); } [Fact] [OuterLoop("Takes over 55% of System.Collections.Tests testing time")] public static void OutOfBoundsRegression() { var dictionary = new Dictionary<string, string>(); foreach (var item in TestData.GetData()) { var operation = item.Item1; var keyBase64 = item.Item2; var key = keyBase64.Length > 0 ? GetString(Convert.FromBase64String(keyBase64)) : string.Empty; if (operation == InputAction.Add) dictionary[key] = key; else if (operation == InputAction.Delete) dictionary.Remove(key); } } } }
Add validation implementation in search module.
namespace TraktApiSharp.Modules { using Enums; using Objects.Basic; using Requests; using Requests.WithoutOAuth.Search; using System.Threading.Tasks; public class TraktSearchModule : TraktBaseModule { public TraktSearchModule(TraktClient client) : base(client) { } public async Task<TraktPaginationListResult<TraktSearchResult>> SearchTextQueryAsync(string query, TraktSearchResultType? type = null, int? year = null, int? page = null, int? limit = null) { return await QueryAsync(new TraktSearchTextQueryRequest(Client) { Query = query, Type = type, Year = year, PaginationOptions = new TraktPaginationOptions(page, limit) }); } public async Task<TraktPaginationListResult<TraktSearchIdLookupResult>> SearchIdLookupAsync(TraktSearchLookupIdType type, string lookupId, int? page = null, int? limit = null) { return await QueryAsync(new TraktSearchIdLookupRequest(Client) { Type = type, LookupId = lookupId, PaginationOptions = new TraktPaginationOptions(page, limit) }); } } }
namespace TraktApiSharp.Modules { using Enums; using Objects.Basic; using Requests; using Requests.WithoutOAuth.Search; using System; using System.Threading.Tasks; public class TraktSearchModule : TraktBaseModule { public TraktSearchModule(TraktClient client) : base(client) { } public async Task<TraktPaginationListResult<TraktSearchResult>> SearchTextQueryAsync(string query, TraktSearchResultType? type = null, int? year = null, int? page = null, int? limit = null) { ValidateQuery(query); return await QueryAsync(new TraktSearchTextQueryRequest(Client) { Query = query, Type = type, Year = year, PaginationOptions = new TraktPaginationOptions(page, limit) }); } public async Task<TraktPaginationListResult<TraktSearchIdLookupResult>> SearchIdLookupAsync(TraktSearchLookupIdType type, string lookupId, int? page = null, int? limit = null) { ValidateIdLookup(lookupId); return await QueryAsync(new TraktSearchIdLookupRequest(Client) { Type = type, LookupId = lookupId, PaginationOptions = new TraktPaginationOptions(page, limit) }); } private void ValidateQuery(string query) { if (string.IsNullOrEmpty(query)) throw new ArgumentException("search query not valid", "query"); } private void ValidateIdLookup(string lookupId) { if (string.IsNullOrEmpty(lookupId)) throw new ArgumentException("search lookup id not valid", "lookupId"); } } }
Fix storyboard loops start time when none of their commands start at 0.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; namespace osu.Game.Storyboards { public class CommandLoop : CommandTimelineGroup { public double LoopStartTime; public int LoopCount; public override double StartTime => LoopStartTime; public override double EndTime => LoopStartTime + CommandsDuration * LoopCount; public CommandLoop(double startTime, int loopCount) { LoopStartTime = startTime; LoopCount = loopCount; } public override IEnumerable<CommandTimeline<T>.TypedCommand> GetCommands<T>(CommandTimelineSelector<T> timelineSelector, double offset = 0) { for (var loop = 0; loop < LoopCount; loop++) { var loopOffset = LoopStartTime + loop * CommandsDuration; foreach (var command in base.GetCommands(timelineSelector, offset + loopOffset)) yield return command; } } public override string ToString() => $"{LoopStartTime} x{LoopCount}"; } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; namespace osu.Game.Storyboards { public class CommandLoop : CommandTimelineGroup { public double LoopStartTime; public int LoopCount; public override double StartTime => LoopStartTime + CommandsStartTime; public override double EndTime => StartTime + CommandsDuration * LoopCount; public CommandLoop(double startTime, int loopCount) { LoopStartTime = startTime; LoopCount = loopCount; } public override IEnumerable<CommandTimeline<T>.TypedCommand> GetCommands<T>(CommandTimelineSelector<T> timelineSelector, double offset = 0) { for (var loop = 0; loop < LoopCount; loop++) { var loopOffset = LoopStartTime + loop * CommandsDuration; foreach (var command in base.GetCommands(timelineSelector, offset + loopOffset)) yield return command; } } public override string ToString() => $"{LoopStartTime} x{LoopCount}"; } }
Add some empty code to InterControlAnimation
using Windows.UI.Xaml; namespace TestAppUWP.Samples.InterControlAnimation { public sealed partial class InterControlAnimation { private static Control2 _control2; private static Control1 _control1; public InterControlAnimation() { InitializeComponent(); ContentPresenter.Content = new Control1(); } private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { ContentPresenter.Content = ContentPresenter.Content is Control1 ? (object) GetControl2() : GetControl1(); } private static Control1 GetControl1() { return _control1 ?? (_control1 = new Control1()); } private static Control2 GetControl2() { return _control2 ?? (_control2 = new Control2()); } } }
using Windows.UI.Xaml; namespace TestAppUWP.Samples.InterControlAnimation { public sealed partial class InterControlAnimation { private static Control2 _control2; private static Control1 _control1; public InterControlAnimation() { InitializeComponent(); ContentPresenter.Content = new Control1(); } private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var changeControlAnimation = new ChangeControlAnimation(); ContentPresenter.Content = ContentPresenter.Content is Control1 ? (object) GetControl2() : GetControl1(); } private static Control1 GetControl1() { return _control1 ?? (_control1 = new Control1()); } private static Control2 GetControl2() { return _control2 ?? (_control2 = new Control2()); } } public class ChangeControlAnimation { } }
Change case for capability with js code.
using TicTacToe.Core.Enums; namespace TicTacToe.Web.ViewModels { public class TurnResultViewModel { public string Status { get; set; } public string ErrorText { get; set; } public bool IsGameDone { get; set; } public PlayerCode Winner { get; set; } public byte OpponentMove { get; set; } } public static class RusultStatus { public static string Error = "error"; public static string Success = "success"; } }
using TicTacToe.Core.Enums; namespace TicTacToe.Web.ViewModels { public class TurnResultViewModel { public string status { get; set; } public string errorText { get; set; } public bool isGameDone { get; set; } public PlayerCode winner { get; set; } public int opponentMove { get; set; } public TurnResultViewModel() { opponentMove = -1; } } public static class RusultStatus { public static string Error = "error"; public static string Success = "success"; } }