Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Refactor logic for thousands (M, MM, MMM).
using System; using System.Collections.Generic; using System.Text; namespace VasysRomanNumeralsKata { public class RomanNumeral { private int? _baseTenRepresentation = null; public RomanNumeral(int baseTenNumber) { _baseTenRepresentation = baseTenNumber; } public string GenerateRomanNumeralRepresntation() { StringBuilder romanNumeralBuilder = new StringBuilder(); int numberOfThousands = (int)_baseTenRepresentation / 1000; if (numberOfThousands > 0) { for(int i = 0; i < numberOfThousands; i++) { romanNumeralBuilder.Append("M"); } } int remainder = (int)_baseTenRepresentation % 1000; if (remainder >= 900) { romanNumeralBuilder.Append("CM"); remainder -= 900; } if(remainder >= 500) { romanNumeralBuilder.Append("D"); remainder -= 500; } if (remainder >= 400) { romanNumeralBuilder.Append("CD"); remainder -= 400; } while(remainder >= 100) { romanNumeralBuilder.Append("C"); remainder -= 100; } int numberOfTens = remainder / 10; if (numberOfTens > 0) { for (int i = 0; i < numberOfTens; i++) { romanNumeralBuilder.Append("X"); } } return romanNumeralBuilder.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; namespace VasysRomanNumeralsKata { public class RomanNumeral { private int? _baseTenRepresentation = null; public RomanNumeral(int baseTenNumber) { _baseTenRepresentation = baseTenNumber; } public string GenerateRomanNumeralRepresntation() { StringBuilder romanNumeralBuilder = new StringBuilder(); int remainder = (int)_baseTenRepresentation; while(remainder / 1000 > 0) { romanNumeralBuilder.Append("M"); remainder -= 1000; } if (remainder >= 900) { romanNumeralBuilder.Append("CM"); remainder -= 900; } if(remainder >= 500) { romanNumeralBuilder.Append("D"); remainder -= 500; } if (remainder >= 400) { romanNumeralBuilder.Append("CD"); remainder -= 400; } while(remainder >= 100) { romanNumeralBuilder.Append("C"); remainder -= 100; } int numberOfTens = remainder / 10; if (numberOfTens > 0) { for (int i = 0; i < numberOfTens; i++) { romanNumeralBuilder.Append("X"); } } return romanNumeralBuilder.ToString(); } } }
Add braces for the 'if (name.Substring(... '
using System; using System.Reflection; namespace AssemblyInfo { class Program { static void Main(string[] args) { if (args != null && args.Length > 0) { Assembly asm = null; var name = args[0]; try { if (name.Substring(name.Length - 4, 4) != ".dll") name += ".dll"; asm = Assembly.LoadFrom(name); } catch { try { var path = AppDomain.CurrentDomain.BaseDirectory + @"\" + name; asm = Assembly.LoadFrom(path); } catch (Exception e) { System.Console.WriteLine(e.Message); return; } } var x = asm.GetName(); System.Console.WriteLine("CodeBase: {0}", x.CodeBase); System.Console.WriteLine("ContentType: {0}", x.ContentType); System.Console.WriteLine("CultureInfo: {0}", x.CultureInfo); System.Console.WriteLine("CultureName: {0}", x.CultureName); System.Console.WriteLine("FullName: {0}", x.FullName); System.Console.WriteLine("Name: {0}", x.Name); System.Console.WriteLine("Version: {0}", x.Version); System.Console.WriteLine("VersionCompatibility: {0}", x.VersionCompatibility); } else { System.Console.WriteLine("Usage: asminfo.exe assembly"); } } } }
using System; using System.Reflection; namespace AssemblyInfo { class Program { static void Main(string[] args) { if (args != null && args.Length > 0) { Assembly asm = null; var name = args[0]; try { if (name.Substring(name.Length - 4, 4) != ".dll") { name += ".dll"; } asm = Assembly.LoadFrom(name); } catch { try { var path = AppDomain.CurrentDomain.BaseDirectory + @"\" + name; asm = Assembly.LoadFrom(path); } catch (Exception e) { System.Console.WriteLine(e.Message); return; } } var x = asm.GetName(); System.Console.WriteLine("CodeBase: {0}", x.CodeBase); System.Console.WriteLine("ContentType: {0}", x.ContentType); System.Console.WriteLine("CultureInfo: {0}", x.CultureInfo); System.Console.WriteLine("CultureName: {0}", x.CultureName); System.Console.WriteLine("FullName: {0}", x.FullName); System.Console.WriteLine("Name: {0}", x.Name); System.Console.WriteLine("Version: {0}", x.Version); System.Console.WriteLine("VersionCompatibility: {0}", x.VersionCompatibility); } else { System.Console.WriteLine("Usage: asminfo.exe assembly"); } } } }
Print filename with each error
using System; using System.Linq; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; // Adapted from // https://blogs.msdn.microsoft.com/ericwhite/2010/03/04/validate-open-xml-documents-using-the-open-xml-sdk-2-0/ namespace XlsxValidator { class MainClass { public static void Main(string[] args) { if (args.Count() == 0) { Console.WriteLine("No document given"); return; } using (SpreadsheetDocument doc = SpreadsheetDocument.Open(args[0], false)) { var validator = new OpenXmlValidator(); var errors = validator.Validate(doc); if (errors.Count() == 0) { Console.WriteLine("Document is valid"); } else { Console.WriteLine("Document is not valid"); } Console.WriteLine(); foreach (var error in errors) { Console.WriteLine("Error description: {0}", error.Description); Console.WriteLine("Content type of part with error: {0}", error.Part.ContentType); Console.WriteLine("Location of error: {0}", error.Path.XPath); Console.WriteLine(); } } } } }
using System; using System.Linq; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; // Adapted from // https://blogs.msdn.microsoft.com/ericwhite/2010/03/04/validate-open-xml-documents-using-the-open-xml-sdk-2-0/ namespace XlsxValidator { class MainClass { public static void Main(string[] args) { if (args.Count() == 0) { Console.WriteLine("No document given"); return; } var path = args[0]; using (SpreadsheetDocument doc = SpreadsheetDocument.Open(path, false)) { var validator = new OpenXmlValidator(); var errors = validator.Validate(doc); if (errors.Count() == 0) { Console.WriteLine("Document is valid"); } else { Console.WriteLine("Document is not valid"); } Console.WriteLine(); foreach (var error in errors) { Console.WriteLine("File: {0}", path); Console.WriteLine("Error: {0}", error.Description); Console.WriteLine("ContentType: {0}", error.Part.ContentType); Console.WriteLine("XPath: {0}", error.Path.XPath); Console.WriteLine(); } } } } }
Add extra check on result type
using Microsoft.AspNetCore.Mvc; using Xunit; using DiceApi.WebApi.Controllers; namespace DiceApi.WebApi.Tests { /// <summary> /// Test class for <see cref="DieController" />. /// </summary> public class DieControllerTest { /// <summary> /// Verifies that Get() returns a BadRequestResult when given an invalid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenSidesLessThanZero_ReturnsBadRequestResult() { var sut = new DieController(); var result = sut.Get(-1); Assert.Equal(typeof(BadRequestResult), result.GetType()); } /// <summary> /// Verifies that Get() returns an OkObjectResult when given an valid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenValidSizeValue_ReturnsOkResult() { var sut = new DieController(); var result = sut.Get(6); Assert.Equal(typeof(OkObjectResult), result.GetType()); } } }
using Microsoft.AspNetCore.Mvc; using Xunit; using DiceApi.WebApi.Controllers; namespace DiceApi.WebApi.Tests { /// <summary> /// Test class for <see cref="DieController" />. /// </summary> public class DieControllerTest { /// <summary> /// Verifies that Get() returns a BadRequestResult when given an invalid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenSidesLessThanZero_ReturnsBadRequestResult() { var sut = new DieController(); var result = sut.Get(-1); Assert.Equal(typeof(BadRequestResult), result.GetType()); } /// <summary> /// Verifies that Get() returns an OkObjectResult when given an valid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenValidSizeValue_ReturnsOkResult() { var sut = new DieController(); var result = sut.Get(6); Assert.Equal(typeof(OkObjectResult), result.GetType()); Assert.Equal(typeof(int), ((OkObjectResult)result).Value.GetType()); } } }
Update sample app to use newer config API
using System; using Serilog; using Serilog.Events; using SerilogWeb.Classic; namespace SerilogWeb.Test { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { ApplicationLifecycleModule.FormDataLoggingLevel = LogEventLevel.Debug; ApplicationLifecycleModule.LogPostedFormData = LogPostedFormDataOption.OnMatch; ApplicationLifecycleModule.ShouldLogPostedFormData = context => context.Response.StatusCode >= 400; // ReSharper disable once PossibleNullReferenceException ApplicationLifecycleModule.RequestFilter = context => context.Request.Url.PathAndQuery.StartsWith("/__browserLink"); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}" ) .CreateLogger(); } } }
using System; using Serilog; using Serilog.Events; using SerilogWeb.Classic; namespace SerilogWeb.Test { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { // ReSharper disable once PossibleNullReferenceException SerilogWebClassic.Configuration .IgnoreRequestsMatching(ctx => ctx.Request.Url.PathAndQuery.StartsWith("/__browserLink")) .EnableFormDataLogging(formData => formData .AtLevel(LogEventLevel.Debug) .OnMatch(ctx => ctx.Response.StatusCode >= 400)); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}" ) .CreateLogger(); } } }
Fix path to internal test data location
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BrightstarDB.InternalTests { internal static class TestConfiguration { public static string DataLocation = "..\\..\\Data\\"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BrightstarDB.InternalTests { internal static class TestConfiguration { public static string DataLocation = "..\\..\\..\\Data\\"; } }
Fix cherry pick, spaces not tabs and remove unused delegate
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; namespace CefSharp { /// <summary> /// Event arguments to the IsBrowserInitializedChanged event handler. /// </summary> public class IsBrowserInitializedChangedEventArgs : EventArgs { public bool IsBrowserInitialized { get; private set; } public IsBrowserInitializedChangedEventArgs(bool isBrowserInitialized) { IsBrowserInitialized = isBrowserInitialized; } } }; /// <summary> /// A delegate type used to listen to IsBrowserInitializedChanged events. /// </summary> public delegate void IsBrowserInitializedChangedEventHandler(object sender, IsBrowserInitializedChangedEventArgs args); }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; namespace CefSharp { /// <summary> /// Event arguments to the IsBrowserInitializedChanged event handler. /// </summary> public class IsBrowserInitializedChangedEventArgs : EventArgs { public bool IsBrowserInitialized { get; private set; } public IsBrowserInitializedChangedEventArgs(bool isBrowserInitialized) { IsBrowserInitialized = isBrowserInitialized; } } }
Fix tableName not correctly saved
using Evolve.Migration; using System.Collections.Generic; using Evolve.Utilities; using Evolve.Connection; namespace Evolve.Metadata { public abstract class MetadataTable : IEvolveMetadata { protected IWrappedConnection _wrappedConnection; public MetadataTable(string schema, string tableName, IWrappedConnection wrappedConnection) { Schema = Check.NotNullOrEmpty(schema, nameof(schema)); TableName = Check.NotNullOrEmpty(schema, nameof(tableName)); _wrappedConnection = Check.NotNull(wrappedConnection, nameof(wrappedConnection)); } public string Schema { get; private set; } public string TableName { get; private set; } public abstract void Lock(); public abstract bool CreateIfNotExists(); public void AddMigrationMetadata(MigrationScript migration, bool success) { CreateIfNotExists(); InternalAddMigrationMetadata(migration, success); } public IEnumerable<MigrationMetadata> GetAllMigrationMetadata() { CreateIfNotExists(); return InternalGetAllMigrationMetadata(); } protected abstract bool IsExists(); protected abstract void Create(); protected abstract void InternalAddMigrationMetadata(MigrationScript migration, bool success); protected abstract IEnumerable<MigrationMetadata> InternalGetAllMigrationMetadata(); } }
using Evolve.Migration; using System.Collections.Generic; using Evolve.Utilities; using Evolve.Connection; namespace Evolve.Metadata { public abstract class MetadataTable : IEvolveMetadata { protected IWrappedConnection _wrappedConnection; public MetadataTable(string schema, string tableName, IWrappedConnection wrappedConnection) { Schema = Check.NotNullOrEmpty(schema, nameof(schema)); TableName = Check.NotNullOrEmpty(tableName, nameof(tableName)); _wrappedConnection = Check.NotNull(wrappedConnection, nameof(wrappedConnection)); } public string Schema { get; private set; } public string TableName { get; private set; } public abstract void Lock(); public abstract bool CreateIfNotExists(); public void AddMigrationMetadata(MigrationScript migration, bool success) { CreateIfNotExists(); InternalAddMigrationMetadata(migration, success); } public IEnumerable<MigrationMetadata> GetAllMigrationMetadata() { CreateIfNotExists(); return InternalGetAllMigrationMetadata(); } protected abstract bool IsExists(); protected abstract void Create(); protected abstract void InternalAddMigrationMetadata(MigrationScript migration, bool success); protected abstract IEnumerable<MigrationMetadata> InternalGetAllMigrationMetadata(); } }
Add tests for `kernel32!SetHandleInformation` and `kernel32!GetHandleInformation`
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; using PInvoke; using Xunit; using static PInvoke.Kernel32; public partial class Kernel32Facts { [Fact] public void GetTickCount_Nonzero() { uint result = GetTickCount(); Assert.NotEqual(0u, result); } [Fact] public void GetTickCount64_Nonzero() { ulong result = GetTickCount64(); Assert.NotEqual(0ul, result); } [Fact] public void SetLastError_ImpactsMarshalGetLastWin32Error() { SetLastError(2); Assert.Equal(2, Marshal.GetLastWin32Error()); } [Fact] public unsafe void GetStartupInfo_Title() { var startupInfo = STARTUPINFO.Create(); GetStartupInfo(ref startupInfo); Assert.NotNull(startupInfo.Title); Assert.NotEqual(0, startupInfo.Title.Length); } }
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; using System.Threading; using PInvoke; using Xunit; using static PInvoke.Kernel32; public partial class Kernel32Facts { [Fact] public void GetTickCount_Nonzero() { uint result = GetTickCount(); Assert.NotEqual(0u, result); } [Fact] public void GetTickCount64_Nonzero() { ulong result = GetTickCount64(); Assert.NotEqual(0ul, result); } [Fact] public void SetLastError_ImpactsMarshalGetLastWin32Error() { SetLastError(2); Assert.Equal(2, Marshal.GetLastWin32Error()); } [Fact] public unsafe void GetStartupInfo_Title() { var startupInfo = STARTUPINFO.Create(); GetStartupInfo(ref startupInfo); Assert.NotNull(startupInfo.Title); Assert.NotEqual(0, startupInfo.Title.Length); } [Fact] public void GetHandleInformation_DoesNotThrow() { var manualResetEvent = new ManualResetEvent(false); GetHandleInformation(manualResetEvent.SafeWaitHandle, out var lpdwFlags); } [Fact] public void SetHandleInformation_DoesNotThrow() { var manualResetEvent = new ManualResetEvent(false); SetHandleInformation( manualResetEvent.SafeWaitHandle, HandleFlags.HANDLE_FLAG_INHERIT | HandleFlags.HANDLE_FLAG_PROTECT_FROM_CLOSE, HandleFlags.HANDLE_FLAG_NONE); } }
Add the Material Manager to the context for injection.
using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>(); injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext(); IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>(); injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } }
using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); IMaterialManager materialManager = managers.GetComponent<MaterialManager>(); injectionBinder.Bind<IMaterialManager>().ToValue(materialManager).ToSingleton().CrossContext(); ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>(); injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext(); IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>(); injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } }
Put body data type check into switch statement
using System; using System.Net; using Arango.fastJSON; namespace Arango.Client.Protocol { internal class Response { internal int StatusCode { get; set; } internal WebHeaderCollection Headers { get; set; } internal string Body { get; set; } internal DataType DataType { get; set; } internal object Data { get; set; } internal Exception Exception { get; set; } internal AEerror Error { get; set; } internal void DeserializeBody() { if (string.IsNullOrEmpty(Body)) { DataType = DataType.Null; Data = null; } else { var trimmedBody = Body.Trim(); // body contains JSON array if (trimmedBody[0] == '[') { DataType = DataType.List; } // body contains JSON object else if (trimmedBody[0] == '{') { DataType = DataType.Document; } else { DataType = DataType.Primitive; } Data = JSON.Parse(trimmedBody); } } } }
using System; using System.Net; using Arango.fastJSON; namespace Arango.Client.Protocol { internal class Response { internal int StatusCode { get; set; } internal WebHeaderCollection Headers { get; set; } internal string Body { get; set; } internal DataType DataType { get; set; } internal object Data { get; set; } internal Exception Exception { get; set; } internal AEerror Error { get; set; } internal void DeserializeBody() { if (string.IsNullOrEmpty(Body)) { DataType = DataType.Null; Data = null; } else { var trimmedBody = Body.Trim(); switch (trimmedBody[0]) { // body contains JSON array case '[': DataType = DataType.List; break; // body contains JSON object case '{': DataType = DataType.Document; break; default: DataType = DataType.Primitive; break; } Data = JSON.Parse(trimmedBody); } } } }
Format date with user culture
using AutoMapper; using SnittListan.Models; using SnittListan.ViewModels; namespace SnittListan.Infrastructure { public class MatchProfile : Profile { protected override void Configure() { Mapper.CreateMap<Match, MatchViewModel>() .ForMember(x => x.Date, o => o.MapFrom(y => y.Date.ToShortDateString())) .ForMember(x => x.Results, o => o.MapFrom(y => y.FormattedLaneScore())) .ForMember(x => x.Teams, o => o.MapFrom(y => string.Format("{0}-{1}", y.HomeTeam, y.OppTeam))); } } }
using System.Threading; using AutoMapper; using SnittListan.Models; using SnittListan.ViewModels; namespace SnittListan.Infrastructure { public class MatchProfile : Profile { protected override void Configure() { Mapper.CreateMap<Match, MatchViewModel>() .ForMember(x => x.Date, o => o.MapFrom(y => y.Date.ToString(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern, Thread.CurrentThread.CurrentCulture))) .ForMember(x => x.Results, o => o.MapFrom(y => y.FormattedLaneScore())) .ForMember(x => x.Teams, o => o.MapFrom(y => string.Format("{0}-{1}", y.HomeTeam, y.OppTeam))); } } }
Revert back to old signature (transpilers get confused with multiple version); add opcode=Call
using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null) { if (from == null) throw new ArgumentException("Unexpected null argument", nameof(from)); if (to == null) throw new ArgumentException("Unexpected null argument", nameof(to)); foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = callOpcode ?? OpCodes.Call; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { if (from == null) throw new ArgumentException("Unexpected null argument", nameof(from)); if (to == null) throw new ArgumentException("Unexpected null argument", nameof(to)); foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = OpCodes.Call; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
Convert Main to be async
// Copyright (c) Martin Costello, 2016. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.Website { using System; using Extensions; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; /// <summary> /// A class representing the entry-point to the application. This class cannot be inherited. /// </summary> public static class Program { /// <summary> /// The main entry-point to the application. /// </summary> /// <param name="args">The arguments to the application.</param> /// <returns> /// The exit code from the application. /// </returns> public static int Main(string[] args) { try { using (var host = BuildWebHost(args)) { host.Run(); } return 0; } catch (Exception ex) { Console.Error.WriteLine($"Unhandled exception: {ex}"); return -1; } } private static IWebHost BuildWebHost(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseKestrel((p) => p.AddServerHeader = false) .UseAutofac() .UseAzureAppServices() .UseApplicationInsights() .UseStartup<Startup>() .CaptureStartupErrors(true) .Build(); } } }
// Copyright (c) Martin Costello, 2016. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.Website { using System; using System.Threading.Tasks; using Extensions; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; /// <summary> /// A class representing the entry-point to the application. This class cannot be inherited. /// </summary> public static class Program { /// <summary> /// The main entry-point to the application. /// </summary> /// <param name="args">The arguments to the application.</param> /// <returns> /// A <see cref="Task{TResult}"/> that returns the exit code from the application. /// </returns> public static async Task<int> Main(string[] args) { try { using (var host = BuildWebHost(args)) { await host.RunAsync(); } return 0; } catch (Exception ex) { Console.Error.WriteLine($"Unhandled exception: {ex}"); return -1; } } private static IWebHost BuildWebHost(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseKestrel((p) => p.AddServerHeader = false) .UseAutofac() .UseAzureAppServices() .UseApplicationInsights() .UseStartup<Startup>() .CaptureStartupErrors(true) .Build(); } } }
Fix for saving window state while minimized on closing
using System.Windows; namespace MilitaryPlanner.Views { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { //InitializeComponent(); } } }
using System.Windows; namespace MilitaryPlanner.Views { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { //InitializeComponent(); } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { base.OnClosing(e); // if window is minimized, restore to avoid opening minimized on next run if(WindowState == System.Windows.WindowState.Minimized) { WindowState = System.Windows.WindowState.Normal; } } } }
Make precedence test public to be discoverable by test runner.
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using ExprOpt = Microsoft.FSharp.Core.FSharpOption<AST.Expression>; using Expr = AST.Expression; namespace ParcelTest { [TestClass] class PrecedenceTests { [TestMethod] public void MultiplicationVsAdditionPrecedenceTest() { var mwb = MockWorkbook.standardMockWorkbook(); var e = mwb.envForSheet(1); var f = "=2*3+1"; ExprOpt asto = Parcel.parseFormula(f, e.Path, e.WorkbookName, e.WorksheetName); Expr correct = Expr.NewBinOpExpr( "+", Expr.NewBinOpExpr( "*", Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 2.0)), Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 3.0)) ), Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 1.0)) ); try { Expr ast = asto.Value; Assert.AreEqual(correct, ast); } catch (NullReferenceException nre) { Assert.Fail("Parse error: " + nre.Message); } } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using ExprOpt = Microsoft.FSharp.Core.FSharpOption<AST.Expression>; using Expr = AST.Expression; namespace ParcelTest { [TestClass] public class PrecedenceTests { [TestMethod] public void MultiplicationVsAdditionPrecedenceTest() { var mwb = MockWorkbook.standardMockWorkbook(); var e = mwb.envForSheet(1); var f = "=2*3+1"; ExprOpt asto = Parcel.parseFormula(f, e.Path, e.WorkbookName, e.WorksheetName); Expr correct = Expr.NewBinOpExpr( "+", Expr.NewBinOpExpr( "*", Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 2.0)), Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 3.0)) ), Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 1.0)) ); try { Expr ast = asto.Value; Assert.AreEqual(correct, ast); } catch (NullReferenceException nre) { Assert.Fail("Parse error: " + nre.Message); } } } }
Fix post filter test after boost/descriptor refactoring
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Nest.Resolvers.Converters; using Newtonsoft.Json; namespace Nest { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof(ReadAsTypeConverter<MatchAllQuery>))] public interface IMatchAllQuery : IQuery { [JsonProperty(PropertyName = "boost")] double? Boost { get; set; } [JsonProperty(PropertyName = "norm_field")] string NormField { get; set; } } public class MatchAllQuery : QueryBase, IMatchAllQuery { public double? Boost { get; set; } public string NormField { get; set; } bool IQuery.Conditionless => false; protected override void WrapInContainer(IQueryContainer container) { container.MatchAllQuery = this; } } public class MatchAllQueryDescriptor : QueryDescriptorBase<MatchAllQueryDescriptor, IMatchAllQuery> , IMatchAllQuery { bool IQuery.Conditionless => false; string IQuery.Name { get; set; } double? IMatchAllQuery.Boost { get; set; } string IMatchAllQuery.NormField { get; set; } public MatchAllQueryDescriptor Boost(double? boost) => Assign(a => a.Boost = boost); public MatchAllQueryDescriptor NormField(string normField) => Assign(a => a.NormField = normField); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Nest.Resolvers.Converters; using Newtonsoft.Json; namespace Nest { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof(ReadAsTypeConverter<MatchAllQuery>))] public interface IMatchAllQuery : IQuery { [JsonProperty(PropertyName = "norm_field")] string NormField { get; set; } } public class MatchAllQuery : QueryBase, IMatchAllQuery { public string NormField { get; set; } bool IQuery.Conditionless => false; protected override void WrapInContainer(IQueryContainer container) { container.MatchAllQuery = this; } } public class MatchAllQueryDescriptor : QueryDescriptorBase<MatchAllQueryDescriptor, IMatchAllQuery> , IMatchAllQuery { bool IQuery.Conditionless => false; string IMatchAllQuery.NormField { get; set; } public MatchAllQueryDescriptor NormField(string normField) => Assign(a => a.NormField = normField); } }
Disable exception throwing when ModelState is not valid
using Abp.AspNetCore.Mvc.Controllers; using Abp.IdentityFramework; using Microsoft.AspNetCore.Identity; namespace Repairis.Controllers { public abstract class RepairisControllerBase: AbpController { protected RepairisControllerBase() { LocalizationSourceName = RepairisConsts.LocalizationSourceName; } protected void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
using Abp.AspNetCore.Mvc.Controllers; using Abp.IdentityFramework; using Abp.Runtime.Validation; using Microsoft.AspNetCore.Identity; namespace Repairis.Controllers { [DisableValidation] public abstract class RepairisControllerBase: AbpController { protected RepairisControllerBase() { LocalizationSourceName = RepairisConsts.LocalizationSourceName; } protected void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
Use ReactiveUI Events for Loaded and SelectionChanged
using ReactiveUI; using Windows.UI.Xaml; namespace Ets.Mobile.Pages.Main { public sealed partial class MainPage { partial void PartialInitialize() { // Ensure to hide the status bar var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView(); statusBar.BackgroundOpacity = 0; statusBar.HideAsync().GetResults(); // Grade Presenter // NOTE: Do not remove this code, can't bind to the presenter's source this.OneWayBind(ViewModel, x => x.GradesPresenter, x => x.Grade.DataContext); // Handle the button visibility according to Pivot Context (SelectedIndex) Loaded += (s, e) => { MainPivot.SelectionChanged += (sender, e2) => { RefreshToday.Visibility = Visibility.Collapsed; RefreshGrade.Visibility = Visibility.Collapsed; switch (MainPivot.SelectedIndex) { case (int)MainPivotItem.Today: RefreshToday.Visibility = Visibility.Visible; break; case (int)MainPivotItem.Grade: RefreshGrade.Visibility = Visibility.Visible; break; } }; }; } } }
using System; using Windows.UI.Xaml; using EventsMixin = Windows.UI.Xaml.Controls.EventsMixin; namespace Ets.Mobile.Pages.Main { public sealed partial class MainPage { partial void PartialInitialize() { // Ensure to hide the status bar var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView(); statusBar.BackgroundOpacity = 0; statusBar.HideAsync().GetResults(); // Handle the button visibility according to Pivot Context (SelectedIndex) this.Events().Loaded.Subscribe(e => { EventsMixin.Events(MainPivot).SelectionChanged.Subscribe(e2 => { RefreshToday.Visibility = Visibility.Collapsed; RefreshGrade.Visibility = Visibility.Collapsed; switch (MainPivot.SelectedIndex) { case (int)MainPivotItem.Today: RefreshToday.Visibility = Visibility.Visible; break; case (int)MainPivotItem.Grade: RefreshGrade.Visibility = Visibility.Visible; break; } }); }); } } }
Add GetTititleEstimate that accepts data from URI.
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } } }
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query) { // All the values in "query" are null or zero // Do some stuff with query if there were anything to do return new string[] { "This is a CORS request.", "That works from any origin." }; } } }
Stop Equinox complaining about session download patch not being static
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Sandbox.Game.World; using Torch.Managers.PatchManager; using Torch.Mod; using VRage.Game; namespace Torch.Patches { [PatchShim] internal class SessionDownloadPatch { internal static void Patch(PatchContext context) { context.GetPattern(typeof(MySession).GetMethod(nameof(MySession.GetWorld))).Suffixes.Add(typeof(SessionDownloadPatch).GetMethod(nameof(SuffixGetWorld), BindingFlags.Static | BindingFlags.NonPublic)); } // ReSharper disable once InconsistentNaming private static void SuffixGetWorld(ref MyObjectBuilder_World __result) { if (!__result.Checkpoint.Mods.Any(m => m.PublishedFileId == TorchModCore.MOD_ID)) __result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(TorchModCore.MOD_ID)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Sandbox.Game.World; using Torch.Managers.PatchManager; using Torch.Mod; using VRage.Game; namespace Torch.Patches { [PatchShim] internal static class SessionDownloadPatch { internal static void Patch(PatchContext context) { context.GetPattern(typeof(MySession).GetMethod(nameof(MySession.GetWorld))).Suffixes.Add(typeof(SessionDownloadPatch).GetMethod(nameof(SuffixGetWorld), BindingFlags.Static | BindingFlags.NonPublic)); } // ReSharper disable once InconsistentNaming private static void SuffixGetWorld(ref MyObjectBuilder_World __result) { if (!__result.Checkpoint.Mods.Any(m => m.PublishedFileId == TorchModCore.MOD_ID)) __result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(TorchModCore.MOD_ID)); } } }
Fix ColoreException test performing wrong comparison.
namespace Colore.Tests { using System; using NUnit.Framework; [TestFixture] public class ColoreExceptionTests { [Test] public void ShouldSetMessage() { const string Expected = "Test message."; Assert.AreEqual(Expected, new ColoreException("Test message.")); } [Test] public void ShouldSetInnerException() { var expected = new Exception("Expected."); var actual = new ColoreException(null, new Exception("Expected.")).InnerException; Assert.AreEqual(expected.GetType(), actual.GetType()); Assert.AreEqual(expected.Message, actual.Message); } } }
namespace Colore.Tests { using System; using NUnit.Framework; [TestFixture] public class ColoreExceptionTests { [Test] public void ShouldSetMessage() { const string Expected = "Test message."; Assert.AreEqual(Expected, new ColoreException("Test message.").Message); } [Test] public void ShouldSetInnerException() { var expected = new Exception("Expected."); var actual = new ColoreException(null, new Exception("Expected.")).InnerException; Assert.AreEqual(expected.GetType(), actual.GetType()); Assert.AreEqual(expected.Message, actual.Message); } } }
Move details to first in list
@model IEnumerable<Soldier> <h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th> <th></th> </tr> </thead> <tbody> @foreach (var soldier in Model) { <tr> <td>@Html.DisplayFor(s => soldier.Rank)</td> <td>@Html.DisplayFor(s => soldier.LastName)</td> <td>@Html.DisplayFor(s => soldier.FirstName)</td> <td>@Html.DisplayFor(s => soldier.Unit)</td> <td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td> <td> @Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id }) @Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id }) </td> </tr> } </tbody> </table>
@model IEnumerable<Soldier> <h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th></th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th> <th></th> </tr> </thead> <tbody> @foreach (var soldier in Model) { <tr> <td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td> <td>@Html.DisplayFor(s => soldier.Rank)</td> <td>@Html.DisplayFor(s => soldier.LastName)</td> <td>@Html.DisplayFor(s => soldier.FirstName)</td> <td>@Html.DisplayFor(s => soldier.Unit)</td> <td> @Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id }, new { @class = "btn btn-default" }) @Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id }, new { @class = "btn btn-default" }) </td> </tr> } </tbody> </table>
Add thread-safe random number instance
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Faker { public static class NumberFaker { private static Random _random = new Random(); public static int Number() { return _random.Next(); } public static int Number(int maxValue) { return _random.Next(maxValue); } public static int Number(int minValue, int maxValue) { return _random.Next(minValue, maxValue); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Faker { public static class NumberFaker { private static readonly RNGCryptoServiceProvider Global = new RNGCryptoServiceProvider(); [ThreadStatic] private static Random _local; private static Random Local { get { Random inst = _local; if (inst == null) { byte[] buffer = new byte[4]; Global.GetBytes(buffer); _local = inst = new Random( BitConverter.ToInt32(buffer, 0)); } return inst; } } public static int Number() { return Local.Next(); } public static int Number(int maxValue) { return Local.Next(maxValue); } public static int Number(int minValue, int maxValue) { return Local.Next(minValue, maxValue); } } }
Use Url instead of UrlPath.
@model IEnumerable<(GommeHDnetForumAPI.Models.Entities.UserInfo UserInfo, Discord.WebSocket.SocketGuild Guild)> <h4>Verifizierungen</h4> <div class="table-responsive"> <table class="table"> <thead> <tr> <th></th> <th> @Html.DisplayNameFor(model => model.UserInfo.Username) </th> <th> @Html.DisplayNameFor(model => model.Guild.Name) </th> </tr> </thead> <tbody> @foreach(var (userInfo, guild) in Model) { <tr> <td> @if(!string.IsNullOrWhiteSpace(userInfo.AvatarUrl)) { <img class="gommehdnet-forum-avatar" src="@userInfo.AvatarUrl" alt="Avatar" /> } </td> <td> <a href="@userInfo.UrlPath">@(string.IsNullOrWhiteSpace(userInfo.Username) ? userInfo.UrlPath : userInfo.Username)</a> </td> <td> <a asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">@guild.Name</a> </td> </tr> } </tbody> </table> </div>
@model IEnumerable<(GommeHDnetForumAPI.Models.Entities.UserInfo UserInfo, Discord.WebSocket.SocketGuild Guild)> <h4>Verifizierungen</h4> <div class="table-responsive"> <table class="table"> <thead> <tr> <th></th> <th> @Html.DisplayNameFor(model => model.UserInfo.Username) </th> <th> @Html.DisplayNameFor(model => model.Guild.Name) </th> </tr> </thead> <tbody> @foreach(var (userInfo, guild) in Model) { <tr> <td> @if(!string.IsNullOrWhiteSpace(userInfo.AvatarUrl)) { <img class="gommehdnet-forum-avatar" src="@userInfo.AvatarUrl" alt="Avatar" /> } </td> <td> <a href="@userInfo.Url">@(string.IsNullOrWhiteSpace(userInfo.Username) ? userInfo.Url : userInfo.Username)</a> </td> <td> <a asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">@guild.Name</a> </td> </tr> } </tbody> </table> </div>
Revert "Changed generic object to a system object"
using System; using System.Collections.Generic; using System.Threading.Tasks; using DomainCore; using DomainCore.Interfaces; namespace Application.Interfaces { /// <summary> /// Primary application interface /// </summary> public interface IInventoryService { /* ReadModel */ // Get all Task<IEnumerable<InventoryItemDto>> InventoryAsync(); // Get one Task<InventoryItemDto> GetItemAsync(Guid id); Task<IEnumerable<AInventoryItemEvent>> InventoryEventsAsync(Guid id); /* Commands */ // Create Item Task PostItemAsync(InventoryItemDto item); // Update Full Item Task PutItemAsync(InventoryItemDto item); // Delete Item Task DeleteItemAsync(Guid id); // Edit Item Task PatchItemCountAsync(Guid id, int count, string reason); Task PatchItemNameAsync(Guid id, string name, string reason); Task PatchItemNoteAsync(Guid id, string note, string reason); // Increase Item count Task IncreaseInventory(Guid id, uint amount, string reason); // Decrease Item count Task DecreaseInventory(Guid id, uint amount, string reason); // Activate Item Task ActivateItem(Guid id, string reason); // Deactivate Item Task DisableItem(Guid id, string reason); } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using DomainCore; namespace Application.Interfaces { public interface IInventoryService { /* ReadModel */ // Get all Task<IEnumerable<InventoryItemDto>> InventoryAsync(); // Get one Task<InventoryItemDto> GetItemAsync(Guid id); Task<IEnumerable<InventoryItemEvent>> InventoryEventsAsync(Guid id); /* Commands */ // Create Item Task PostItemAsync(InventoryItemDto item); // Update Full Item Task PutItemAsync(InventoryItemDto item); // Delete Item Task DeleteItemAsync(Guid id); // Edit Item Task PatchItemCountAsync(Guid id, int count, string reason); Task PatchItemNameAsync(Guid id, string name, string reason); Task PatchItemNoteAsync(Guid id, string note, string reason); // Increase Item count Task IncreaseInventory(Guid id, uint amount, string reason); // Decrease Item count Task DecreaseInventory(Guid id, uint amount, string reason); // Activate Item Task ActivateItem(Guid id, string reason); // Deactivate Item Task DisableItem(Guid id, string reason); } }
Add documentation for movie images.
namespace TraktApiSharp.Objects.Get.Movies { using Basic; using Newtonsoft.Json; public class TraktMovieImages { [JsonProperty(PropertyName = "fanart")] public TraktImageSet FanArt { get; set; } [JsonProperty(PropertyName = "poster")] public TraktImageSet Poster { get; set; } [JsonProperty(PropertyName = "logo")] public TraktImage Logo { get; set; } [JsonProperty(PropertyName = "clearart")] public TraktImage ClearArt { get; set; } [JsonProperty(PropertyName = "banner")] public TraktImage Banner { get; set; } [JsonProperty(PropertyName = "thumb")] public TraktImage Thumb { get; set; } } }
namespace TraktApiSharp.Objects.Get.Movies { using Basic; using Newtonsoft.Json; /// <summary>A collection of images and image sets for a Trakt movie.</summary> public class TraktMovieImages { /// <summary>Gets or sets the fan art image set.</summary> [JsonProperty(PropertyName = "fanart")] public TraktImageSet FanArt { get; set; } /// <summary>Gets or sets the poster image set.</summary> [JsonProperty(PropertyName = "poster")] public TraktImageSet Poster { get; set; } /// <summary>Gets or sets the loge image.</summary> [JsonProperty(PropertyName = "logo")] public TraktImage Logo { get; set; } /// <summary>Gets or sets the clear art image.</summary> [JsonProperty(PropertyName = "clearart")] public TraktImage ClearArt { get; set; } /// <summary>Gets or sets the banner image.</summary> [JsonProperty(PropertyName = "banner")] public TraktImage Banner { get; set; } /// <summary>Gets or sets the thumb image.</summary> [JsonProperty(PropertyName = "thumb")] public TraktImage Thumb { get; set; } } }
Create the repository only when it's needed for deployment.
using System; using System.Collections.Generic; using System.Linq; using Kudu.Core.SourceControl; namespace Kudu.Core.Deployment { public class DeploymentManager : IDeploymentManager { private readonly IRepository _repository; private readonly IDeployerFactory _deployerFactory; public DeploymentManager(IRepositoryManager repositoryManager, IDeployerFactory deployerFactory) { _repository = repositoryManager.GetRepository(); _deployerFactory = deployerFactory; } public IEnumerable<DeployResult> GetResults() { throw new NotImplementedException(); } public DeployResult GetResult(string id) { throw new NotImplementedException(); } public void Deploy(string id) { IDeployer deployer = _deployerFactory.CreateDeployer(); deployer.Deploy(id); } public void Deploy() { var activeBranch = _repository.GetBranches().FirstOrDefault(b => b.Active); string id = _repository.CurrentId; if (activeBranch != null) { _repository.Update(activeBranch.Name); } else { _repository.Update(id); } Deploy(id); } } }
using System; using System.Collections.Generic; using System.Linq; using Kudu.Core.SourceControl; namespace Kudu.Core.Deployment { public class DeploymentManager : IDeploymentManager { private readonly IRepositoryManager _repositoryManager; private readonly IDeployerFactory _deployerFactory; public DeploymentManager(IRepositoryManager repositoryManager, IDeployerFactory deployerFactory) { _repositoryManager = repositoryManager; _deployerFactory = deployerFactory; } public IEnumerable<DeployResult> GetResults() { throw new NotImplementedException(); } public DeployResult GetResult(string id) { throw new NotImplementedException(); } public void Deploy(string id) { IDeployer deployer = _deployerFactory.CreateDeployer(); deployer.Deploy(id); } public void Deploy() { var repository = _repositoryManager.GetRepository(); if (repository == null) { return; } var activeBranch = repository.GetBranches().FirstOrDefault(b => b.Active); string id = repository.CurrentId; if (activeBranch != null) { repository.Update(activeBranch.Name); } else { repository.Update(id); } Deploy(id); } } }
Sort languages by ascending order.
using System.Collections.ObjectModel; using CoCo.UI.Data; namespace CoCo.UI.ViewModels { public class OptionViewModel : BaseViewModel { public OptionViewModel(Option option, IResetValuesProvider resetValuesProvider) { // TODO: it will invoke one event at invocation of clear and by one event per added item // Write custom BulkObservableCollection to avoid so many events Languages.Clear(); foreach (var language in option.Languages) { Languages.Add(new LanguageViewModel(language, resetValuesProvider)); } } public ObservableCollection<LanguageViewModel> Languages { get; } = new ObservableCollection<LanguageViewModel>(); private LanguageViewModel _selectedLanguage; public LanguageViewModel SelectedLanguage { get { if (_selectedLanguage is null && Languages.Count > 0) { SelectedLanguage = Languages[0]; } return _selectedLanguage; } set => SetProperty(ref _selectedLanguage, value); } public Option ExtractData() { var option = new Option(); foreach (var languageViewModel in Languages) { option.Languages.Add(languageViewModel.ExtractData()); } return option; } } }
using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Data; using CoCo.UI.Data; namespace CoCo.UI.ViewModels { public class OptionViewModel : BaseViewModel { private readonly ObservableCollection<LanguageViewModel> _languages = new ObservableCollection<LanguageViewModel>(); public OptionViewModel(Option option, IResetValuesProvider resetValuesProvider) { // TODO: it will invoke one event at invocation of clear and by one event per added item // Write custom BulkObservableCollection to avoid so many events _languages.Clear(); foreach (var language in option.Languages) { _languages.Add(new LanguageViewModel(language, resetValuesProvider)); } Languages = CollectionViewSource.GetDefaultView(_languages); Languages.SortDescriptions.Add(new SortDescription(nameof(LanguageViewModel.Name), ListSortDirection.Ascending)); } public ICollectionView Languages { get; } private LanguageViewModel _selectedLanguage; public LanguageViewModel SelectedLanguage { get { if (_selectedLanguage is null && Languages.MoveCurrentToFirst()) { SelectedLanguage = (LanguageViewModel)Languages.CurrentItem; } return _selectedLanguage; } set => SetProperty(ref _selectedLanguage, value); } public Option ExtractData() { var option = new Option(); foreach (var languageViewModel in _languages) { option.Languages.Add(languageViewModel.ExtractData()); } return option; } } }
Add the licence header and remove unused usings
using osu.Framework.Allocation; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using System; using System.Collections.Generic; using osuTK; namespace osu.Framework.Tests.Visual.Sprites { public class TestSceneTexturedTriangle : FrameworkTestScene { public TestSceneTexturedTriangle() { Add(new TexturedTriangle { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(300, 150) }); } private class TexturedTriangle : Triangle { [BackgroundDependencyLoader] private void load(TextureStore textures) { Texture = textures.Get(@"sample-texture"); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using osuTK; namespace osu.Framework.Tests.Visual.Sprites { public class TestSceneTexturedTriangle : FrameworkTestScene { public TestSceneTexturedTriangle() { Add(new TexturedTriangle { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(300, 150) }); } private class TexturedTriangle : Triangle { [BackgroundDependencyLoader] private void load(TextureStore textures) { Texture = textures.Get(@"sample-texture"); } } } }
Allow skipping publish of package when fixing docs.
public sealed class AppVeyorSettings { public bool IsLocal { get; set; } public bool IsRunningOnAppVeyor { get; set; } public bool IsPullRequest { get; set; } public bool IsDevelopBranch { get; set; } public bool IsMasterBranch { get; set; } public bool IsTaggedBuild { get; set; } public bool IsMaintenanceBuild { get; set; } public static AppVeyorSettings Initialize(ICakeContext context) { var buildSystem = context.BuildSystem(); var branchName = buildSystem.AppVeyor.Environment.Repository.Branch; var commitMessage = buildSystem.AppVeyor.Environment.Repository.Commit.Message?.Trim(); var isMaintenanceBuild = commitMessage?.StartsWith("(build)", StringComparison.OrdinalIgnoreCase) ?? false; return new AppVeyorSettings { IsLocal = buildSystem.IsLocalBuild, IsRunningOnAppVeyor = buildSystem.AppVeyor.IsRunningOnAppVeyor, IsPullRequest = buildSystem.AppVeyor.Environment.PullRequest.IsPullRequest, IsDevelopBranch = "develop".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsMasterBranch = "master".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsTaggedBuild = IsBuildTagged(buildSystem), IsMaintenanceBuild = isMaintenanceBuild }; } public static bool IsBuildTagged(BuildSystem buildSystem) { return buildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(buildSystem.AppVeyor.Environment.Repository.Tag.Name); } }
public sealed class AppVeyorSettings { public bool IsLocal { get; set; } public bool IsRunningOnAppVeyor { get; set; } public bool IsPullRequest { get; set; } public bool IsDevelopBranch { get; set; } public bool IsMasterBranch { get; set; } public bool IsTaggedBuild { get; set; } public bool IsMaintenanceBuild { get; set; } public static AppVeyorSettings Initialize(ICakeContext context) { var buildSystem = context.BuildSystem(); var branchName = buildSystem.AppVeyor.Environment.Repository.Branch; var commitMessage = buildSystem.AppVeyor.Environment.Repository.Commit.Message?.Trim(); var isMaintenanceBuild = (commitMessage?.StartsWith("(build)", StringComparison.OrdinalIgnoreCase) ?? false) || (commitMessage?.StartsWith("(docs)", StringComparison.OrdinalIgnoreCase) ?? false); return new AppVeyorSettings { IsLocal = buildSystem.IsLocalBuild, IsRunningOnAppVeyor = buildSystem.AppVeyor.IsRunningOnAppVeyor, IsPullRequest = buildSystem.AppVeyor.Environment.PullRequest.IsPullRequest, IsDevelopBranch = "develop".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsMasterBranch = "master".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsTaggedBuild = IsBuildTagged(buildSystem), IsMaintenanceBuild = isMaintenanceBuild }; } public static bool IsBuildTagged(BuildSystem buildSystem) { return buildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(buildSystem.AppVeyor.Environment.Repository.Tag.Name); } }
Increase the version to 1.1.1.
using System.Reflection; using System.Resources; 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("BindableApplicationBar")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Filip Skakun")] [assembly: AssemblyProduct("BindableApplicationBar")] [assembly: AssemblyCopyright("Copyright © Filip Skakun, 2011-2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d0df5e03-2f69-4d10-a40d-25afcbbb7e09")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
using System.Reflection; using System.Resources; 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("BindableApplicationBar")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Filip Skakun")] [assembly: AssemblyProduct("BindableApplicationBar")] [assembly: AssemblyCopyright("Copyright © Filip Skakun, 2011-2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d0df5e03-2f69-4d10-a40d-25afcbbb7e09")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.1.1")] [assembly: AssemblyFileVersion("1.1.1")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
Change release manager zip file name
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReleaseManager { class Program { static void Main(string[] args) { try { if (args.Length == 0) { return; } var mainFileName = args[0]; var version = FileVersionInfo.GetVersionInfo(mainFileName).FileVersion; var archive = ZipFile.Open("Release_" + version + ".zip", ZipArchiveMode.Create); archive.CreateEntryFromFile(mainFileName, mainFileName); for (int i = 1; i < args.Length; i++) { archive.CreateEntryFromFile(args[i], args[i]); } archive.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Environment.Exit(1); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReleaseManager { class Program { static void Main(string[] args) { try { if (args.Length == 0) { return; } var mainFileName = args[0]; var version = FileVersionInfo.GetVersionInfo(mainFileName).FileVersion; var archive = ZipFile.Open(version + ".zip", ZipArchiveMode.Create); archive.CreateEntryFromFile(mainFileName, mainFileName); for (int i = 1; i < args.Length; i++) { archive.CreateEntryFromFile(args[i], args[i]); } archive.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Environment.Exit(1); } } } }
Fix nullref when exiting the last screen.
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Screens; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A <see cref="BreadcrumbControl"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack. /// </summary> public class ScreenBreadcrumbControl : BreadcrumbControl<Screen> { private Screen last; public ScreenBreadcrumbControl(Screen initialScreen) { Current.ValueChanged += newScreen => { if (last != newScreen && !newScreen.IsCurrentScreen) newScreen.MakeCurrent(); }; onPushed(initialScreen); } private void screenChanged(Screen newScreen) { if (last != null) { last.Exited -= screenChanged; last.ModePushed -= onPushed; } last = newScreen; newScreen.Exited += screenChanged; newScreen.ModePushed += onPushed; Current.Value = newScreen; } private void onPushed(Screen screen) { Items.ToList().SkipWhile(i => i != Current.Value).Skip(1).ForEach(RemoveItem); AddItem(screen); screenChanged(screen); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Screens; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A <see cref="BreadcrumbControl"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack. /// </summary> public class ScreenBreadcrumbControl : BreadcrumbControl<Screen> { private Screen last; public ScreenBreadcrumbControl(Screen initialScreen) { Current.ValueChanged += newScreen => { if (last != newScreen && !newScreen.IsCurrentScreen) newScreen.MakeCurrent(); }; onPushed(initialScreen); } private void screenChanged(Screen newScreen) { if (newScreen == null) return; if (last != null) { last.Exited -= screenChanged; last.ModePushed -= onPushed; } last = newScreen; newScreen.Exited += screenChanged; newScreen.ModePushed += onPushed; Current.Value = newScreen; } private void onPushed(Screen screen) { Items.ToList().SkipWhile(i => i != Current.Value).Skip(1).ForEach(RemoveItem); AddItem(screen); screenChanged(screen); } } }
Improve console menu for "visual" tests
using System; using R7.University.Core.Templates; namespace R7.University.Core.Tests { class Program { static void Main (string [] args) { Console.WriteLine ("Please enter test number and press [Enter]:"); Console.WriteLine ("1. Workbook to CSV"); Console.WriteLine ("2. Workbook to linear CSV"); Console.WriteLine ("0. Exit"); if (int.TryParse (Console.ReadLine (), out int testNum)) { switch (testNum) { case 1: WorkbookToCsv (); break; case 2: WorkbookToLinearCsv (); break; } } } static void WorkbookToCsv () { var workbookManager = new WorkbookManager (); Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.CSV)); } static void WorkbookToLinearCsv () { var workbookManager = new WorkbookManager (); Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.LinearCSV)); } } }
using System; using R7.University.Core.Templates; namespace R7.University.Core.Tests { class Program { static void Main (string [] args) { while (true) { Console.WriteLine ("> Please enter test number and press [Enter]:"); Console.WriteLine ("---"); Console.WriteLine ("1. Workbook to CSV"); Console.WriteLine ("2. Workbook to linear CSV"); Console.WriteLine ("0. Exit"); if (int.TryParse (Console.ReadLine (), out int testNum)) { switch (testNum) { case 1: WorkbookToCsv (); break; case 2: WorkbookToLinearCsv (); break; case 0: return; } Console.WriteLine ("> Press any key to continue..."); Console.ReadKey (); Console.WriteLine (); } } } static void WorkbookToCsv () { Console.WriteLine ("--- Start test output"); var workbookManager = new WorkbookManager (); Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.CSV)); Console.WriteLine ("--- End test output"); } static void WorkbookToLinearCsv () { Console.WriteLine ("--- Start test output"); var workbookManager = new WorkbookManager (); Console.Write (workbookManager.SerializeWorkbook ("./assets/templates/workbook-1.xls", WorkbookSerializationFormat.LinearCSV)); Console.WriteLine ("--- End test output"); } } }
Introduce variable to make code more readable
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using ActiproSoftware.Text.Implementation; namespace NQueryViewerActiproWpf { [Export(typeof(ILanguageServiceRegistrar))] internal sealed class ComposableLanguageServiceRegistrar : ILanguageServiceRegistrar { [ImportMany] public IEnumerable<Lazy<object, ILanguageServiceMetadata>> LanguageServices { get; set; } public void RegisterServices(SyntaxLanguage syntaxLanguage) { foreach (var languageService in LanguageServices) { var type = languageService.Metadata.ServiceType; syntaxLanguage.RegisterService(type, languageService.Value); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using ActiproSoftware.Text.Implementation; namespace NQueryViewerActiproWpf { [Export(typeof(ILanguageServiceRegistrar))] internal sealed class ComposableLanguageServiceRegistrar : ILanguageServiceRegistrar { [ImportMany] public IEnumerable<Lazy<object, ILanguageServiceMetadata>> LanguageServices { get; set; } public void RegisterServices(SyntaxLanguage syntaxLanguage) { foreach (var languageService in LanguageServices) { var serviceType = languageService.Metadata.ServiceType; var service = languageService.Value; syntaxLanguage.RegisterService(serviceType, service); } } } }
Format code like a civilized man
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LRU.Net { public class LruCache<TKey, TValue> { private readonly int _maxObjects; private OrderedDictionary _data; public LruCache(int maxObjects = 1000) { _maxObjects = maxObjects; _data = new OrderedDictionary(); } public void Add(TKey key, TValue value) { if (_data.Count >= _maxObjects) { _data.RemoveAt(0); } _data.Add(key, value); } public TValue Get(TKey key) { if (!_data.Contains(key)) throw new Exception(); var result = _data[key]; if (result == null) throw new Exception(); _data.Remove(key); _data.Add(key, result); return (TValue)result; } public bool Contains(TKey key) { return _data.Contains(key); } public TValue this[TKey key] { get { return Get(key); } set { Add(key, value); } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LRU.Net { public class LruCache<TKey, TValue> { private readonly int _maxObjects; private OrderedDictionary _data; public LruCache(int maxObjects = 1000) { _maxObjects = maxObjects; _data = new OrderedDictionary(); } public void Add(TKey key, TValue value) { if (_data.Count >= _maxObjects) { _data.RemoveAt(0); } _data.Add(key, value); } public TValue Get(TKey key) { if (!_data.Contains(key)) { throw new Exception($"Could not find item with key {key}"); } var result = _data[key]; _data.Remove(key); _data.Add(key, result); return (TValue)result; } public bool Contains(TKey key) { return _data.Contains(key); } public TValue this[TKey key] { get { return Get(key); } set { Add(key, value); } } } }
Fix path building for plugins views
namespace Nubot.Core.Nancy { using System.Linq; using Abstractions; using global::Nancy; using global::Nancy.Conventions; using global::Nancy.TinyIoc; public class Bootstrapper : DefaultNancyBootstrapper { private readonly IRobot _robot; public Bootstrapper(IRobot robot) { _robot = robot; } /// <summary> /// Configures the container using AutoRegister followed by registration /// of default INancyModuleCatalog and IRouteResolver. /// </summary> /// <param name="container">Container instance</param> protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register(_robot); } protected override void ConfigureConventions(NancyConventions nancyConventions) { base.ConfigureConventions(nancyConventions); foreach (var staticPath in _robot.RobotPlugins.OfType<HttpPluginBase>().SelectMany(httpPlugin => httpPlugin.StaticPaths)) { nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory(staticPath.Item1, staticPath.Item2)); } nancyConventions.ViewLocationConventions.Add((viewName, model, viewLocationContext) => string.Concat("plugins/", viewLocationContext.ModulePath, "/Views/", viewName)); } } }
namespace Nubot.Core.Nancy { using System.Linq; using Abstractions; using global::Nancy; using global::Nancy.Conventions; using global::Nancy.TinyIoc; public class Bootstrapper : DefaultNancyBootstrapper { private readonly IRobot _robot; public Bootstrapper(IRobot robot) { _robot = robot; } /// <summary> /// Configures the container using AutoRegister followed by registration /// of default INancyModuleCatalog and IRouteResolver. /// </summary> /// <param name="container">Container instance</param> protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register(_robot); } protected override void ConfigureConventions(NancyConventions nancyConventions) { base.ConfigureConventions(nancyConventions); var httpPluginsStaticPaths = _robot.RobotPlugins.OfType<HttpPluginBase>().SelectMany(httpPlugin => httpPlugin.StaticPaths); foreach (var staticPath in httpPluginsStaticPaths) { nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory(staticPath.Item1, staticPath.Item2)); } nancyConventions.ViewLocationConventions.Add((viewName, model, viewLocationContext) => string.Concat("plugins", viewLocationContext.ModulePath, "/Views/", viewName)); } } }
Remove wrong parameter from FFMPEG audio example
private async Task SendAsync(IAudioClient client, string path) { // Create FFmpeg using the previous example var ffmpeg = CreateStream(path); var output = ffmpeg.StandardOutput.BaseStream; var discord = client.CreatePCMStream(AudioApplication.Mixed, 1920); await output.CopyToAsync(discord); await discord.FlushAsync(); }
private async Task SendAsync(IAudioClient client, string path) { // Create FFmpeg using the previous example var ffmpeg = CreateStream(path); var output = ffmpeg.StandardOutput.BaseStream; var discord = client.CreatePCMStream(AudioApplication.Mixed); await output.CopyToAsync(discord); await discord.FlushAsync(); }
Add missing documentation for `SourceChanged`
// 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 JetBrains.Annotations; namespace osu.Game.Skinning { /// <summary> /// Provides access to skinnable elements. /// </summary> public interface ISkinSource : ISkin { event Action SourceChanged; /// <summary> /// Find the first (if any) skin that can fulfill the lookup. /// This should be used for cases where subsequent lookups (for related components) need to occur on the same skin. /// </summary> /// <returns>The skin to be used for subsequent lookups, or <c>null</c> if none is available.</returns> [CanBeNull] ISkin FindProvider(Func<ISkin, bool> lookupFunction); /// <summary> /// Retrieve all sources available for lookup, with highest priority source first. /// </summary> IEnumerable<ISkin> AllSources { get; } } }
// 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 JetBrains.Annotations; namespace osu.Game.Skinning { /// <summary> /// Provides access to skinnable elements. /// </summary> public interface ISkinSource : ISkin { /// <summary> /// Fired whenever a source change occurs, signalling that consumers should re-query as required. /// </summary> event Action SourceChanged; /// <summary> /// Find the first (if any) skin that can fulfill the lookup. /// This should be used for cases where subsequent lookups (for related components) need to occur on the same skin. /// </summary> /// <returns>The skin to be used for subsequent lookups, or <c>null</c> if none is available.</returns> [CanBeNull] ISkin FindProvider(Func<ISkin, bool> lookupFunction); /// <summary> /// Retrieve all sources available for lookup, with highest priority source first. /// </summary> IEnumerable<ISkin> AllSources { get; } } }
Use assembly version from NugetCracker assembly to print headline
using System; using NugetCracker.Persistence; namespace NugetCracker { class Program { private static MetaProjectPersistence _metaProjectPersistence; static void Main(string[] args) { Console.WriteLine("NugetCracker 0.1\nSee https://github.com/monoman/NugetCracker\n"); _metaProjectPersistence = new MetaProjectPersistence(args.GetMetaProjectFilePath()); Console.WriteLine("Using {0}", _metaProjectPersistence.FilePath); Console.WriteLine("Will be scanning directories:"); foreach (string dir in _metaProjectPersistence.ListOfDirectories) Console.WriteLine("-- '{0}' > '{1}'", dir, _metaProjectPersistence.ToAbsolutePath(dir)); } } }
using System; using NugetCracker.Persistence; namespace NugetCracker { class Program { private static MetaProjectPersistence _metaProjectPersistence; static Version Version { get { return new System.Reflection.AssemblyName(System.Reflection.Assembly.GetCallingAssembly().FullName).Version; } } static void Main(string[] args) { Console.WriteLine("NugetCracker {0}\nSee https://github.com/monoman/NugetCracker\n", Version.ToString(2)); _metaProjectPersistence = new MetaProjectPersistence(args.GetMetaProjectFilePath()); Console.WriteLine("Using {0}", _metaProjectPersistence.FilePath); Console.WriteLine("Will be scanning directories:"); foreach (string dir in _metaProjectPersistence.ListOfDirectories) Console.WriteLine("-- '{0}' > '{1}'", dir, _metaProjectPersistence.ToAbsolutePath(dir)); Console.WriteLine("Done!"); } } }
Remove unnecessary HttpClient registration in Unity
using System.Net.Http; using Microsoft.Practices.Unity; using Moq; using MyGetConnector.Repositories; namespace MyGetConnector.Tests { public static class TestUnityConfig { public static IUnityContainer GetMockedContainer() { var container = new UnityContainer(); container.RegisterInstance(new HttpClient()); container.RegisterInstance(typeof(ITriggerRepository), new Mock<ITriggerRepository>(MockBehavior.Strict).Object); return container; } } }
using System.Net.Http; using Microsoft.Practices.Unity; using Moq; using MyGetConnector.Repositories; namespace MyGetConnector.Tests { public static class TestUnityConfig { public static IUnityContainer GetMockedContainer() { var container = new UnityContainer(); container.RegisterInstance(typeof(ITriggerRepository), new Mock<ITriggerRepository>(MockBehavior.Strict).Object); return container; } } }
Fix already closed connection and 'kak go napravi tova' exception
using System; using System.Collections.Concurrent; using RabbitMQ.Client; namespace Elders.Cronus.Transport.RabbitMQ { public class PublisherChannelResolver { private readonly ConcurrentDictionary<string, IModel> channelPerBoundedContext; private readonly ConnectionResolver connectionResolver; private static readonly object @lock = new object(); public PublisherChannelResolver(ConnectionResolver connectionResolver) { channelPerBoundedContext = new ConcurrentDictionary<string, IModel>(); this.connectionResolver = connectionResolver; } public IModel Resolve(string boundedContext, IRabbitMqOptions options) { IModel channel = GetExistingChannel(boundedContext); if (channel is null || channel.IsClosed) { lock (@lock) { channel = GetExistingChannel(boundedContext); if (channel is null || channel.IsClosed) { var connection = connectionResolver.Resolve(boundedContext, options); channel = connection.CreateModel(); channel.ConfirmSelect(); if (channelPerBoundedContext.TryAdd(boundedContext, channel) == false) { throw new Exception("Kak go napravi tova?"); } } } } return channel; } private IModel GetExistingChannel(string boundedContext) { channelPerBoundedContext.TryGetValue(boundedContext, out IModel channel); return channel; } } }
using System.Collections.Generic; using RabbitMQ.Client; namespace Elders.Cronus.Transport.RabbitMQ { public class PublisherChannelResolver { private readonly Dictionary<string, IModel> channelPerBoundedContext; private readonly ConnectionResolver connectionResolver; private static readonly object @lock = new object(); public PublisherChannelResolver(ConnectionResolver connectionResolver) { channelPerBoundedContext = new Dictionary<string, IModel>(); this.connectionResolver = connectionResolver; } public IModel Resolve(string boundedContext, IRabbitMqOptions options) { IModel channel = GetExistingChannel(boundedContext); if (channel is null || channel.IsClosed) { lock (@lock) { channel = GetExistingChannel(boundedContext); if (channel?.IsClosed == true) { channelPerBoundedContext.Remove(boundedContext); } if (channel is null) { var connection = connectionResolver.Resolve(boundedContext, options); IModel scopedChannel = connection.CreateModel(); scopedChannel.ConfirmSelect(); channelPerBoundedContext.Add(boundedContext, scopedChannel); } } } return GetExistingChannel(boundedContext); } private IModel GetExistingChannel(string boundedContext) { channelPerBoundedContext.TryGetValue(boundedContext, out IModel channel); return channel; } } }
Handle long values when writing version variables
using System.Buffers; using System.Buffers.Text; using System.Text.Json; using System.Text.Json.Serialization; using GitVersion.Extensions; namespace GitVersion.OutputVariables; public class VersionVariablesJsonNumberConverter : JsonConverter<string> { public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(string); public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.Number && typeToConvert == typeof(string)) return reader.GetString() ?? ""; var span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan; if (Utf8Parser.TryParse(span, out long number, out var bytesConsumed) && span.Length == bytesConsumed) return number.ToString(); var data = reader.GetString(); throw new InvalidOperationException($"'{data}' is not a correct expected value!") { Source = nameof(VersionVariablesJsonNumberConverter) }; } public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options) { if (value.IsNullOrWhiteSpace()) { writer.WriteNullValue(); } else if (int.TryParse(value, out var number)) { writer.WriteNumberValue(number); } else { throw new InvalidOperationException($"'{value}' is not a correct expected value!") { Source = nameof(VersionVariablesJsonStringConverter) }; } } public override bool HandleNull => true; }
using System.Buffers; using System.Buffers.Text; using System.Text.Json; using System.Text.Json.Serialization; using GitVersion.Extensions; namespace GitVersion.OutputVariables; public class VersionVariablesJsonNumberConverter : JsonConverter<string> { public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(string); public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.Number && typeToConvert == typeof(string)) return reader.GetString() ?? ""; var span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan; if (Utf8Parser.TryParse(span, out long number, out var bytesConsumed) && span.Length == bytesConsumed) return number.ToString(); var data = reader.GetString(); throw new InvalidOperationException($"'{data}' is not a correct expected value!") { Source = nameof(VersionVariablesJsonNumberConverter) }; } public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options) { if (value.IsNullOrWhiteSpace()) { writer.WriteNullValue(); } else if (long.TryParse(value, out var number)) { writer.WriteNumberValue(number); } else { throw new InvalidOperationException($"'{value}' is not a correct expected value!") { Source = nameof(VersionVariablesJsonStringConverter) }; } } public override bool HandleNull => true; }
Correct behaviour of Lazy ORM implementation
using System; using System.Linq; using DataAccessExamples.Core.Data; using DataAccessExamples.Core.ViewModels; namespace DataAccessExamples.Core.Services { public class LazyOrmDepartmentService : IDepartmentService { private readonly EmployeesContext context; public LazyOrmDepartmentService(EmployeesContext context) { this.context = context; } public DepartmentList ListDepartments() { return new DepartmentList { Departments = context.Departments.OrderBy(d => d.Code).Select(d => new DepartmentSummary { Code = d.Code, Name = d.Name }) }; } public DepartmentList ListAverageSalaryPerDepartment() { return new DepartmentList { Departments = context.Departments.AsEnumerable().Select(d => new DepartmentSalary { Code = d.Code, Name = d.Name, AverageSalary = (int) d.DepartmentEmployees.Select( e => e.Employee.Salaries.LastOrDefault(s => s.ToDate > DateTime.Now)) .Where(s => s != null) .Average(s => s.Amount) }) }; } } }
using System; using System.Linq; using DataAccessExamples.Core.Data; using DataAccessExamples.Core.ViewModels; namespace DataAccessExamples.Core.Services { public class LazyOrmDepartmentService : IDepartmentService { private readonly EmployeesContext context; public LazyOrmDepartmentService(EmployeesContext context) { this.context = context; } public DepartmentList ListDepartments() { return new DepartmentList { Departments = context.Departments.OrderBy(d => d.Code).Select(d => new DepartmentSummary { Code = d.Code, Name = d.Name }) }; } public DepartmentList ListAverageSalaryPerDepartment() { return new DepartmentList { Departments = context.Departments.AsEnumerable().Select(d => new DepartmentSalary { Code = d.Code, Name = d.Name, AverageSalary = (int) d.DepartmentEmployees.Select( e => e.Employee.Salaries.LastOrDefault(s => s.ToDate > DateTime.Now)) .Where(s => s != null) .Average(s => s.Amount) }).OrderByDescending(d => d.AverageSalary) }; } } }
Add zoom into rasterlayer data in the sample
using System; using Mapsui.Layers; using Mapsui.Providers; using Mapsui.Styles; using Mapsui.UI; using Mapsui.Utilities; namespace Mapsui.Samples.Common.Maps { public class RasterizingLayerSample : ISample { public string Name => "Rasterizing Layer"; public string Category => "Special"; public void Setup(IMapControl mapControl) { mapControl.Map = CreateMap(); } public static Map CreateMap() { var map = new Map(); map.Layers.Add(OpenStreetMap.CreateTileLayer()); map.Layers.Add(new RasterizingLayer(CreateRandomPointLayer())); return map; } private static MemoryLayer CreateRandomPointLayer() { var rnd = new Random(); var features = new Features(); for (var i = 0; i < 100; i++) { var feature = new Feature { Geometry = new Geometries.Point(rnd.Next(0, 5000000), rnd.Next(0, 5000000)) }; features.Add(feature); } var provider = new MemoryProvider(features); return new MemoryLayer { DataSource = provider, Style = new SymbolStyle { SymbolType = SymbolType.Triangle, Fill = new Brush(Color.Red) } }; } } }
using System; using Mapsui.Layers; using Mapsui.Providers; using Mapsui.Styles; using Mapsui.UI; using Mapsui.Utilities; namespace Mapsui.Samples.Common.Maps { public class RasterizingLayerSample : ISample { public string Name => "Rasterizing Layer"; public string Category => "Special"; public void Setup(IMapControl mapControl) { mapControl.Map = CreateMap(); } public static Map CreateMap() { var map = new Map(); map.Layers.Add(OpenStreetMap.CreateTileLayer()); map.Layers.Add(new RasterizingLayer(CreateRandomPointLayer())); map.Home = n => n.NavigateTo(map.Layers[1].Envelope.Grow(map.Layers[1].Envelope.Width * 0.1)); return map; } private static MemoryLayer CreateRandomPointLayer() { var rnd = new Random(3462); // Fix the random seed so the features don't move after a refresh var features = new Features(); for (var i = 0; i < 100; i++) { var feature = new Feature { Geometry = new Geometries.Point(rnd.Next(0, 5000000), rnd.Next(0, 5000000)) }; features.Add(feature); } var provider = new MemoryProvider(features); return new MemoryLayer { DataSource = provider, Style = new SymbolStyle { SymbolType = SymbolType.Triangle, Fill = new Brush(Color.Red) } }; } } }
Increment version for new 'skip' querystring support
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XeroApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xero")] [assembly: AssemblyProduct("XeroApi")] [assembly: AssemblyCopyright("Copyright © Xero 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.8")] [assembly: AssemblyFileVersion("1.1.0.8")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XeroApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xero")] [assembly: AssemblyProduct("XeroApi")] [assembly: AssemblyCopyright("Copyright © Xero 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.9")] [assembly: AssemblyFileVersion("1.1.0.9")]
Change access of Write() to internal
using System.IO; namespace Leaf.Nodes { /// <summary> /// Base class for all node types. /// </summary> public abstract class Node { /// <summary> /// Writes the data of the node to a stream. /// </summary> /// <param name="writer">Writer to use for putting data in the stream.</param> public abstract void Write(BinaryWriter writer); } }
using System.IO; namespace Leaf.Nodes { /// <summary> /// Base class for all node types. /// </summary> public abstract class Node { /// <summary> /// Writes the data of the node to a stream. /// </summary> /// <param name="writer">Writer to use for putting data in the stream.</param> internal abstract void Write(BinaryWriter writer); } }
Update fb-usertoken grant to reuser Facebook id
// 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.Threading.Tasks; namespace Nether.Data.Identity { public static class LoginProvider { public const string UserNamePassword = "password"; public const string FacebookUserAccessToken = "facebook-user-access-token"; } }
// 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.Threading.Tasks; namespace Nether.Data.Identity { public static class LoginProvider { public const string UserNamePassword = "password"; public const string FacebookUserAccessToken = "Facebook"; // use the same identifier as the implicit flow for facebook } }
Create a temporary library file and rename it to reduce the chance of library corruption
using Rareform.Validation; using System.Collections.Generic; using System.IO; namespace Espera.Core.Management { public class LibraryFileWriter : ILibraryWriter { private readonly string targetPath; public LibraryFileWriter(string targetPath) { if (targetPath == null) Throw.ArgumentNullException(() => targetPath); this.targetPath = targetPath; } public void Write(IEnumerable<LocalSong> songs, IEnumerable<Playlist> playlists, string songSourcePath) { using (FileStream targetStream = File.Create(this.targetPath)) { LibraryWriter.Write(songs, playlists, songSourcePath, targetStream); } } } }
using Rareform.Validation; using System; using System.Collections.Generic; using System.IO; namespace Espera.Core.Management { public class LibraryFileWriter : ILibraryWriter { private readonly string targetPath; public LibraryFileWriter(string targetPath) { if (targetPath == null) Throw.ArgumentNullException(() => targetPath); this.targetPath = targetPath; } public void Write(IEnumerable<LocalSong> songs, IEnumerable<Playlist> playlists, string songSourcePath) { // Create a temporary file, write the library it, then delete the original library file // and rename our new one. This ensures that there is a minimum possibility of things // going wrong, for example if the process is killed mid-writing. string tempFilePath = Path.Combine(Path.GetDirectoryName(this.targetPath), Guid.NewGuid().ToString()); using (FileStream targetStream = File.Create(tempFilePath)) { LibraryWriter.Write(songs, playlists, songSourcePath, targetStream); } File.Delete(this.targetPath); File.Move(tempFilePath, this.targetPath); } } }
Change Teamupdate time interval to 180s.
namespace Mitternacht.Common { public class TimeConstants { public const int WaitForForum = 500; public const int TeamUpdate = 60 * 1000; public const int Birthday = 60 * 1000; } }
namespace Mitternacht.Common { public class TimeConstants { public const int WaitForForum = 500; public const int TeamUpdate = 3 * 60 * 1000; public const int Birthday = 60 * 1000; } }
Call GetBaseException instead of manually unwrapping exception types.
using System; using System.Reflection; namespace NuGet { public static class ExceptionUtility { public static Exception Unwrap(Exception exception) { if (exception == null) { throw new ArgumentNullException("exception"); } if (exception.InnerException == null) { return exception; } // Always return the inner exception from a target invocation exception if (exception.GetType() == typeof(TargetInvocationException)) { return exception.InnerException; } // Flatten the aggregate before getting the inner exception if (exception.GetType() == typeof(AggregateException)) { return ((AggregateException)exception).Flatten().InnerException; } return exception; } } }
using System; using System.Reflection; namespace NuGet { public static class ExceptionUtility { public static Exception Unwrap(Exception exception) { if (exception == null) { throw new ArgumentNullException("exception"); } if (exception.InnerException == null) { return exception; } // Always return the inner exception from a target invocation exception if (exception is AggregateException || exception is TargetInvocationException) { return exception.GetBaseException(); } return exception; } } }
Add comment to demo teamcity
namespace Fixie.Behaviors { public interface CaseBehavior { void Execute(Case @case, object instance); } }
namespace Fixie.Behaviors { public interface CaseBehavior { void Execute(Case @case, object instance); //comment to demo teamcity } }
Make default value of SignedPetitions as array.
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Infopulse.EDemocracy.Model.BusinessEntities { public class UserDetailInfo : BaseEntity { [JsonIgnore] public int UserID { get; set; } [Required] public string FirstName { get; set; } public string MiddleName { get; set; } [Required] public string LastName { get; set; } public string ZipCode { get; set; } [Required] public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } [Required] public string City { get; set; } public string Region { get; set; } public string Country { get; set; } [JsonIgnore] public string CreatedBy { get; set; } [JsonIgnore] public DateTime CreatedDate { get; set; } [JsonIgnore] public string ModifiedBy { get; set; } [JsonIgnore] public DateTime? ModifiedDate { get; set; } public User User { get; set; } public List<Petition> CreatedPetitions { get; set; } public List<Petition> SignedPetitions { get; set; } public UserDetailInfo() { this.CreatedPetitions = new List<Petition>(); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Infopulse.EDemocracy.Model.BusinessEntities { public class UserDetailInfo : BaseEntity { [JsonIgnore] public int UserID { get; set; } [Required] public string FirstName { get; set; } public string MiddleName { get; set; } [Required] public string LastName { get; set; } public string ZipCode { get; set; } [Required] public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } [Required] public string City { get; set; } public string Region { get; set; } public string Country { get; set; } [JsonIgnore] public string CreatedBy { get; set; } [JsonIgnore] public DateTime CreatedDate { get; set; } [JsonIgnore] public string ModifiedBy { get; set; } [JsonIgnore] public DateTime? ModifiedDate { get; set; } public User User { get; set; } public List<Petition> CreatedPetitions { get; set; } public List<Petition> SignedPetitions { get; set; } public UserDetailInfo() { this.CreatedPetitions = new List<Petition>(); this.SignedPetitions = new List<Petition>(); } } }
Update tests with new specifications of Mapping
using System; using EntityFramework.Mapping; using Xunit; using Tracker.SqlServer.CodeFirst; using Tracker.SqlServer.CodeFirst.Entities; using Tracker.SqlServer.Entities; using EntityFramework.Extensions; using Task = Tracker.SqlServer.Entities.Task; namespace Tracker.SqlServer.Test { /// <summary> /// Summary description for MappingObjectContext /// </summary> public class MappingObjectContext { [Fact] public void GetEntityMapTask() { //var db = new TrackerEntities(); //var metadata = db.MetadataWorkspace; //var map = db.Tasks.GetEntityMap<Task>(); //Assert.Equal("[dbo].[Task]", map.TableName); } [Fact] public void GetEntityMapAuditData() { var db = new TrackerContext(); var resolver = new MetadataMappingProvider(); var map = resolver.GetEntityMap(typeof(AuditData), db); //var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>(); Assert.Equal("[dbo].[Audit]", map.TableName); } [Fact] public void GetInheritedEntityMapAuditData() { var db = new TrackerContext(); var resolver = new MetadataMappingProvider(); var map = resolver.GetEntityMap(typeof(CodeFirst.Entities.Task), db); //var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>(); Assert.Equal("[dbo].[Task]", map.TableName); } } }
using System; using EntityFramework.Mapping; using Xunit; using Tracker.SqlServer.CodeFirst; using Tracker.SqlServer.CodeFirst.Entities; using Tracker.SqlServer.Entities; using EntityFramework.Extensions; using Task = Tracker.SqlServer.Entities.Task; namespace Tracker.SqlServer.Test { /// <summary> /// Summary description for MappingObjectContext /// </summary> public class MappingObjectContext { [Fact] public void GetEntityMapTask() { //var db = new TrackerEntities(); //var metadata = db.MetadataWorkspace; //var map = db.Tasks.GetEntityMap<Task>(); //Assert.Equal("[dbo].[Task]", map.TableName); } [Fact] public void GetEntityMapAuditData() { var db = new TrackerContext(); var resolver = new MetadataMappingProvider(); var map = resolver.GetEntityMap(typeof(AuditData), db); //var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>(); Assert.Equal("Audit", map.TableName); Assert.Equal("dbo", map.SchemaName); } [Fact] public void GetInheritedEntityMapAuditData() { var db = new TrackerContext(); var resolver = new MetadataMappingProvider(); var map = resolver.GetEntityMap(typeof(CodeFirst.Entities.Task), db); //var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>(); Assert.Equal("Task", map.TableName); Assert.Equal("dbo", map.SchemaName); } } }
Remove in-code resharper disable statement
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// The purpose of this class is to provide a cached reference to the main camera. Calling Camera.main /// executes a FindByTag on the scene, which will get worse and worse with more tagged objects. /// </summary> public static class CameraCache { private static Camera cachedCamera; /// <summary> /// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet. /// </summary> public static Camera Main { get { // ReSharper disable once ConvertIfStatementToReturnStatement if (cachedCamera == null) { return Refresh(Camera.main); } return cachedCamera; } } /// <summary> /// Set the cached camera to a new reference and return it /// </summary> /// <param name="newMain">New main camera to cache</param> public static Camera Refresh(Camera newMain) { return cachedCamera = newMain; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// The purpose of this class is to provide a cached reference to the main camera. Calling Camera.main /// executes a FindByTag on the scene, which will get worse and worse with more tagged objects. /// </summary> public static class CameraCache { private static Camera cachedCamera; /// <summary> /// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet. /// </summary> public static Camera Main { get { if (cachedCamera == null) { return Refresh(Camera.main); } return cachedCamera; } } /// <summary> /// Set the cached camera to a new reference and return it /// </summary> /// <param name="newMain">New main camera to cache</param> public static Camera Refresh(Camera newMain) { return cachedCamera = newMain; } } }
Adjust collection editor to list by milestone
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { public override void OnInspectorGUI() { MicrogameCollection collection = (MicrogameCollection)target; if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); EditorUtility.SetDirty(collection); } if (GUILayout.Button("Update Build Path")) { collection.updateBuildPath(); EditorUtility.SetDirty(collection); } DrawDefaultInspector(); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using System.Linq; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { MicrogameCollection collection; private List<MicrogameList> microgames; private class MicrogameList { public string milestoneName; public bool show = false; public List<string> idList; public MicrogameList() { idList = new List<string>(); } } private void OnEnable() { collection = (MicrogameCollection)target; setMicrogames(); } void setMicrogames() { microgames = new List<MicrogameList>(); var collectionMicrogames = collection.microgames; var milestoneNames = Enum.GetNames(typeof(MicrogameTraits.Milestone)); for (int i = milestoneNames.Length - 1; i >= 0; i--) { var milestoneMicrogames = collectionMicrogames.Where(a => (int)a.difficultyTraits[0].milestone == i); var newList = new MicrogameList(); newList.milestoneName = milestoneNames[i]; foreach (var milestoneMicrogame in milestoneMicrogames) { newList.idList.Add(milestoneMicrogame.microgameId); } microgames.Add(newList); } } public override void OnInspectorGUI() { if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); setMicrogames(); EditorUtility.SetDirty(collection); } if (GUILayout.Button("Update Build Path")) { collection.updateBuildPath(); EditorUtility.SetDirty(collection); } GUILayout.Label("Indexed Microgames:"); var names = Enum.GetNames(typeof(MicrogameTraits.Milestone)); foreach (var microgameList in microgames) { microgameList.show = EditorGUILayout.Foldout(microgameList.show, microgameList.milestoneName); if (microgameList.show) { foreach (var microgameId in microgameList.idList) { EditorGUILayout.LabelField(" " + microgameId); } } } } }
Simplify MethodReplacer and keep backwards compatibility
using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { private static IEnumerable<CodeInstruction> Replacer(IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode opcode) { if (from == null) throw new ArgumentException("Unexpected null argument", nameof(from)); if (to == null) throw new ArgumentException("Unexpected null argument", nameof(to)); foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = opcode; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { return Replacer(instructions, from, to, OpCodes.Call); } public static IEnumerable<CodeInstruction> ConstructorReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { return Replacer(instructions, from, to, OpCodes.Newobj); } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { if (from == null) throw new ArgumentException("Unexpected null argument", nameof(from)); if (to == null) throw new ArgumentException("Unexpected null argument", nameof(to)); foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = to.IsConstructor ? OpCodes.Newobj : OpCodes.Call; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
Check for int.MaxValue when incrementing retry counter
using System; using Polly.Utilities; namespace Polly.Retry { internal partial class RetryPolicyStateWithSleepDurationProvider : IRetryPolicyState { private int _errorCount; private readonly Func<int, TimeSpan> _sleepDurationProvider; private readonly Action<Exception, TimeSpan, Context> _onRetry; private readonly Context _context; public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan, Context> onRetry, Context context) { this._sleepDurationProvider = sleepDurationProvider; _onRetry = onRetry; _context = context; } public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan> onRetry) : this(sleepDurationProvider, (exception, timespan, context) => onRetry(exception, timespan), null) { } public bool CanRetry(Exception ex) { if (_errorCount < int.MaxValue) { _errorCount += 1; } else { } var currentTimeSpan = _sleepDurationProvider(_errorCount); _onRetry(ex, currentTimeSpan, _context); SystemClock.Sleep(currentTimeSpan); return true; } } }
using System; using Polly.Utilities; namespace Polly.Retry { internal partial class RetryPolicyStateWithSleepDurationProvider : IRetryPolicyState { private int _errorCount; private readonly Func<int, TimeSpan> _sleepDurationProvider; private readonly Action<Exception, TimeSpan, Context> _onRetry; private readonly Context _context; public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan, Context> onRetry, Context context) { this._sleepDurationProvider = sleepDurationProvider; _onRetry = onRetry; _context = context; } public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan> onRetry) : this(sleepDurationProvider, (exception, timespan, context) => onRetry(exception, timespan), null) { } public bool CanRetry(Exception ex) { if (_errorCount < int.MaxValue) { _errorCount += 1; } var currentTimeSpan = _sleepDurationProvider(_errorCount); _onRetry(ex, currentTimeSpan, _context); SystemClock.Sleep(currentTimeSpan); return true; } } }
Remove the reading of the response... extra overhead not needed
using System; using System.Net.Http; using System.Threading.Tasks; namespace Glimpse.Agent { public class HttpChannelSender : IChannelSender, IDisposable { private readonly HttpClient _httpClient; private readonly HttpClientHandler _httpHandler; public HttpChannelSender() { _httpHandler = new HttpClientHandler(); _httpClient = new HttpClient(_httpHandler); } public async void PublishMessage(IMessage message) { // TODO: Needs error handelling // TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync try { var response = await _httpClient.PostAsJsonAsync("http://localhost:5210/Glimpse/Agent", message); // Check that response was successful or throw exception response.EnsureSuccessStatusCode(); // Read response asynchronously as JsonValue and write out top facts for each country var result = await response.Content.ReadAsStringAsync(); } catch (Exception e) { // TODO: Bad thing happened } } public void Dispose() { _httpClient.Dispose(); _httpHandler.Dispose(); } } }
using System; using System.Net.Http; using System.Threading.Tasks; namespace Glimpse.Agent { public class HttpChannelSender : IChannelSender, IDisposable { private readonly HttpClient _httpClient; private readonly HttpClientHandler _httpHandler; public HttpChannelSender() { _httpHandler = new HttpClientHandler(); _httpClient = new HttpClient(_httpHandler); } public async void PublishMessage(IMessage message) { // TODO: Needs error handelling // TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync try { var response = await _httpClient.PostAsJsonAsync("http://localhost:5210/Glimpse/Agent", message); // Check that response was successful or throw exception response.EnsureSuccessStatusCode(); } catch (Exception e) { // TODO: Bad thing happened } } public void Dispose() { _httpClient.Dispose(); _httpHandler.Dispose(); } } }
Hide a defintion for internal use
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; namespace DotNetKit.Windows.Media { public static class VisualTreeModule { public static FrameworkElement FindChild(DependencyObject obj, string childName) { if (obj == null) return null; var queue = new Queue<DependencyObject>(); queue.Enqueue(obj); while (queue.Count > 0) { obj = queue.Dequeue(); var childCount = VisualTreeHelper.GetChildrenCount(obj); for (var i = 0; i < childCount; i++) { var child = VisualTreeHelper.GetChild(obj, i); var fe = child as FrameworkElement; if (fe != null && fe.Name == childName) { return fe; } queue.Enqueue(child); } } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; namespace DotNetKit.Windows.Media { static class VisualTreeModule { public static FrameworkElement FindChild(DependencyObject obj, string childName) { if (obj == null) return null; var queue = new Queue<DependencyObject>(); queue.Enqueue(obj); while (queue.Count > 0) { obj = queue.Dequeue(); var childCount = VisualTreeHelper.GetChildrenCount(obj); for (var i = 0; i < childCount; i++) { var child = VisualTreeHelper.GetChild(obj, i); var fe = child as FrameworkElement; if (fe != null && fe.Name == childName) { return fe; } queue.Enqueue(child); } } return null; } } }
Put AMEE Ribbon Panel under Analyze tab
using System; using System.IO; using System.Windows.Forms; using System.Windows.Media.Imaging; using Autodesk.Revit.UI; namespace AMEE_in_Revit.Addin { public class AMEEPanel : IExternalApplication { // ExternalCommands assembly path static string AddInPath = typeof(AMEEPanel).Assembly.Location; // Button icons directory static string ButtonIconsFolder = Path.GetDirectoryName(AddInPath); // uiApplication static UIApplication uiApplication = null; public Result OnStartup(UIControlledApplication application) { try { var panel = application.CreateRibbonPanel("AMEE"); AddAMEEConnectButton(panel); panel.AddSeparator(); return Result.Succeeded; } catch (Exception ex) { MessageBox.Show(ex.ToString(), "AMEE-in-Revit error"); return Result.Failed; } } private void AddAMEEConnectButton(RibbonPanel panel) { var pushButton = panel.AddItem(new PushButtonData("launchAMEEConnect", "AMEE Connect", AddInPath, "AMEE_in_Revit.Addin.LaunchAMEEConnectCommand")) as PushButton; pushButton.ToolTip = "Say Hello World"; // Set the large image shown on button pushButton.LargeImage = new BitmapImage(new Uri(ButtonIconsFolder+ @"\AMEE.ico")); } public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } } }
using System; using System.IO; using System.Windows.Forms; using System.Windows.Media.Imaging; using Autodesk.Revit.UI; namespace AMEE_in_Revit.Addin { public class AMEEPanel : IExternalApplication { // ExternalCommands assembly path static string AddInPath = typeof(AMEEPanel).Assembly.Location; // Button icons directory static string ButtonIconsFolder = Path.GetDirectoryName(AddInPath); // uiApplication static UIApplication uiApplication = null; public Result OnStartup(UIControlledApplication application) { try { var panel = application.CreateRibbonPanel(Tab.Analyze, "AMEE"); AddAMEEConnectButton(panel); panel.AddSeparator(); return Result.Succeeded; } catch (Exception ex) { MessageBox.Show(ex.ToString(), "AMEE-in-Revit error"); return Result.Failed; } } private void AddAMEEConnectButton(RibbonPanel panel) { var pushButton = panel.AddItem(new PushButtonData("launchAMEEConnect", "AMEE Connect", AddInPath, "AMEE_in_Revit.Addin.LaunchAMEEConnectCommand")) as PushButton; pushButton.ToolTip = "Say Hello World"; // Set the large image shown on button pushButton.LargeImage = new BitmapImage(new Uri(ButtonIconsFolder+ @"\AMEE.ico")); } public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } } }
Update on hourglass script. Still not in action
using UnityEngine; using System.Collections; public class Hourglass : Trigger { public Animator cutScene; public override void Activate() { UtilControls.Freeze(); cutScene.Play("cutscene"); GameObject.FindGameObjectWithTag("ThingsController").GetComponent<ThingsController>().ClearCurrentMemory(); } public override void Deactivate() { /* nothing */ } public override void Interact() { /* nothing */ } }
using UnityEngine; using System.Collections; public class Hourglass : Trigger { public GameObject cutsceneObject; public Animator cutScene; void Start() { //cutScene = cutsceneObject.GetComponent<Animator>(); } public override void Activate() { UtilControls.Freeze(); cutScene.Play("cutscene"); GameObject.FindGameObjectWithTag("ThingsController").GetComponent<ThingsController>().ClearCurrentMemory(); } public override void Deactivate() { /* nothing */ } public override void Interact() { /* nothing */ } }
Save files as UTF-8 for consistency.
namespace Fixie.Execution.Listeners { using System; using System.IO; using System.Xml.Linq; public class ReportListener<TXmlFormat> : Handler<AssemblyStarted>, Handler<ClassStarted>, Handler<CaseCompleted>, Handler<ClassCompleted>, Handler<AssemblyCompleted> where TXmlFormat : XmlFormat, new() { Report report; ClassReport currentClass; readonly Action<Report> save; public ReportListener(Action<Report> save) { this.save = save; } public ReportListener() : this(Save) { } public void Handle(AssemblyStarted message) { report = new Report(message.Assembly); } public void Handle(ClassStarted message) { currentClass = new ClassReport(message.Class); report.Add(currentClass); } public void Handle(CaseCompleted message) { currentClass.Add(message); } public void Handle(ClassCompleted message) { currentClass = null; } public void Handle(AssemblyCompleted message) { save(report); report = null; } static void Save(Report report) { var format = new TXmlFormat(); var xDocument = format.Transform(report); var filePath = Path.GetFullPath(report.Assembly.Location) + ".xml"; using (var stream = new FileStream(filePath, FileMode.Create)) using (var writer = new StreamWriter(stream)) xDocument.Save(writer, SaveOptions.None); } } }
namespace Fixie.Execution.Listeners { using System; using System.IO; using System.Xml.Linq; public class ReportListener<TXmlFormat> : Handler<AssemblyStarted>, Handler<ClassStarted>, Handler<CaseCompleted>, Handler<ClassCompleted>, Handler<AssemblyCompleted> where TXmlFormat : XmlFormat, new() { Report report; ClassReport currentClass; readonly Action<Report> save; public ReportListener(Action<Report> save) { this.save = save; } public ReportListener() : this(Save) { } public void Handle(AssemblyStarted message) { report = new Report(message.Assembly); } public void Handle(ClassStarted message) { currentClass = new ClassReport(message.Class); report.Add(currentClass); } public void Handle(CaseCompleted message) { currentClass.Add(message); } public void Handle(ClassCompleted message) { currentClass = null; } public void Handle(AssemblyCompleted message) { save(report); report = null; } static void Save(Report report) { var format = new TXmlFormat(); var xDocument = format.Transform(report); var filePath = Path.GetFullPath(report.Assembly.Location) + ".xml"; using (var stream = new FileStream(filePath, FileMode.Create)) using (var writer = new StreamWriter(stream)) xDocument.Save(writer, SaveOptions.None); } } }
Fix default color temperature values
using System.Collections.Generic; namespace Common.Data { public class TemperatureOverlayState { public bool CustomRangesEnabled { get; set; } = true; public List<float> Temperatures => new List<float> { Aqua, Turquoise, Blue, Green, Lime, Orange, RedOrange, Red }; public float Red { get; set; } = 1800; public float RedOrange { get; set; } = 773; public float Orange { get; set; } = 373; public float Lime { get; set; } = 303; public float Green { get; set; } = 293; public float Blue { get; set; } = 0.1f; public float Turquoise { get; set; } = 273; public float Aqua { get; set; } = 0; public bool LogThresholds { get; set; } = false; } }
using System.Collections.Generic; namespace Common.Data { public class TemperatureOverlayState { public bool CustomRangesEnabled { get; set; } = true; public List<float> Temperatures => new List<float> { Aqua, Turquoise, Blue, Green, Lime, Orange, RedOrange, Red }; public float Red { get; set; } = 1800; public float RedOrange { get; set; } = 0.1f; public float Orange { get; set; } = 323; public float Lime { get; set; } = 293; public float Green { get; set; } = 273; public float Blue { get; set; } = 0.2f; public float Turquoise { get; set; } = 0.1f; public float Aqua { get; set; } = 0; public bool LogThresholds { get; set; } = false; } }
Add description to service resource
using Digirati.IIIF.Model.JsonLD; using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types { public class Service : JSONLDBase, IService { [JsonProperty(Order = 10, PropertyName = "profile")] public dynamic Profile { get; set; } [JsonProperty(Order = 11, PropertyName = "label")] public MetaDataValue Label { get; set; } } }
using Digirati.IIIF.Model.JsonLD; using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types { public class Service : JSONLDBase, IService { [JsonProperty(Order = 10, PropertyName = "profile")] public dynamic Profile { get; set; } [JsonProperty(Order = 11, PropertyName = "label")] public MetaDataValue Label { get; set; } [JsonProperty(Order = 12, PropertyName = "description")] public MetaDataValue Description { get; set; } } }
Fix exception caused by getting directory name from empty string in runner config editor
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using SSMScripter.Runner; namespace SSMScripter.Config { public partial class RunnerConfigForm : Form { private RunConfig _runConfig; public RunnerConfigForm() { InitializeComponent(); } public RunnerConfigForm(RunConfig runConfig) : this() { _runConfig = runConfig; tbTool.Text = _runConfig.IsUndefined() ? String.Empty : (_runConfig.RunTool ?? String.Empty); tbArgs.Text = _runConfig.RunArgs ?? String.Empty; } private void btnOk_Click(object sender, EventArgs e) { _runConfig.RunTool = tbTool.Text; _runConfig.RunArgs = tbArgs.Text; DialogResult = DialogResult.OK; } private void btnTool_Click(object sender, EventArgs e) { using(OpenFileDialog dialog = new OpenFileDialog()) { dialog.InitialDirectory = Path.GetDirectoryName(tbTool.Text) ?? String.Empty; dialog.FileName = Path.GetFileName(tbTool.Text) ?? String.Empty; dialog.Filter = "Exe files (*.exe)|*.exe|All files (*.*)|*.*"; dialog.RestoreDirectory = true; if (dialog.ShowDialog() == DialogResult.OK) { tbTool.Text = dialog.FileName; } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using SSMScripter.Runner; namespace SSMScripter.Config { public partial class RunnerConfigForm : Form { private RunConfig _runConfig; public RunnerConfigForm() { InitializeComponent(); } public RunnerConfigForm(RunConfig runConfig) : this() { _runConfig = runConfig; tbTool.Text = _runConfig.IsUndefined() ? String.Empty : (_runConfig.RunTool ?? String.Empty); tbArgs.Text = _runConfig.RunArgs ?? String.Empty; } private void btnOk_Click(object sender, EventArgs e) { _runConfig.RunTool = tbTool.Text; _runConfig.RunArgs = tbArgs.Text; DialogResult = DialogResult.OK; } private void btnTool_Click(object sender, EventArgs e) { using(OpenFileDialog dialog = new OpenFileDialog()) { if (!String.IsNullOrEmpty(tbTool.Text)) dialog.InitialDirectory = Path.GetDirectoryName(tbTool.Text); dialog.FileName = Path.GetFileName(tbTool.Text) ?? String.Empty; dialog.Filter = "Exe files (*.exe)|*.exe|All files (*.*)|*.*"; dialog.RestoreDirectory = true; if (dialog.ShowDialog() == DialogResult.OK) { tbTool.Text = dialog.FileName; } } } } }
Set env vars in GitHub Actions
namespace NerdBank.GitVersioning.CloudBuildServices { using System; using System.Collections.Generic; using System.IO; using Nerdbank.GitVersioning; internal class GitHubActions : ICloudBuild { public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true"; public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent"; public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null; public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null; public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA"); private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF"); public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { return new Dictionary<string, string>(); } public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { return new Dictionary<string, string>(); } } }
namespace NerdBank.GitVersioning.CloudBuildServices { using System; using System.Collections.Generic; using System.IO; using Nerdbank.GitVersioning; internal class GitHubActions : ICloudBuild { public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true"; public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent"; public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null; public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null; public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA"); private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF"); public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { return new Dictionary<string, string>(); } public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##[set-env name={name};]{value}"); return GetDictionaryFor(name, value); } private static IReadOnlyDictionary<string, string> GetDictionaryFor(string variableName, string value) { return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { GetEnvironmentVariableNameForVariable(variableName), value }, }; } private static string GetEnvironmentVariableNameForVariable(string name) => name.ToUpperInvariant().Replace('.', '_'); } }
Change uow to default to IsolationLevel.RepeatableRead
using System; using System.Data; using Dapper.FastCrud; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public class UnitOfWork : DbTransaction, IUnitOfWork { public SqlDialect SqlDialect { get; } private readonly Guid _guid = Guid.NewGuid(); public UnitOfWork(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable, bool sessionOnlyForThisUnitOfWork = false) : base(factory) { if (sessionOnlyForThisUnitOfWork) { Session = session; } Transaction = session.BeginTransaction(isolationLevel); SqlDialect = session.SqlDialect; } protected bool Equals(UnitOfWork other) { return _guid.Equals(other._guid); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((UnitOfWork) obj); } public override int GetHashCode() { return _guid.GetHashCode(); } public static bool operator ==(UnitOfWork left, UnitOfWork right) { return Equals(left, right); } public static bool operator !=(UnitOfWork left, UnitOfWork right) { return !Equals(left, right); } } }
using System; using System.Data; using Dapper.FastCrud; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public class UnitOfWork : DbTransaction, IUnitOfWork { public SqlDialect SqlDialect { get; } private readonly Guid _guid = Guid.NewGuid(); public UnitOfWork(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.RepeatableRead, bool sessionOnlyForThisUnitOfWork = false) : base(factory) { if (sessionOnlyForThisUnitOfWork) { Session = session; } Transaction = session.BeginTransaction(isolationLevel); SqlDialect = session.SqlDialect; } protected bool Equals(UnitOfWork other) { return _guid.Equals(other._guid); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((UnitOfWork) obj); } public override int GetHashCode() { return _guid.GetHashCode(); } public static bool operator ==(UnitOfWork left, UnitOfWork right) { return Equals(left, right); } public static bool operator !=(UnitOfWork left, UnitOfWork right) { return !Equals(left, right); } } }
Revert to main menu on 0 balls left.
using System.Collections; using System.Collections.Generic; using UnityEngine; using Zenject; public class ScoreCounter : MonoBehaviour { [Inject] public StageStats Stats { get; private set; } void Start() { Stats.BallsTotal = Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length; StartCoroutine(Count()); } IEnumerator Count() { while (true) { yield return new WaitForSeconds(1); Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using Zenject; public class ScoreCounter : MonoBehaviour { [Inject] public StageStats Stats { get; private set; } void Start() { Stats.BallsTotal = Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length; StartCoroutine(Count()); } IEnumerator Count() { while (true) { yield return new WaitForSeconds(1); Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length; if (Stats.BallsLeft == 0) { SceneManager.LoadScene("MainMenu"); } } } }
Add delay for ReloadActiveScene to prevent stuck button
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class ReloadScene : MonoBehaviour { GlobalControl globalController; bool allowLevelLoad = true; void OnEnable() { allowLevelLoad = true; } // Use this for initialization public void ReloadActiveScene () { if (allowLevelLoad) { allowLevelLoad = false; globalController = (GlobalControl)FindObjectOfType(typeof(GlobalControl)); globalController.globalMultiplayerManager.gameObject.SetActive(true); SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } } }
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class ReloadScene : MonoBehaviour { GlobalControl globalController; bool allowLevelLoad = true; void OnEnable() { allowLevelLoad = true; } // Use this for initialization public void ReloadActiveScene () { if (allowLevelLoad) { allowLevelLoad = false; Invoke("LoadScene", 0.33f); } } private void LoadScene() { globalController = (GlobalControl)FindObjectOfType(typeof(GlobalControl)); globalController.globalMultiplayerManager.gameObject.SetActive(true); SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } }
Use the options when connecting to GitHub
using Nito.AsyncEx; using Octokit; using System; using System.Collections.Generic; using System.Linq; namespace Alteridem.GetChanges { class Program { static int Main(string[] args) { var options = new Options(); if (!CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine(options.GetUsage()); return -1; } AsyncContext.Run(() => MainAsync(options)); Console.WriteLine("*** Press ENTER to Exit ***"); Console.ReadLine(); return 0; } static async void MainAsync(Options options) { var github = new GitHubApi("nunit", "nunit"); var milestones = await github.GetAllMilestones(); var issues = await github.GetClosedIssues(); var noMilestoneIssues = from i in issues where i.Milestone == null select i; DisplayIssuesForMilestone("Issues with no milestone", noMilestoneIssues); foreach (var milestone in milestones) { var milestoneIssues = from i in issues where i.Milestone != null && i.Milestone.Number == milestone.Number select i; DisplayIssuesForMilestone(milestone.Title, milestoneIssues); } } static void DisplayIssuesForMilestone(string milestone, IEnumerable<Issue> issues) { Console.WriteLine("## {0}", milestone); Console.WriteLine(); foreach (var issue in issues) { Console.WriteLine(" * {0:####} {1}", issue.Number, issue.Title); } Console.WriteLine(); } } }
using Nito.AsyncEx; using Octokit; using System; using System.Collections.Generic; using System.Linq; namespace Alteridem.GetChanges { class Program { static int Main(string[] args) { var options = new Options(); if (!CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine(options.GetUsage()); return -1; } AsyncContext.Run(() => MainAsync(options)); Console.WriteLine("*** Press ENTER to Exit ***"); Console.ReadLine(); return 0; } static async void MainAsync(Options options) { var github = new GitHubApi(options.Organization, options.Repository); var milestones = await github.GetAllMilestones(); var issues = await github.GetClosedIssues(); var noMilestoneIssues = from i in issues where i.Milestone == null select i; DisplayIssuesForMilestone("Issues with no milestone", noMilestoneIssues); foreach (var milestone in milestones) { var milestoneIssues = from i in issues where i.Milestone != null && i.Milestone.Number == milestone.Number select i; DisplayIssuesForMilestone(milestone.Title, milestoneIssues); } } static void DisplayIssuesForMilestone(string milestone, IEnumerable<Issue> issues) { Console.WriteLine("## {0}", milestone); Console.WriteLine(); foreach (var issue in issues) { Console.WriteLine(" * {0:####} {1}", issue.Number, issue.Title); } Console.WriteLine(); } } }
Allow setting grouping hash and context
using System.Collections.Generic; using System.Linq; namespace Bugsnag { public class Event : Dictionary<string, object> { public Event(IConfiguration configuration, System.Exception exception, Severity severity) { this["payloadVersion"] = 2; this["exceptions"] = new Exceptions(exception).ToArray(); this["app"] = new App(configuration); switch (severity) { case Severity.Info: this["severity"] = "info"; break; case Severity.Warning: this["severity"] = "warning"; break; default: this["severity"] = "error"; break; } } public Exception[] Exceptions { get { return this["exceptions"] as Exception[]; } set { this.AddToPayload("exceptions", value); } } } }
using System.Collections.Generic; using System.Linq; namespace Bugsnag { public class Event : Dictionary<string, object> { public Event(IConfiguration configuration, System.Exception exception, Severity severity) { this["payloadVersion"] = 4; this["exceptions"] = new Exceptions(exception).ToArray(); this["app"] = new App(configuration); switch (severity) { case Severity.Info: this["severity"] = "info"; break; case Severity.Warning: this["severity"] = "warning"; break; default: this["severity"] = "error"; break; } } public Exception[] Exceptions { get { return this["exceptions"] as Exception[]; } set { this.AddToPayload("exceptions", value); } } public string Context { get { return this["context"] as string; } set { this.AddToPayload("context", value); } } public string GroupingHash { get { return this["groupingHash"] as string; } set { this.AddToPayload("groupingHash", value); } } } }
Add ToHashSet extension methods on IEnumerable.
/* * John.Hall <john.hall@camtechconsultants.com> * Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved. */ using System; using System.Collections.Generic; namespace CTC.CvsntGitImporter.Utils { /// <summary> /// Extension methods for IEnumerable. /// </summary> static class IEnumerableExtensions { /// <summary> /// Perform the equivalent of String.Join on a sequence. /// </summary> /// <typeparam name="T">the type of the elements of source</typeparam> /// <param name="source">the sequence of values to join</param> /// <param name="separator">a string to insert between each item</param> /// <returns>a string containing the items in the sequence concenated and separated by the separator</returns> public static string StringJoin<T>(this IEnumerable<T> source, string separator) { return String.Join(separator, source); } } }
/* * John.Hall <john.hall@camtechconsultants.com> * Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved. */ using System; using System.Collections.Generic; namespace CTC.CvsntGitImporter.Utils { /// <summary> /// Extension methods for IEnumerable. /// </summary> static class IEnumerableExtensions { /// <summary> /// Perform the equivalent of String.Join on a sequence. /// </summary> /// <typeparam name="T">the type of the elements of source</typeparam> /// <param name="source">the sequence of values to join</param> /// <param name="separator">a string to insert between each item</param> /// <returns>a string containing the items in the sequence concenated and separated by the separator</returns> public static string StringJoin<T>(this IEnumerable<T> source, string separator) { return String.Join(separator, source); } /// <summary> /// Create a HashSet from a list of items. /// </summary> public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) { return new HashSet<T>(source); } /// <summary> /// Create a HashSet from a list of items. /// </summary> public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer) { return new HashSet<T>(source, comparer); } } }
Add missing final validation pass (bytes read == 0)
//----------------------------------------------------------------------- // <copyright file="ValidatingReceiver.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace CommSample { using System; using System.Threading.Tasks; internal sealed class ValidatingReceiver { private readonly Receiver receiver; private readonly DataOracle oracle; private byte lastSeen; private int lastCount; public ValidatingReceiver(MemoryChannel channel, Logger logger, int bufferSize, DataOracle oracle) { this.receiver = new Receiver(channel, logger, bufferSize); this.oracle = oracle; this.receiver.DataReceived += this.OnDataReceived; } public Task<long> RunAsync() { return this.receiver.RunAsync(); } private void OnDataReceived(object sender, DataEventArgs e) { for (int i = 0; i < e.BytesRead; ++i) { if (this.lastSeen != e.Buffer[i]) { if (this.lastSeen != 0) { this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount); } this.lastSeen = e.Buffer[i]; this.lastCount = 0; } ++this.lastCount; } } } }
//----------------------------------------------------------------------- // <copyright file="ValidatingReceiver.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace CommSample { using System; using System.Threading.Tasks; internal sealed class ValidatingReceiver { private readonly Receiver receiver; private readonly DataOracle oracle; private byte lastSeen; private int lastCount; public ValidatingReceiver(MemoryChannel channel, Logger logger, int bufferSize, DataOracle oracle) { this.receiver = new Receiver(channel, logger, bufferSize); this.oracle = oracle; this.receiver.DataReceived += this.OnDataReceived; } public Task<long> RunAsync() { return this.receiver.RunAsync(); } private void OnDataReceived(object sender, DataEventArgs e) { for (int i = 0; i < e.BytesRead; ++i) { if (this.lastSeen != e.Buffer[i]) { if (this.lastSeen != 0) { this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount); } this.lastSeen = e.Buffer[i]; this.lastCount = 0; } ++this.lastCount; } if (e.BytesRead == 0) { this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount); } } } }
Implement code making the previously failing unit test pass.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ploeh.AutoFixture { public static class IFixtureExtensions { public static IEnumerable<T> Repeat<T>(this IFixture fixture, Func<T> function) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ploeh.AutoFixture { public static class IFixtureExtensions { public static IEnumerable<T> Repeat<T>(this IFixture fixture, Func<T> function) { if (fixture == null) { throw new ArgumentNullException("fixture"); } throw new NotImplementedException(); } } }
Allow a zone and version to be specified in the tzvalidate controller
// Copyright 2016 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Microsoft.AspNetCore.Mvc; using NodaTime.TimeZones; using NodaTime.TzValidate.NodaDump; using System.IO; using System.Net; namespace NodaTime.Web.Controllers { public class TzValidateController : Controller { // This will do something soon :) [Route("/tzvalidate/generate")] public IActionResult Generate(int startYear = 1, int endYear = 2035) { var source = TzdbDateTimeZoneSource.Default; var writer = new StringWriter(); var options = new Options { FromYear = startYear, ToYear = endYear }; var dumper = new ZoneDumper(source, options); dumper.Dump(writer); return new ContentResult { Content = writer.ToString(), ContentType = "text/plain", StatusCode = (int) HttpStatusCode.OK }; } } }
// Copyright 2016 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Microsoft.AspNetCore.Mvc; using NodaTime.TimeZones; using NodaTime.TzValidate.NodaDump; using NodaTime.Web.Models; using System.IO; using System.Linq; using System.Net; namespace NodaTime.Web.Controllers { public class TzValidateController : Controller { private readonly ITzdbRepository repository; public TzValidateController(ITzdbRepository repository) => this.repository = repository; [Route("/tzvalidate/generate")] public IActionResult Generate(int startYear = 1, int endYear = 2035, string zone = null, string version = null) { if (startYear < 1 || endYear > 3000 || startYear > endYear) { return BadRequest("Invalid start/end year combination"); } var source = TzdbDateTimeZoneSource.Default; if (version != null) { var release = repository.GetRelease($"tzdb{version}.nzd"); if (release == null) { return BadRequest("Unknown version"); } source = TzdbDateTimeZoneSource.FromStream(release.GetContent()); } if (zone != null && !source.GetIds().Contains(zone)) { return BadRequest("Unknown zone"); } var writer = new StringWriter(); var options = new Options { FromYear = startYear, ToYear = endYear, ZoneId = zone }; var dumper = new ZoneDumper(source, options); dumper.Dump(writer); return new ContentResult { Content = writer.ToString(), ContentType = "text/plain", StatusCode = (int) HttpStatusCode.OK }; } } }
Change default for DetailedAppointments to 'false'
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; namespace CalSync.Infrastructure { class Config { public int SyncRangeDays { get; private set; } public string TargetEmailAddress { get; private set; } public bool Receive { get; private set; } public bool DetailedAppointment { get; private set; } public bool Send { get; private set; } public String ErrorMessage { get; private set; } public static Config Read() { try { return new Config() { SyncRangeDays = int.Parse(ConfigurationManager.AppSettings["SyncRangeDays"]), TargetEmailAddress = ConfigurationManager.AppSettings["TargetEmailAddress"], Receive = bool.Parse(ConfigurationManager.AppSettings["Receive"] ?? "true"), DetailedAppointment = bool.Parse(ConfigurationManager.AppSettings["DetailedAppointment"] ?? "true"), Send = bool.Parse(ConfigurationManager.AppSettings["Send"] ?? "true"), }; } catch(Exception e) { if(e is ConfigurationErrorsException || e is FormatException || e is OverflowException ) { return new Config() { ErrorMessage = e.Message }; } throw; } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; namespace CalSync.Infrastructure { class Config { public int SyncRangeDays { get; private set; } public string TargetEmailAddress { get; private set; } public bool Receive { get; private set; } public bool Send { get; private set; } public bool DetailedAppointment { get; private set; } public String ErrorMessage { get; private set; } public static Config Read() { try { return new Config() { SyncRangeDays = int.Parse(ConfigurationManager.AppSettings["SyncRangeDays"]), TargetEmailAddress = ConfigurationManager.AppSettings["TargetEmailAddress"], Receive = bool.Parse(ConfigurationManager.AppSettings["Receive"] ?? "true"), Send = bool.Parse(ConfigurationManager.AppSettings["Send"] ?? "true"), DetailedAppointment = bool.Parse(ConfigurationManager.AppSettings["DetailedAppointment"] ?? "false"), }; } catch(Exception e) { if(e is ConfigurationErrorsException || e is FormatException || e is OverflowException ) { return new Config() { ErrorMessage = e.Message }; } throw; } } } }
Fix to work with Anonymous Roles
using System; using System.Linq; using System.Web.Mvc; using FujiyBlog.Core.DomainObjects; namespace FujiyBlog.Web.Infrastructure { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizePermissionAttribute : AuthorizeAttribute { public AuthorizePermissionAttribute(params Permission[] permissions) { if (permissions == null) { throw new ArgumentNullException("permissions"); } Roles = string.Join(",", permissions.Select(r => r.ToString())); } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); filterContext.HttpContext.Response.StatusCode = 401; filterContext.HttpContext.Response.WriteFile("~/errors/401.htm"); filterContext.HttpContext.Response.End(); } } }
using System; using System.Linq; using System.Security.Principal; using System.Web; using System.Web.Mvc; using FujiyBlog.Core.DomainObjects; using FujiyBlog.Core.Extensions; namespace FujiyBlog.Web.Infrastructure { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizePermissionAttribute : AuthorizeAttribute { public AuthorizePermissionAttribute(params Permission[] permissions) { if (permissions == null) { throw new ArgumentNullException("permissions"); } Roles = string.Join(",", permissions.Select(r => r.ToString())); } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } IPrincipal user = httpContext.User; var usersSplit = SplitString(Users); var rolesSplit = SplitString(Roles).Select(x => (Permission) Enum.Parse(typeof (Permission), x)).ToArray(); if (usersSplit.Length > 0 && !usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) { return false; } if (rolesSplit.Length > 0 && !rolesSplit.Any(user.IsInRole)) { return false; } return true; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); filterContext.HttpContext.Response.StatusCode = 401; filterContext.HttpContext.Response.WriteFile("~/errors/401.htm"); filterContext.HttpContext.Response.End(); } static string[] SplitString(string original) { if (String.IsNullOrEmpty(original)) { return new string[0]; } var split = from piece in original.Split(',') let trimmed = piece.Trim() where !String.IsNullOrEmpty(trimmed) select trimmed; return split.ToArray(); } } }
Rename finished, Bumped version to 0.9
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NowinWebServer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Boris Letocha")] [assembly: AssemblyProduct("NowinWebServer")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")] // 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("0.8.0.0")] [assembly: AssemblyFileVersion("0.8.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Nowin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Boris Letocha")] [assembly: AssemblyProduct("Nowin")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")] // 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("0.9.0.0")] [assembly: AssemblyFileVersion("0.9.0.0")]
Update key-only querystring comparisons to use "" rather than null to make it more compatible with form data
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RichardSzalay.MockHttp.Matchers { public class QueryStringMatcher : IMockedRequestMatcher { readonly IEnumerable<KeyValuePair<string, string>> values; public QueryStringMatcher(string queryString) : this(ParseQueryString(queryString)) { } public QueryStringMatcher(IEnumerable<KeyValuePair<string, string>> values) { this.values = values; } public bool Matches(System.Net.Http.HttpRequestMessage message) { var queryString = ParseQueryString(message.RequestUri.Query.TrimStart('?')); return values.All(matchPair => queryString.Any(p => p.Key == matchPair.Key && p.Value == matchPair.Value)); } internal static IEnumerable<KeyValuePair<string, string>> ParseQueryString(string input) { return input.TrimStart('?').Split('&') .Select(pair => StringUtil.Split(pair, '=', 2)) .Select(pair => new KeyValuePair<string, string>( Uri.UnescapeDataString(pair[0]), pair.Length == 2 ? Uri.UnescapeDataString(pair[1]) : null )) .ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RichardSzalay.MockHttp.Matchers { public class QueryStringMatcher : IMockedRequestMatcher { readonly IEnumerable<KeyValuePair<string, string>> values; public QueryStringMatcher(string queryString) : this(ParseQueryString(queryString)) { } public QueryStringMatcher(IEnumerable<KeyValuePair<string, string>> values) { this.values = values; } public bool Matches(System.Net.Http.HttpRequestMessage message) { var queryString = ParseQueryString(message.RequestUri.Query.TrimStart('?')); return values.All(matchPair => queryString.Any(p => p.Key == matchPair.Key && p.Value == matchPair.Value)); } internal static IEnumerable<KeyValuePair<string, string>> ParseQueryString(string input) { return input.TrimStart('?').Split('&') .Select(pair => StringUtil.Split(pair, '=', 2)) .Select(pair => new KeyValuePair<string, string>( Uri.UnescapeDataString(pair[0]), pair.Length == 2 ? Uri.UnescapeDataString(pair[1]) : "" )) .ToList(); } } }
Add offsite types for installment citi
using System.Runtime.Serialization; namespace Omise.Models { public enum OffsiteTypes { [EnumMember(Value = null)] None, [EnumMember(Value = "internet_banking_scb")] InternetBankingSCB, [EnumMember(Value = "internet_banking_bbl")] InternetBankingBBL, [EnumMember(Value = "internet_banking_ktb")] InternetBankingKTB, [EnumMember(Value = "internet_banking_bay")] InternetBankingBAY, [EnumMember(Value = "alipay")] AlipayOnline, [EnumMember(Value = "installment_bay")] InstallmentBAY, [EnumMember(Value = "installment_kbank")] InstallmentKBank, [EnumMember(Value = "bill_payment_tesco_lotus")] BillPaymentTescoLotus, [EnumMember(Value = "barcode_alipay")] BarcodeAlipay, [EnumMember(Value = "paynow")] Paynow, [EnumMember(Value = "points_citi")] PointsCiti, [EnumMember(Value = "promptpay")] PromptPay, [EnumMember(Value = "truemoney")] TrueMoney } }
using System.Runtime.Serialization; namespace Omise.Models { public enum OffsiteTypes { [EnumMember(Value = null)] None, [EnumMember(Value = "internet_banking_scb")] InternetBankingSCB, [EnumMember(Value = "internet_banking_bbl")] InternetBankingBBL, [EnumMember(Value = "internet_banking_ktb")] InternetBankingKTB, [EnumMember(Value = "internet_banking_bay")] InternetBankingBAY, [EnumMember(Value = "alipay")] AlipayOnline, [EnumMember(Value = "installment_bay")] InstallmentBAY, [EnumMember(Value = "installment_kbank")] InstallmentKBank, [EnumMember(Value = "installment_citi")] InstallmentCiti, [EnumMember(Value = "bill_payment_tesco_lotus")] BillPaymentTescoLotus, [EnumMember(Value = "barcode_alipay")] BarcodeAlipay, [EnumMember(Value = "paynow")] Paynow, [EnumMember(Value = "points_citi")] PointsCiti, [EnumMember(Value = "promptpay")] PromptPay, [EnumMember(Value = "truemoney")] TrueMoney } }
Normalize line endings in text viewer
using System.IO; using System.Linq; using System.Windows.Forms; using GUI.Utils; namespace GUI.Types.Viewers { public class ByteViewer : IViewer { public static bool IsAccepted() => true; public TabPage Create(VrfGuiContext vrfGuiContext, byte[] input) { var tab = new TabPage(); var resTabs = new TabControl { Dock = DockStyle.Fill, }; tab.Controls.Add(resTabs); var bvTab = new TabPage("Hex"); var bv = new System.ComponentModel.Design.ByteViewer { Dock = DockStyle.Fill, }; bvTab.Controls.Add(bv); resTabs.TabPages.Add(bvTab); if (input == null) { input = File.ReadAllBytes(vrfGuiContext.FileName); } if (!input.Contains<byte>(0x00)) { var textTab = new TabPage("Text"); var text = new TextBox { Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical, Multiline = true, ReadOnly = true, Text = System.Text.Encoding.UTF8.GetString(input), }; textTab.Controls.Add(text); resTabs.TabPages.Add(textTab); resTabs.SelectedTab = textTab; } Program.MainForm.Invoke((MethodInvoker)(() => { bv.SetBytes(input); })); return tab; } } }
using System.IO; using System.Linq; using System.Windows.Forms; using GUI.Utils; namespace GUI.Types.Viewers { public class ByteViewer : IViewer { public static bool IsAccepted() => true; public TabPage Create(VrfGuiContext vrfGuiContext, byte[] input) { var tab = new TabPage(); var resTabs = new TabControl { Dock = DockStyle.Fill, }; tab.Controls.Add(resTabs); var bvTab = new TabPage("Hex"); var bv = new System.ComponentModel.Design.ByteViewer { Dock = DockStyle.Fill, }; bvTab.Controls.Add(bv); resTabs.TabPages.Add(bvTab); if (input == null) { input = File.ReadAllBytes(vrfGuiContext.FileName); } if (!input.Contains<byte>(0x00)) { var textTab = new TabPage("Text"); var text = new TextBox { Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical, Multiline = true, ReadOnly = true, Text = Utils.Utils.NormalizeLineEndings(System.Text.Encoding.UTF8.GetString(input)), }; textTab.Controls.Add(text); resTabs.TabPages.Add(textTab); resTabs.SelectedTab = textTab; } Program.MainForm.Invoke((MethodInvoker)(() => { bv.SetBytes(input); })); return tab; } } }
Move default Dashboard API base address to constant
using System; using Microsoft.Extensions.Options; namespace Meraki { /// <summary> /// Initialize a <see cref="MerakiDashboardClientSettings"/> object. /// </summary> internal class MerakiDashboardClientSettingsSetup : ConfigureOptions<MerakiDashboardClientSettings> { /// <summary> /// Create a new <see cref="MerakiDashboardClientSettingsSetup"/> object. /// </summary> public MerakiDashboardClientSettingsSetup() : base(ConfigureOptions) { // Do nothing } /// <summary> /// Configure the <see cref="MerakiDashboardClientSettings"/> object. /// </summary> /// <param name="options"> /// The <see cref="MerakiDashboardClientSettings"/> object to configure. /// </param> private static void ConfigureOptions(MerakiDashboardClientSettings options) { options.Address = new Uri("https://dashboard.meraki.com", UriKind.Absolute); options.Key = ""; } } }
using System; using Microsoft.Extensions.Options; namespace Meraki { /// <summary> /// Initialize a <see cref="MerakiDashboardClientSettings"/> object. /// </summary> internal class MerakiDashboardClientSettingsSetup : ConfigureOptions<MerakiDashboardClientSettings> { public static readonly string DefaultMerakiDashboardApiBaseAddress = "https://dashboard.meraki.com"; /// <summary> /// Create a new <see cref="MerakiDashboardClientSettingsSetup"/> object. /// </summary> public MerakiDashboardClientSettingsSetup() : base(ConfigureOptions) { // Do nothing } /// <summary> /// Configure the <see cref="MerakiDashboardClientSettings"/> object. /// </summary> /// <param name="options"> /// The <see cref="MerakiDashboardClientSettings"/> object to configure. /// </param> private static void ConfigureOptions(MerakiDashboardClientSettings options) { options.Address = new Uri(DefaultMerakiDashboardApiBaseAddress, UriKind.Absolute); options.Key = ""; } } }
Change user.config format to app.confg schema
using System.Linq; using System.Xml.Linq; namespace Tests.Daterpillar.Helpers { public static class ConnectionString { private static readonly string _configFile = "database.config.xml"; public static string GetMySQLServerConnectionString() { return GetConnectionString("mysql"); } public static string GetSQLServerConnectionString() { return GetConnectionString("mssql"); } internal static string GetConnectionString(string name) { var doc = XDocument.Load(_configFile); var connectionStrings = doc.Element("connectionStrings"); var record = (from element in connectionStrings.Descendants("add") where element.Attribute("name").Value == name select element) .First(); var connStr = new System.Data.Common.DbConnectionStringBuilder(); connStr.Add("server", record.Attribute("server").Value); connStr.Add("user", record.Attribute("user").Value); connStr.Add("password", record.Attribute("password").Value); return connStr.ConnectionString; } } }
using System.Configuration; namespace Tests.Daterpillar.Helpers { public static class ConnectionString { public static string GetMySQLServerConnectionString() { return GetConnectionString("mysql"); } public static string GetSQLServerConnectionString() { return GetConnectionString("mssql"); } internal static string GetConnectionString(string name) { var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = "user.config" }; var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); return config.ConnectionStrings.ConnectionStrings[name].ConnectionString; } } }
Tweak google analytics detection to work on twitter.com
using CefSharp; namespace TweetDuck.Core.Handling{ class RequestHandlerBrowser : RequestHandler{ public override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status){ browser.Reload(); } public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback){ if (request.ResourceType == ResourceType.Script && request.Url.Contains("google_analytics.")){ return CefReturnValue.Cancel; } return CefReturnValue.Continue; } } }
using CefSharp; namespace TweetDuck.Core.Handling{ class RequestHandlerBrowser : RequestHandler{ public override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status){ browser.Reload(); } public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback){ if (request.ResourceType == ResourceType.Script && request.Url.Contains("analytics.")){ return CefReturnValue.Cancel; } return CefReturnValue.Continue; } } }
Add back combo colours for osu!classic
// 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.Audio; using osu.Framework.IO.Stores; using osuTK.Graphics; namespace osu.Game.Skinning { public class DefaultLegacySkin : LegacySkin { public DefaultLegacySkin(IResourceStore<byte[]> storage, AudioManager audioManager) : base(Info, storage, audioManager, string.Empty) { Configuration.CustomColours["SliderBall"] = new Color4(2, 170, 255, 255); } public static SkinInfo Info { get; } = new SkinInfo { ID = -1, // this is temporary until database storage is decided upon. Name = "osu!classic", Creator = "team osu!" }; } }
// 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.Audio; using osu.Framework.IO.Stores; using osuTK.Graphics; namespace osu.Game.Skinning { public class DefaultLegacySkin : LegacySkin { public DefaultLegacySkin(IResourceStore<byte[]> storage, AudioManager audioManager) : base(Info, storage, audioManager, string.Empty) { Configuration.CustomColours["SliderBall"] = new Color4(2, 170, 255, 255); Configuration.ComboColours.AddRange(new[] { new Color4(255, 192, 0, 255), new Color4(0, 202, 0, 255), new Color4(18, 124, 255, 255), new Color4(242, 24, 57, 255), }); } public static SkinInfo Info { get; } = new SkinInfo { ID = -1, // this is temporary until database storage is decided upon. Name = "osu!classic", Creator = "team osu!" }; } }
Update tạm fix lỗi Home/Index
using MomWorld.DataContexts; using MomWorld.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MomWorld.Controllers { public class HomeController : Controller { private ArticleDb articleDb = new ArticleDb(); private IdentityDb identityDb = new IdentityDb(); public ActionResult Index() { List<Article> articles = articleDb.Articles.OrderBy(art=>art.PostedDate).Take(5).ToList(); ViewData["Top5Articles"] = articles; if (User.Identity.IsAuthenticated) { var user = identityDb.Users.FirstOrDefault(u => u.UserName.Equals(User.Identity.Name)); ViewData["CurrentUser"] = user; } return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } [HttpPost] public void uploadnow(HttpPostedFileWrapper upload) { if (upload != null) { string ImageName = upload.FileName; string path = System.IO.Path.Combine(Server.MapPath("~/Images/uploads"), ImageName); upload.SaveAs(path); } } } }
using MomWorld.DataContexts; using MomWorld.Entities; using MomWorld.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MomWorld.Controllers { public class HomeController : Controller { private ArticleDb articleDb = new ArticleDb(); private IdentityDb identityDb = new IdentityDb(); public ActionResult Index() { List<Article> articles = articleDb.Articles.OrderBy(art=>art.PostedDate).Take(5).ToList(); ViewData["Top5Articles"] = articles; if (User.Identity.IsAuthenticated) { var user = identityDb.Users.FirstOrDefault(u => u.UserName.Equals(User.Identity.Name)); ViewData["CurrentUser"] = user; } else { //Fix sau ViewData["CurrentUser"] = new ApplicationUser(); } return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } [HttpPost] public void uploadnow(HttpPostedFileWrapper upload) { if (upload != null) { string ImageName = upload.FileName; string path = System.IO.Path.Combine(Server.MapPath("~/Images/uploads"), ImageName); upload.SaveAs(path); } } } }
Refactor Add Doubles Operation to use GetValues and CloneWithValues
namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AddDoubleDoubleOperation : IBinaryOperation<double, double, double> { public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2) { Tensor<double> result = new Tensor<double>(); result.SetValue(tensor1.GetValue() + tensor2.GetValue()); return result; } } }
namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AddDoubleDoubleOperation : IBinaryOperation<double, double, double> { public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2) { double[] values1 = tensor1.GetValues(); int l = values1.Length; double[] values2 = tensor2.GetValues(); double[] newvalues = new double[l]; for (int k = 0; k < l; k++) newvalues[k] = values1[k] + values2[k]; return tensor1.CloneWithNewValues(newvalues); } } }
Remove Obselete ViewModel Property for SendGrid Password
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Portal.CMS.Web.Areas.Admin.ViewModels.SettingManager { public class SetupViewModel { [Required] [DisplayName("Website Name")] public string WebsiteName { get; set; } [Required] [DisplayName("Website Description")] public string WebsiteDescription { get; set; } [DisplayName("Google Tracking Code")] public string GoogleAnalyticsId { get; set; } [DisplayName("Email From Address")] public string EmailFromAddress { get; set; } [DisplayName("SendGrid API Key")] public string SendGridApiKey { get; set; } [DisplayName("SendGrid Password")] public string SendGridPassword { get; set; } [DisplayName("CDN Address")] public string CDNAddress { get; set; } } }
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Portal.CMS.Web.Areas.Admin.ViewModels.SettingManager { public class SetupViewModel { [Required] [DisplayName("Website Name")] public string WebsiteName { get; set; } [Required] [DisplayName("Website Description")] public string WebsiteDescription { get; set; } [DisplayName("Google Tracking Code")] public string GoogleAnalyticsId { get; set; } [DisplayName("Email From Address")] public string EmailFromAddress { get; set; } [DisplayName("SendGrid API Key")] public string SendGridApiKey { get; set; } [DisplayName("CDN Address")] public string CDNAddress { get; set; } } }
Fix whitespace bug with dictionary support
using System; using System.IO; using System.Linq; using System.Text; namespace HandlebarsDotNet.Compiler.Lexer { internal class WordParser : Parser { private const string validWordStartCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$.@"; public override Token Parse(TextReader reader) { if (IsWord(reader)) { var buffer = AccumulateWord(reader); if (buffer.Contains("=")) { return Token.HashParameter(buffer); } else { return Token.Word(buffer); } } return null; } private bool IsWord(TextReader reader) { var peek = (char)reader.Peek(); return validWordStartCharacters.Contains(peek.ToString()); } private string AccumulateWord(TextReader reader) { StringBuilder buffer = new StringBuilder(); var inString = false; while (true) { if (!inString) { var peek = (char)reader.Peek(); if (peek == '}' || peek == '~' || peek == ')' || char.IsWhiteSpace(peek)) { break; } } var node = reader.Read(); if (node == -1) { throw new InvalidOperationException("Reached end of template before the expression was closed."); } if (node == '\'' || node == '"') { inString = !inString; } buffer.Append((char)node); } return buffer.ToString(); } } }
using System; using System.IO; using System.Linq; using System.Text; namespace HandlebarsDotNet.Compiler.Lexer { internal class WordParser : Parser { private const string validWordStartCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$.@[]"; public override Token Parse(TextReader reader) { if (IsWord(reader)) { var buffer = AccumulateWord(reader); if (buffer.Contains("=")) { return Token.HashParameter(buffer); } else { return Token.Word(buffer); } } return null; } private bool IsWord(TextReader reader) { var peek = (char)reader.Peek(); return validWordStartCharacters.Contains(peek.ToString()); } private string AccumulateWord(TextReader reader) { StringBuilder buffer = new StringBuilder(); var inString = false; while (true) { if (!inString) { var peek = (char)reader.Peek(); if (peek == '}' || peek == '~' || peek == ')' || (char.IsWhiteSpace(peek) && !buffer.ToString().Contains("["))) { break; } } var node = reader.Read(); if (node == -1) { throw new InvalidOperationException("Reached end of template before the expression was closed."); } if (node == '\'' || node == '"') { inString = !inString; } buffer.Append((char)node); } return buffer.ToString().Trim(); } } }
Enable Mongo entity auto-create and auto-ID
using System; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.IdGenerators; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver; using RightpointLabs.ConferenceRoom.Domain.Models; using RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Models; namespace RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Collections { public abstract class EntityCollectionDefinition<T> where T : Entity { protected EntityCollectionDefinition(IMongoConnectionHandler connectionHandler) { if (connectionHandler == null) throw new ArgumentNullException("connectionHandler"); // ReSharper disable once VirtualMemberCallInConstructor Collection = connectionHandler.Database.GetCollection<T>(CollectionName); // setup serialization if (!BsonClassMap.IsClassMapRegistered(typeof(Entity))) { try { BsonClassMap.RegisterClassMap<Entity>( cm => { cm.AutoMap(); cm.SetIdMember(cm.GetMemberMap(i => i.Id)); cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance).SetSerializer(new StringSerializer(BsonType.ObjectId)); }); } catch (ArgumentException) { // this fails with an argument exception at startup, but otherwise works fine. Probably should try to figure out why, but ignoring it is easier :( } } } public readonly MongoCollection<T> Collection; protected virtual string CollectionName => typeof(T).Name.Replace("Entity", "").ToLower() + "s"; } }
using System; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.IdGenerators; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver; using RightpointLabs.ConferenceRoom.Domain.Models; using RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Models; namespace RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Collections { public abstract class EntityCollectionDefinition<T> where T : Entity { protected EntityCollectionDefinition(IMongoConnectionHandler connectionHandler) { if (connectionHandler == null) throw new ArgumentNullException("connectionHandler"); // ReSharper disable once VirtualMemberCallInConstructor Collection = connectionHandler.Database.GetCollection<T>(CollectionName, new MongoCollectionSettings() { AssignIdOnInsert = true}); // setup serialization if (!BsonClassMap.IsClassMapRegistered(typeof(Entity))) { if (!Collection.Exists()) { // ReSharper disable once VirtualMemberCallInConstructor Collection.Database.CreateCollection(CollectionName); } try { BsonClassMap.RegisterClassMap<Entity>( cm => { cm.AutoMap(); cm.SetIdMember(cm.GetMemberMap(i => i.Id)); cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance).SetSerializer(new StringSerializer(BsonType.ObjectId)); }); } catch (ArgumentException) { // this fails with an argument exception at startup, but otherwise works fine. Probably should try to figure out why, but ignoring it is easier :( } } } public readonly MongoCollection<T> Collection; protected virtual string CollectionName => typeof(T).Name.Replace("Entity", "").ToLower() + "s"; } }
Add damage capabilities to the enemy
using UnityEngine; public class AttackHandler : MonoBehaviour { [HideInInspector] public float damage; [HideInInspector] public float duration; [HideInInspector] public BoxCollider hitBox; private float timer = 0f; void Start() { hitBox = gameObject.GetComponent<BoxCollider>(); } void Update() { timer += Time.deltaTime; if(timer >= duration) { timer = 0f; hitBox.enabled = false; } } void OnTriggerEnter(Collider other) { bool isPlayer = other.GetComponent<Collider>().CompareTag("Player"); if(isPlayer) { // Debug.Log("ATTACK"); } } }
using UnityEngine; public class AttackHandler : MonoBehaviour { [HideInInspector] public float damage; [HideInInspector] public float duration; [HideInInspector] public BoxCollider hitBox; private float timer = 0f; void Start() { hitBox = gameObject.GetComponent<BoxCollider>(); } void Update() { timer += Time.deltaTime; if(timer >= duration) { timer = 0f; hitBox.enabled = false; } } void OnTriggerEnter(Collider other) { bool isPlayer = other.GetComponent<Collider>().CompareTag("Player"); if(isPlayer) { other.gameObject.GetComponent<CharacterStatus>().life.decrease(damage); } } }
Split CheckBox test into two, give better name.
using NUnit.Framework; using tungsten.core.Elements; using tungsten.core.Search; using tungsten.nunit; namespace tungsten.sampletest { [TestFixture] public class CheckBoxTest : TestBase { [Test] public void Hupp() { var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain")); var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff")); checkBox.AssertThat(x => x.IsChecked(), Is.True); checkBox.Click(); checkBox.AssertThat(x => x.IsChecked(), Is.False); } } }
using NUnit.Framework; using tungsten.core.Elements; using tungsten.core.Search; using tungsten.nunit; namespace tungsten.sampletest { [TestFixture] public class CheckBoxTest : TestBase { [Test] public void CheckBoxIsChecked() { var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain")); var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff")); checkBox.AssertThat(x => x.IsChecked(), Is.True); checkBox.Click(); checkBox.AssertThat(x => x.IsChecked(), Is.False); } [Test] public void CheckBoxChangeIsChecked() { var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain")); var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff")); checkBox.Click(); checkBox.AssertThat(x => x.IsChecked(), Is.False); } } }
Revert Strip large data values out of events
using System; using System.Collections.Generic; using Exceptionless.Core.Pipeline; using Exceptionless.Core.Extensions; using Exceptionless.Core.Models; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Linq; using Microsoft.Extensions.Logging; namespace Exceptionless.Core.Plugins.EventParser { [Priority(0)] public class JsonEventParserPlugin : PluginBase, IEventParserPlugin { private readonly JsonSerializerSettings _settings; private readonly JsonSerializer _serializer; public JsonEventParserPlugin(IOptions<AppOptions> options, JsonSerializerSettings settings) : base(options) { _settings = settings; _serializer = JsonSerializer.CreateDefault(_settings); } public List<PersistentEvent> ParseEvents(string input, int apiVersion, string userAgent) { if (apiVersion < 2) return null; var events = new List<PersistentEvent>(); var reader = new JsonTextReader(new StringReader(input)); reader.DateParseHandling = DateParseHandling.None; while (reader.Read()) { if (reader.TokenType == JsonToken.StartObject) { var ev = JToken.ReadFrom(reader); var data = ev["data"]; if (data != null) { foreach (var property in data.Children<JProperty>()) { // strip out large data entries if (property.Value.ToString().Length > 50000) { property.Value = "(Data Too Large)"; } } } try { events.Add(ev.ToObject<PersistentEvent>(_serializer)); } catch (Exception ex) { _logger.LogError(ex, "Error deserializing event."); } } } return events.Count > 0 ? events : null; } } }
using System; using System.Collections.Generic; using Exceptionless.Core.Pipeline; using Exceptionless.Core.Extensions; using Exceptionless.Core.Models; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Exceptionless.Core.Plugins.EventParser { [Priority(0)] public class JsonEventParserPlugin : PluginBase, IEventParserPlugin { private readonly JsonSerializerSettings _settings; public JsonEventParserPlugin(IOptions<AppOptions> options, JsonSerializerSettings settings) : base(options) { _settings = settings; } public List<PersistentEvent> ParseEvents(string input, int apiVersion, string userAgent) { if (apiVersion < 2) return null; var events = new List<PersistentEvent>(); switch (input.GetJsonType()) { case JsonType.Object: { if (input.TryFromJson(out PersistentEvent ev, _settings)) events.Add(ev); break; } case JsonType.Array: { if (input.TryFromJson(out PersistentEvent[] parsedEvents, _settings)) events.AddRange(parsedEvents); break; } } return events.Count > 0 ? events : null; } } }
Update the mask check in the Bit() extension method
namespace elbsms_core { internal static class Extensions { internal static bool Bit(this byte v, int bit) { int mask = 1 << bit; return (v & mask) == mask; } internal static bool Bit(this int v, int bit) { int mask = 1 << bit; return (v & mask) == mask; } internal static bool EvenParity(this int v) { v ^= v >> 4; v ^= v >> 2; v ^= v >> 1; return (v & 1) != 1; } } }
namespace elbsms_core { internal static class Extensions { internal static bool Bit(this byte v, int bit) { int mask = 1 << bit; return (v & mask) != 0; } internal static bool Bit(this int v, int bit) { int mask = 1 << bit; return (v & mask) != 0; } internal static bool EvenParity(this int v) { v ^= v >> 4; v ^= v >> 2; v ^= v >> 1; return (v & 1) != 1; } } }
Move to .NET Standard - cleanup
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using SoundCloud.Api; using SoundCloud.Api.Entities; using SoundCloud.Api.Entities.Enums; using SoundCloud.Api.QueryBuilders; namespace ConsoleApp { internal static class Program { private static async Task Main(string[] args) { var serviceCollection = new ServiceCollection(); serviceCollection.AddSoundCloudClient(string.Empty, args[0]); using (var provider = serviceCollection.BuildServiceProvider()) { var client = provider.GetService<SoundCloudClient>(); var entity = await client.Resolve.GetEntityAsync("https://soundcloud.com/diplo"); if (entity.Kind != Kind.User) { Console.WriteLine("Couldn't resolve account of diplo"); return; } var diplo = entity as User; Console.WriteLine($"Found: {diplo.Username} @ {diplo.PermalinkUrl}"); var tracks = await client.Users.GetTracksAsync(diplo, 10); Console.WriteLine(); Console.WriteLine("Latest 10 Tracks:"); foreach (var track in tracks) { Console.WriteLine(track.Title); } var majorLazerResults = await client.Tracks.GetAllAsync(new TrackQueryBuilder { SearchString = "Major Lazer", Limit = 10 }); Console.WriteLine(); Console.WriteLine("Found Major Lazer Tracks:"); foreach (var track in majorLazerResults) { Console.WriteLine(track.Title); } } } } }
using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using SoundCloud.Api; using SoundCloud.Api.Entities; using SoundCloud.Api.Entities.Enums; using SoundCloud.Api.QueryBuilders; namespace ConsoleApp { internal static class Program { private static async Task Main(string[] args) { var serviceCollection = new ServiceCollection(); serviceCollection.AddSoundCloudClient(string.Empty, args[0]); using (var provider = serviceCollection.BuildServiceProvider()) { var client = provider.GetService<SoundCloudClient>(); var entity = await client.Resolve.GetEntityAsync("https://soundcloud.com/diplo"); if (entity.Kind != Kind.User) { Console.WriteLine("Couldn't resolve account of diplo"); return; } var diplo = entity as User; Console.WriteLine($"Found: {diplo.Username} @ {diplo.PermalinkUrl}"); var tracks = await client.Users.GetTracksAsync(diplo, 10); Console.WriteLine(); Console.WriteLine("Latest 10 Tracks:"); foreach (var track in tracks) { Console.WriteLine(track.Title); } var majorLazerResults = await client.Tracks.GetAllAsync(new TrackQueryBuilder { SearchString = "Major Lazer", Limit = 10 }); Console.WriteLine(); Console.WriteLine("Found Major Lazer Tracks:"); foreach (var track in majorLazerResults) { Console.WriteLine(track.Title); } } } } }
Add some settings to bugsnag
using Bugsnag; using Bugsnag.Clients; using EarTrumpet.Extensions; using System; using System.Diagnostics; using System.IO; using Windows.ApplicationModel; namespace EarTrumpet.Services { class ErrorReportingService { internal static void Initialize() { try { #if DEBUG WPFClient.Config.ApiKey = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\eartrumpet.bugsnag.apikey"); #endif WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal"; WPFClient.Start(); WPFClient.Config.BeforeNotify(OnBeforeNotify); } catch (Exception ex) { Trace.WriteLine(ex); } } private static bool OnBeforeNotify(Event error) { error.Metadata.AddToTab("Device", "machineName", "<redacted>"); error.Metadata.AddToTab("Device", "hostname", "<redacted>"); return true; } } }
using Bugsnag; using Bugsnag.Clients; using EarTrumpet.Extensions; using EarTrumpet.Misc; using System; using System.Diagnostics; using System.IO; using Windows.ApplicationModel; namespace EarTrumpet.Services { class ErrorReportingService { internal static void Initialize() { try { #if DEBUG WPFClient.Config.ApiKey = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\eartrumpet.bugsnag.apikey"); #endif WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal"; WPFClient.Start(); WPFClient.Config.BeforeNotify(OnBeforeNotify); } catch (Exception ex) { Trace.WriteLine(ex); } } private static bool OnBeforeNotify(Event error) { // Remove default metadata we don't need nor want. error.Metadata.AddToTab("Device", "machineName", "<redacted>"); error.Metadata.AddToTab("Device", "hostname", "<redacted>"); error.Metadata.AddToTab("AppSettings", "IsLightTheme", GetNoError(() => SystemSettings.IsLightTheme)); error.Metadata.AddToTab("AppSettings", "IsRTL", GetNoError(() => SystemSettings.IsRTL)); error.Metadata.AddToTab("AppSettings", "IsTransparencyEnabled", GetNoError(() => SystemSettings.IsTransparencyEnabled)); error.Metadata.AddToTab("AppSettings", "UseAccentColor", GetNoError(() => SystemSettings.UseAccentColor)); return true; } private static string GetNoError(Func<object> get) { try { var ret = get(); return ret == null ? "null" : ret.ToString(); } catch (Exception ex) { return $"{ex}"; } } } }
Change type of MaximumBytesPerSec to long
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using MetroTrilithon.Serialization; namespace TirkxDownloader.Models.Settings { public class DownloadingSetting { public static SerializableProperty<int> MaximumBytesPerSec { get; } = new SerializableProperty<int>(GetKey(), SettingsProviders.Local, 0); public static SerializableProperty<byte> MaxConcurrentDownload { get; } = new SerializableProperty<byte>(GetKey(), SettingsProviders.Local, 1); private static string GetKey([CallerMemberName] string caller = "") { return nameof(DownloadingSetting) + "." + caller; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using MetroTrilithon.Serialization; namespace TirkxDownloader.Models.Settings { public class DownloadingSetting { public static SerializableProperty<long> MaximumBytesPerSec { get; } = new SerializableProperty<long>(GetKey(), SettingsProviders.Local, 0); public static SerializableProperty<byte> MaxConcurrentDownload { get; } = new SerializableProperty<byte>(GetKey(), SettingsProviders.Local, 1); private static string GetKey([CallerMemberName] string caller = "") { return nameof(DownloadingSetting) + "." + caller; } } }
Add timeout to decoration etl-run
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; using NBi.Core.Etl; using NBi.Xml.Items; namespace NBi.Xml.Decoration.Command { public class EtlRunXml : DecorationCommandXml, IEtlRunCommand { [XmlAttribute("server")] public string Server { get; set; } [XmlAttribute("path")] public string Path { get; set; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("username")] public string UserName { get; set; } [XmlAttribute("password")] public string Password { get; set; } [XmlAttribute("catalog")] public string Catalog { get; set; } [XmlAttribute("folder")] public string Folder { get; set; } [XmlAttribute("project")] public string Project { get; set; } [XmlAttribute("bits-32")] public bool Is32Bits { get; set; } [XmlIgnore] public List<EtlParameter> Parameters { get { return InternalParameters.ToList<EtlParameter>(); } set { throw new NotImplementedException(); } } [XmlElement("parameter")] public List<EtlParameterXml> InternalParameters { get; set; } public EtlRunXml() { InternalParameters = new List<EtlParameterXml>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; using NBi.Core.Etl; using NBi.Xml.Items; namespace NBi.Xml.Decoration.Command { public class EtlRunXml : DecorationCommandXml, IEtlRunCommand { [XmlAttribute("server")] public string Server { get; set; } [XmlAttribute("path")] public string Path { get; set; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("username")] public string UserName { get; set; } [XmlAttribute("password")] public string Password { get; set; } [XmlAttribute("catalog")] public string Catalog { get; set; } [XmlAttribute("folder")] public string Folder { get; set; } [XmlAttribute("project")] public string Project { get; set; } [XmlAttribute("bits-32")] public bool Is32Bits { get; set; } [XmlAttribute("timeout")] public int Timeout { get; set; } [XmlIgnore] public List<EtlParameter> Parameters { get { return InternalParameters.ToList<EtlParameter>(); } set { throw new NotImplementedException(); } } [XmlElement("parameter")] public List<EtlParameterXml> InternalParameters { get; set; } public EtlRunXml() { InternalParameters = new List<EtlParameterXml>(); } } }