Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add cinsole coloring for server URL
#region using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.Owin.Hosting; using Owin; using Saturn72.Core; using Saturn72.Core.Configuration; using Saturn72.Core.Extensibility; using Saturn72.Extensions; #endregion namespace Saturn72.Module.Owin { public class OwinModule : IModule { private string _baseUri; private CancellationTokenSource _tokenSource; public void Load() { _baseUri = ConfigManager.GetConfigMap<OwinConfigMap>().Config.ServerUri; } public void Start() { Guard.HasValue(_baseUri); Trace.WriteLine("Starting web Server. Feel free to browse to {0}...".AsFormat(_baseUri)); _tokenSource = new CancellationTokenSource(); Task.Run(() => StartWebServer(), _tokenSource.Token); } public void Stop() { _tokenSource.Cancel(); } private void StartWebServer() { Action<IAppBuilder> startupAction = appBuilder => new Startup().Configure(appBuilder); using (WebApp.Start(_baseUri, startupAction)) { Trace.WriteLine("web server started. uri: " + _baseUri); //TODO: remove busy wait from here . replace with HttpServer while (true) { //Console.ReadLine(); } } Console.WriteLine("web server stoped"); } } }
#region using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.Owin.Hosting; using Owin; using Saturn72.Core; using Saturn72.Core.Configuration; using Saturn72.Core.Extensibility; using Saturn72.Extensions; #endregion namespace Saturn72.Module.Owin { public class OwinModule : IModule { private string _baseUri; private CancellationTokenSource _tokenSource; public void Load() { _baseUri = ConfigManager.GetConfigMap<OwinConfigMap>().Config.ServerUri; } public void Start() { Guard.HasValue(_baseUri); PublishUrlMessage(); _tokenSource = new CancellationTokenSource(); Task.Run(() => StartWebServer(), _tokenSource.Token); } private void PublishUrlMessage() { var tmpColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Cyan; Trace.WriteLine("Starting web Server. Feel free to browse to {0}...".AsFormat(_baseUri)); Console.ForegroundColor = tmpColor; } public void Stop() { _tokenSource.Cancel(); } private void StartWebServer() { Action<IAppBuilder> startupAction = appBuilder => new Startup().Configure(appBuilder); using (WebApp.Start(_baseUri, startupAction)) { Trace.WriteLine("web server started. uri: " + _baseUri); //TODO: remove busy wait from here . replace with HttpServer while (true) { //Console.ReadLine(); } } Console.WriteLine("web server stoped"); } } }
Use configured base url for swagger test
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace Nether.Web.IntegrationTests { public class SwaggerTests { [Fact] public async Task GET_Swagger_returns_200_OK() { var client = new HttpClient(); var response = await client.GetAsync("http://localhost:5000/api/swagger/v0.1/swagger.json"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace Nether.Web.IntegrationTests { public class SwaggerTests { [Fact] public async Task GET_Swagger_returns_200_OK() { var client = new HttpClient(); var response = await client.GetAsync($"{WebTestBase.BaseUrl}/api/swagger/v0.1/swagger.json"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } }
Fix `MultiplayerMatchFooter` test crash due to missing `PopoverContainer`
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Screens.OnlinePlay.Multiplayer.Match; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene { [SetUp] public new void Setup() => Schedule(() => { Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Height = 50, Child = new MultiplayerMatchFooter() }; }); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; using osu.Game.Screens.OnlinePlay.Multiplayer.Match; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene { [SetUp] public new void Setup() => Schedule(() => { Child = new PopoverContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Height = 50, Child = new MultiplayerMatchFooter() }; }); } }
Exclude git specific files from beeing resolved.
using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Documents; using System.Windows.Media.Media3D; using Common.Logging; using NCmdLiner.SolutionCreator.Library.Common; namespace NCmdLiner.SolutionCreator.Library.Services { public class FolderResolver : IFolderResolver { private readonly ITextResolver _textResolver; private readonly IFileResolver _fileResolver; private readonly ILog _logger; public FolderResolver(ITextResolver textResolver, IFileResolver fileResolver, ILog logger) { _textResolver = textResolver; _fileResolver = fileResolver; _logger = logger; } public void Resolve(string sourceFolder, string targetFolder) { if (!Directory.Exists(sourceFolder)) throw new DirectoryNotFoundException("Source folder not found: " + sourceFolder); var sourceDirectory = new DirectoryInfo(sourceFolder); var sourceDirectories = sourceDirectory.GetDirectories("*", SearchOption.AllDirectories).ToList(); var sourceFiles = sourceDirectory.GetFiles("*", SearchOption.AllDirectories).ToList(); foreach (var sourceSubDirectory in sourceDirectories) { var targetSubDirectory = new DirectoryInfo(_textResolver.Resolve(sourceSubDirectory.FullName.Replace(sourceFolder, targetFolder))); Directory.CreateDirectory(targetSubDirectory.FullName); } foreach (var sourceFile in sourceFiles) { var targetFile = new FileInfo(_textResolver.Resolve(sourceFile.FullName.Replace(sourceFolder, targetFolder))); _fileResolver.Resolve(sourceFile.FullName, targetFile.FullName); } } } }
using System.IO; using System.Linq; using Common.Logging; namespace NCmdLiner.SolutionCreator.Library.Services { public class FolderResolver : IFolderResolver { private readonly ITextResolver _textResolver; private readonly IFileResolver _fileResolver; private readonly ILog _logger; public FolderResolver(ITextResolver textResolver, IFileResolver fileResolver, ILog logger) { _textResolver = textResolver; _fileResolver = fileResolver; _logger = logger; } public void Resolve(string sourceFolder, string targetFolder) { if (!Directory.Exists(sourceFolder)) throw new DirectoryNotFoundException("Source folder not found: " + sourceFolder); var sourceDirectory = new DirectoryInfo(sourceFolder); var sourceDirectories = sourceDirectory.GetDirectories("*", SearchOption.AllDirectories).ToList(); var sourceFiles = sourceDirectory.GetFiles("*", SearchOption.AllDirectories).ToList(); foreach (var sourceSubDirectory in sourceDirectories) { var targetSubDirectory = new DirectoryInfo(_textResolver.Resolve(sourceSubDirectory.FullName.Replace(sourceFolder, targetFolder))); Directory.CreateDirectory(targetSubDirectory.FullName); } foreach (var sourceFile in sourceFiles) { if (sourceFile.Name == ".git" || sourceFile.Name == ".gitignore") continue; var targetFile = new FileInfo(_textResolver.Resolve(sourceFile.FullName.Replace(sourceFolder, targetFolder))); _fileResolver.Resolve(sourceFile.FullName, targetFile.FullName); } } } }
Disable Entity Framework Lazy Loading
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DeploymentCockpit.Interfaces; namespace DeploymentCockpit.Data { public class UnitOfWorkFactory : IUnitOfWorkFactory { public IUnitOfWork Create() { return new UnitOfWork(new DeploymentCockpitEntities()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DeploymentCockpit.Interfaces; namespace DeploymentCockpit.Data { public class UnitOfWorkFactory : IUnitOfWorkFactory { public IUnitOfWork Create() { var ctx = new DeploymentCockpitEntities(); ctx.Configuration.LazyLoadingEnabled = false; return new UnitOfWork(ctx); } } }
Set default tile size to 32. Change it via config.
using System; using Memoria.Prime.Ini; namespace Memoria { public sealed partial class Configuration { private sealed class GraphicsSection : IniSection { public readonly IniValue<Int32> BattleFPS; public readonly IniValue<Int32> MovieFPS; public readonly IniValue<Int32> BattleSwirlFrames; public readonly IniValue<Boolean> WidescreenSupport; public readonly IniValue<Int32> TileSize; public readonly IniValue<Int32> SkipIntros; public readonly IniValue<Int32> GarnetHair; public GraphicsSection() : base(nameof(GraphicsSection), false) { BattleFPS = BindInt32(nameof(BattleFPS), 15); MovieFPS = BindInt32(nameof(MovieFPS), 15); BattleSwirlFrames = BindInt32(nameof(BattleSwirlFrames), 115); WidescreenSupport = BindBoolean(nameof(WidescreenSupport), true); TileSize = BindInt32(nameof(TileSize), 64); SkipIntros = BindInt32(nameof(SkipIntros), 0); GarnetHair = BindInt32(nameof(GarnetHair), 0); } } } }
using System; using Memoria.Prime.Ini; namespace Memoria { public sealed partial class Configuration { private sealed class GraphicsSection : IniSection { public readonly IniValue<Int32> BattleFPS; public readonly IniValue<Int32> MovieFPS; public readonly IniValue<Int32> BattleSwirlFrames; public readonly IniValue<Boolean> WidescreenSupport; public readonly IniValue<Int32> TileSize; public readonly IniValue<Int32> SkipIntros; public readonly IniValue<Int32> GarnetHair; public GraphicsSection() : base(nameof(GraphicsSection), false) { BattleFPS = BindInt32(nameof(BattleFPS), 15); MovieFPS = BindInt32(nameof(MovieFPS), 15); BattleSwirlFrames = BindInt32(nameof(BattleSwirlFrames), 115); WidescreenSupport = BindBoolean(nameof(WidescreenSupport), true); TileSize = BindInt32(nameof(TileSize), 32); SkipIntros = BindInt32(nameof(SkipIntros), 0); GarnetHair = BindInt32(nameof(GarnetHair), 0); } } } }
Revert "Height and width should be optional according to the spec."
using Digirati.IIIF.Model.JsonLD; using Digirati.IIIF.Serialisation; using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types.ImageApi { // Also known as an "info.json" public class ImageService : JSONLDBase, IImageService, IHasService { // Allow additional context //public override dynamic Context //{ // get { return "http://iiif.io/api/image/2/context.json"; } //} [JsonProperty(Order = 4, PropertyName = "protocol")] public string Protocol { get { return "http://iiif.io/api/image"; } } [JsonProperty(Order = 35, PropertyName = "height")] public int? Height { get; set; } [JsonProperty(Order = 36, PropertyName = "width")] public int? Width { get; set; } [JsonProperty(Order = 37, PropertyName = "sizes")] public Size[] Sizes { get; set; } [JsonProperty(Order = 38, PropertyName = "tiles")] public TileSource[] Tiles { get; set; } // IProfile or IProfile[] [JsonProperty(Order = 39, PropertyName = "profile")] [JsonConverter(typeof(ProfileSerialiser))] public dynamic Profile { get; set; } // Service or Service[] - not currently an interface [JsonProperty(Order = 99, PropertyName = "service")] [JsonConverter(typeof(ServiceSerialiser))] public dynamic Service { get; set; } } }
using Digirati.IIIF.Model.JsonLD; using Digirati.IIIF.Serialisation; using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types.ImageApi { // Also known as an "info.json" public class ImageService : JSONLDBase, IImageService, IHasService { // Allow additional context //public override dynamic Context //{ // get { return "http://iiif.io/api/image/2/context.json"; } //} [JsonProperty(Order = 4, PropertyName = "protocol")] public string Protocol { get { return "http://iiif.io/api/image"; } } [JsonProperty(Order = 35, PropertyName = "height")] public int Height { get; set; } [JsonProperty(Order = 36, PropertyName = "width")] public int Width { get; set; } [JsonProperty(Order = 37, PropertyName = "sizes")] public Size[] Sizes { get; set; } [JsonProperty(Order = 38, PropertyName = "tiles")] public TileSource[] Tiles { get; set; } // IProfile or IProfile[] [JsonProperty(Order = 39, PropertyName = "profile")] [JsonConverter(typeof(ProfileSerialiser))] public dynamic Profile { get; set; } // Service or Service[] - not currently an interface [JsonProperty(Order = 99, PropertyName = "service")] [JsonConverter(typeof(ServiceSerialiser))] public dynamic Service { get; set; } } }
Fix crash when starting administrative by typo in filename
using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; namespace HotChocolatey.Administrative { public class AdministrativeCommanderProvider { private Process administrativeProcess; public AdministrativeCommander Create(Action<string> outputLineCallback) { StartAdmin(); return new AdministrativeCommander(outputLineCallback); } public void Close() { if (!(administrativeProcess?.HasExited ?? true)) { new AdministrativeCommander(a => { }).Die(); } } private void StartAdmin() { if (administrativeProcess?.HasExited ?? true) { administrativeProcess = new Process { StartInfo = { FileName = GetFileName(), Verb = "runas", CreateNoWindow = true, UseShellExecute = true, WindowStyle = ProcessWindowStyle.Hidden } }; administrativeProcess.Start(); Thread.Sleep(100); } } private static string GetFileName() { return Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "HotChocolateyAdministrator.exe"); } } }
using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; namespace HotChocolatey.Administrative { public class AdministrativeCommanderProvider { private Process administrativeProcess; public AdministrativeCommander Create(Action<string> outputLineCallback) { StartAdmin(); return new AdministrativeCommander(outputLineCallback); } public void Close() { if (!(administrativeProcess?.HasExited ?? true)) { new AdministrativeCommander(a => { }).Die(); } } private void StartAdmin() { if (administrativeProcess?.HasExited ?? true) { administrativeProcess = new Process { StartInfo = { FileName = GetFileName(), Verb = "runas", CreateNoWindow = true, UseShellExecute = true, WindowStyle = ProcessWindowStyle.Hidden } }; administrativeProcess.Start(); Thread.Sleep(100); } } private static string GetFileName() { return Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "HotChocolatey.Administrator.exe"); } } }
Add AssemblyFileVersion attribute to assembly
// ----------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Zack Loveless"> // Copyright (c) Zack Loveless. All rights reserved. // </copyright> // ----------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyTitle("Lantea.Core")] [assembly: AssemblyDescription("")]
// ----------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Zack Loveless"> // Copyright (c) Zack Loveless. All rights reserved. // </copyright> // ----------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyTitle("Lantea.Core")] [assembly: AssemblyDescription("")] //[assembly: AssemblyFileVersion("1.0.1")]
Add observable that fires when a section view is about to be created
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()); } } }
using System; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using SolidWorks.Interop.sldworks; namespace SolidworksAddinFramework { public static class ModelViewManagerExtensions { private static readonly ISubject<SectionViewData> _CreateSectionViewObservable = new Subject<SectionViewData>(); public static IObservable<SectionViewData> CreateSectionViewObservable => _CreateSectionViewObservable.AsObservable(); public static IDisposable CreateSectionView(this IModelViewManager modelViewManager, Action<SectionViewData> config) { var data = modelViewManager.CreateSectionViewData(); config(data); _CreateSectionViewObservable.OnNext(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()); } } }
Resolve ambiguity by using HTTP verbs.
 using System.Web.Mvc; namespace OdeToFood.Controllers { public class CuisineController : Controller { // // GET: /Cuisine/ // Without HTTP verbs, invoking search is ambiguous. (Note that the // MVC framework finds the request ambiguous even though R# // reports that the version of Search with the optional parameter // is **hidden** by the parameterless version.) public ActionResult Search(string name = "french") { // Back to returning simple content. var encodedName = Server.HtmlEncode(name); return Content(encodedName); } public ActionResult Search() { return Content("Search!"); } } }
 using System.Web.Mvc; namespace OdeToFood.Controllers { public class CuisineController : Controller { // // GET: /Cuisine/ // Using HTTP verbs allows the framework to resolve the ambiguity. [HttpPost] public ActionResult Search(string name = "french") { // Back to returning simple content. var encodedName = Server.HtmlEncode(name); return Content(encodedName); } [HttpGet] public ActionResult Search() { return Content("Search!"); } } }
Allow API beatmap requests using interface type
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly BeatmapInfo beatmapInfo; public GetBeatmapRequest(BeatmapInfo beatmapInfo) { this.beatmapInfo = beatmapInfo; } protected override string Target => $@"beatmaps/lookup?id={beatmapInfo.OnlineBeatmapID}&checksum={beatmapInfo.MD5Hash}&filename={System.Uri.EscapeUriString(beatmapInfo.Path ?? string.Empty)}"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; #nullable enable namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly IBeatmapInfo beatmapInfo; private readonly string filename; public GetBeatmapRequest(IBeatmapInfo beatmapInfo) { this.beatmapInfo = beatmapInfo; filename = (beatmapInfo as BeatmapInfo)?.Path ?? string.Empty; } protected override string Target => $@"beatmaps/lookup?id={beatmapInfo.OnlineID}&checksum={beatmapInfo.MD5Hash}&filename={System.Uri.EscapeUriString(filename)}"; } }
Add new block types to the enum
using System; namespace ValveResourceFormat { public enum BlockType { #pragma warning disable 1591 RERL = 1, REDI, NTRO, DATA, VBIB, VXVS, SNAP, #pragma warning restore 1591 } }
using System; namespace ValveResourceFormat { public enum BlockType { #pragma warning disable 1591 RERL = 1, REDI, NTRO, DATA, VBIB, VXVS, SNAP, CTRL, MDAT, MBUF, ANIM, ASEQ, AGRP, PHYS, #pragma warning restore 1591 } }
Rename "Latency Monitor" widget to "Network Monitor"
namespace DesktopWidgets.Widgets.LatencyMonitor { public static class Metadata { public const string FriendlyName = "Latency Monitor"; } }
namespace DesktopWidgets.Widgets.LatencyMonitor { public static class Metadata { public const string FriendlyName = "Network Monitor"; } }
Fix poison and short term effects that weren't working due to missing call to effectResult on DecreaseCT.
using System; using System.Xml; using Magecrawl.GameEngine.Effects.EffectResults; namespace Magecrawl.GameEngine.Effects { internal class ShortTermEffect : StatusEffect { public ShortTermEffect() { CTLeft = 0; m_effectResult = null; } public ShortTermEffect(EffectResult effect) { CTLeft = 0; m_effectResult = effect; } public int CTLeft { get; set; } public void Extend(double ratio) { CTLeft = (int)(CTLeft * ratio); } public virtual void DecreaseCT(int decrease) { CTLeft -= decrease; } internal override void Dismiss() { CTLeft = 0; } internal override void SetDefaults() { CTLeft = m_effectResult.DefaultEffectLength; } #region IXmlSerializable Members public override void ReadXml(XmlReader reader) { base.ReadXml(reader); CTLeft = reader.ReadElementContentAsInt(); } public override void WriteXml(XmlWriter writer) { base.WriteXml(writer); writer.WriteElementString("CTLeft", CTLeft.ToString()); } #endregion } }
using System; using System.Xml; using Magecrawl.GameEngine.Effects.EffectResults; namespace Magecrawl.GameEngine.Effects { internal class ShortTermEffect : StatusEffect { public ShortTermEffect() { CTLeft = 0; m_effectResult = null; } public ShortTermEffect(EffectResult effect) { CTLeft = 0; m_effectResult = effect; } public int CTLeft { get; set; } public void Extend(double ratio) { CTLeft = (int)(CTLeft * ratio); } public virtual void DecreaseCT(int decrease) { CTLeft -= decrease; m_effectResult.DecreaseCT(decrease, CTLeft); } internal override void Dismiss() { CTLeft = 0; } internal override void SetDefaults() { CTLeft = m_effectResult.DefaultEffectLength; } #region IXmlSerializable Members public override void ReadXml(XmlReader reader) { base.ReadXml(reader); CTLeft = reader.ReadElementContentAsInt(); } public override void WriteXml(XmlWriter writer) { base.WriteXml(writer); writer.WriteElementString("CTLeft", CTLeft.ToString()); } #endregion } }
Add Documents property to the user model.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CompetitionPlatform.Models { public class AuthenticateModel { public string FullName { get; set; } public string Password { get; set; } } public class CompetitionPlatformUser { public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string GetFullName() { return FirstName + " " + LastName; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CompetitionPlatform.Models { public class AuthenticateModel { public string FullName { get; set; } public string Password { get; set; } } public class CompetitionPlatformUser { public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Documents { get; set; } public string GetFullName() { return FirstName + " " + LastName; } } }
Add test settings loading from enviroment for appVeyor.
using System; using System.IO; using Newtonsoft.Json; namespace VimeoDotNet.Tests.Settings { internal class SettingsLoader { private const string SETTINGS_FILE = "vimeoSettings.json"; public static VimeoApiTestSettings LoadSettings() { if (!File.Exists(SETTINGS_FILE)) { // File was not found so create a new one with blanks SaveSettings(new VimeoApiTestSettings()); throw new Exception(string.Format("The file {0} was not found. A file was created, please fill in the information", SETTINGS_FILE)); } var json = File.ReadAllText(SETTINGS_FILE); return JsonConvert.DeserializeObject<VimeoApiTestSettings>(json); } public static void SaveSettings(VimeoApiTestSettings settings) { var json = JsonConvert.SerializeObject(settings, Formatting.Indented); System.IO.File.WriteAllText(SETTINGS_FILE, json); } } }
using System; using System.IO; using Newtonsoft.Json; namespace VimeoDotNet.Tests.Settings { internal class SettingsLoader { private const string SETTINGS_FILE = "vimeoSettings.json"; public static VimeoApiTestSettings LoadSettings() { if (!File.Exists(SETTINGS_FILE)) { // File was not found so create a new one with blanks SaveSettings(new VimeoApiTestSettings()); throw new Exception(string.Format("The file {0} was not found. A file was created, please fill in the information", SETTINGS_FILE)); } var fromEnv = GetSettingsFromEnvVars(); if (fromEnv.UserId != 0) return fromEnv; var json = File.ReadAllText(SETTINGS_FILE); return JsonConvert.DeserializeObject<VimeoApiTestSettings>(json); } private static VimeoApiTestSettings GetSettingsFromEnvVars() { long userId; long.TryParse(Environment.GetEnvironmentVariable("UserId"), out userId); long albumId; long.TryParse(Environment.GetEnvironmentVariable("AlbumId"), out albumId); long channelId; long.TryParse(Environment.GetEnvironmentVariable("ChannelId"), out channelId); long videoId; long.TryParse(Environment.GetEnvironmentVariable("VideoId"), out videoId); return new VimeoApiTestSettings() { ClientId = Environment.GetEnvironmentVariable("ClientId"), ClientSecret = Environment.GetEnvironmentVariable("ClientSecret"), AccessToken = Environment.GetEnvironmentVariable("AccessToken"), UserId = userId, AlbumId = albumId, ChannelId = channelId, VideoId = videoId, }; } public static void SaveSettings(VimeoApiTestSettings settings) { var json = JsonConvert.SerializeObject(settings, Formatting.Indented); System.IO.File.WriteAllText(SETTINGS_FILE, json); } } }
Use Substitution character instead of question mark
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Octet.cs" company="Steven Liekens"> // The MIT License (MIT) // </copyright> // <summary> // // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using JetBrains.Annotations; using Txt.Core; namespace Txt.ABNF.Core.OCTET { public class Octet : Element { /// <summary>Initializes a new instance of the <see cref="Element" /> class with a given element to copy.</summary> /// <param name="element">The element to copy.</param> /// <exception cref="ArgumentNullException">The value of <paramref name="element" /> is a null reference.</exception> public Octet([NotNull] Element element) : base(element) { } /// <summary> /// Initializes a new instance of the <see cref="Element" /> class with a given string of terminal values and its /// context. /// </summary> /// <param name="terminals">The terminal values.</param> /// <param name="context">An object that describes the current element's context.</param> /// <exception cref="ArgumentNullException"> /// The value of <paramref name="terminals" /> or <paramref name="context" /> is a /// null reference. /// </exception> public Octet(int value, [NotNull] ITextContext context) : base("?", context) { Value = value; } public int Value { get; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Octet.cs" company="Steven Liekens"> // The MIT License (MIT) // </copyright> // <summary> // // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using JetBrains.Annotations; using Txt.Core; namespace Txt.ABNF.Core.OCTET { public class Octet : Element { /// <summary>Initializes a new instance of the <see cref="Element" /> class with a given element to copy.</summary> /// <param name="element">The element to copy.</param> /// <exception cref="ArgumentNullException">The value of <paramref name="element" /> is a null reference.</exception> public Octet([NotNull] Element element) : base(element) { } /// <summary> /// Initializes a new instance of the <see cref="Element" /> class with a given string of terminal values and its /// context. /// </summary> /// <param name="terminals">The terminal values.</param> /// <param name="context">An object that describes the current element's context.</param> /// <exception cref="ArgumentNullException"> /// The value of <paramref name="terminals" /> or <paramref name="context" /> is a /// null reference. /// </exception> public Octet(int value, [NotNull] ITextContext context) : base("\uFFFD", context) { Value = value; } public int Value { get; } } }
Simplify finding the last completed attempt
using LiveSplit.Options; using System; using System.Linq; namespace LiveSplit.Model.Comparisons { public class LastCompletedRunComparisonGenerator : IComparisonGenerator { public IRun Run { get; set; } public const string ComparisonName = "Last Completed Run"; public const string ShortComparisonName = "Last Completed Run"; public string Name => ComparisonName; public LastCompletedRunComparisonGenerator(IRun run) { Run = run; } public void Generate(TimingMethod method) { Attempt? mostRecentCompleted = null; foreach (var attempt in Run.AttemptHistory) { if ( attempt.Time[method] != null && ( mostRecentCompleted == null || ( mostRecentCompleted.Value.Ended - attempt.Ended ).Value.Seconds < 0 ) ) { mostRecentCompleted = attempt; } } TimeSpan? totalTime = TimeSpan.Zero; for (var ind = 0; ind < Run.Count; ind++) { TimeSpan? segmentTime; if (mostRecentCompleted != null) segmentTime = Run[ind].SegmentHistory[mostRecentCompleted.Value.Index][method]; else segmentTime = null; var time = new Time(Run[ind].Comparisons[Name]); if (totalTime != null && segmentTime != null) { totalTime += segmentTime; time[method] = totalTime; } else time[method] = null; Run[ind].Comparisons[Name] = time; } } public void Generate(ISettings settings) { Generate(TimingMethod.RealTime); Generate(TimingMethod.GameTime); } } }
using LiveSplit.Options; using System; using System.Linq; namespace LiveSplit.Model.Comparisons { public class LastCompletedRunComparisonGenerator : IComparisonGenerator { public IRun Run { get; set; } public const string ComparisonName = "Last Completed Run"; public const string ShortComparisonName = "Last Run"; public string Name => ComparisonName; public LastCompletedRunComparisonGenerator(IRun run) { Run = run; } public void Generate(TimingMethod method) { Attempt? mostRecentCompleted = null; foreach (var attempt in Run.AttemptHistory.Reverse()) { if (attempt.Time[method] != null) { mostRecentCompleted = attempt; break; } } TimeSpan? totalTime = TimeSpan.Zero; for (var ind = 0; ind < Run.Count; ind++) { TimeSpan? segmentTime; if (mostRecentCompleted != null) segmentTime = Run[ind].SegmentHistory[mostRecentCompleted.Value.Index][method]; else segmentTime = null; var time = new Time(Run[ind].Comparisons[Name]); if (totalTime != null && segmentTime != null) { totalTime += segmentTime; time[method] = totalTime; } else time[method] = null; Run[ind].Comparisons[Name] = time; } } public void Generate(ISettings settings) { Generate(TimingMethod.RealTime); Generate(TimingMethod.GameTime); } } }
Make the devtools controller Admin
using System.Web.Mvc; using Orchard.DevTools.Models; using Orchard.Localization; using Orchard.Mvc.ViewModels; using Orchard.Themes; using Orchard.UI.Notify; namespace Orchard.DevTools.Controllers { [Themed] public class HomeController : Controller { private readonly INotifier _notifier; public HomeController(INotifier notifier) { _notifier = notifier; T = NullLocalizer.Instance; } public Localizer T { get; set; } public ActionResult Index() { return View(new BaseViewModel()); } public ActionResult NotAuthorized() { _notifier.Warning(T("Simulated error goes here.")); return new HttpUnauthorizedResult(); } public ActionResult Simple() { return View(new Simple { Title = "This is a simple text", Quantity = 5 }); } public ActionResult _RenderableAction() { return PartialView("_RenderableAction", "This is render action"); } public ActionResult SimpleMessage() { _notifier.Information(T("Notifier works without BaseViewModel")); return RedirectToAction("Simple"); } [Themed(false)] public ActionResult SimpleNoTheme() { return View("Simple", new Simple { Title = "This is not themed", Quantity = 5 }); } } }
using System.Web.Mvc; using Orchard.DevTools.Models; using Orchard.Localization; using Orchard.Mvc.ViewModels; using Orchard.Themes; using Orchard.UI.Notify; using Orchard.UI.Admin; namespace Orchard.DevTools.Controllers { [Themed] [Admin] public class HomeController : Controller { private readonly INotifier _notifier; public HomeController(INotifier notifier) { _notifier = notifier; T = NullLocalizer.Instance; } public Localizer T { get; set; } public ActionResult Index() { return View(new BaseViewModel()); } public ActionResult NotAuthorized() { _notifier.Warning(T("Simulated error goes here.")); return new HttpUnauthorizedResult(); } public ActionResult Simple() { return View(new Simple { Title = "This is a simple text", Quantity = 5 }); } public ActionResult _RenderableAction() { return PartialView("_RenderableAction", "This is render action"); } public ActionResult SimpleMessage() { _notifier.Information(T("Notifier works without BaseViewModel")); return RedirectToAction("Simple"); } [Themed(false)] public ActionResult SimpleNoTheme() { return View("Simple", new Simple { Title = "This is not themed", Quantity = 5 }); } } }
Enable internal PDF viewer in WPF project
using System.Windows; namespace CefSharp.MinimalExample.Wpf { public partial class App : Application { public App() { //Perform dependency check to make sure all relevant resources are in our output directory. Cef.Initialize(new CefSettings(), shutdownOnProcessExit: true, performDependencyCheck: true); } } }
using System.Windows; namespace CefSharp.MinimalExample.Wpf { public partial class App : Application { public App() { //Perform dependency check to make sure all relevant resources are in our output directory. var settings = new CefSettings(); settings.EnableInternalPdfViewerOffScreen(); Cef.Initialize(settings, shutdownOnProcessExit: true, performDependencyCheck: true); } } }
Disable SQL test for nano
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Data.SqlClient.Tests { public class SqlConnectionBasicTests { [Fact] public void ConnectionTest() { using (TestTdsServer server = TestTdsServer.StartTestServer()) { using (SqlConnection connection = new SqlConnection(server.ConnectionString)) { connection.Open(); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Integ auth on Test server is supported on Windows right now public void IntegratedAuthConnectionTest() { using (TestTdsServer server = TestTdsServer.StartTestServer()) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(server.ConnectionString); builder.IntegratedSecurity = true; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { connection.Open(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Data.SqlClient.Tests { public class SqlConnectionBasicTests { [Fact] public void ConnectionTest() { using (TestTdsServer server = TestTdsServer.StartTestServer()) { using (SqlConnection connection = new SqlConnection(server.ConnectionString)) { connection.Open(); } } } [PlatformSpecific(TestPlatforms.Windows)] // Integ auth on Test server is supported on Windows right now [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))] // https://github.com/dotnet/corefx/issues/19218 public void IntegratedAuthConnectionTest() { using (TestTdsServer server = TestTdsServer.StartTestServer()) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(server.ConnectionString); builder.IntegratedSecurity = true; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { connection.Open(); } } } } }
Add property to report deltas
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Windows; using System.Windows.Input; namespace MouseRx2Wpf { public class EventsExtension<TElement> where TElement : UIElement { public TElement Target { get; } public IObservable<IObservable<Vector>> MouseDrag { get; } public EventsExtension(TElement target) { Target = target; // Replaces events with IObservable objects. var mouseDown = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseDown)).Select(e => e.EventArgs); var mouseMove = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseMove)).Select(e => e.EventArgs); var mouseUp = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseUp)).Select(e => e.EventArgs); var mouseLeave = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseLeave)).Select(e => e.EventArgs); var mouseDownEnd = mouseUp.Merge(mouseLeave); MouseDrag = mouseDown .Select(e => e.GetPosition(Target)) .Select(p0 => mouseMove .TakeUntil(mouseDownEnd) .Select(e => e.GetPosition(Target) - p0)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Windows; using System.Windows.Input; namespace MouseRx2Wpf { public class EventsExtension<TElement> where TElement : UIElement { public TElement Target { get; } public IObservable<IObservable<Vector>> MouseDrag { get; } Point MouseDragLastPoint; public IObservable<Vector> MouseDragDelta { get; } public EventsExtension(TElement target) { Target = target; // Replaces events with IObservable objects. var mouseDown = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseDown)).Select(e => e.EventArgs); var mouseMove = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseMove)).Select(e => e.EventArgs); var mouseUp = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseUp)).Select(e => e.EventArgs); var mouseLeave = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseLeave)).Select(e => e.EventArgs); var mouseDownEnd = mouseUp.Merge(mouseLeave); MouseDrag = mouseDown .Select(e => e.GetPosition(Target)) .Select(p0 => mouseMove .TakeUntil(mouseDownEnd) .Select(e => e.GetPosition(Target) - p0)); // Reports a change vector from the previous position. MouseDragDelta = mouseDown .Select(e => e.GetPosition(Target)) .Do(p => MouseDragLastPoint = p) .SelectMany(p0 => mouseMove .TakeUntil(mouseDownEnd) .Select(e => new { p1 = MouseDragLastPoint, p2 = e.GetPosition(Target) }) .Do(_ => MouseDragLastPoint = _.p2) .Select(_ => _.p2 - _.p1)); } } }
Add fix: use StopWatch instead of DateTime
namespace DotNetRu.Clients.UI.Pages { using System; using DotNetRu.Clients.Portable.Interfaces; using DotNetRu.Clients.Portable.Model; using Xamarin.Forms; public abstract class BasePage : ContentPage, IProvidePageInfo { private DateTime appeared; public abstract AppPage PageType { get; } protected string ItemId { get; set; } protected override void OnAppearing() { this.appeared = DateTime.UtcNow; App.Logger.TrackPage(this.PageType.ToString(), this.ItemId); base.OnAppearing(); } protected override void OnDisappearing() { App.Logger.TrackTimeSpent(this.PageType.ToString(), this.ItemId, DateTime.UtcNow - this.appeared); base.OnDisappearing(); } } }
using System.Diagnostics; namespace DotNetRu.Clients.UI.Pages { using System; using DotNetRu.Clients.Portable.Interfaces; using DotNetRu.Clients.Portable.Model; using Xamarin.Forms; public abstract class BasePage : ContentPage, IProvidePageInfo { private Stopwatch appeared; public abstract AppPage PageType { get; } protected string ItemId { get; set; } protected override void OnAppearing() { this.appeared = Stopwatch.StartNew(); App.Logger.TrackPage(this.PageType.ToString(), this.ItemId); base.OnAppearing(); } protected override void OnDisappearing() { App.Logger.TrackTimeSpent(this.PageType.ToString(), this.ItemId, TimeSpan.FromTicks(DateTime.UtcNow.Ticks).Subtract(this.appeared.Elapsed)); base.OnDisappearing(); } } }
Refactor artwork clean up code
using System; using System.Collections.Generic; using System.Linq; using Windows.Storage; using Audiotica.Core.Extensions; using Audiotica.Core.Windows.Helpers; using Audiotica.Database.Services.Interfaces; using Audiotica.Windows.Services.Interfaces; using Autofac; namespace Audiotica.Windows.AppEngine.Bootstrppers { public class LibraryBootstrapper : AppBootStrapper { public override void OnStart(IComponentContext context) { var service = context.Resolve<ILibraryService>(); var insights = context.Resolve<IInsightsService>(); using (var timer = insights.TrackTimeEvent("LibraryLoaded")) { service.Load(); timer.AddProperty("Track count", service.Tracks.Count.ToString()); } var matchingService = context.Resolve<ILibraryMatchingService>(); matchingService.OnStartup(); CleanupFiles(service); } private void CleanupFiles(ILibraryService service) { CleanupFiles(s => !service.Tracks.Any(p => p.ArtistArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Artists/"); CleanupFiles(s => !service.Tracks.Any(p => p.ArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Albums/"); } private async void CleanupFiles(Func<string, bool> shouldDelete, string folderPath) { var folder = await StorageHelper.GetFolderAsync(folderPath); var files = await folder.GetFilesAsync(); foreach (var file in files.Where(file => shouldDelete(file.Name))) { await file.DeleteAsync(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Windows.Storage; using Audiotica.Core.Extensions; using Audiotica.Core.Windows.Helpers; using Audiotica.Database.Services.Interfaces; using Audiotica.Windows.Services.Interfaces; using Autofac; namespace Audiotica.Windows.AppEngine.Bootstrppers { public class LibraryBootstrapper : AppBootStrapper { public override void OnStart(IComponentContext context) { var service = context.Resolve<ILibraryService>(); var insights = context.Resolve<IInsightsService>(); using (var timer = insights.TrackTimeEvent("LibraryLoaded")) { service.Load(); timer.AddProperty("Track count", service.Tracks.Count.ToString()); } var matchingService = context.Resolve<ILibraryMatchingService>(); matchingService.OnStartup(); CleanupFiles(s => !service.Tracks.Any(p => p.ArtistArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Artists/"); CleanupFiles(s => !service.Tracks.Any(p => p.ArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Albums/"); } private static async void CleanupFiles(Func<string, bool> shouldDelete, string folderPath) { var folder = await StorageHelper.GetFolderAsync(folderPath); var files = await folder.GetFilesAsync(); foreach (var file in files.Where(file => shouldDelete(file.Name))) { await file.DeleteAsync(); } } } }
Use route handler defined for instance
using System.Web.Mvc; using System.Web.Routing; namespace RestfulRouting { public abstract class Mapper { private readonly IRouteHandler _routeHandler; protected Mapper() { _routeHandler = new MvcRouteHandler(); } protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods) { return new Route(path, new RouteValueDictionary(new { controller, action }), new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }), new MvcRouteHandler()); } } }
using System.Web.Mvc; using System.Web.Routing; namespace RestfulRouting { public abstract class Mapper { private readonly IRouteHandler _routeHandler; protected Mapper() { _routeHandler = new MvcRouteHandler(); } protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods) { return new Route(path, new RouteValueDictionary(new { controller, action }), new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }), _routeHandler); } } }
Fix Less compiler unit tests to expect filename in error messages.
using Should; using Xunit; namespace Cassette.Less { public class LessCompiler_Compile { [Fact] public void Compile_converts_LESS_into_CSS() { var compiler = new LessCompiler(_ => @"@color: #4d926f; #header { color: @color; }"); var css = compiler.CompileFile(""); css.ShouldEqual("#header {\n color: #4d926f;\n}\n"); } [Fact] public void Compile_invalid_LESS_throws_exception() { var compiler = new LessCompiler(_ => "#unclosed_rule {"); var exception = Assert.Throws<LessCompileException>(delegate { compiler.CompileFile(""); }); exception.Message.ShouldEqual("Missing closing `}`"); } [Fact] public void Compile_LESS_that_fails_parsing_throws_LessCompileException() { var compiler = new LessCompiler(_ => "#fail { - }"); var exception = Assert.Throws<LessCompileException>(delegate { compiler.CompileFile(""); }); exception.Message.ShouldEqual("Syntax Error on line 1"); } } }
using Should; using Xunit; namespace Cassette.Less { public class LessCompiler_Compile { [Fact] public void Compile_converts_LESS_into_CSS() { var compiler = new LessCompiler(_ => @"@color: #4d926f; #header { color: @color; }"); var css = compiler.CompileFile("test.less"); css.ShouldEqual("#header {\n color: #4d926f;\n}\n"); } [Fact] public void Compile_invalid_LESS_throws_exception() { var compiler = new LessCompiler(_ => "#unclosed_rule {"); var exception = Assert.Throws<LessCompileException>(delegate { compiler.CompileFile("test.less"); }); exception.Message.ShouldEqual("Less compile error in test.less:\r\nMissing closing `}`"); } [Fact] public void Compile_LESS_that_fails_parsing_throws_LessCompileException() { var compiler = new LessCompiler(_ => "#fail { - }"); var exception = Assert.Throws<LessCompileException>(delegate { compiler.CompileFile("test.less"); }); exception.Message.ShouldEqual("Less compile error in test.less:\r\nSyntax Error on line 1"); } } }
Add light theme setting support
using Microsoft.Win32; namespace EarTrumpet.Services { public static class UserSystemPreferencesService { public static bool IsTransparencyEnabled { get { using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) { return (int)baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").GetValue("EnableTransparency", 0) > 0; } } } public static bool UseAccentColor { get { using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) { return (int)baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").GetValue("ColorPrevalence", 0) > 0; } } } } }
using Microsoft.Win32; namespace EarTrumpet.Services { public static class UserSystemPreferencesService { public static bool IsTransparencyEnabled { get { using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) { return (int)baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").GetValue("EnableTransparency", 0) > 0; } } } public static bool UseAccentColor { get { using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) { return (int)baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").GetValue("ColorPrevalence", 0) > 0; } } } public static bool IsLightTheme { get { using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) { return (int)baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").GetValue("AppsUseLightTheme", 0) > 0; } } } } }
Fix .NET Standard assembly assets path.
using System; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; public static class PackageExporter { [MenuItem("Tools/Export Unitypackage")] public static void Export() { // configure var root = "Scripts/MagicOnion"; var exportPath = "./MagicOnion.Client.Unity.unitypackage"; var path = Path.Combine(Application.dataPath, root); var assets = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories) .Where(x => Path.GetExtension(x) == ".cs" || Path.GetExtension(x) == ".asmdef" || Path.GetExtension(x) == ".json" || Path.GetExtension(x) == ".meta") .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/")) .ToArray(); var netStandardsAsset = Directory.EnumerateFiles(Path.Combine(Application.dataPath, "Plugins/System.Threading.Tasks.Extensions"), "*", SearchOption.AllDirectories) .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/")) .ToArray(); assets = assets.Concat(netStandardsAsset).ToArray(); UnityEngine.Debug.Log("Export below files" + Environment.NewLine + string.Join(Environment.NewLine, assets)); AssetDatabase.ExportPackage( assets, exportPath, ExportPackageOptions.Default); UnityEngine.Debug.Log("Export complete: " + Path.GetFullPath(exportPath)); } }
using System; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; public static class PackageExporter { [MenuItem("Tools/Export Unitypackage")] public static void Export() { // configure var root = "Scripts/MagicOnion"; var exportPath = "./MagicOnion.Client.Unity.unitypackage"; var path = Path.Combine(Application.dataPath, root); var assets = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories) .Where(x => Path.GetExtension(x) == ".cs" || Path.GetExtension(x) == ".asmdef" || Path.GetExtension(x) == ".json" || Path.GetExtension(x) == ".meta") .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/")) .ToArray(); var netStandardsAsset = Directory.EnumerateFiles(Path.Combine(Application.dataPath, "Plugins"), "System.*", SearchOption.AllDirectories) .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/")) .ToArray(); assets = assets.Concat(netStandardsAsset).ToArray(); UnityEngine.Debug.Log("Export below files" + Environment.NewLine + string.Join(Environment.NewLine, assets)); AssetDatabase.ExportPackage( assets, exportPath, ExportPackageOptions.Default); UnityEngine.Debug.Log("Export complete: " + Path.GetFullPath(exportPath)); } }
Change MaxDocs from int to long
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nest { [JsonObject(MemberSerialization.OptIn)] [JsonConverter(typeof(ReadAsTypeJsonConverter<RolloverConditions>))] public interface IRolloverConditions { [JsonProperty("max_age")] Time MaxAge { get; set; } [JsonProperty("max_docs")] int MaxDocs { get; set; } } public class RolloverConditions : IRolloverConditions { public Time MaxAge { get; set; } public int MaxDocs { get; set; } } public class RolloverConditionsDescriptor : DescriptorBase<RolloverConditionsDescriptor, IRolloverConditions>, IRolloverConditions { Time IRolloverConditions.MaxAge { get; set; } int IRolloverConditions.MaxDocs { get; set; } public RolloverConditionsDescriptor MaxAge(Time maxAge) => Assign(a => a.MaxAge = maxAge); public RolloverConditionsDescriptor MaxDocs(int maxDocs) => Assign(a => a.MaxDocs = maxDocs); } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nest { [JsonObject(MemberSerialization.OptIn)] [JsonConverter(typeof(ReadAsTypeJsonConverter<RolloverConditions>))] public interface IRolloverConditions { [JsonProperty("max_age")] Time MaxAge { get; set; } [JsonProperty("max_docs")] long MaxDocs { get; set; } } public class RolloverConditions : IRolloverConditions { public Time MaxAge { get; set; } public long MaxDocs { get; set; } } public class RolloverConditionsDescriptor : DescriptorBase<RolloverConditionsDescriptor, IRolloverConditions>, IRolloverConditions { Time IRolloverConditions.MaxAge { get; set; } long IRolloverConditions.MaxDocs { get; set; } public RolloverConditionsDescriptor MaxAge(Time maxAge) => Assign(a => a.MaxAge = maxAge); public RolloverConditionsDescriptor MaxDocs(int maxDocs) => Assign(a => a.MaxDocs = maxDocs); } }
Replace parantheses with nullable-bool equality operation
// 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.Beatmaps { public static class BeatSyncProviderExtensions { /// <summary> /// Check whether beat sync is currently available. /// </summary> public static bool CheckBeatSyncAvailable(this IBeatSyncProvider provider) => provider.Clock != null; /// <summary> /// Whether the beat sync provider is currently in a kiai section. Should make everything more epic. /// </summary> public static bool CheckIsKiaiTime(this IBeatSyncProvider provider) => provider.Clock != null && (provider.ControlPoints?.EffectPointAt(provider.Clock.CurrentTime).KiaiMode ?? false); } }
// 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.Beatmaps { public static class BeatSyncProviderExtensions { /// <summary> /// Check whether beat sync is currently available. /// </summary> public static bool CheckBeatSyncAvailable(this IBeatSyncProvider provider) => provider.Clock != null; /// <summary> /// Whether the beat sync provider is currently in a kiai section. Should make everything more epic. /// </summary> public static bool CheckIsKiaiTime(this IBeatSyncProvider provider) => provider.Clock != null && provider.ControlPoints?.EffectPointAt(provider.Clock.CurrentTime).KiaiMode == true; } }
Add "Ranked & Approved Beatmaps" section
// 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.Online.API.Requests; using osu.Game.Overlays.Profile.Sections.Beatmaps; namespace osu.Game.Overlays.Profile.Sections { public class BeatmapsSection : ProfileSection { public override string Title => "Beatmaps"; public override string Identifier => "beatmaps"; public BeatmapsSection() { Children = new[] { new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, "Favourite Beatmaps", "None... yet."), }; } } }
// 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.Online.API.Requests; using osu.Game.Overlays.Profile.Sections.Beatmaps; namespace osu.Game.Overlays.Profile.Sections { public class BeatmapsSection : ProfileSection { public override string Title => "Beatmaps"; public override string Identifier => "beatmaps"; public BeatmapsSection() { Children = new[] { new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, "Favourite Beatmaps", "None... yet."), new PaginatedBeatmapContainer(BeatmapSetType.Ranked_And_Approved, User, "Ranked & Approved Beatmaps", "None... yet."), }; } } }
Update Console Program with the Repository call - Add the GetRoleMessageForNoneTest test method to test the None case
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Training.CSharpWorkshop.Tests { [TestClass] public class ProgramTests { [Ignore] [TestMethod] public void IgnoreTest() { Assert.Fail(); } [TestMethod()] public void GetRoleMessageForAdminTest() { // Arrange var userName = "Andrew"; var expected = "Role: Admin."; // Act var actual = Program.GetRoleMessage(userName); // Assert Assert.AreEqual(expected, actual); } [TestMethod()] public void GetRoleMessageForGuestTest() { // Arrange var userName = "Dave"; var expected = "Role: Guest."; // Act var actual = Program.GetRoleMessage(userName); // Assert Assert.AreEqual(expected, actual); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Training.CSharpWorkshop.Tests { [TestClass] public class ProgramTests { [Ignore] [TestMethod] public void IgnoreTest() { Assert.Fail(); } [TestMethod()] public void GetRoleMessageForAdminTest() { // Arrange var userName = "Andrew"; var expected = "Role: Admin."; // Act var actual = Program.GetRoleMessage(userName); // Assert Assert.AreEqual(expected, actual); } [TestMethod()] public void GetRoleMessageForGuestTest() { // Arrange var userName = "Dave"; var expected = "Role: Guest."; // Act var actual = Program.GetRoleMessage(userName); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void GetRoleMessageForNoneTest() { // Arrange var userName = "Don"; var expected = "Role: None."; // Act var actual = Program.GetRoleMessage(userName); // Assert Assert.AreEqual(expected, actual); } } }
Standardize JSON date/time values on UTC
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Totem.Runtime.Json { /// <summary> /// Settings used when serializing and deserializing objects in the Totem runtime /// </summary> public class TotemSerializerSettings : JsonSerializerSettings { public TotemSerializerSettings() { Formatting = Formatting.Indented; TypeNameHandling = TypeNameHandling.Auto; ContractResolver = new TotemContractResolver(); Binder = new TotemSerializationBinder(); Converters.Add(new StringEnumConverter()); Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffZ" }); } public bool CamelCaseProperties { get { var knownResolver = ContractResolver as TotemContractResolver; return knownResolver != null && knownResolver.CamelCaseProperties; } set { var knownResolver = ContractResolver as TotemContractResolver; if(knownResolver != null) { knownResolver.CamelCaseProperties = value; } } } public JsonSerializer CreateSerializer() { return JsonSerializer.Create(this); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Totem.Runtime.Json { /// <summary> /// Settings used when serializing and deserializing objects in the Totem runtime /// </summary> public class TotemSerializerSettings : JsonSerializerSettings { public TotemSerializerSettings() { Formatting = Formatting.Indented; TypeNameHandling = TypeNameHandling.Auto; ContractResolver = new TotemContractResolver(); Binder = new TotemSerializationBinder(); Converters.AddRange( new StringEnumConverter(), new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal, DateTimeFormat = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern }); DateTimeZoneHandling = DateTimeZoneHandling.Utc; DateFormatHandling = DateFormatHandling.IsoDateFormat; } public bool CamelCaseProperties { get { var knownResolver = ContractResolver as TotemContractResolver; return knownResolver != null && knownResolver.CamelCaseProperties; } set { var knownResolver = ContractResolver as TotemContractResolver; if(knownResolver != null) { knownResolver.CamelCaseProperties = value; } } } public JsonSerializer CreateSerializer() { return JsonSerializer.Create(this); } } }
Add missing xmldoc to interface class
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Input.StateChanges.Events; namespace osu.Framework.Input.StateChanges { public interface ISourcedFromTouch { TouchStateChangeEvent TouchEvent { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Input.StateChanges.Events; namespace osu.Framework.Input.StateChanges { /// <summary> /// Denotes an input which was sourced from a touch event. /// Generally used to mark when an alternate input was triggered from a touch source (ie. touch being emulated as a mouse). /// </summary> public interface ISourcedFromTouch { /// <summary> /// The source touch event. /// </summary> TouchStateChangeEvent TouchEvent { get; set; } } }
Fix for superclass properties (NH-3318)
using System.Reflection; namespace NHibernate.Mapping.ByCode.Impl.CustomizersImpl { public class ComposedIdCustomizer<TEntity> : PropertyContainerCustomizer<TEntity>, IComposedIdMapper<TEntity> where TEntity : class { public ComposedIdCustomizer(IModelExplicitDeclarationsHolder explicitDeclarationsHolder, ICustomizersHolder customizersHolder) : base(explicitDeclarationsHolder, customizersHolder, null) {} protected override void RegisterPropertyMapping<TProperty>(System.Linq.Expressions.Expression<System.Func<TEntity, TProperty>> property, System.Action<IPropertyMapper> mapping) { MemberInfo member = TypeExtensions.DecodeMemberAccessExpression(property); ExplicitDeclarationsHolder.AddAsPartOfComposedId(member); base.RegisterPropertyMapping(property, mapping); } protected override void RegisterManyToOneMapping<TProperty>(System.Linq.Expressions.Expression<System.Func<TEntity, TProperty>> property, System.Action<IManyToOneMapper> mapping) { MemberInfo member = TypeExtensions.DecodeMemberAccessExpression(property); ExplicitDeclarationsHolder.AddAsPartOfComposedId(member); base.RegisterManyToOneMapping(property, mapping); } } }
using System.Reflection; namespace NHibernate.Mapping.ByCode.Impl.CustomizersImpl { public class ComposedIdCustomizer<TEntity> : PropertyContainerCustomizer<TEntity>, IComposedIdMapper<TEntity> where TEntity : class { public ComposedIdCustomizer(IModelExplicitDeclarationsHolder explicitDeclarationsHolder, ICustomizersHolder customizersHolder) : base(explicitDeclarationsHolder, customizersHolder, null) {} protected override void RegisterPropertyMapping<TProperty>(System.Linq.Expressions.Expression<System.Func<TEntity, TProperty>> property, System.Action<IPropertyMapper> mapping) { MemberInfo member = TypeExtensions.DecodeMemberAccessExpressionOf(property); ExplicitDeclarationsHolder.AddAsPartOfComposedId(member); base.RegisterPropertyMapping(property, mapping); } protected override void RegisterManyToOneMapping<TProperty>(System.Linq.Expressions.Expression<System.Func<TEntity, TProperty>> property, System.Action<IManyToOneMapper> mapping) { MemberInfo member = TypeExtensions.DecodeMemberAccessExpressionOf(property); ExplicitDeclarationsHolder.AddAsPartOfComposedId(member); base.RegisterManyToOneMapping(property, mapping); } } }
Update assembly version to v1.99 to prepare for v2.0 release
using System.Reflection; [assembly: AssemblyCompany("Picoe Software Solutions Inc.")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")] [assembly: AssemblyInformationalVersion("1.3.0")]
using System.Reflection; [assembly: AssemblyCompany("Picoe Software Solutions Inc.")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.99.0.0")] [assembly: AssemblyFileVersion("1.99.0.0")] [assembly: AssemblyInformationalVersion("1.99.0")]
Add link to where the async relay command is from
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace AutoReservation.Ui.ViewModels { public class AsyncRelayCommand : ICommand { protected readonly Predicate<object> _canExecute; protected Func<object, Task> _asyncExecute; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public AsyncRelayCommand(Func<object, Task> execute) : this(execute, null) { } public AsyncRelayCommand(Func<object, Task> asyncExecute, Predicate<object> canExecute) { _asyncExecute = asyncExecute; _canExecute = canExecute; } public bool CanExecute(object parameter) { if (_canExecute == null) { return true; } return _canExecute(parameter); } public async void Execute(object parameter) { await ExecuteAsync(parameter); } protected virtual async Task ExecuteAsync(object parameter) { await _asyncExecute(parameter); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace AutoReservation.Ui.ViewModels { /** * From: http://blog.mycupof.net/2012/08/23/mvvm-asyncdelegatecommand-what-asyncawait-can-do-for-uidevelopment/ */ public class AsyncRelayCommand : ICommand { protected readonly Predicate<object> _canExecute; protected Func<object, Task> _asyncExecute; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public AsyncRelayCommand(Func<object, Task> execute) : this(execute, null) { } public AsyncRelayCommand(Func<object, Task> asyncExecute, Predicate<object> canExecute) { _asyncExecute = asyncExecute; _canExecute = canExecute; } public bool CanExecute(object parameter) { if (_canExecute == null) { return true; } return _canExecute(parameter); } public async void Execute(object parameter) { await ExecuteAsync(parameter); } protected virtual async Task ExecuteAsync(object parameter) { await _asyncExecute(parameter); } } }
Allow for blank status description
using System; using System.Web; namespace WebServer { public class StatusCode : IHttpHandler { public void ProcessRequest(HttpContext context) { string statusCodeString = context.Request.QueryString["statuscode"]; string statusDescription = context.Request.QueryString["statusdescription"]; try { int statusCode = int.Parse(statusCodeString); context.Response.StatusCode = statusCode; if (!string.IsNullOrEmpty(statusDescription)) { context.Response.StatusDescription = statusDescription; } } catch (Exception) { context.Response.StatusCode = 500; context.Response.StatusDescription = "Error parsing statuscode: " + statusCodeString; } } public bool IsReusable { get { return true; } } } }
using System; using System.Web; namespace WebServer { public class StatusCode : IHttpHandler { public void ProcessRequest(HttpContext context) { string statusCodeString = context.Request.QueryString["statuscode"]; string statusDescription = context.Request.QueryString["statusdescription"]; try { int statusCode = int.Parse(statusCodeString); context.Response.StatusCode = statusCode; if (statusDescription != null) { context.Response.StatusDescription = statusDescription; } } catch (Exception) { context.Response.StatusCode = 500; context.Response.StatusDescription = "Error parsing statuscode: " + statusCodeString; } } public bool IsReusable { get { return true; } } } }
Fix bug from 1 to 3
//We are given numbers N and M and the following operations: // * `N = N+1` // * `N = N+2` // * `N = N*2` // - Write a program that finds the shortest sequence of operations from the list above that starts from `N` and finishes in `M`. // - _Hint_: use a queue. // - Example: `N = 5`, `M = 16` // - Sequence: 5 &rarr; 7 &rarr; 8 &rarr; 16 namespace SequenceOfOperations { using System; using System.Collections.Generic; using System.Linq; internal class Program { public static void Main() { int start = 5; int end = 26; var sequence = GetShortestSequence(start, end); Console.WriteLine(string.Join(" -> ", sequence)); } private static IEnumerable<int> GetShortestSequence(int start, int end) { var sequence = new Queue<int>(); while (start <= end) { sequence.Enqueue(end); if (end / 2 >= start) { if (end % 2 == 0) { end /= 2; } else { end--; } } else { if (end - 2 >= start) { end -= 2; } else { end--; } } } return sequence.Reverse(); } } }
//We are given numbers N and M and the following operations: // * `N = N+1` // * `N = N+2` // * `N = N*2` // - Write a program that finds the shortest sequence of operations from the list above that starts from `N` and finishes in `M`. // - _Hint_: use a queue. // - Example: `N = 5`, `M = 16` // - Sequence: 5 &rarr; 7 &rarr; 8 &rarr; 16 namespace SequenceOfOperations { using System; using System.Collections.Generic; using System.Linq; internal class Program { public static void Main() { int start = 5; int end = 26; var sequence = GetShortestSequence(start, end); Console.WriteLine(string.Join(" -> ", sequence)); } private static IEnumerable<int> GetShortestSequence(int start, int end) { var sequence = new Queue<int>(); while (start <= end) { sequence.Enqueue(end); if (end / 2 > start) { if (end % 2 == 0) { end /= 2; } else { end--; } } else { if (end - 2 >= start) { end -= 2; } else { end--; } } } return sequence.Reverse(); } } }
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
Revert "Add test trying to recreate the issue"
using Xunit; using Unity.SolrNetCloudIntegration; using Unity; namespace SolrNet.Cloud.Tests { public class UnityTests { private IUnityContainer Setup() { return new SolrNetContainerConfiguration().ConfigureContainer( new FakeProvider(), new UnityContainer()); } [Fact] public void ShouldResolveBasicOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrBasicOperations<FakeEntity>>()); } [Fact] public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>()); } [Fact] public void ShouldResolveOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrOperations<FakeEntity>>()); } [Fact] public void ShouldResolveReadOnlyOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>()); } [Fact] public void ShouldResolveIOperations () { using (var container = new UnityContainer()) { var cont = new Unity.SolrNetCloudIntegration.SolrNetContainerConfiguration().ConfigureContainer(new FakeProvider(), container); var obj = cont.Resolve<ISolrOperations<Camera>>(); } } public class Camera { [Attributes.SolrField("Name")] public string Name { get; set; } [Attributes.SolrField("UID")] public int UID { get; set; } [Attributes.SolrField("id")] public string Id { get; set; } } } }
using Xunit; using Unity.SolrNetCloudIntegration; using Unity; namespace SolrNet.Cloud.Tests { public class UnityTests { private IUnityContainer Setup() { return new SolrNetContainerConfiguration().ConfigureContainer( new FakeProvider(), new UnityContainer()); } [Fact] public void ShouldResolveBasicOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrBasicOperations<FakeEntity>>()); } [Fact] public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>()); } [Fact] public void ShouldResolveOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrOperations<FakeEntity>>()); } [Fact] public void ShouldResolveReadOnlyOperationsFromStartupContainer() { Assert.NotNull( Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>()); } } }
Fix Environment Variable check for TeamCity Log
using System; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Module.Shared; using CakeBuildLog = Cake.Core.Diagnostics.CakeBuildLog; namespace Cake.TeamCity.Module { public class TeamCityLog : ICakeLog { public TeamCityLog(IConsole console, Verbosity verbosity = Verbosity.Normal) { _cakeLogImplementation = new CakeBuildLog(console, verbosity); } private readonly ICakeLog _cakeLogImplementation; public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args) { if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("TF_BUILD"))) { switch (level) { case LogLevel.Fatal: case LogLevel.Error: _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information, "##teamcity[buildProblem description='{0}']", string.Format(format, args)); break; case LogLevel.Warning: _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information, "##teamcity[message text='{0}' status='WARNING']", string.Format(format, args)); break; case LogLevel.Information: case LogLevel.Verbose: case LogLevel.Debug: break; default: throw new ArgumentOutOfRangeException(nameof(level), level, null); } } _cakeLogImplementation.Write(verbosity, level, format, args); } public Verbosity Verbosity { get { return _cakeLogImplementation.Verbosity; } set { _cakeLogImplementation.Verbosity = value; } } } }
using System; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Module.Shared; using CakeBuildLog = Cake.Core.Diagnostics.CakeBuildLog; namespace Cake.TeamCity.Module { public class TeamCityLog : ICakeLog { public TeamCityLog(IConsole console, Verbosity verbosity = Verbosity.Normal) { _cakeLogImplementation = new CakeBuildLog(console, verbosity); } private readonly ICakeLog _cakeLogImplementation; public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args) { if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) { switch (level) { case LogLevel.Fatal: case LogLevel.Error: _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information, "##teamcity[buildProblem description='{0}']", string.Format(format, args)); break; case LogLevel.Warning: _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information, "##teamcity[message text='{0}' status='WARNING']", string.Format(format, args)); break; case LogLevel.Information: case LogLevel.Verbose: case LogLevel.Debug: break; default: throw new ArgumentOutOfRangeException(nameof(level), level, null); } } _cakeLogImplementation.Write(verbosity, level, format, args); } public Verbosity Verbosity { get { return _cakeLogImplementation.Verbosity; } set { _cakeLogImplementation.Verbosity = value; } } } }
Remove service event source for now
using System; using System.Threading.Tasks; using Messages_Stateless; using NServiceBus; namespace Back_Stateless { public class SubmitOrderHandler : IHandleMessages<SubmitOrder> { private OrderContext orderContext; public SubmitOrderHandler(OrderContext orderContext) { this.orderContext = orderContext; } public async Task Handle(SubmitOrder message, IMessageHandlerContext context) { var order = new Order { ConfirmationId = message.ConfirmationId, SubmittedOn = message.SubmittedOn, ProcessedOn = DateTime.UtcNow }; orderContext.Orders.Add(order); await orderContext.SaveChangesAsync(); ServiceEventSource.Current.Write(nameof(SubmitOrder), message); } } }
using System; using System.Threading.Tasks; using Messages_Stateless; using NServiceBus; namespace Back_Stateless { public class SubmitOrderHandler : IHandleMessages<SubmitOrder> { private OrderContext orderContext; public SubmitOrderHandler(OrderContext orderContext) { this.orderContext = orderContext; } public async Task Handle(SubmitOrder message, IMessageHandlerContext context) { var order = new Order { ConfirmationId = message.ConfirmationId, SubmittedOn = message.SubmittedOn, ProcessedOn = DateTime.UtcNow }; orderContext.Orders.Add(order); await orderContext.SaveChangesAsync(); } } }
Allow to run build even if git repo informations are not available
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); _versionContext.Git = GitVersion(); return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { var increment = 0; while(increment < 10) { try { var version = VersionContext.BuildVersion; if(increment > 0) version += "-" + increment; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; } } }
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); try { _versionContext.Git = GitVersion(); } catch { _versionContext.Git = new Cake.Common.Tools.GitVersion.GitVersion(); } return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { var increment = 0; while(increment < 10) { try { var version = VersionContext.BuildVersion; if(increment > 0) version += "-" + increment; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; } } }
Add tests to check if contracts are working (currently disabled)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RazorEngine; using NUnit.Framework; namespace Test.RazorEngine { /// <summary> /// Various general tests. /// </summary> [TestFixture] public class VariousTestsFixture { /// <summary> /// Test if we can call GetTypes on the RazorEngine assembly. /// This will make sure all SecurityCritical attributes are valid. /// </summary> [Test] public void AssemblyIsScannable() { typeof(Engine).Assembly.GetTypes(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RazorEngine; using NUnit.Framework; namespace Test.RazorEngine { /// <summary> /// Various general tests. /// </summary> [TestFixture] public class VariousTestsFixture { /// <summary> /// Test if we can call GetTypes on the RazorEngine assembly. /// This will make sure all SecurityCritical attributes are valid. /// </summary> [Test] public void AssemblyIsScannable() { typeof(Engine).Assembly.GetTypes(); } /* /// <summary> /// Check that Contracts are enabled and work on this build machine. /// </summary> [Test] [ExpectedException(typeof(ArgumentException))] public void ConstractsWork() { System.Diagnostics.Contracts.Contract.Requires<ArgumentException>(false); } [Test] //[ExpectedException(typeof(Exception))] public void ConstractsWork_2() { System.Diagnostics.Contracts.Contract.Requires(false); }*/ } }
Fix nullability mismatch on partial declarations
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; namespace System.Collections.Generic { /// <summary> /// These public methods are required by RegexWriter. /// </summary> internal ref partial struct ValueListBuilder<T> { [MethodImpl(MethodImplOptions.AggressiveInlining)] public T Pop() { _pos--; return _span[_pos]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Runtime.CompilerServices; namespace System.Collections.Generic { /// <summary> /// These public methods are required by RegexWriter. /// </summary> internal ref partial struct ValueListBuilder<T> { [MethodImpl(MethodImplOptions.AggressiveInlining)] public T Pop() { _pos--; return _span[_pos]; } } }
Read panorama name entries into a list
using System; using System.IO; using System.Text; namespace ValveResourceFormat.ResourceTypes { public class Panorama : Blocks.ResourceData { public byte[] Data { get; private set; } public uint Crc32 { get; private set; } public override void Read(BinaryReader reader, Resource resource) { reader.BaseStream.Position = this.Offset; Crc32 = reader.ReadUInt32(); var size = reader.ReadUInt16(); int headerSize = 4 + 2; for (var i = 0; i < size; i++) { var name = reader.ReadNullTermString(Encoding.UTF8); reader.ReadBytes(4); // TODO: ???? headerSize += name.Length + 1 + 4; // string length + null byte + 4 bytes } Data = reader.ReadBytes((int)this.Size - headerSize); if (ValveResourceFormat.Crc32.Compute(Data) != Crc32) { throw new InvalidDataException("CRC32 mismatch for read data."); } } public override string ToString() { return Encoding.UTF8.GetString(Data); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace ValveResourceFormat.ResourceTypes { public class Panorama : Blocks.ResourceData { public class NameEntry { public string Name { get; set; } public uint CRC32 { get; set; } // TODO: unconfirmed } public List<NameEntry> Names; public byte[] Data { get; private set; } public uint CRC32 { get; private set; } public Panorama() { Names = new List<NameEntry>(); } public override void Read(BinaryReader reader, Resource resource) { reader.BaseStream.Position = this.Offset; CRC32 = reader.ReadUInt32(); var size = reader.ReadUInt16(); int headerSize = 4 + 2; for (var i = 0; i < size; i++) { var entry = new NameEntry { Name = reader.ReadNullTermString(Encoding.UTF8), CRC32 = reader.ReadUInt32(), }; Names.Add(entry); headerSize += entry.Name.Length + 1 + 4; // string length + null byte + 4 bytes } Data = reader.ReadBytes((int)this.Size - headerSize); if (Crc32.Compute(Data) != CRC32) { throw new InvalidDataException("CRC32 mismatch for read data."); } } public override string ToString() { return Encoding.UTF8.GetString(Data); } } }
Update stack trace decoding to match Java
// Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. // // 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 Hazelcast.Util; namespace Hazelcast.Client.Protocol.Codec { internal static class StackTraceElementCodec { public static StackTraceElement Decode(IClientMessage clientMessage) { var declaringClass = clientMessage.GetStringUtf8(); var methodName = clientMessage.GetStringUtf8(); var fileName_notNull = clientMessage.GetBoolean(); string fileName = null; if (fileName_notNull) { fileName = clientMessage.GetStringUtf8(); } var lineNumber = clientMessage.GetInt(); return new StackTraceElement(declaringClass, methodName, fileName, lineNumber); } } }
// Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. // // 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 Hazelcast.Util; namespace Hazelcast.Client.Protocol.Codec { internal static class StackTraceElementCodec { public static StackTraceElement Decode(IClientMessage clientMessage) { var declaringClass = clientMessage.GetStringUtf8(); var methodName = clientMessage.GetStringUtf8(); var filename_Null = clientMessage.GetBoolean(); string fileName = null; if (!filename_Null) { fileName = clientMessage.GetStringUtf8(); } var lineNumber = clientMessage.GetInt(); return new StackTraceElement(declaringClass, methodName, fileName, lineNumber); } } }
Use an extension to parse the RTE macros into rendered macros
using Umbraco.Core; using Archetype.Umbraco.Models; namespace Archetype.Umbraco.Extensions { public static class Extensions { //lifted from the core as it is marked 'internal' public static bool DetectIsJson(this string input) { input = input.Trim(); return input.StartsWith("{") && input.EndsWith("}") || input.StartsWith("[") && input.EndsWith("]"); } public static bool IsArchetype(this Property prop) { return prop.PropertyEditorAlias.InvariantEquals(Constants.PropertyEditorAlias); } } }
using System; using System.Web; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; using Umbraco.Core; using Umbraco.Web; using Archetype.Umbraco.Models; namespace Archetype.Umbraco.Extensions { public static class Extensions { //lifted from the core as it is marked 'internal' public static bool DetectIsJson(this string input) { input = input.Trim(); return input.StartsWith("{") && input.EndsWith("}") || input.StartsWith("[") && input.EndsWith("]"); } public static bool IsArchetype(this Property prop) { return prop.PropertyEditorAlias.InvariantEquals(Constants.PropertyEditorAlias); } public static HtmlString ParseMacros(this string input, UmbracoHelper umbHelper) { var regex = new Regex("(<div class=\".*umb-macro-holder.*\".*macroAlias=\"(\\w*)\"(.*)\\/>.*\\/div>)"); var match = regex.Match(input); while (match.Success) { var parms = match.Groups[3].ToString().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); var dictionary = new Dictionary<string, object>(); foreach (var parm in parms) { var thisParm = parm.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries); dictionary.Add(thisParm[0], thisParm[1].Substring(1, thisParm[1].Length - 2)); } input = input.Replace(match.Groups[0].ToString(), umbHelper.RenderMacro(match.Groups[2].ToString(), dictionary).ToHtmlString()); match = regex.Match(input); } return new HtmlString(input); } } }
Fix click on item event after adding header wrapper
using System; using System.Linq; using Android.OS; using Android.Views; using Android.Widget; using Toggl.Joey.UI.Adapters; using ListFragment = Android.Support.V4.App.ListFragment; namespace Toggl.Joey.UI.Fragments { public class RecentTimeEntriesListFragment : ListFragment { public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); var headerView = new View (Activity); headerView.SetMinimumHeight (6); ListView.AddHeaderView (headerView); ListAdapter = new RecentTimeEntriesAdapter (); } public override void OnListItemClick (ListView l, View v, int position, long id) { var adapter = l.Adapter as RecentTimeEntriesAdapter; if (adapter == null) return; var model = adapter.GetModel (position); if (model == null) return; model.Continue (); } } }
using System; using System.Linq; using Android.OS; using Android.Views; using Android.Widget; using Toggl.Joey.UI.Adapters; using ListFragment = Android.Support.V4.App.ListFragment; namespace Toggl.Joey.UI.Fragments { public class RecentTimeEntriesListFragment : ListFragment { public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); var headerView = new View (Activity); headerView.SetMinimumHeight (6); ListView.AddHeaderView (headerView); ListAdapter = new RecentTimeEntriesAdapter (); } public override void OnListItemClick (ListView l, View v, int position, long id) { var headerAdapter = l.Adapter as HeaderViewListAdapter; RecentTimeEntriesAdapter adapter = null; if (headerAdapter != null) adapter = headerAdapter.WrappedAdapter as RecentTimeEntriesAdapter; if (adapter == null) return; var model = adapter.GetModel (position); if (model == null) return; model.Continue (); } } }
Add user beatmap availability property
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using Newtonsoft.Json; using osu.Game.Users; namespace osu.Game.Online.Multiplayer { [Serializable] public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser> { public readonly int UserID; public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle; public User? User { get; set; } [JsonConstructor] public MultiplayerRoomUser(in int userId) { UserID = userId; } public bool Equals(MultiplayerRoomUser other) { if (ReferenceEquals(this, other)) return true; return UserID == other.UserID; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((MultiplayerRoomUser)obj); } public override int GetHashCode() => UserID.GetHashCode(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using Newtonsoft.Json; using osu.Game.Online.Rooms; using osu.Game.Users; namespace osu.Game.Online.Multiplayer { [Serializable] public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser> { public readonly int UserID; public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle; /// <summary> /// The availability state of the beatmap, set to <see cref="DownloadState.LocallyAvailable"/> by default. /// </summary> public BeatmapAvailability BeatmapAvailability { get; set; } = new BeatmapAvailability(DownloadState.LocallyAvailable); public User? User { get; set; } [JsonConstructor] public MultiplayerRoomUser(in int userId) { UserID = userId; } public bool Equals(MultiplayerRoomUser other) { if (ReferenceEquals(this, other)) return true; return UserID == other.UserID; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((MultiplayerRoomUser)obj); } public override int GetHashCode() => UserID.GetHashCode(); } }
Fix regression (unit tests were failing because of this)
using System.Collections.Generic; using System.Linq; using FastMember; using Newtonsoft.Json; namespace MyAccounts.Business.Extensions { public static class ObjectExtensions { public static IDictionary<string, string> ToRawMembersDictionary(this object obj) { var accessor = TypeAccessor.Create(obj.GetType()); var members = accessor.GetMembers(); var keyvalues = members.ToDictionary(m => m.Name, m => JsonConvert.ToString(accessor[obj, m.Name])); return keyvalues; } public static void SetFromRawMembersDictionary(this object obj, IDictionary<string, string> keyvalues) { var typeAccessor = TypeAccessor.Create(obj.GetType()); foreach (var member in typeAccessor.GetMembers()) { if (keyvalues.ContainsKey(member.Name)) { var @override = keyvalues[member.Name]; typeAccessor[obj, member.Name] = JsonConvert.DeserializeObject(@override, member.Type); } } } } }
using System.Collections.Generic; using System.Linq; using FastMember; using Newtonsoft.Json; namespace MyAccounts.Business.Extensions { public static class ObjectExtensions { public static IDictionary<string, string> ToRawMembersDictionary(this object obj) { var accessor = TypeAccessor.Create(obj.GetType()); var members = accessor.GetMembers(); var keyvalues = members.ToDictionary(m => m.Name, m => accessor[obj, m.Name]?.ToString()); return keyvalues; } public static void SetFromRawMembersDictionary(this object obj, IDictionary<string, string> keyvalues) { var typeAccessor = TypeAccessor.Create(obj.GetType()); foreach (var member in typeAccessor.GetMembers()) { if (keyvalues.ContainsKey(member.Name)) { var @override = keyvalues[member.Name]; typeAccessor[obj, member.Name] = JsonConvert.DeserializeObject(@override, member.Type); } } } } }
Fix imported images being scaled on some systems.
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; namespace PixelPet.Commands { internal class ImportBitmapCmd : CliCommand { public ImportBitmapCmd() : base ("Import-Bitmap", new Parameter[] { new Parameter(true, new ParameterValue("path")), }) { } public override void Run(Workbench workbench, Cli cli) { string path = this.FindUnnamedParameter(0).Values[0].GetValue(); cli.Log("Importing bitmap " + Path.GetFileName(path) + "..."); // Load bitmap. using (Bitmap bmp = new Bitmap(path)) { // Import bitmap to workbench. workbench.ClearBitmap(bmp.Width, bmp.Height); workbench.Graphics.CompositingMode = CompositingMode.SourceCopy; workbench.Graphics.DrawImageUnscaled(bmp, 0, 0); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; namespace PixelPet.Commands { internal class ImportBitmapCmd : CliCommand { public ImportBitmapCmd() : base ("Import-Bitmap", new Parameter[] { new Parameter(true, new ParameterValue("path")), }) { } public override void Run(Workbench workbench, Cli cli) { string path = this.FindUnnamedParameter(0).Values[0].GetValue(); cli.Log("Importing bitmap " + Path.GetFileName(path) + "..."); // Load bitmap. using (Bitmap bmp = new Bitmap(path)) { // Import bitmap to workbench. workbench.ClearBitmap(bmp.Width, bmp.Height); workbench.Graphics.CompositingMode = CompositingMode.SourceCopy; workbench.Graphics.DrawImage(bmp, 0, 0, bmp.Width, bmp.Height); } } } }
Make internals of Taut visible to Taut.Test.
using System.Resources; 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("Taut")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Taut")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Resources; 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("Taut")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Taut")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Taut.Test")]
Reword exception to be more descriptive
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Framework.Localisation { /// <summary> /// Indicates that the members of an enum can be localised. /// </summary> [AttributeUsage(AttributeTargets.Enum)] public sealed class LocalisableEnumAttribute : Attribute { /// <summary> /// The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s. /// </summary> public readonly Type MapperType; /// <summary> /// Creates a new <see cref="LocalisableEnumAttribute"/>. /// </summary> /// <param name="mapperType">The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.</param> public LocalisableEnumAttribute(Type mapperType) { MapperType = mapperType; if (!typeof(IEnumLocalisationMapper).IsAssignableFrom(mapperType)) throw new ArgumentException($"Mapper type must inherit from {nameof(EnumLocalisationMapper<Enum>)}."); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Extensions.TypeExtensions; namespace osu.Framework.Localisation { /// <summary> /// Indicates that the members of an enum can be localised. /// </summary> [AttributeUsage(AttributeTargets.Enum)] public sealed class LocalisableEnumAttribute : Attribute { /// <summary> /// The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s. /// </summary> public readonly Type MapperType; /// <summary> /// Creates a new <see cref="LocalisableEnumAttribute"/>. /// </summary> /// <param name="mapperType">The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.</param> public LocalisableEnumAttribute(Type mapperType) { MapperType = mapperType; if (!typeof(IEnumLocalisationMapper).IsAssignableFrom(mapperType)) throw new ArgumentException($"Type \"{mapperType.ReadableName()}\" must inherit from {nameof(EnumLocalisationMapper<Enum>)}.", nameof(mapperType)); } } }
Reset cookies before setting (otherwise merges existing with new)
namespace AngleSharp.Services.Default { using System; using System.Net; /// <summary> /// Represents the default cookie service. This class can be inherited. /// </summary> public class MemoryCookieService : ICookieService { readonly CookieContainer _container; /// <summary> /// Creates a new cookie service for non-persistent cookies. /// </summary> public MemoryCookieService() { _container = new CookieContainer(); } /// <summary> /// Gets or sets the cookies for the given origin. /// </summary> /// <param name="origin">The origin of the cookie.</param> /// <returns>The cookie header.</returns> public String this[String origin] { get { return _container.GetCookieHeader(new Uri(origin)); } set { _container.SetCookies(new Uri(origin), value); } } } }
namespace AngleSharp.Services.Default { using System; using System.Net; /// <summary> /// Represents the default cookie service. This class can be inherited. /// </summary> public class MemoryCookieService : ICookieService { readonly CookieContainer _container; /// <summary> /// Creates a new cookie service for non-persistent cookies. /// </summary> public MemoryCookieService() { _container = new CookieContainer(); } /// <summary> /// Gets or sets the cookies for the given origin. /// </summary> /// <param name="origin">The origin of the cookie.</param> /// <returns>The cookie header.</returns> public String this[String origin] { get { return _container.GetCookieHeader(new Uri(origin)); } set { var domain = new Uri(origin); var cookies = _container.GetCookies(domain); foreach (Cookie cookie in cookies) cookie.Expired = true; _container.SetCookies(domain, value); } } } }
Fix error with fastest lap ranking
using ErgastApi.Client.Attributes; using ErgastApi.Responses; using ErgastApi.Responses.Models; namespace ErgastApi.Requests { public abstract class StandardRequest<TResponse> : ErgastRequest<TResponse> where TResponse : ErgastResponse { [UrlSegment("constructors")] public virtual string ConstructorId { get; set; } [UrlSegment("circuits")] public virtual string CircuitId { get; set; } [UrlSegment("fastests")] public virtual int? FastestLapRank { get; set; } [UrlSegment("results")] public virtual int? FinishingPosition { get; set; } // Grid / starting position [UrlSegment("grid")] public virtual int? QualifyingPosition { get; set; } [UrlSegment("status")] public virtual FinishingStatusId? FinishingStatus { get; set; } } }
using ErgastApi.Client.Attributes; using ErgastApi.Responses; using ErgastApi.Responses.Models; namespace ErgastApi.Requests { public abstract class StandardRequest<TResponse> : ErgastRequest<TResponse> where TResponse : ErgastResponse { [UrlSegment("constructors")] public virtual string ConstructorId { get; set; } [UrlSegment("circuits")] public virtual string CircuitId { get; set; } [UrlSegment("fastest")] public virtual int? FastestLapRank { get; set; } [UrlSegment("results")] public virtual int? FinishingPosition { get; set; } // Grid / starting position [UrlSegment("grid")] public virtual int? QualifyingPosition { get; set; } [UrlSegment("status")] public virtual FinishingStatusId? FinishingStatus { get; set; } } }
Remove permission request to storage
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("StatisticsRomania.Droid")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StatisticsRomania.Droid")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Add some common permissions, these can be removed if not needed [assembly: UsesPermission(Android.Manifest.Permission.Internet)] [assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("StatisticsRomania.Droid")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StatisticsRomania.Droid")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Add some common permissions, these can be removed if not needed [assembly: UsesPermission(Android.Manifest.Permission.Internet)]
Fix main window not displaying map difficulty when watching
using osu_StreamCompanion.Code.Core.DataTypes; using osu_StreamCompanion.Code.Interfeaces; using osu_StreamCompanion.Code.Windows; namespace osu_StreamCompanion.Code.Modules.MapDataGetters.Window { public class WindowDataGetter :IModule,IMapDataGetter,IMainWindowUpdater { private MainWindowUpdater _mainwindowHandle; public bool Started { get; set; } public void Start(ILogger logger) { Started = true; //throw new System.NotImplementedException(); } public void SetNewMap(MapSearchResult map) { if (map.FoundBeatmaps) { var nowPlaying = string.Format("{0} - {1}", map.BeatmapsFound[0].ArtistRoman,map.BeatmapsFound[0].TitleRoman); if (map.Action == OsuStatus.Playing) nowPlaying += string.Format(" [{0}] {1}", map.BeatmapsFound[0].DiffName,map.Mods?.Item2 ?? ""); _mainwindowHandle.NowPlaying = nowPlaying; } else { _mainwindowHandle.NowPlaying = "notFound:( " + map.MapSearchString; } } public void GetMainWindowHandle(MainWindowUpdater mainWindowHandle) { _mainwindowHandle = mainWindowHandle; } } }
using osu_StreamCompanion.Code.Core.DataTypes; using osu_StreamCompanion.Code.Interfeaces; using osu_StreamCompanion.Code.Windows; namespace osu_StreamCompanion.Code.Modules.MapDataGetters.Window { public class WindowDataGetter :IModule,IMapDataGetter,IMainWindowUpdater { private MainWindowUpdater _mainwindowHandle; public bool Started { get; set; } public void Start(ILogger logger) { Started = true; } public void SetNewMap(MapSearchResult map) { if (map.FoundBeatmaps) { var nowPlaying = string.Format("{0} - {1}", map.BeatmapsFound[0].ArtistRoman,map.BeatmapsFound[0].TitleRoman); if (map.Action == OsuStatus.Playing || map.Action == OsuStatus.Watching) nowPlaying += string.Format(" [{0}] {1}", map.BeatmapsFound[0].DiffName,map.Mods?.Item2 ?? ""); _mainwindowHandle.NowPlaying = nowPlaying; } else { _mainwindowHandle.NowPlaying = "notFound:( " + map.MapSearchString; } } public void GetMainWindowHandle(MainWindowUpdater mainWindowHandle) { _mainwindowHandle = mainWindowHandle; } } }
Fix macOS plataform Unit Testing
using System; using System.IO; namespace Hangfire.LiteDB.Test.Utils { #pragma warning disable 1591 public static class ConnectionUtils { private const string Ext = "db"; private static string GetConnectionString() { return Path.GetFullPath(string.Format("Hangfire-LiteDB-Tests.{0}", Ext)); } public static LiteDbStorage CreateStorage() { var storageOptions = new LiteDbStorageOptions(); return CreateStorage(storageOptions); } public static LiteDbStorage CreateStorage(LiteDbStorageOptions storageOptions) { return new LiteDbStorage(GetConnectionString(), storageOptions); } public static HangfireDbContext CreateConnection() { return CreateStorage().Connection; } } #pragma warning restore 1591 }
using System; using System.IO; namespace Hangfire.LiteDB.Test.Utils { #pragma warning disable 1591 public static class ConnectionUtils { private const string Ext = "db"; private static string GetConnectionString() { var pathDb = Path.GetFullPath(string.Format("Hangfire-LiteDB-Tests.{0}", Ext)); return @"Filename=" + pathDb + "; mode=Exclusive"; } public static LiteDbStorage CreateStorage() { var storageOptions = new LiteDbStorageOptions(); return CreateStorage(storageOptions); } public static LiteDbStorage CreateStorage(LiteDbStorageOptions storageOptions) { var connectionString = GetConnectionString(); return new LiteDbStorage(connectionString, storageOptions); } public static HangfireDbContext CreateConnection() { return CreateStorage().Connection; } } #pragma warning restore 1591 }
Fix my idiotic Coroutine firing
using System; using System.Collections; using UnityEngine; public class ClockText : MonoBehaviour { private TextMesh _textMesh = null; private void Awake() { _textMesh = GetComponent<TextMesh>(); } private void Update() { StartCoroutine(UpdatePerSecond()); } private IEnumerator UpdatePerSecond() { while (true) { _textMesh.text = DateTime.Now.ToString("dddd dd MMMM HH:mm"); yield return new WaitForSeconds(1.0f); } } }
using System; using System.Collections; using UnityEngine; public class ClockText : MonoBehaviour { private TextMesh _textMesh = null; private void Awake() { _textMesh = GetComponent<TextMesh>(); } private void OnEnable() { StartCoroutine(UpdatePerSecond()); } private void OnDisable() { StopAllCoroutines(); } private IEnumerator UpdatePerSecond() { while (true) { _textMesh.text = DateTime.Now.ToString("dddd dd MMMM HH:mm"); yield return new WaitForSeconds(1.0f); } } }
Add logging to home controller.
using Akka.Actor; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace TrivialWebApiWithActor.Web { public class GreetController : Controller { readonly IActorRef _greeter; public GreetController(IActorRef greeter) { _greeter = greeter; } public async Task<IActionResult> Index(string name = "stranger") { string greeting = await _greeter.Ask<string>(new GreetMe { Name = name }); return Ok(greeting); } } }
using Akka.Actor; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Threading.Tasks; namespace TrivialWebApiWithActor.Web { public class GreetController : Controller { readonly IActorRef _greeter; public GreetController(ILogger<GreetController> logger, IActorRef greeter) { Log = logger; _greeter = greeter; } ILogger Log { get; } public async Task<IActionResult> Index(string name = "stranger") { Log.LogInformation("Greeting '{Name}'...", name); string greeting = await _greeter.Ask<string>(new GreetMe { Name = name }); return Ok(greeting); } } }
Add a test helper that allows marking spans in the query text
using System; using NQuery.Data.Samples; namespace NQuery.Authoring.UnitTests { internal static class CompilationFactory { private static readonly DataContext DataContext = DataContextFactory.CreateNorthwind(); public static Compilation CreateQuery(string query) { int position; return CreateQuery(query, out position); } public static Compilation CreateQuery(string query, out int position) { position = query.IndexOf('|'); if (position >= 0) query = query.Remove(position, 1); var syntaxTree = SyntaxTree.ParseQuery(query); return new Compilation(DataContext, syntaxTree); } } }
using System; using NQuery.Data.Samples; using NQuery.Text; namespace NQuery.Authoring.UnitTests { internal static class CompilationFactory { private static readonly DataContext DataContext = DataContextFactory.CreateNorthwind(); public static Compilation CreateQuery(string query) { var syntaxTree = SyntaxTree.ParseQuery(query); return new Compilation(DataContext, syntaxTree); } public static Compilation CreateQuery(string query, out int position) { position = query.IndexOf('|'); if (position < 0) throw new ArgumentException("The position must be marked with a pipe, such as 'SELECT e.Empl|oyeeId'"); query = query.Remove(position, 1); return CreateQuery(query); } public static Compilation CreateQuery(string query, out TextSpan span) { var start = query.IndexOf('{'); var end = query.IndexOf('}') - 1; if (start < 0 || end < 0) throw new ArgumentException("The span must be marked with braces, such as 'SELECT {e.EmployeeId}'"); span = TextSpan.FromBounds(start, end); query = query.Remove(start, 1).Remove(end, 1); return CreateQuery(query); } } }
Set obsolete Bus.Defer extension methods to error rather than warn. We'll remove these shortly.
using System; using System.Threading.Tasks; using Nimbus.MessageContracts; namespace Nimbus { public static class BackwardCompatibilityAdaptorExtensions { [Obsolete("Deprecated in favour of .SendAt(...) and .SendAfter(...) methods. This adaptor method will be removed in a future release.")] public static Task Defer<TBusCommand>(this IBus bus, TimeSpan delay, TBusCommand busCommand) where TBusCommand : IBusCommand { var deliveryTime = DateTimeOffset.UtcNow.Add(delay); return bus.SendAt(busCommand, deliveryTime); } [Obsolete("Deprecated in favour of .SendAt(...) and .SendAfter(...) methods. This adaptor method will be removed in a future release.")] public static Task Defer<TBusCommand>(this IBus bus, DateTimeOffset processAt, TBusCommand busCommand) where TBusCommand : IBusCommand { return bus.SendAt(busCommand, processAt); } } }
using System; using System.Threading.Tasks; using Nimbus.MessageContracts; namespace Nimbus { public static class BackwardCompatibilityAdaptorExtensions { [Obsolete("Deprecated in favour of .SendAt(...) and .SendAfter(...) methods. This adaptor method will be removed in a future release.", true)] public static Task Defer<TBusCommand>(this IBus bus, TimeSpan delay, TBusCommand busCommand) where TBusCommand : IBusCommand { var deliveryTime = DateTimeOffset.UtcNow.Add(delay); return bus.SendAt(busCommand, deliveryTime); } [Obsolete("Deprecated in favour of .SendAt(...) and .SendAfter(...) methods. This adaptor method will be removed in a future release.", true)] public static Task Defer<TBusCommand>(this IBus bus, DateTimeOffset processAt, TBusCommand busCommand) where TBusCommand : IBusCommand { return bus.SendAt(busCommand, processAt); } } }
Fix bug: delete likes to the calendar with the specified id
using System; using System.Collections.Generic; using System.Linq; using Oogstplanner.Data; using Oogstplanner.Models; namespace Oogstplanner.Services { public class CalendarLikingService : ServiceBase, ICalendarLikingService { readonly IUserService userService; public CalendarLikingService( IOogstplannerUnitOfWork unitOfWork, IUserService userService) : base(unitOfWork) { if (userService == null) { throw new ArgumentNullException("userService"); } this.userService = userService; } User currentUser; protected User CurrentUser { get { int currentUserId = userService.GetCurrentUserId(); currentUser = userService.GetUser(currentUserId); return currentUser; } } public void Like(int calendarId) { var like = new Like { User = CurrentUser }; var calendarLikes = UnitOfWork.Calendars.GetById(calendarId).Likes; if (calendarLikes.Any(l => l.User.Id == CurrentUser.Id)) { return; } calendarLikes.Add(like); UnitOfWork.Commit(); } public void UnLike(int calendarId) { var likeToDelete = UnitOfWork.Likes.SingleOrDefault(l => l.User.Id == CurrentUser.Id); if (likeToDelete == null) { return; } UnitOfWork.Likes.Delete(likeToDelete); UnitOfWork.Commit(); } public IEnumerable<Like> GetLikes(int calendarId) { return UnitOfWork.Likes.GetByCalendarId(calendarId); } } }
using System; using System.Collections.Generic; using System.Linq; using Oogstplanner.Data; using Oogstplanner.Models; namespace Oogstplanner.Services { public class CalendarLikingService : ServiceBase, ICalendarLikingService { readonly IUserService userService; public CalendarLikingService( IOogstplannerUnitOfWork unitOfWork, IUserService userService) : base(unitOfWork) { if (userService == null) { throw new ArgumentNullException("userService"); } this.userService = userService; } User currentUser; protected User CurrentUser { get { int currentUserId = userService.GetCurrentUserId(); currentUser = userService.GetUser(currentUserId); return currentUser; } } public void Like(int calendarId) { var like = new Like { User = CurrentUser }; var calendarLikes = UnitOfWork.Calendars.GetById(calendarId).Likes; if (calendarLikes.Any(l => l.User.Id == CurrentUser.Id)) { return; } calendarLikes.Add(like); UnitOfWork.Commit(); } public void UnLike(int calendarId) { var likeToDelete = UnitOfWork.Likes.SingleOrDefault( l => l.Calendar.Id == calendarId && l.User.Id == CurrentUser.Id); if (likeToDelete == null) { return; } UnitOfWork.Likes.Delete(likeToDelete); UnitOfWork.Commit(); } public IEnumerable<Like> GetLikes(int calendarId) { return UnitOfWork.Likes.GetByCalendarId(calendarId); } } }
Remove expression type (not supported in unity)
using System.Collections.Generic; using HarryPotterUnity.Cards.Interfaces; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Cards.Generic { [UsedImplicitly] public class Lesson : GenericCard, IPersistentCard { public enum LessonTypes { Creatures = 0, Charms, Transfiguration, Potions, Quidditch } [UsedImplicitly, SerializeField] private LessonTypes _lessonType; public LessonTypes LessonType => _lessonType; protected override void OnClickAction(List<GenericCard> targets) { Player.InPlay.Add(this); Player.Hand.Remove(this); } public void OnEnterInPlayAction() { if (!Player.LessonTypesInPlay.Contains(_lessonType)) { Player.LessonTypesInPlay.Add(_lessonType); } Player.AmountLessonsInPlay++; State = CardStates.InPlay; } public void OnExitInPlayAction() { Player.AmountLessonsInPlay--; Player.UpdateLessonTypesInPlay(); } //Lesson Cards don't implement these methods public void OnInPlayBeforeTurnAction() { } public void OnInPlayAfterTurnAction() { } public void OnSelectedAction() { } } }
using System.Collections.Generic; using HarryPotterUnity.Cards.Interfaces; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Cards.Generic { [UsedImplicitly] public class Lesson : GenericCard, IPersistentCard { public enum LessonTypes { Creatures = 0, Charms, Transfiguration, Potions, Quidditch } [UsedImplicitly, SerializeField] private LessonTypes _lessonType; public LessonTypes LessonType { get { return _lessonType; } } protected override void OnClickAction(List<GenericCard> targets) { Player.InPlay.Add(this); Player.Hand.Remove(this); } public void OnEnterInPlayAction() { if (!Player.LessonTypesInPlay.Contains(_lessonType)) { Player.LessonTypesInPlay.Add(_lessonType); } Player.AmountLessonsInPlay++; State = CardStates.InPlay; } public void OnExitInPlayAction() { Player.AmountLessonsInPlay--; Player.UpdateLessonTypesInPlay(); } //Lesson Cards don't implement these methods public void OnInPlayBeforeTurnAction() { } public void OnInPlayAfterTurnAction() { } public void OnSelectedAction() { } } }
Use faster polling for handling dashboard buttons.
using Microsoft.Azure.Jobs.Host.Bindings; using Microsoft.Azure.Jobs.Host.Executors; using Microsoft.Azure.Jobs.Host.Indexers; using Microsoft.Azure.Jobs.Host.Listeners; using Microsoft.Azure.Jobs.Host.Loggers; using Microsoft.WindowsAzure.Storage.Queue; namespace Microsoft.Azure.Jobs.Host.Queues.Listeners { internal static class HostMessageListener { public static IListener Create(CloudQueue queue, IExecuteFunction executor, IFunctionIndexLookup functionLookup, IFunctionInstanceLogger functionInstanceLogger, HostBindingContext context) { ITriggerExecutor<CloudQueueMessage> triggerExecutor = new HostMessageExecutor(executor, functionLookup, functionInstanceLogger, context); ICanFailCommand command = new PollQueueCommand(queue, poisonQueue: null, triggerExecutor: triggerExecutor); IntervalSeparationTimer timer = ExponentialBackoffTimerCommand.CreateTimer(command, QueuePollingIntervals.Minimum, QueuePollingIntervals.Maximum); return new TimerListener(timer); } } }
using System; using Microsoft.Azure.Jobs.Host.Bindings; using Microsoft.Azure.Jobs.Host.Executors; using Microsoft.Azure.Jobs.Host.Indexers; using Microsoft.Azure.Jobs.Host.Listeners; using Microsoft.Azure.Jobs.Host.Loggers; using Microsoft.WindowsAzure.Storage.Queue; namespace Microsoft.Azure.Jobs.Host.Queues.Listeners { internal static class HostMessageListener { private static readonly TimeSpan maxmimum = TimeSpan.FromMinutes(1); public static IListener Create(CloudQueue queue, IExecuteFunction executor, IFunctionIndexLookup functionLookup, IFunctionInstanceLogger functionInstanceLogger, HostBindingContext context) { ITriggerExecutor<CloudQueueMessage> triggerExecutor = new HostMessageExecutor(executor, functionLookup, functionInstanceLogger, context); ICanFailCommand command = new PollQueueCommand(queue, poisonQueue: null, triggerExecutor: triggerExecutor); // Use a shorter maximum polling interval for run/abort from dashboard. IntervalSeparationTimer timer = ExponentialBackoffTimerCommand.CreateTimer(command, QueuePollingIntervals.Minimum, maxmimum); return new TimerListener(timer); } } }
Send data back to client.
using ML.TypingClassifier.Models; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ML.TypingClassifier.Controllers { [RoutePrefix("sink")] public class SinkController : ApiController { private static readonly string ConnString = "Server=tcp:zg8hk2j3i5.database.windows.net,1433;Database=typingcAFGz4D1Xe;User ID=classifier@zg8hk2j3i5;Password=M3talt0ad;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"; private readonly DataAccess _dataAccess; public SinkController() { _dataAccess = new DataAccess(ConnString); } [Route("")] public IHttpActionResult Get() { return Ok(_dataAccess.All()); } [Route("{email}")] public IHttpActionResult GetByEmail(string email) { var sample = _dataAccess.Single(email); if (sample == null) return NotFound(); return Ok(sample); } [Route("")] public IHttpActionResult Post(Sample data) { _dataAccess.Add(data); return Ok(); } } }
using ML.TypingClassifier.Models; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ML.TypingClassifier.Controllers { [RoutePrefix("sink")] public class SinkController : ApiController { private static readonly string ConnString = "Server=tcp:zg8hk2j3i5.database.windows.net,1433;Database=typingcAFGz4D1Xe;User ID=classifier@zg8hk2j3i5;Password=M3talt0ad;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"; private readonly DataAccess _dataAccess; public SinkController() { _dataAccess = new DataAccess(ConnString); } [Route("")] public IHttpActionResult Get() { return Ok(_dataAccess.All()); } [Route("{email}")] public IHttpActionResult GetByEmail(string email) { var sample = _dataAccess.Single(email); if (sample == null) return NotFound(); return Ok(sample); } [Route("")] public IHttpActionResult Post(Sample data) { _dataAccess.Add(data); return Ok(data); } } }
Add very basic REST methods for todomvc using in-memory list
using System; using System.Collections.Generic; using System.Linq; using NServiceMVC; using AttributeRouting; namespace NServiceMVC.Examples.Todomvc.Controllers { public class TodosController : ServiceController { [GET("todos")] public IEnumerable<Models.Todo> Index() { return new List<Models.Todo>() { new Models.Todo() { Text = "Item1", }, new Models.Todo() { Text = "Item2", Done = true, } }; } } }
using System; using System.Collections.Generic; using System.Linq; using NServiceMVC; using AttributeRouting; using System.ComponentModel; namespace NServiceMVC.Examples.Todomvc.Controllers { public class TodosController : ServiceController { private static IList<Models.Todo> Todos; // in-memory static list. Note no thread-safety! public TodosController() { if (Todos == null) Todos = new List<Models.Todo>(); // initialize the list if it's not already } [GET("todos")] [Description("List all Todos")] public IEnumerable<Models.Todo> Index() { return Todos; } [POST("todos")] [Description("Add a Todo")] public Models.Todo Add(Models.Todo item) { Todos.Add(item); return item; } [PUT("todos/{id}")] [Description("Update an existing Todo")] public object Update(Guid id, Models.Todo item) { var existing = (from t in Todos where t.Id == id select t).FirstOrDefault(); if (existing != null) existing = item; return null; } [DELETE("todos/{id}")] [Description("Delete a Todo")] public object Delete(Guid id) { var existing = (from t in Todos where t.Id == id select t).FirstOrDefault(); Todos.Remove(existing); return null; } } }
Add tracks for Twitter crawler
using System.Collections.Generic; namespace Twitter.Streaming.Configurations { public interface ITwitterListnerConfiguration { ITwitterCredential Credentials { get; } IEnumerable<string> Tracks { get; } IEnumerable<int> Languages { get; } } public class TwitterListnerConfiguration : ITwitterListnerConfiguration { public ITwitterCredential Credentials => new TwitterCredential(); public IEnumerable<string> Tracks => new[] {"Azure", "AWS", "GCP", "#GlobalAzure"}; public IEnumerable<int> Languages => new[] {12}; } }
using System.Collections.Generic; namespace Twitter.Streaming.Configurations { public interface ITwitterListnerConfiguration { ITwitterCredential Credentials { get; } IEnumerable<string> Tracks { get; } IEnumerable<int> Languages { get; } } public class TwitterListnerConfiguration : ITwitterListnerConfiguration { public ITwitterCredential Credentials => new TwitterCredential(); public IEnumerable<string> Tracks => new[] { "Azure", "AWS", "GCP", "#GlobalAzure", "#msdevcon", "#devconschool" }; public IEnumerable<int> Languages => new[] { 12 }; } }
Use the fully qualified name when searching for complete declarations.
using System; using CppSharp.Types; namespace CppSharp.Passes { public class ResolveIncompleteDeclsPass : TranslationUnitPass { public ResolveIncompleteDeclsPass() { } public override bool VisitClassDecl(Class @class) { if (@class.Ignore) return false; if (!@class.IsIncomplete) goto Out; if (@class.CompleteDeclaration != null) goto Out; @class.CompleteDeclaration = Library.FindCompleteClass(@class.Name); if (@class.CompleteDeclaration == null) Console.WriteLine("Unresolved declaration: {0}", @class.Name); Out: return base.VisitClassDecl(@class); } } public static class ResolveIncompleteDeclsExtensions { public static void ResolveIncompleteDecls(this PassBuilder builder) { var pass = new ResolveIncompleteDeclsPass(); builder.AddPass(pass); } } }
using System; using CppSharp.Types; namespace CppSharp.Passes { public class ResolveIncompleteDeclsPass : TranslationUnitPass { public ResolveIncompleteDeclsPass() { } public override bool VisitClassDecl(Class @class) { if (@class.Ignore) return false; if (!@class.IsIncomplete) goto Out; if (@class.CompleteDeclaration != null) goto Out; @class.CompleteDeclaration = Library.FindCompleteClass( @class.QualifiedName); if (@class.CompleteDeclaration == null) Console.WriteLine("Unresolved declaration: {0}", @class.Name); Out: return base.VisitClassDecl(@class); } } public static class ResolveIncompleteDeclsExtensions { public static void ResolveIncompleteDecls(this PassBuilder builder) { var pass = new ResolveIncompleteDeclsPass(); builder.AddPass(pass); } } }
Add comment about checking for PowerShell DLL loaded.
using System; using System.Diagnostics; using O365.Security.ETW; namespace hiddentreasure_etw_demo { public static class PowerShellImageLoad { public static UserTrace CreateTrace() { var filter = new EventFilter(Filter .EventIdIs(5) .And(UnicodeString.IContains("ImageName", @"\System.Management.Automation.dll"))); filter.OnEvent += (IEventRecord r) => { var pid = (int)r.ProcessId; var processName = Process.GetProcessById(pid).ProcessName; var imageName = r.GetUnicodeString("ImageName"); Console.WriteLine($"{processName} (PID: {pid}) loaded {imageName}"); }; var provider = new Provider("Microsoft-Windows-Kernel-Process"); provider.AddFilter(filter); var trace = new UserTrace(); trace.Enable(provider); return trace; } } }
using System; using System.Diagnostics; using O365.Security.ETW; namespace hiddentreasure_etw_demo { public static class PowerShellImageLoad { public static UserTrace CreateTrace() { // Unfortunately, this detection won't work for // processes that *already* have System.Management.Automation.dll // loaded into them. It does not check existing state, only activity // that occurs while the monitoring is enabled. var filter = new EventFilter(Filter .EventIdIs(5) .And(UnicodeString.IContains("ImageName", @"\System.Management.Automation.dll"))); filter.OnEvent += (IEventRecord r) => { var pid = (int)r.ProcessId; var processName = Process.GetProcessById(pid).ProcessName; var imageName = r.GetUnicodeString("ImageName"); Console.WriteLine($"{processName} (PID: {pid}) loaded {imageName}"); }; var provider = new Provider("Microsoft-Windows-Kernel-Process"); provider.AddFilter(filter); var trace = new UserTrace(); trace.Enable(provider); return trace; } } }
Change log level from warning to information
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using Microsoft.Extensions.Logging; using System.Threading.Tasks; using IdentityServer4.Models; namespace IdentityServer4.Validation { /// <summary> /// Default resource owner password validator (no implementation == not supported) /// </summary> /// <seealso cref="IdentityServer4.Validation.IResourceOwnerPasswordValidator" /> public class NotSupportedResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator { private readonly ILogger _logger; /// <summary> /// Initializes a new instance of the <see cref="NotSupportedResourceOwnerPasswordValidator"/> class. /// </summary> /// <param name="logger">The logger.</param> public NotSupportedResourceOwnerPasswordValidator(ILogger<NotSupportedResourceOwnerPasswordValidator> logger) { _logger = logger; } /// <summary> /// Validates the resource owner password credential /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { context.Result = new GrantValidationResult(TokenRequestErrors.UnsupportedGrantType); _logger.LogWarning("Resource owner password credential type not supported. Configure an IResourceOwnerPasswordValidator."); return Task.CompletedTask; } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using Microsoft.Extensions.Logging; using System.Threading.Tasks; using IdentityServer4.Models; namespace IdentityServer4.Validation { /// <summary> /// Default resource owner password validator (no implementation == not supported) /// </summary> /// <seealso cref="IdentityServer4.Validation.IResourceOwnerPasswordValidator" /> public class NotSupportedResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator { private readonly ILogger _logger; /// <summary> /// Initializes a new instance of the <see cref="NotSupportedResourceOwnerPasswordValidator"/> class. /// </summary> /// <param name="logger">The logger.</param> public NotSupportedResourceOwnerPasswordValidator(ILogger<NotSupportedResourceOwnerPasswordValidator> logger) { _logger = logger; } /// <summary> /// Validates the resource owner password credential /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { context.Result = new GrantValidationResult(TokenRequestErrors.UnsupportedGrantType); _logger.LogInformation("Resource owner password credential type not supported. Configure an IResourceOwnerPasswordValidator."); return Task.CompletedTask; } } }
Fix unit link for vehicles
@model IEnumerable<Unit> <div class="page-header"> <h1>Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default btn-xs" })</h1> </div> <table class="table table-striped"> <thead> <tr> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Name)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)</th> <th></th> </tr> </thead> <tbody> @foreach (var unit in Model) { <tr> <td>@Html.DisplayFor(s => unit)</td> <td>@Html.DisplayFor(s => unit.UIC)</td> <td> @Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id }, new { @class = "btn btn-default btn-xs" }) @Html.ActionLink("Vehicles", "Index", "Vehicles", new { unit = unit.Id }, new { @class = "btn btn-default btn-xs" }) @Html.ActionLink("Edit", "Edit", new { unit.Id }, new { @class = "btn btn-default btn-xs" }) </td> </tr> } </tbody> </table>
@model IEnumerable<Unit> <div class="page-header"> <h1>Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default btn-xs" })</h1> </div> <table class="table table-striped"> <thead> <tr> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Name)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)</th> <th></th> </tr> </thead> <tbody> @foreach (var unit in Model) { <tr> <td>@Html.DisplayFor(s => unit)</td> <td>@Html.DisplayFor(s => unit.UIC)</td> <td> @Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id }, new { @class = "btn btn-default btn-xs" }) @Html.ActionLink("Vehicles", "Index", "Vehicles", new { Units = new int[] { unit.Id } }, new { @class = "btn btn-default btn-xs" }) @Html.ActionLink("Edit", "Edit", new { unit.Id }, new { @class = "btn btn-default btn-xs" }) </td> </tr> } </tbody> </table>
Add constructors to WebHost settings.
using System.IO; using System.Web.Hosting; namespace NuGet.Lucene.Web { public class NuGetWebApiWebHostSettings : NuGetWebApiSettings { protected override string MapPathFromAppSetting(string key, string defaultValue) { var path = base.GetAppSetting(key, defaultValue); if (string.IsNullOrEmpty(path)) return path; if (Path.IsPathRooted(path)) return path; return HostingEnvironment.MapPath(path); } } }
using System.Collections.Specialized; using System.IO; using System.Web.Hosting; namespace NuGet.Lucene.Web { public class NuGetWebApiWebHostSettings : NuGetWebApiSettings { public NuGetWebApiWebHostSettings(string prefix) : base(prefix) { } public NuGetWebApiWebHostSettings(string prefix, NameValueCollection settings, NameValueCollection roleMappings) : base(prefix, settings, roleMappings) { } protected override string MapPathFromAppSetting(string key, string defaultValue) { var path = base.GetAppSetting(key, defaultValue); if (string.IsNullOrEmpty(path)) return path; if (Path.IsPathRooted(path)) return path; return HostingEnvironment.MapPath(path); } } }
Support binding as the parameter value
using Sakuno.UserInterface.ObjectOperations; using System; using System.Windows.Markup; namespace Sakuno.UserInterface.Commands { public class InvokeMethodExtension : MarkupExtension { string r_Method; object r_Parameter; public InvokeMethodExtension(string rpMethod) : this(rpMethod, null) { } public InvokeMethodExtension(string rpMethod, object rpParameter) { r_Method = rpMethod; r_Parameter = rpParameter; } public override object ProvideValue(IServiceProvider rpServiceProvider) { var rInvokeMethod = new InvokeMethod() { Method = r_Method }; if (r_Parameter != null) rInvokeMethod.Parameters.Add(new MethodParameter() { Value = r_Parameter }); return new ObjectOperationCommand() { Operations = { rInvokeMethod } }; } } }
using Sakuno.UserInterface.ObjectOperations; using System; using System.Windows.Data; using System.Windows.Markup; namespace Sakuno.UserInterface.Commands { public class InvokeMethodExtension : MarkupExtension { string r_Method; object r_Parameter; public InvokeMethodExtension(string rpMethod) : this(rpMethod, null) { } public InvokeMethodExtension(string rpMethod, object rpParameter) { r_Method = rpMethod; r_Parameter = rpParameter; } public override object ProvideValue(IServiceProvider rpServiceProvider) { var rInvokeMethod = new InvokeMethod() { Method = r_Method }; if (r_Parameter != null) { var rParameter = new MethodParameter(); var rBinding = r_Parameter as Binding; if (rBinding == null) rParameter.Value = r_Parameter; else BindingOperations.SetBinding(rParameter, MethodParameter.ValueProperty, rBinding); rInvokeMethod.Parameters.Add(rParameter); } return new ObjectOperationCommand() { Operations = { rInvokeMethod } }; } } }
Add auth endpoint to API
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using System.Net; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { public class UsersController : ApiController { private readonly IMemoryCache cache; private async Task<Soldier> CurrentUser() => await UserService.FindAsync(db, User, cache); public UsersController(IMemoryCache cache, Database db) : base(db) { this.cache = cache; } [HttpGet("me")] public async Task<dynamic> Current() { // GET: api/users/me var user = await CurrentUser(); if (user == null) return StatusCode((int)HttpStatusCode.BadRequest); return new { user.Id, user.FirstName, user.LastName, user.CivilianEmail }; } } }
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { public class UsersController : ApiController { private static readonly HttpClient http = new HttpClient(); private readonly IMemoryCache cache; private readonly IOptions<Auth0Settings> auth0; private async Task<Soldier> CurrentUser() => await UserService.FindAsync(db, User, cache); public UsersController(IMemoryCache cache, Database db, IOptions<Auth0Settings> auth0) : base(db) { this.cache = cache; this.auth0 = auth0; } [HttpPost("~/api/auth"), AllowAnonymous] public async Task<IActionResult> Authenticate(String username, String password) { var request = JsonConvert.SerializeObject(new { client_id = auth0.Value.ClientId, client_secret = auth0.Value.ClientSecret, audience = auth0.Value.ApiIdentifier, grant_type = "password", username, password }); var result = await http.PostAsync($"https://{auth0.Value.Domain}/oauth/token", new StringContent(request, Encoding.UTF8, "application/json")); var json = await result.Content.ReadAsStringAsync(); var model = JsonConvert.DeserializeAnonymousType(json, new { access_token = "", token_type = "", expires_in = 0 }); return Json(model); } [HttpGet("me")] public async Task<dynamic> Current() { // GET: api/users/me var user = await CurrentUser(); if (user == null) return StatusCode((int)HttpStatusCode.BadRequest); return new { user.Id, user.FirstName, user.LastName, user.CivilianEmail }; } } }
Add url short format uniqueness
using System; using System.Collections.Generic; using System.Linq; using UrlShortenerApi.Data; using UrlShortenerApi.Models; namespace UrlShortenerApi.Repositories { public class UrlRepository : IUrlRepository { ApplicationDbContext _context; public UrlRepository(ApplicationDbContext context) { _context = context; } public void Add(Url item) { item.ShortFormat = UrlShortenerLib.Shortener.GenerateShortFormat(6); item.CreationDate = DateTime.Now; _context.Urls.Add(item); _context.SaveChanges(); } public IEnumerable<Url> GetAll() { return _context.Urls.ToList(); } public Url Find(System.Guid id) { return _context.Urls.SingleOrDefault(m => m.Id == id); } public Url Find(string shortFormat) { return _context.Urls.SingleOrDefault(m => m.ShortFormat == shortFormat); } } }
using System; using System.Collections.Generic; using System.Linq; using UrlShortenerApi.Data; using UrlShortenerApi.Models; namespace UrlShortenerApi.Repositories { public class UrlRepository : IUrlRepository { ApplicationDbContext _context; public UrlRepository(ApplicationDbContext context) { _context = context; } public void Add(Url item) { do { item.ShortFormat = UrlShortenerLib.Shortener.GenerateShortFormat(6); } while (!ShortFormatIsUnique(item.ShortFormat)); item.CreationDate = DateTime.Now; _context.Urls.Add(item); _context.SaveChanges(); } public IEnumerable<Url> GetAll() { return _context.Urls.ToList(); } public Url Find(System.Guid id) { return _context.Urls.SingleOrDefault(m => m.Id == id); } public Url Find(string shortFormat) { return _context.Urls.SingleOrDefault(m => m.ShortFormat == shortFormat); } private bool ShortFormatIsUnique(string shortFormat) { Url item = Find(shortFormat); if (item != null) { return false; } else { return true; } } } }
Add debug info for failed import.
 using System.Collections.Generic; using DataHelpers.Contracts; namespace DataHelpers { /// <summary> /// Base class validator. All validators should be derived from this class. /// </summary> public class ValidationRunner { /// <summary> /// Check to see if the current validation chain is valid. /// </summary> /// <returns>true if valid, otherwise false</returns> public bool IsValid(ImportData readBundle, IValidator validator) { var valid = true; foreach (Row row in readBundle.rows) { validator.Validate(row); if (!row.valid) { valid = false; } } return valid; } } }
 using System.Collections.Generic; using DataHelpers.Contracts; namespace DataHelpers { /// <summary> /// Base class validator. All validators should be derived from this class. /// </summary> public class ValidationRunner { /// <summary> /// Check to see if the current validation chain is valid. /// </summary> /// <returns>true if valid, otherwise false</returns> public bool IsValid(ImportData readBundle, IValidator validator) { var valid = true; foreach (Row row in readBundle.rows) { validator.Validate(row); if (!row.valid) { valid = false; Debug.LogError("Import failed " + row.errorMessage); } } return valid; } } }
Fix a Bug where Merging Sections causes Problems
using System.Linq; using GekkoAssembler.IntermediateRepresentation; namespace GekkoAssembler.Optimizers { public class WriteDataOptimizer : IOptimizer { public IRCodeBlock Optimize(IRCodeBlock block) { var units = block.Units; var replaced = true; while (replaced) { replaced = false; var last = units.FirstOrDefault(); foreach (var current in units.Skip(1)) { if (current is IRWriteData && last is IRWriteData) { var currentWriteData = current as IRWriteData; var lastWriteData = last as IRWriteData; if (currentWriteData.Address == lastWriteData.Address + lastWriteData.Data.Length) { var combined = new IRCombinedWriteData(lastWriteData, currentWriteData); units = units.TakeWhile(x => x != last) .Concat(new[] { combined }) .Concat(units.SkipWhile(x => x != current).Skip(1)) .AsReadOnly(); replaced = true; break; } } last = current; } } return new IRCodeBlock(units.Select(x => x is IRCodeBlock ? Optimize(x as IRCodeBlock) : x)); } } }
using System.Linq; using GekkoAssembler.IntermediateRepresentation; namespace GekkoAssembler.Optimizers { public class WriteDataOptimizer : IOptimizer { public IRCodeBlock Optimize(IRCodeBlock block) { var units = block.Units; var replaced = true; while (replaced) { replaced = false; var last = units.FirstOrDefault(); foreach (var current in units.Skip(1)) { if (current is IRWriteData && last is IRWriteData) { var currentWriteData = current as IRWriteData; var lastWriteData = last as IRWriteData; var lastBeganAligned = lastWriteData.Address % 4 == 0; var consecutive = currentWriteData.Address == lastWriteData.Address + lastWriteData.Data.Length; if (lastBeganAligned && consecutive) { var combined = new IRCombinedWriteData(lastWriteData, currentWriteData); units = units.TakeWhile(x => x != last) .Concat(new[] { combined }) .Concat(units.SkipWhile(x => x != current).Skip(1)) .AsReadOnly(); replaced = true; break; } } last = current; } } return new IRCodeBlock(units.Select(x => x is IRCodeBlock ? Optimize(x as IRCodeBlock) : x)); } } }
Add playlist tags hidden property
using System.Xml.Serialization; namespace SevenDigital.Api.Schema.Playlists.Response.Endpoints { public class PlaylistTag { [XmlElement("name")] public string Name { get; set; } } }
using System.Xml.Serialization; namespace SevenDigital.Api.Schema.Playlists.Response.Endpoints { public class PlaylistTag { [XmlElement("name")] public string Name { get; set; } [XmlElement("hidden")] public bool Hidden { get; set; } } }
Support for Inno Setup 6
using System.IO; using Microsoft.Win32; namespace Cosmos.Build.Builder.Services { internal class InnoSetupService : IInnoSetupService { private const string InnoSetupRegistryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 5_is1"; public string GetInnoSetupInstallationPath() { using (var localMachineKey32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) { using (var key = localMachineKey32.OpenSubKey(InnoSetupRegistryKey, false)) { if (key?.GetValue("InstallLocation") is string innoSetupPath) { if (Directory.Exists(innoSetupPath)) { return innoSetupPath; } } } } return null; } } }
using System.IO; using Microsoft.Win32; namespace Cosmos.Build.Builder.Services { internal class InnoSetupService : IInnoSetupService { private const string InnoSetupRegistryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 6_is1"; public string GetInnoSetupInstallationPath() { using (var localMachineKey32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) { using (var key = localMachineKey32.OpenSubKey(InnoSetupRegistryKey, false)) { if (key?.GetValue("InstallLocation") is string innoSetupPath) { if (Directory.Exists(innoSetupPath)) { return innoSetupPath; } } } } return null; } } }
Test only on same thread. Multi-threaded test needs to be platform-specific.
using System; using NUnit.Framework; using Realms; using System.Threading; using System.IO; namespace IntegrationTests.Shared { [TestFixture] public class NotificationTests { private string _databasePath; private Realm _realm; private void WriteOnDifferentThread(Action<Realm> action) { var thread = new Thread(() => { var r = Realm.GetInstance(_databasePath); r.Write(() => action(r)); r.Close(); }); thread.Start(); thread.Join(); } [SetUp] private void Setup() { _databasePath = Path.GetTempFileName(); _realm = Realm.GetInstance(_databasePath); } [Test] public void ShouldTriggerRealmChangedEvent() { // Arrange var wasNotified = false; _realm.RealmChanged += (sender, e) => { wasNotified = true; }; // Act WriteOnDifferentThread((realm) => { realm.CreateObject<Person>(); }); // Assert Assert.That(wasNotified, "RealmChanged notification was not triggered"); } } }
using System; using NUnit.Framework; using Realms; using System.Threading; using System.IO; namespace IntegrationTests.Shared { [TestFixture] public class NotificationTests { private string _databasePath; private Realm _realm; [SetUp] public void Setup() { _databasePath = Path.GetTempFileName(); _realm = Realm.GetInstance(_databasePath); } [Test] public void ShouldTriggerRealmChangedEvent() { // Arrange var wasNotified = false; _realm.RealmChanged += (sender, e) => { wasNotified = true; }; // Act _realm.Write(() => _realm.CreateObject<Person>()); // Assert Assert.That(wasNotified, "RealmChanged notification was not triggered"); } } }
Use GetRandomFileName when a specific extension is needed
using System; using System.IO; namespace NuGetPe { public sealed class TemporaryFile : IDisposable { public TemporaryFile(Stream stream, string? extension = null) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (string.IsNullOrWhiteSpace(extension) || extension[0] != '.') { extension = string.Empty; } FileName = Path.GetTempFileName() + extension; using var fstream = File.Open(FileName, FileMode.Create); stream.CopyTo(fstream); fstream.Flush(); } public string FileName { get; } public long Length => new FileInfo(FileName).Length; private bool _disposed; public void Dispose() { if (!_disposed) { _disposed = true; try { File.Delete(FileName); } catch // best effort { } } } } }
using System; using System.IO; namespace NuGetPe { public sealed class TemporaryFile : IDisposable { public TemporaryFile(Stream stream, string? extension = null) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (string.IsNullOrWhiteSpace(extension) || extension[0] != '.') { FileName = Path.GetTempFileName(); } else { FileName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + extension); } using var fstream = File.Open(FileName, FileMode.Create); stream.CopyTo(fstream); fstream.Flush(); } public string FileName { get; } public long Length => new FileInfo(FileName).Length; private bool _disposed; public void Dispose() { if (!_disposed) { _disposed = true; try { File.Delete(FileName); } catch // best effort { } } } } }
Refactor to not use unity's lifecycle event as a method directly
using UnityEngine; using System.Collections; public class DamageDealer : MonoBehaviour { public float damageToDeal = 1; // Use this for initialization void OnCollisionStay2D(Collision2D col) { OnTriggerEnter2D(col.collider); } void OnTriggerStay2D(Collider2D col) { OnTriggerEnter2D(col); } void OnCollisionEnter2D(Collision2D col) { OnTriggerEnter2D(col.collider); } void OnTriggerEnter2D(Collider2D col) { col.GetComponent<PlayerStatus>().TakeDamage (damageToDeal); var knockbackAngle = -(transform.position - col.gameObject.transform.position).normalized; knockbackAngle.Normalize (); col.GetComponent<PlayerMovement>().KnockBack (knockbackAngle); // col.transform.BroadcastMessage("TakeDamage",new CollisionData(damageToDeal,gameObject), SendMessageOptions.DontRequireReceiver); } }
using UnityEngine; using System.Collections; public class DamageDealer : MonoBehaviour { public float damageToDeal = 1; void OnCollisionStay2D(Collision2D col) { handleCollision(col.collider); } void OnTriggerStay2D(Collider2D col) { handleCollision(col); } void OnCollisionEnter2D(Collision2D col) { handleCollision(col.collider); } void OnTriggerEnter2D(Collider2D col) { handleCollision (col); } private void handleCollision (Collider2D col) { col.GetComponent<PlayerStatus> ().TakeDamage (damageToDeal); var knockbackAngle = -(transform.position - col.gameObject.transform.position).normalized; knockbackAngle.Normalize (); col.GetComponent<PlayerMovement> ().KnockBack (knockbackAngle); } }
Update GetCustomAttribute extensions to support taking in type.
namespace EPPlusEnumerable { using System; using System.Reflection; internal static class Extensions { public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute { return (T)Attribute.GetCustomAttribute(element, typeof(T), inherit); } public static T GetCustomAttribute<T>(this MemberInfo element) where T : Attribute { return (T)Attribute.GetCustomAttribute(element, typeof(T)); } public static object GetValue(this PropertyInfo element, Object obj) { return element.GetValue(obj, BindingFlags.Default, null, null, null); } } }
namespace EPPlusEnumerable { using System; using System.Reflection; internal static class Extensions { public static T GetCustomAttribute<T>(this MemberInfo element, Type type, bool inherit) where T : Attribute { var attr = (T)Attribute.GetCustomAttribute(element, typeof(T), inherit); if (attr == null) { return element.GetMetaAttribute<T>(type, inherit); } return attr; } public static T GetCustomAttribute<T>(this MemberInfo element, Type type) where T : Attribute { var attr = (T)Attribute.GetCustomAttribute(element, typeof(T)); if (attr == null) { return element.GetMetaAttribute<T>(type); } return attr; } public static object GetValue(this PropertyInfo element, Object obj) { return element.GetValue(obj, BindingFlags.Default, null, null, null); } } }
Add copyright header, make property readonly
using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Editor.UnitTests { internal static class TextEditorFactoryExtensions { public static DisposableTextView CreateDisposableTextView(this ITextEditorFactoryService textEditorFactory) { return new DisposableTextView(textEditorFactory.CreateTextView()); } public static DisposableTextView CreateDisposableTextView(this ITextEditorFactoryService textEditorFactory, ITextBuffer buffer) { return new DisposableTextView(textEditorFactory.CreateTextView(buffer)); } } public class DisposableTextView : IDisposable { public DisposableTextView(IWpfTextView textView) { this.TextView = textView; } public IWpfTextView TextView { get; private set; } public void Dispose() { TextView.Close(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using System; namespace Microsoft.CodeAnalysis.Editor.UnitTests { internal static class TextEditorFactoryExtensions { public static DisposableTextView CreateDisposableTextView(this ITextEditorFactoryService textEditorFactory) { return new DisposableTextView(textEditorFactory.CreateTextView()); } public static DisposableTextView CreateDisposableTextView(this ITextEditorFactoryService textEditorFactory, ITextBuffer buffer) { return new DisposableTextView(textEditorFactory.CreateTextView(buffer)); } } public class DisposableTextView : IDisposable { public DisposableTextView(IWpfTextView textView) { this.TextView = textView; } public IWpfTextView TextView { get; } public void Dispose() { TextView.Close(); } } }
Rework tests to not be visual and use headless game host
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Input; using osu.Framework.Testing; namespace osu.Framework.Tests.Platform { [TestFixture] public class UserInputManagerTest : TestCase { [Test] public void IsAliveTest() { AddAssert("UserInputManager is alive", () => new UserInputManager().IsAlive); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Platform; namespace osu.Framework.Tests.Platform { [TestFixture] public class UserInputManagerTest { [Test] public void IsAliveTest() { using (var client = new TestHeadlessGameHost(@"client", true)) { var testGame = new TestTestGame(); client.Run(testGame); Assert.IsTrue(testGame.IsRootAlive); } } private class TestHeadlessGameHost : HeadlessGameHost { public Drawable CurrentRoot => Root; public TestHeadlessGameHost(string hostname, bool bindIPC) : base(hostname, bindIPC) { } } private class TestTestGame : TestGame { public bool IsRootAlive; protected override void LoadComplete() { IsRootAlive = ((TestHeadlessGameHost)Host).CurrentRoot.IsAlive; Exit(); } } } }
Move exception handling below all the cases
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Graphics; using osuTK.Graphics; namespace osu.Game.Overlays.Home.Friends { public class FriendsOnlineStatusItem : OverlayUpdateStreamItem<FriendsBundle> { public FriendsOnlineStatusItem(FriendsBundle value) : base(value) { } protected override string GetMainText => Value.Status.ToString(); protected override string GetAdditionalText => Value.Count.ToString(); protected override Color4 GetBarColour(OsuColour colours) { switch (Value.Status) { default: throw new ArgumentException($@"{Value.Status} status does not provide a colour in {nameof(GetBarColour)}."); case FriendsOnlineStatus.All: return Color4.White; case FriendsOnlineStatus.Online: return colours.GreenLight; case FriendsOnlineStatus.Offline: return Color4.Black; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Graphics; using osuTK.Graphics; namespace osu.Game.Overlays.Home.Friends { public class FriendsOnlineStatusItem : OverlayUpdateStreamItem<FriendsBundle> { public FriendsOnlineStatusItem(FriendsBundle value) : base(value) { } protected override string GetMainText => Value.Status.ToString(); protected override string GetAdditionalText => Value.Count.ToString(); protected override Color4 GetBarColour(OsuColour colours) { switch (Value.Status) { case FriendsOnlineStatus.All: return Color4.White; case FriendsOnlineStatus.Online: return colours.GreenLight; case FriendsOnlineStatus.Offline: return Color4.Black; default: throw new ArgumentException($@"{Value.Status} status does not provide a colour in {nameof(GetBarColour)}."); } } } }
Fix mania not getting its own selection handler
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Edit.Blueprints; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Screens.Edit.Compose.Components; namespace osu.Game.Rulesets.Mania.Edit { public class ManiaBlueprintContainer : ComposeBlueprintContainer { public ManiaBlueprintContainer(IEnumerable<DrawableHitObject> drawableHitObjects) : base(drawableHitObjects) { } public override OverlaySelectionBlueprint CreateBlueprintFor(DrawableHitObject hitObject) { switch (hitObject) { case DrawableNote note: return new NoteSelectionBlueprint(note); case DrawableHoldNote holdNote: return new HoldNoteSelectionBlueprint(holdNote); } return base.CreateBlueprintFor(hitObject); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Edit.Blueprints; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Screens.Edit.Compose.Components; namespace osu.Game.Rulesets.Mania.Edit { public class ManiaBlueprintContainer : ComposeBlueprintContainer { public ManiaBlueprintContainer(IEnumerable<DrawableHitObject> drawableHitObjects) : base(drawableHitObjects) { } public override OverlaySelectionBlueprint CreateBlueprintFor(DrawableHitObject hitObject) { switch (hitObject) { case DrawableNote note: return new NoteSelectionBlueprint(note); case DrawableHoldNote holdNote: return new HoldNoteSelectionBlueprint(holdNote); } return base.CreateBlueprintFor(hitObject); } protected override SelectionHandler CreateSelectionHandler() => new ManiaSelectionHandler(); } }
Fix the bug that the config for NUnit was not in the correct folder
using System; using System.IO; using System.Linq; namespace NBi.Service.RunnerConfig { class NUnitRunnerConfigBuilder : AbstractRunnerConfigBuilder { public NUnitRunnerConfigBuilder() : base("NBi.config", "NUnit.nunit") { } public NUnitRunnerConfigBuilder(IFilePersister filePersister) : this() { base.filePersister = filePersister; } protected override string CalculateRunnerProjectFullPath() { return base.CalculateRunnerProjectFullPath() + ".nunit"; } protected override string CalculateConfigFullPath() { return BasePath + TestSuite + Path.GetFileNameWithoutExtension(this.Filename) + ".config"; } } }
using System; using System.IO; using System.Linq; namespace NBi.Service.RunnerConfig { class NUnitRunnerConfigBuilder : AbstractRunnerConfigBuilder { public NUnitRunnerConfigBuilder() : base("NBi.config", "NUnit.nunit") { } public NUnitRunnerConfigBuilder(IFilePersister filePersister) : this() { base.filePersister = filePersister; } protected override string CalculateRunnerProjectFullPath() { return base.CalculateRunnerProjectFullPath() + ".nunit"; } protected override string CalculateConfigFullPath() { return BasePath + Path.GetFileNameWithoutExtension(this.Filename) + ".config"; } } }
Clear heart on returned heartbeat
using System; using System.Threading; using System.Threading.Tasks; using Knapcode.CheckRepublic.Logic.Entities; using Microsoft.EntityFrameworkCore; namespace Knapcode.CheckRepublic.Logic.Business { public class HeartbeatService : IHeartbeatService { private readonly CheckContext _context; public HeartbeatService(CheckContext context) { _context = context; } public async Task<Heartbeat> CreateHeartbeatAsync(string heartGroupName, string heartName, CancellationToken token) { var time = DateTimeOffset.UtcNow; var heart = await _context .Hearts .Include(x => x.HeartGroup) .FirstOrDefaultAsync(x => x.HeartGroup.Name == heartGroupName && x.Name == heartName, token); if (heart == null) { var heartGroup = await _context .HeartGroups .FirstOrDefaultAsync(x => x.Name == heartGroupName, token); if (heartGroup == null) { heartGroup = new HeartGroup { Name = heartGroupName }; } heart = new Heart { HeartGroup = heartGroup, Name = heartName }; } var heartbeat = new Heartbeat { Heart = heart, Time = time }; _context.Heartbeats.Add(heartbeat); await _context.SaveChangesAsync(token); return heartbeat; } } }
using System; using System.Threading; using System.Threading.Tasks; using Knapcode.CheckRepublic.Logic.Entities; using Microsoft.EntityFrameworkCore; namespace Knapcode.CheckRepublic.Logic.Business { public class HeartbeatService : IHeartbeatService { private readonly CheckContext _context; public HeartbeatService(CheckContext context) { _context = context; } public async Task<Heartbeat> CreateHeartbeatAsync(string heartGroupName, string heartName, CancellationToken token) { var time = DateTimeOffset.UtcNow; var heart = await _context .Hearts .Include(x => x.HeartGroup) .FirstOrDefaultAsync(x => x.HeartGroup.Name == heartGroupName && x.Name == heartName, token); if (heart == null) { var heartGroup = await _context .HeartGroups .FirstOrDefaultAsync(x => x.Name == heartGroupName, token); if (heartGroup == null) { heartGroup = new HeartGroup { Name = heartGroupName }; } heart = new Heart { HeartGroup = heartGroup, Name = heartName }; } var heartbeat = new Heartbeat { Heart = heart, Time = time }; _context.Heartbeats.Add(heartbeat); await _context.SaveChangesAsync(token); // Clear unnecessary information heartbeat.Heart = null; return heartbeat; } } }
Update script injection tags to match what the scripts are expecting
using System; using Glimpse.Common; using Glimpse.Initialization; using Microsoft.AspNet.Razor.Runtime.TagHelpers; namespace Glimpse.Agent.Razor { [HtmlTargetElement("body")] public class ScriptInjector : TagHelper { private readonly Guid _requestId; private readonly ScriptOptions _scriptOptions; public ScriptInjector(IGlimpseContextAccessor context, IScriptOptionsProvider scriptOptionsProvider) { _requestId = context.RequestId; _scriptOptions = scriptOptionsProvider.BuildInstance(); } public override int Order => int.MaxValue; public override void Process(TagHelperContext context, TagHelperOutput output) { output.PostContent.SetContentEncoded( $@"<script src=""{_scriptOptions.HudScriptTemplate}"" data-request-id=""{_requestId.ToString("N")}"" data-client-template=""{_scriptOptions.ClientScriptTemplate}"" async></script> <script src=""{_scriptOptions.BrowserAgentScriptTemplate}"" data-request-id=""{_requestId.ToString("N")}"" data-action-template=""{_scriptOptions.MessageIngressTemplate}"" async></script>"); } } }
using System; using Glimpse.Common; using Glimpse.Initialization; using Microsoft.AspNet.Razor.Runtime.TagHelpers; namespace Glimpse.Agent.Razor { [HtmlTargetElement("body")] public class ScriptInjector : TagHelper { private readonly Guid _requestId; private readonly ScriptOptions _scriptOptions; public ScriptInjector(IGlimpseContextAccessor context, IScriptOptionsProvider scriptOptionsProvider) { _requestId = context.RequestId; _scriptOptions = scriptOptionsProvider.BuildInstance(); } public override int Order => int.MaxValue; public override void Process(TagHelperContext context, TagHelperOutput output) { output.PostContent.SetContentEncoded( $@"<script src=""{_scriptOptions.HudScriptTemplate}"" id=""__glimpse_hud"" data-request-id=""{_requestId.ToString("N")}"" data-client-template=""{_scriptOptions.ClientScriptTemplate}"" async></script> <script src=""{_scriptOptions.BrowserAgentScriptTemplate}"" id=""__glimpse_browser_agent"" data-request-id=""{_requestId.ToString("N")}"" data-message-ingress-template=""{_scriptOptions.MessageIngressTemplate}"" async></script>"); } } }
Add namespace for Response.Write extension.
using System; using System.Threading.Tasks; using Newtonsoft.Json; namespace Microsoft.AspNet.Mvc { public class SmartJsonResult : ActionResult { public SmartJsonResult() : base() { } public JsonSerializerSettings Settings { get; set; } public object Data { get; set; } public int? StatusCode { get; set; } public override Task ExecuteResultAsync(ActionContext context) { //if (!context.IsChildAction) //{ // if (StatusCode.HasValue) // { // context.HttpContext.Response.StatusCode = StatusCode.Value; // } // context.HttpContext.Response.ContentType = "application/json"; // context.HttpContext.Response.ContentEncoding = Encoding.UTF8; //} return context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(Data, Settings ?? new JsonSerializerSettings())); } } }
using System; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Newtonsoft.Json; namespace Microsoft.AspNet.Mvc { public class SmartJsonResult : ActionResult { public SmartJsonResult() : base() { } public JsonSerializerSettings Settings { get; set; } public object Data { get; set; } public int? StatusCode { get; set; } public override Task ExecuteResultAsync(ActionContext context) { //if (!context.IsChildAction) //{ // if (StatusCode.HasValue) // { // context.HttpContext.Response.StatusCode = StatusCode.Value; // } // context.HttpContext.Response.ContentType = "application/json"; // context.HttpContext.Response.ContentEncoding = Encoding.UTF8; //} return context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(Data, Settings ?? new JsonSerializerSettings())); } } }
Update so it's once again in line with the interface and preferred paradigm (RegisterTrigger).
using System.Collections.Generic; // Using directives for plugin use. using MeidoCommon; using System.ComponentModel.Composition; [Export(typeof(IMeidoHook))] public class MyClass : IMeidoHook { readonly IIrcComm irc; public string Prefix { get; set; } public string Name { get { return "MyClass"; } } public string Version { get { return "0.10"; } } public Dictionary<string,string> Help { get { return new Dictionary<string, string>() { {"trigger", "trigger does x"} }; } } [ImportingConstructor] public MyClass(IIrcComm ircComm) { irc = ircComm; irc.AddChannelMessageHandler(HandleChannelMessage); } public void HandleChannelMessage(IIrcMessage ircMessage) { // Do something } }
using System.Collections.Generic; // Using directives for plugin use. using MeidoCommon; using System.ComponentModel.Composition; // IMeidoHook wants you to implement `Name`, `Version`, `Help` and the `Stop` method. [Export(typeof(IMeidoHook))] public class MyClass : IMeidoHook { public string Name { get { return "MyClass"; } } public string Version { get { return "0.10"; } } public Dictionary<string,string> Help { get { return new Dictionary<string, string>() { {"example", "example [args] - does something."} }; } } public void Stop() {} [ImportingConstructor] public MyClass(IIrcComm irc, IMeidoComm meido) { meido.RegisterTrigger("example", ExampleTrigger); } public void ExampleTrigger(IIrcMessage ircMessage) { // Do something, like: ircMessage.Reply("Example trigger triggered."); } }
Revert "CV-500 Added ApprenticeshipCompleted to UserAction"
using System; using SFA.DAS.CommitmentsV2.Types; namespace SFA.DAS.CommitmentsV2.Messages.Events { public class EntityStateChangedEvent { public Guid CorrelationId { get; set; } public UserAction StateChangeType { get; set; } public string EntityType { get; set; } public long EmployerAccountId { get; set; } public long ProviderId { get; set; } public long EntityId { get; set; } public string InitialState { get; set; } public string UpdatedState { get; set; } public string UpdatingUserId { get; set; } public string UpdatingUserName { get; set; } public Party UpdatingParty { get; set; } public DateTime UpdatedOn { get; set; } } public enum UserAction { ApproveCohort, SendCohort, AddDraftApprenticeship, ApprenticeshipCompleted, UpdateDraftApprenticeship, CreateCohort, CreateCohortWithOtherParty, DeleteDraftApprenticeship, DeleteCohort, ApproveTransferRequest, RejectTransferRequest, CompletionPayment } }
using System; using SFA.DAS.CommitmentsV2.Types; namespace SFA.DAS.CommitmentsV2.Messages.Events { public class EntityStateChangedEvent { public Guid CorrelationId { get; set; } public UserAction StateChangeType { get; set; } public string EntityType { get; set; } public long EmployerAccountId { get; set; } public long ProviderId { get; set; } public long EntityId { get; set; } public string InitialState { get; set; } public string UpdatedState { get; set; } public string UpdatingUserId { get; set; } public string UpdatingUserName { get; set; } public Party UpdatingParty { get; set; } public DateTime UpdatedOn { get; set; } } public enum UserAction { ApproveCohort, SendCohort, AddDraftApprenticeship, UpdateDraftApprenticeship, CreateCohort, CreateCohortWithOtherParty, DeleteDraftApprenticeship, DeleteCohort, ApproveTransferRequest, RejectTransferRequest, CompletionPayment } }
Change ctor parameter from byte to ArraySegment<byte>
using System; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { public IPAddrPrefix(byte[] data, AddressFamily afi = AddressFamily.IP) { DecodeFromBytes(data, afi); } public byte Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public int GetByteLength() { return 1 + (Length + 7) / 8; } public void DecodeFromBytes(byte[] data, AddressFamily afi) { Length = data[0]; if (Length <= 0) return; var byteLength = (Length + 7) / 8; var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Buffer.BlockCopy(data, 1, ipBytes, 0, byteLength); Prefix = new IPAddress(ipBytes); } } }
using System; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { public IPAddrPrefix(ArraySegment<byte> data, AddressFamily afi = AddressFamily.IP) { Length = data.Array[data.Offset]; var ipBytes = new byte[ByteLength - 1]; Array.Copy(data.Array, data.Offset + 1, ipBytes, 0, ipBytes.Length); DecodeFromBytes(ipBytes, afi); } internal int ByteLength { get { return 1 + (Length + 7) / 8; } } public int Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public void DecodeFromBytes(byte[] data, AddressFamily afi = AddressFamily.IP) { var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Array.Copy(data, 0, ipBytes, 0, data.Length); Prefix = new IPAddress(ipBytes); } } }
Remove hard coded variable name.
using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace Junctionizer.UI.Columns { public partial class DependentOnFinalSizeColumn { public DependentOnFinalSizeColumn() { InitializeComponent(); } public override BindingBase Binding { get => base.Binding; set { base.Binding = value; var path = ((Binding) Binding).Path.Path; var lastDotIndex = path.LastIndexOf('.'); var pathToFolder = lastDotIndex < 0 ? string.Empty : path.Substring(0, lastDotIndex + 1); AddCellStyle(pathToFolder); } } private void AddCellStyle(string pathToFolder) { CellStyle = new Style(typeof(DataGridCell), (Style) Application.Current.FindResource("RightAlignCell")); var trigger = new DataTrigger { Binding = new Binding(pathToFolder + "HasFinalSize"), Value = "False" }; trigger.Setters.Add(new Setter(FontStyleProperty, FontStyles.Italic)); trigger.Setters.Add(new Setter(FontWeightProperty, FontWeights.SemiBold)); CellStyle.Triggers.Add(trigger); } } }
using System.Windows; using System.Windows.Controls; using System.Windows.Data; using Junctionizer.Model; namespace Junctionizer.UI.Columns { public partial class DependentOnFinalSizeColumn { public DependentOnFinalSizeColumn() { InitializeComponent(); } public override BindingBase Binding { get => base.Binding; set { base.Binding = value; var path = ((Binding) Binding).Path.Path; var lastDotIndex = path.LastIndexOf('.'); var pathToFolder = lastDotIndex < 0 ? string.Empty : path.Substring(0, lastDotIndex + 1); AddCellStyle(pathToFolder); } } private void AddCellStyle(string pathToFolder) { CellStyle = new Style(typeof(DataGridCell), (Style) Application.Current.FindResource("RightAlignCell")); var trigger = new DataTrigger { Binding = new Binding(pathToFolder + nameof(GameFolder.HasFinalSize)), Value = "False" }; trigger.Setters.Add(new Setter(FontStyleProperty, FontStyles.Italic)); trigger.Setters.Add(new Setter(FontWeightProperty, FontWeights.SemiBold)); CellStyle.Triggers.Add(trigger); } } }
Use assignment instead of binding
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Graphics; using osu.Framework.Bindables; using osu.Framework.Graphics.Shapes; using osu.Framework.Allocation; using osu.Game.Graphics; using osu.Game.Overlays.Rankings; namespace osu.Game.Tests.Visual.Online { public class TestSceneRankingsScopeSelector : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(RankingsScopeSelector), }; private readonly Box background; public TestSceneRankingsScopeSelector() { var scope = new Bindable<RankingsScope>(); AddRange(new Drawable[] { background = new Box { RelativeSizeAxes = Axes.Both }, new RankingsScopeSelector { Anchor = Anchor.Centre, Origin = Anchor.Centre, Current = { BindTarget = scope } } }); AddStep(@"Select country", () => scope.Value = RankingsScope.Country); AddStep(@"Select performance", () => scope.Value = RankingsScope.Performance); AddStep(@"Select score", () => scope.Value = RankingsScope.Score); AddStep(@"Select spotlights", () => scope.Value = RankingsScope.Spotlights); } [BackgroundDependencyLoader] private void load(OsuColour colours) { background.Colour = colours.GreySeafoam; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Graphics; using osu.Framework.Bindables; using osu.Framework.Graphics.Shapes; using osu.Framework.Allocation; using osu.Game.Graphics; using osu.Game.Overlays.Rankings; namespace osu.Game.Tests.Visual.Online { public class TestSceneRankingsScopeSelector : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(RankingsScopeSelector), }; private readonly Box background; public TestSceneRankingsScopeSelector() { var scope = new Bindable<RankingsScope>(); AddRange(new Drawable[] { background = new Box { RelativeSizeAxes = Axes.Both }, new RankingsScopeSelector { Anchor = Anchor.Centre, Origin = Anchor.Centre, Current = scope } }); AddStep(@"Select country", () => scope.Value = RankingsScope.Country); AddStep(@"Select performance", () => scope.Value = RankingsScope.Performance); AddStep(@"Select score", () => scope.Value = RankingsScope.Score); AddStep(@"Select spotlights", () => scope.Value = RankingsScope.Spotlights); } [BackgroundDependencyLoader] private void load(OsuColour colours) { background.Colour = colours.GreySeafoam; } } }