Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Remove ConcurrentQueue wrapper around input enumerable and just iterate it directly in the Run method | using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
namespace BulkWriter.Pipeline.Internal
{
internal class StartEtlPipelineStep<TIn> : EtlPipelineStep<TIn, TIn>
{
public StartEtlPipelineStep(EtlPipelineContext pipelineContext, IEnumerable<TIn> enumerable) : base(pipelineContext, new BlockingCollection<TIn>(new ConcurrentQueue<TIn>(enumerable)))
{
}
public override void Run(CancellationToken cancellationToken)
{
var enumerable = InputCollection.GetConsumingEnumerable(cancellationToken);
RunSafely(() =>
{
foreach (var item in enumerable)
{
OutputCollection.Add(item, cancellationToken);
}
});
}
}
} | using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
namespace BulkWriter.Pipeline.Internal
{
internal class StartEtlPipelineStep<TIn> : EtlPipelineStep<TIn, TIn>
{
private readonly IEnumerable<TIn> _inputEnumerable;
public StartEtlPipelineStep(EtlPipelineContext pipelineContext, IEnumerable<TIn> inputEnumerable) : base(pipelineContext, new BlockingCollection<TIn>())
{
_inputEnumerable = inputEnumerable;
}
public override void Run(CancellationToken cancellationToken)
{
RunSafely(() =>
{
foreach (var item in _inputEnumerable)
{
OutputCollection.Add(item, cancellationToken);
}
});
}
}
} |
Add all opcodes to the enum | namespace Mos6510.Instructions
{
public enum Opcode
{
Inx,
Iny,
Nop,
And,
Ora,
Eor,
Adc,
Clc,
Lda,
Sbc,
Sta,
Ldx,
Ldy,
}
}
| namespace Mos6510.Instructions
{
public enum Opcode
{
Adc, // Add Memory to Accumulator with Carry
And, // "AND" Memory with Accumulator
Asl, // Shift Left One Bit (Memory or Accumulator)
Bcc, // Branch on Carry Clear
Bcs, // Branch on Carry Set
Beq, // Branch on Result Zero
Bit, // Test Bits in Memory with Accumulator
Bmi, // Branch on Result Minus
Bne, // Branch on Result not Zero
Bpl, // Branch on Result Plus
Brk, // Force Break
Bvc, // Branch on Overflow Clear
Bvs, // Branch on Overflow Set
Clc, // Clear Carry Flag
Cld, // Clear Decimal Mode
Cli, // Clear interrupt Disable Bit
Clv, // Clear Overflow Flag
Cmp, // Compare Memory and Accumulator
Cpx, // Compare Memory and Index X
Cpy, // Compare Memory and Index Y
Dec, // Decrement Memory by One
Dex, // Decrement Index X by One
Dey, // Decrement Index Y by One
Eor, // "Exclusive-Or" Memory with Accumulator
Inc, // Increment Memory by One
Inx, // Increment Index X by One
Iny, // Increment Index Y by One
Jmp, // Jump to New Location
Jsr, // Jump to New Location Saving Return Address
Lda, // Load Accumulator with Memory
Ldx, // Load Index X with Memory
Ldy, // Load Index Y with Memory
Lsr, // Shift Right One Bit (Memory or Accumulator)
Nop, // No Operation
Ora, // "OR" Memory with Accumulator
Pha, // Push Accumulator on Stack
Php, // Push Processor Status on Stack
Pla, // Pull Accumulator from Stack
Plp, // Pull Processor Status from Stack
Rol, // Rotate One Bit Left (Memory or Accumulator)
Ror, // Rotate One Bit Right (Memory or Accumulator)
Rti, // Return from Interrupt
Rts, // Return from Subroutine
Sbc, // Subtract Memory from Accumulator with Borrow
Sec, // Set Carry Flag
Sed, // Set Decimal Mode
Sei, // Set Interrupt Disable Status
Sta, // Store Accumulator in Memory
Stx, // Store Index X in Memory
Sty, // Store Index Y in Memory
Tax, // Transfer Accumulator to Index X
Tay, // Transfer Accumulator to Index Y
Tsx, // Transfer Stack Pointer to Index X
Txa, // Transfer Index X to Accumulator
Txs, // Transfer Index X to Stack Pointer
Tya, // Transfer Index Y to Accumulator
}
}
|
Fix wrong json key of WeekdayOfMonth property. | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Omise.Models
{
public class ScheduleOnRequest : Request
{
[JsonProperty("weekdays")]
public Weekdays[] Weekdays { get; set; }
[JsonProperty("days_of_month")]
public int[] DaysOfMonth { get; set; }
[JsonProperty("weekdays_of_month")]
public String WeekdayOfMonth { get; set; }
}
public class CreateScheduleRequest : Request
{
public int Every { get; set; }
public SchedulePeriod Period { get; set; }
public ScheduleOnRequest On { get; set; }
[JsonProperty("start_date")]
public DateTime? StartDate { get; set; }
[JsonProperty("end_date")]
public DateTime? EndDate { get; set; }
public ChargeScheduling Charge { get; set; }
public TransferScheduling Transfer { get; set; }
public CreateScheduleRequest()
{
On = new ScheduleOnRequest();
}
}
}
| using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Omise.Models
{
public class ScheduleOnRequest : Request
{
[JsonProperty("weekdays")]
public Weekdays[] Weekdays { get; set; }
[JsonProperty("days_of_month")]
public int[] DaysOfMonth { get; set; }
[JsonProperty("weekday_of_month")]
public String WeekdayOfMonth { get; set; }
}
public class CreateScheduleRequest : Request
{
public int Every { get; set; }
public SchedulePeriod Period { get; set; }
public ScheduleOnRequest On { get; set; }
[JsonProperty("start_date")]
public DateTime? StartDate { get; set; }
[JsonProperty("end_date")]
public DateTime? EndDate { get; set; }
public ChargeScheduling Charge { get; set; }
public TransferScheduling Transfer { get; set; }
public CreateScheduleRequest()
{
On = new ScheduleOnRequest();
}
}
}
|
Make ExcludeFromCodeCoverage compatibility stub internal | #if NET35 || UAP
using System;
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
public class ExcludeFromCodeCoverageAttribute : Attribute
{
}
}
#endif | #if NET35 || UAP
using System;
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
internal class ExcludeFromCodeCoverageAttribute : Attribute
{
}
}
#endif |
Disable EF Core transaction test. | using System;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.Tests.Domain;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
namespace Abp.EntityFrameworkCore.Tests
{
public class Transaction_Tests : EntityFrameworkCoreModuleTestBase
{
private readonly IUnitOfWorkManager _uowManager;
private readonly IRepository<Blog> _blogRepository;
public Transaction_Tests()
{
_uowManager = Resolve<IUnitOfWorkManager>();
_blogRepository = Resolve<IRepository<Blog>>();
}
[Fact]
public async Task Should_Rollback_Transaction_On_Failure()
{
const string exceptionMessage = "This is a test exception!";
var blogName = Guid.NewGuid().ToString("N");
try
{
using (_uowManager.Begin())
{
await _blogRepository.InsertAsync(
new Blog(blogName, $"http://{blogName}.com/")
);
throw new ApplicationException(exceptionMessage);
}
}
catch (ApplicationException ex) when (ex.Message == exceptionMessage)
{
}
await UsingDbContextAsync(async context =>
{
var blog = await context.Blogs.FirstOrDefaultAsync(b => b.Name == blogName);
blog.ShouldNotBeNull();
});
}
}
} | using System;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.Tests.Domain;
using Microsoft.EntityFrameworkCore;
using Shouldly;
namespace Abp.EntityFrameworkCore.Tests
{
//WE CAN NOT TEST TRANSACTIONS SINCE INMEMORY DB DOES NOT SUPPORT IT! TODO: Use SQLite
public class Transaction_Tests : EntityFrameworkCoreModuleTestBase
{
private readonly IUnitOfWorkManager _uowManager;
private readonly IRepository<Blog> _blogRepository;
public Transaction_Tests()
{
_uowManager = Resolve<IUnitOfWorkManager>();
_blogRepository = Resolve<IRepository<Blog>>();
}
//[Fact]
public async Task Should_Rollback_Transaction_On_Failure()
{
const string exceptionMessage = "This is a test exception!";
var blogName = Guid.NewGuid().ToString("N");
try
{
using (_uowManager.Begin())
{
await _blogRepository.InsertAsync(
new Blog(blogName, $"http://{blogName}.com/")
);
throw new ApplicationException(exceptionMessage);
}
}
catch (ApplicationException ex) when (ex.Message == exceptionMessage)
{
}
await UsingDbContextAsync(async context =>
{
var blog = await context.Blogs.FirstOrDefaultAsync(b => b.Name == blogName);
blog.ShouldNotBeNull();
});
}
}
} |
Make card image types optional | using Newtonsoft.Json;
namespace Alexa.NET.Response
{
public class CardImage
{
[JsonProperty("smallImageUrl")]
[JsonRequired]
public string SmallImageUrl { get; set; }
[JsonProperty("largeImageUrl")]
[JsonRequired]
public string LargeImageUrl { get; set; }
}
}
| using Newtonsoft.Json;
namespace Alexa.NET.Response
{
public class CardImage
{
[JsonProperty("smallImageUrl",NullValueHandling = NullValueHandling.Ignore)]
public string SmallImageUrl { get; set; }
[JsonProperty("largeImageUrl", NullValueHandling = NullValueHandling.Ignore)]
public string LargeImageUrl { get; set; }
}
}
|
Fix typo in Asp.Net 4.5 Sample app (Simple4) | @{
ViewBag.Title = "Configuration Settings for Spring Cloud Config Server";
}
<h2>@ViewBag.Title.</h2>
<h4>spring:cloud:config:enabled = @ViewBag.Enabled</h4>
<h4>spring:cloud:config:env = @ViewBag.Environment</h4>
<h4>spring:cloud:config:failFast = @ViewBag,FailFast</h4>
<h4>spring:cloud:config:name = @ViewBag.Name</h4>
<h4>spring:cloud:config:label = @ViewBag.Label</h4>
<h4>spring:cloud:config:username = @ViewBag.Username</h4>
<h4>spring:cloud:config:password = @ViewBag.Password</h4>
<h4>spring:cloud:config:validate_certificates = @ViewBag.ValidateCertificates</h4>
| @{
ViewBag.Title = "Configuration Settings for Spring Cloud Config Server";
}
<h2>@ViewBag.Title.</h2>
<h4>spring:cloud:config:enabled = @ViewBag.Enabled</h4>
<h4>spring:cloud:config:env = @ViewBag.Environment</h4>
<h4>spring:cloud:config:failFast = @ViewBag.FailFast</h4>
<h4>spring:cloud:config:name = @ViewBag.Name</h4>
<h4>spring:cloud:config:label = @ViewBag.Label</h4>
<h4>spring:cloud:config:username = @ViewBag.Username</h4>
<h4>spring:cloud:config:password = @ViewBag.Password</h4>
<h4>spring:cloud:config:validate_certificates = @ViewBag.ValidateCertificates</h4>
|
Introduce Null Argument check if context is null on RequestIgnorerManager | using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Http;
namespace Glimpse.Agent.Web
{
public class DefaultRequestIgnorerManager : IRequestIgnorerManager
{
public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor)
{
RequestIgnorers = requestIgnorerProvider.Instances;
HttpContextAccessor = httpContextAccessor;
}
private IEnumerable<IRequestIgnorer> RequestIgnorers { get; }
private IHttpContextAccessor HttpContextAccessor { get; }
public bool ShouldIgnore()
{
return ShouldIgnore(HttpContextAccessor.HttpContext);
}
public bool ShouldIgnore(HttpContext context)
{
if (RequestIgnorers.Any())
{
foreach (var policy in RequestIgnorers)
{
if (policy.ShouldIgnore(context))
{
return true;
}
}
}
return false;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Http;
namespace Glimpse.Agent.Web
{
public class DefaultRequestIgnorerManager : IRequestIgnorerManager
{
public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor)
{
RequestIgnorers = requestIgnorerProvider.Instances;
HttpContextAccessor = httpContextAccessor;
}
private IEnumerable<IRequestIgnorer> RequestIgnorers { get; }
private IHttpContextAccessor HttpContextAccessor { get; }
public bool ShouldIgnore()
{
return ShouldIgnore(HttpContextAccessor.HttpContext);
}
public bool ShouldIgnore(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (RequestIgnorers.Any())
{
foreach (var policy in RequestIgnorers)
{
if (policy.ShouldIgnore(context))
{
return true;
}
}
}
return false;
}
}
} |
Fix AutomapHelper to only return assemblies decorated with IgnitionAutomapAttribute | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Ignition.Foundation.Core.Automap
{
public static class IgnitionAutomapHelper
{
public static IEnumerable<Assembly> GetAutomappedAssemblies()
{
var automappedAssemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Select(Assembly.Load).ToList();
// load possible standalone assemblies
automappedAssemblies.AddRange(AppDomain.CurrentDomain.GetAssemblies()
.Where(IsAutomappedAssembly)
.Where(a => !automappedAssemblies.Contains(a))
.Select(a => Assembly.Load(a.FullName)));
return automappedAssemblies.ToList();
}
public static IEnumerable<Assembly> GetAutomappedAssembliesInCurrentDomain()
{
var automappedAssemblies = AppDomain.CurrentDomain.GetAssemblies()
.Where(IsAutomappedAssembly)
.Select(a => Assembly.Load(a.FullName));
return automappedAssemblies.ToList();
}
public static bool IsAutomappedAssembly(Assembly assembly)
{
return assembly.GetCustomAttributes(typeof(IgnitionAutomapAttribute)).Any();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Ignition.Foundation.Core.Automap
{
public static class IgnitionAutomapHelper
{
public static IEnumerable<Assembly> GetAutomappedAssemblies()
{
var automappedAssemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies()
.Select(Assembly.Load)
.Where(IsAutomappedAssembly)
.ToList();
// load possible standalone assemblies
automappedAssemblies.AddRange(AppDomain.CurrentDomain.GetAssemblies()
.Where(IsAutomappedAssembly)
.Where(a => !automappedAssemblies.Contains(a))
.Select(a => Assembly.Load(a.FullName)));
return automappedAssemblies.ToList();
}
public static IEnumerable<Assembly> GetAutomappedAssembliesInCurrentDomain()
{
var automappedAssemblies = AppDomain.CurrentDomain.GetAssemblies()
.Where(IsAutomappedAssembly)
.Select(a => Assembly.Load(a.FullName));
return automappedAssemblies.ToList();
}
public static bool IsAutomappedAssembly(Assembly assembly)
{
return assembly.GetCustomAttributes(typeof(IgnitionAutomapAttribute)).Any();
}
}
}
|
Fix delay bug on resetting | using UnityEngine;
public class GameController : MonoBehaviour
{
GlobalGame game;
public float previewTime, previewTimer, confirmTime, confirmTimer;
public GlobalGame Game
{
get { return game; }
set { game = value; }
}
public void Confirm()
{
game.Confirm();
}
public void Undo()
{
game.Undo();
}
public void Redo()
{
game.Redo();
}
public void Reset()
{
GetComponent<GameInitialization>().ResetGame();
}
void Update()
{
if (game.ActivePlayer() is AI && !game.GameOver())
{
if(game.HasNextMove)
{
if (confirmTimer <= 0)
{
Game.Confirm();
confirmTimer = confirmTime;
return;
}
else
{
confirmTimer -= Time.deltaTime;
return;
}
}
else
{
if (previewTimer <= 0)
{
Game.Preview(((AI)game.ActivePlayer()).BestMove());
previewTimer = previewTime;
return;
}
else
{
previewTimer -= Time.deltaTime;
return;
}
}
}
else
{
confirmTimer = confirmTime;
previewTimer = previewTime;
}
}
}
| using UnityEngine;
public class GameController : MonoBehaviour
{
GlobalGame game;
public float previewTime, previewTimer, confirmTime, confirmTimer;
public GlobalGame Game
{
get { return game; }
set { game = value; }
}
public void Confirm()
{
game.Confirm();
}
public void Undo()
{
game.Undo();
}
public void Redo()
{
game.Redo();
}
public void Reset()
{
confirmTimer = confirmTime;
previewTimer = previewTime;
GetComponent<GameInitialization>().ResetGame();
}
void Update()
{
if (game.ActivePlayer() is AI && !game.GameOver())
{
if(game.HasNextMove)
{
if (confirmTimer <= 0)
{
Game.Confirm();
confirmTimer = confirmTime;
return;
}
else
{
confirmTimer -= Time.deltaTime;
return;
}
}
else
{
if (previewTimer <= 0)
{
Game.Preview(((AI)game.ActivePlayer()).BestMove());
previewTimer = previewTime;
return;
}
else
{
previewTimer -= Time.deltaTime;
return;
}
}
}
else
{
confirmTimer = confirmTime;
previewTimer = previewTime;
}
}
}
|
Add comments, better error handling to new class. | using System;
using System.Threading.Tasks;
using System.Xml.Serialization;
using LtiLibrary.Core.Outcomes.v1;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.IO;
namespace LtiLibrary.AspNet.Outcomes.v1
{
public class ImsxXmlMediaTypeModelBinder : IModelBinder
{
private static readonly XmlSerializer ImsxRequestSerializer = new XmlSerializer(typeof(imsx_POXEnvelopeType),
null, null, new XmlRootAttribute("imsx_POXEnvelopeRequest"),
"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0");
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext));
using (var reader = new StreamReader(bindingContext.HttpContext.Request.Body))
{
var model = ImsxRequestSerializer.Deserialize(reader);
bindingContext.Result = ModelBindingResult.Success(model);
}
return null;
}
}
}
| using LtiLibrary.Core.Outcomes.v1;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace LtiLibrary.AspNet.Outcomes.v1
{
/// <summary>
/// Use this ModelBinder to deserialize imsx_POXEnvelopeRequest XML. For example,
/// <code>public ImsxXmlMediaTypeResult Post([ModelBinder(BinderType = typeof(ImsxXmlMediaTypeModelBinder))] imsx_POXEnvelopeType request)</code>
/// </summary>
public class ImsxXmlMediaTypeModelBinder : IModelBinder
{
private static readonly XmlSerializer ImsxRequestSerializer = new XmlSerializer(typeof(imsx_POXEnvelopeType),
null, null, new XmlRootAttribute("imsx_POXEnvelopeRequest"),
"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0");
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext));
if (bindingContext.HttpContext?.Request == null || !bindingContext.HttpContext.Request.ContentType.Equals("application/xml"))
{
bindingContext.Result = ModelBindingResult.Failed();
}
else
{
try
{
using (var reader = new StreamReader(bindingContext.HttpContext.Request.Body))
{
var model = ImsxRequestSerializer.Deserialize(reader);
bindingContext.Result = ModelBindingResult.Success(model);
}
}
catch
{
bindingContext.Result = ModelBindingResult.Failed();
}
}
return null;
}
}
}
|
Use more appropriate exception (can also never happen - JSON.NET uses the CanWrite property). | using System;
using Lloyd.AzureMailGateway.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Lloyd.AzureMailGateway.Core.JsonConverters
{
public class AddressConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => (objectType == typeof(Address));
public override bool CanWrite
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jobject = JObject.Load(reader);
var email = (string)jobject["eMail"];
var name = (string)jobject["name"];
return new Address(email, name);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
=> throw new NotImplementedException();
}
} | using System;
using Lloyd.AzureMailGateway.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Lloyd.AzureMailGateway.Core.JsonConverters
{
public class AddressConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => (objectType == typeof(Address));
public override bool CanWrite
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jobject = JObject.Load(reader);
var email = (string)jobject["eMail"];
var name = (string)jobject["name"];
return new Address(email, name);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
=> throw new InvalidOperationException("AddressConverter is for read only usage.");
}
} |
Add a rotating box for indication of a good game template state | // 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;
namespace TemplateGame.Game
{
public class TemplateGameGame : osu.Framework.Game
{
[BackgroundDependencyLoader]
private void load()
{
// Add your game components here
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osuTK;
using osuTK.Graphics;
namespace TemplateGame.Game
{
public class TemplateGameGame : osu.Framework.Game
{
private Box box;
[BackgroundDependencyLoader]
private void load()
{
// Add your game components here.
// The rotating box can be removed.
Child = box = new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Colour = Color4.Orange,
Size = new Vector2(200),
};
box.Loop(b => b.RotateTo(0).RotateTo(360, 2500));
}
}
}
|
Fix the subscription drop script | using System.IO;
using NServiceBus.Persistence.Sql.ScriptBuilder;
class SubscriptionWriter
{
public static void WriteSubscriptionScript(string scriptPath, BuildSqlDialect sqlDialect)
{
var createPath = Path.Combine(scriptPath, "Subscription_Create.sql");
File.Delete(createPath);
using (var writer = File.CreateText(createPath))
{
SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect);
}
var dropPath = Path.Combine(scriptPath, "Subscription_Drop.sql");
File.Delete(dropPath);
using (var writer = File.CreateText(dropPath))
{
SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect);
}
}
} | using System.IO;
using NServiceBus.Persistence.Sql.ScriptBuilder;
class SubscriptionWriter
{
public static void WriteSubscriptionScript(string scriptPath, BuildSqlDialect sqlDialect)
{
var createPath = Path.Combine(scriptPath, "Subscription_Create.sql");
File.Delete(createPath);
using (var writer = File.CreateText(createPath))
{
SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect);
}
var dropPath = Path.Combine(scriptPath, "Subscription_Drop.sql");
File.Delete(dropPath);
using (var writer = File.CreateText(dropPath))
{
SubscriptionScriptBuilder.BuildDropScript(writer, sqlDialect);
}
}
} |
Make sure we receive a meaningful response | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NFluent;
using NUnit.Framework;
namespace AppVeyorServices.IntegrationTests
{
[TestFixture]
public class AppVeyorGatewayTests
{
[Test]
public void GetProjects_Always_ReturnsListOfProjects()
{
var apiToken = System.Configuration.ConfigurationManager.AppSettings["ApiKey"];
var gateway = new AppVeyorGateway(apiToken);
var projects = gateway.GetProjects();
Check.That(projects).IsNotNull();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NFluent;
using NUnit.Framework;
namespace AppVeyorServices.IntegrationTests
{
[TestFixture]
public class AppVeyorGatewayTests
{
[Test]
public void GetProjects_Always_ReturnsListOfProjects()
{
var apiToken = System.Configuration.ConfigurationManager.AppSettings["ApiKey"];
var gateway = new AppVeyorGateway(apiToken);
var projects = gateway.GetProjects();
Check.That(projects).IsNotNull();
var project = projects[0];
Check.That(project.Name).IsNotNull();
Check.That(project.Slug).IsNotNull();
}
}
}
|
Add a blank line test | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASPVariables
{
public partial class SessionResultsPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblResults.Text = (string)(Session["FirstName"]);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASPVariables
{
public partial class SessionResultsPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblResults.Text = (string)(Session["FirstName"]);
}
}
} |
Add setting to bypass front-to-back | // 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.Configuration;
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings.Sections.Debug
{
public class GeneralSettings : SettingsSubsection
{
protected override string Header => "General";
[BackgroundDependencyLoader]
private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig)
{
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = "Show log overlay",
Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay)
},
new SettingsCheckbox
{
LabelText = "Performance logging",
Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.PerformanceLogging)
},
new SettingsCheckbox
{
LabelText = "Bypass caching (slow)",
Bindable = config.GetBindable<bool>(DebugSetting.BypassCaching)
},
};
}
}
}
| // 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.Configuration;
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings.Sections.Debug
{
public class GeneralSettings : SettingsSubsection
{
protected override string Header => "General";
[BackgroundDependencyLoader]
private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig)
{
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = "Show log overlay",
Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay)
},
new SettingsCheckbox
{
LabelText = "Performance logging",
Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.PerformanceLogging)
},
new SettingsCheckbox
{
LabelText = "Bypass caching (slow)",
Bindable = config.GetBindable<bool>(DebugSetting.BypassCaching)
},
new SettingsCheckbox
{
LabelText = "Bypass front-to-back render pass",
Bindable = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass)
}
};
}
}
}
|
Return Journal entries latest first | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Apollo.Data.ResultModels;
using Dapper;
namespace Apollo.Data
{
public interface IJournalDataService
{
Task<IReadOnlyList<JournalEntry>> GetAllJournalEntries();
Task CreateJournalEntry(JournalEntry entry);
}
public class JournalDataService : IJournalDataService
{
private readonly IDbConnectionFactory connectionFactory;
public JournalDataService(IDbConnectionFactory connectionFactory)
{
this.connectionFactory = connectionFactory;
}
public async Task<IReadOnlyList<JournalEntry>> GetAllJournalEntries()
{
using (var connection = await connectionFactory.GetConnection())
{
var results = await connection.QueryAsync<JournalEntry>("select * from journal");
return results.ToList();
}
}
public async Task CreateJournalEntry(JournalEntry entry)
{
using (var connection = await connectionFactory.GetConnection())
{
connection.Execute(@"
insert into journal(note, created_at)
values (@note, current_timestamp)",
new {note = entry.note});
}
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Apollo.Data.ResultModels;
using Dapper;
namespace Apollo.Data
{
public interface IJournalDataService
{
Task<IReadOnlyList<JournalEntry>> GetAllJournalEntries();
Task CreateJournalEntry(JournalEntry entry);
}
public class JournalDataService : IJournalDataService
{
private readonly IDbConnectionFactory connectionFactory;
public JournalDataService(IDbConnectionFactory connectionFactory)
{
this.connectionFactory = connectionFactory;
}
public async Task<IReadOnlyList<JournalEntry>> GetAllJournalEntries()
{
using (var connection = await connectionFactory.GetConnection())
{
var query = "select * from journal order by id desc";
var results = await connection
.QueryAsync<JournalEntry>(query);
return results.ToList();
}
}
public async Task CreateJournalEntry(JournalEntry entry)
{
using (var connection = await connectionFactory.GetConnection())
{
connection.Execute(@"
insert into journal(note, created_at)
values (@note, current_timestamp)",
new {note = entry.note});
}
}
}
} |
Add xmldoc warning against use of FramesPerSecond | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Timing
{
/// <summary>
/// A clock which will only update its current time when a frame proces is triggered.
/// Useful for keeping a consistent time state across an individual update.
/// </summary>
public interface IFrameBasedClock : IClock
{
/// <summary>
/// Elapsed time since last frame in milliseconds.
/// </summary>
double ElapsedFrameTime { get; }
double FramesPerSecond { get; }
FrameTimeInfo TimeInfo { get; }
/// <summary>
/// Processes one frame. Generally should be run once per update loop.
/// </summary>
void ProcessFrame();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Timing
{
/// <summary>
/// A clock which will only update its current time when a frame proces is triggered.
/// Useful for keeping a consistent time state across an individual update.
/// </summary>
public interface IFrameBasedClock : IClock
{
/// <summary>
/// Elapsed time since last frame in milliseconds.
/// </summary>
double ElapsedFrameTime { get; }
/// <summary>
/// A moving average representation of the frames per second of this clock.
/// Do not use this for any timing purposes (use <see cref="ElapsedFrameTime"/> instead).
/// </summary>
double FramesPerSecond { get; }
FrameTimeInfo TimeInfo { get; }
/// <summary>
/// Processes one frame. Generally should be run once per update loop.
/// </summary>
void ProcessFrame();
}
}
|
Replace field by access to base class | using System;
using System.Collections.Generic;
namespace NQuery.Language
{
public sealed class ExpressionSelectColumnSyntax : SelectColumnSyntax
{
private readonly ExpressionSyntax _expression;
private readonly AliasSyntax _alias;
private readonly SyntaxToken? _commaToken;
public ExpressionSelectColumnSyntax(ExpressionSyntax expression, AliasSyntax alias, SyntaxToken? commaToken)
: base(commaToken)
{
_expression = expression;
_alias = alias;
_commaToken = commaToken;
}
public override SyntaxKind Kind
{
get { return SyntaxKind.ExpressionSelectColumn; }
}
public override IEnumerable<SyntaxNodeOrToken> GetChildren()
{
yield return _expression;
if (_alias != null)
yield return _alias;
if (_commaToken != null)
yield return _commaToken.Value;
}
public ExpressionSyntax Expression
{
get { return _expression; }
}
public AliasSyntax Alias
{
get { return _alias; }
}
}
} | using System;
using System.Collections.Generic;
namespace NQuery.Language
{
public sealed class ExpressionSelectColumnSyntax : SelectColumnSyntax
{
private readonly ExpressionSyntax _expression;
private readonly AliasSyntax _alias;
public ExpressionSelectColumnSyntax(ExpressionSyntax expression, AliasSyntax alias, SyntaxToken? commaToken)
: base(commaToken)
{
_expression = expression;
_alias = alias;
}
public override SyntaxKind Kind
{
get { return SyntaxKind.ExpressionSelectColumn; }
}
public override IEnumerable<SyntaxNodeOrToken> GetChildren()
{
yield return _expression;
if (_alias != null)
yield return _alias;
if (CommaToken != null)
yield return CommaToken.Value;
}
public ExpressionSyntax Expression
{
get { return _expression; }
}
public AliasSyntax Alias
{
get { return _alias; }
}
}
} |
Use SkinnableSprite for approach circle | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
{
public class ApproachCircle : Container
{
public override bool RemoveWhenNotAlive => false;
public ApproachCircle()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
Child = new SkinnableDrawable("Play/osu/approachcircle", name => new Sprite { Texture = textures.Get(name) });
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Textures;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
{
public class ApproachCircle : Container
{
public override bool RemoveWhenNotAlive => false;
public ApproachCircle()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
Child = new SkinnableSprite("Play/osu/approachcircle");
}
}
}
|
Use port 80 by default for containerizer | using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using Owin.WebSocket;
using Owin.WebSocket.Extensions;
using System.Threading.Tasks;
namespace Containerizer
{
public class Program
{
static void Main(string[] args)
{
// Start OWIN host
try
{
using (WebApp.Start<Startup>("http://*:" + args[0] + "/"))
{
Console.WriteLine("SUCCESS: started");
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync("http://localhost:" + args[0] + "/api/ping").Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.WriteLine("Hit a key");
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine("ERRROR: " + ex.Message);
}
}
}
} | using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using Owin.WebSocket;
using Owin.WebSocket.Extensions;
using System.Threading.Tasks;
namespace Containerizer
{
public class Program
{
static void Main(string[] args)
{
var port = (args.Length == 1 ? args[0] : "80");
// Start OWIN host
try
{
using (WebApp.Start<Startup>("http://*:" + port + "/"))
{
Console.WriteLine("SUCCESS: started");
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync("http://localhost:" + port + "/api/ping").Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.WriteLine("Hit a key");
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine("ERRROR: " + ex.Message);
}
}
}
} |
Allow downloading files from administrative mode | @using Humanizer
@model FilesOverviewModel
@{
ViewBag.Title = "Uploaded file overview";
}
<h2>@ViewBag.Title</h2>
@{
var sortedFiles = Model.Files.OrderBy(x => x.Metadata.OriginalFileName);
}
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>File name</th>
<th>Uploaded on</th>
<th>Expires</th>
</tr>
</thead>
<tbody>
@foreach (var file in sortedFiles) {
<tr>
<td><code>@file.Id</code></td>
<td>@file.Metadata.OriginalFileName</td>
<td>
@file.Metadata.UploadedOn.Humanize()
</td>
<td>
@file.Metadata.Expiration.Humanize()
</td>
</tr>
}
</tbody>
</table> | @using Humanizer
@model FilesOverviewModel
@{
ViewBag.Title = "Uploaded file overview";
}
<h2>@ViewBag.Title</h2>
@{
var sortedFiles = Model.Files.OrderBy(x => x.Metadata.OriginalFileName);
}
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>File name</th>
<th>Uploaded on</th>
<th>Expires</th>
</tr>
</thead>
<tbody>
@foreach (var file in sortedFiles) {
<tr>
<td><code>@file.Id</code></td>
<td>
<a asp-route="DownloadFile" asp-route-id="@file.Id">@file.Metadata.OriginalFileName</a>
</td>
<td>
@file.Metadata.UploadedOn.Humanize()
</td>
<td>
@file.Metadata.Expiration.Humanize()
</td>
</tr>
}
</tbody>
</table> |
Call InitializeComponent, if no code-behind | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
namespace MicroMVVM
{
public static class ViewLocator
{
public static UIElement LocateForModel(object model)
{
var viewName = model.GetType().FullName;
var modelName = Regex.Replace(viewName, @"ViewModel", "View");
var modelType = Assembly.GetEntryAssembly().GetType(modelName);
if (modelType == null)
throw new Exception(String.Format("Unable to find a View with type {0}", modelName));
var instance = Activator.CreateInstance(modelType);
if (!(instance is UIElement))
throw new Exception(String.Format("Managed to create a {0}, but it wasn't a UIElement", modelName));
return (UIElement)instance;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
namespace MicroMVVM
{
public static class ViewLocator
{
public static UIElement LocateForModel(object model)
{
var modelName = model.GetType().FullName;
var viewName = Regex.Replace(modelName, @"ViewModel", "View");
var viewType = Assembly.GetEntryAssembly().GetType(modelName);
if (viewType == null)
throw new Exception(String.Format("Unable to find a View with type {0}", viewName));
var instance = Activator.CreateInstance(viewType);
if (!(instance is UIElement))
throw new Exception(String.Format("Managed to create a {0}, but it wasn't a UIElement", viewName));
var initializer = viewType.GetMethod("InitializeComponent", BindingFlags.Public | BindingFlags.Instance);
if (initializer != null)
initializer.Invoke(instance, null);
return (UIElement)instance;
}
}
}
|
Remove unnecessary code and fix double nesting causing filtering to not work | // 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Localisation;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Overlays.Settings.Sections.Gameplay
{
public class AudioSettings : SettingsSubsection
{
protected override LocalisableString Header => GameplaySettingsStrings.AudioHeader;
private Bindable<float> positionalHitsoundsLevel;
private FillFlowContainer<SettingsSlider<float>> positionalHitsoundsSettings;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config, OsuConfigManager osuConfig)
{
positionalHitsoundsLevel = osuConfig.GetBindable<float>(OsuSetting.PositionalHitsoundsLevel);
Children = new Drawable[]
{
positionalHitsoundsSettings = new FillFlowContainer<SettingsSlider<float>>
{
Direction = FillDirection.Vertical,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Masking = true,
Children = new[]
{
new SettingsSlider<float>
{
LabelText = AudioSettingsStrings.PositionalLevel,
Current = positionalHitsoundsLevel,
KeyboardStep = 0.01f,
DisplayAsPercentage = true
}
}
},
new SettingsCheckbox
{
LabelText = GameplaySettingsStrings.AlwaysPlayFirstComboBreak,
Current = config.GetBindable<bool>(OsuSetting.AlwaysPlayFirstComboBreak)
}
};
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Localisation;
namespace osu.Game.Overlays.Settings.Sections.Gameplay
{
public class AudioSettings : SettingsSubsection
{
protected override LocalisableString Header => GameplaySettingsStrings.AudioHeader;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config, OsuConfigManager osuConfig)
{
Children = new Drawable[]
{
new SettingsSlider<float>
{
LabelText = AudioSettingsStrings.PositionalLevel,
Keywords = new[] { @"positional", @"balance" },
Current = osuConfig.GetBindable<float>(OsuSetting.PositionalHitsoundsLevel),
KeyboardStep = 0.01f,
DisplayAsPercentage = true
},
new SettingsCheckbox
{
LabelText = GameplaySettingsStrings.AlwaysPlayFirstComboBreak,
Current = config.GetBindable<bool>(OsuSetting.AlwaysPlayFirstComboBreak)
}
};
}
}
}
|
Fix layout switcher tool menu path | using UnityEditor;
using UnityEngine;
namespace SpaceTrader.Util.EditorUtil {
public static class AspectRatioLayoutSwitcherEditor {
[MenuItem("SpaceTrader/Refresh All Layout Switchers")]
private static void RefreshAllSwitchersInScene() {
var switchers = Object.FindObjectsOfType<AspectRatioLayoutSwitcher>();
foreach (var switcher in switchers) {
if (switcher.isActiveAndEnabled) {
switcher.SendMessage("OnRectTransformDimensionsChange");
Debug.Log($"refreshed layout of {switcher.name}", switcher);
}
}
}
}
} | using UnityEditor;
using UnityEngine;
namespace SpaceTrader.Util.EditorUtil {
public static class AspectRatioLayoutSwitcherEditor {
[MenuItem("Tools/SpaceTrader/Refresh All Layout Switchers")]
private static void RefreshAllSwitchersInScene() {
var switchers = Object.FindObjectsOfType<AspectRatioLayoutSwitcher>();
foreach (var switcher in switchers) {
if (switcher.isActiveAndEnabled) {
switcher.SendMessage("OnRectTransformDimensionsChange");
Debug.Log($"refreshed layout of {switcher.name}", switcher);
}
}
}
}
}
|
Make the test pass for PostgreSQL, using a bit of a hack | using System;
using System.Data;
using System.Text;
using NHibernate.Engine;
using NExpression = NHibernate.Expression;
using NHibernate.SqlCommand;
using NHibernate.Type;
using NHibernate.DomainModel;
using NUnit.Framework;
namespace NHibernate.Test.ExpressionTest
{
/// <summary>
/// Summary description for InsensitiveLikeExpressionFixture.
/// </summary>
[TestFixture]
public class InsensitiveLikeExpressionFixture : BaseExpressionFixture
{
[Test]
public void InsentitiveLikeSqlStringTest()
{
ISession session = factory.OpenSession();
NExpression.Expression expression = NExpression.Expression.InsensitiveLike("Address", "12 Adress");
SqlString sqlString = expression.ToSqlString(factoryImpl, typeof(Simple), "simple_alias");
string expectedSql = "lower(simple_alias.address) like :simple_alias.address";
Parameter[] expectedParams = new Parameter[1];
Parameter firstParam = new Parameter( "address", "simple_alias", new SqlTypes.StringSqlType() );
expectedParams[0] = firstParam;
CompareSqlStrings(sqlString, expectedSql, expectedParams);
session.Close();
}
}
}
| using System;
using System.Data;
using System.Text;
using NHibernate.Engine;
using NExpression = NHibernate.Expression;
using NHibernate.SqlCommand;
using NHibernate.Type;
using NHibernate.DomainModel;
using NUnit.Framework;
namespace NHibernate.Test.ExpressionTest
{
/// <summary>
/// Summary description for InsensitiveLikeExpressionFixture.
/// </summary>
[TestFixture]
public class InsensitiveLikeExpressionFixture : BaseExpressionFixture
{
[Test]
public void InsentitiveLikeSqlStringTest()
{
ISession session = factory.OpenSession();
NExpression.Expression expression = NExpression.Expression.InsensitiveLike("Address", "12 Adress");
SqlString sqlString = expression.ToSqlString(factoryImpl, typeof(Simple), "simple_alias");
string expectedSql = "lower(simple_alias.address) like :simple_alias.address";
if ((factory as ISessionFactoryImplementor).Dialect is Dialect.PostgreSQLDialect)
{
expectedSql = "simple_alias.address ilike :simple_alias.address";
}
Parameter[] expectedParams = new Parameter[1];
Parameter firstParam = new Parameter( "address", "simple_alias", new SqlTypes.StringSqlType() );
expectedParams[0] = firstParam;
CompareSqlStrings(sqlString, expectedSql, expectedParams);
session.Close();
}
}
}
|
Reduce diff size: undo autoformat. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace DummyConsoleApp
{
public class Program
{
static void Main(string[] args)
{
var exitCodeToReturn = int.Parse(args[0]);
var millisecondsToSleep = int.Parse(args[1]);
var linesOfStandardOutput = int.Parse(args[2]);
var linesOfStandardError = int.Parse(args[3]);
Thread.Sleep(millisecondsToSleep);
for (var i = 0; i < linesOfStandardOutput; i++)
Console.WriteLine("Standard output line #{0}", i + 1);
for (var i = 0; i < linesOfStandardError; i++)
Console.Error.WriteLine("Standard error line #{0}", i + 1);
Environment.Exit(exitCodeToReturn);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace DummyConsoleApp
{
public class Program
{
static void Main(string[] args)
{
int exitCodeToReturn = int.Parse(args[0]);
int millisecondsToSleep = int.Parse(args[1]);
int linesOfStandardOutput = int.Parse(args[2]);
int linesOfStandardError = int.Parse(args[3]);
Thread.Sleep(millisecondsToSleep);
for (int i = 0; i < linesOfStandardOutput; i++)
{
Console.WriteLine("Standard output line #{0}", i + 1);
}
for (int i = 0; i < linesOfStandardError; i++)
{
Console.Error.WriteLine("Standard error line #{0}", i + 1);
}
Environment.Exit(exitCodeToReturn);
}
}
}
|
Switch over to using Regex extension | using System;
using Glimpse.Agent.Web.Options;
using Microsoft.Framework.OptionsModel;
namespace Glimpse.Agent.Web
{
public class GlimpseAgentWebOptionsSetup : ConfigureOptions<GlimpseAgentWebOptions>
{
public GlimpseAgentWebOptionsSetup() : base(ConfigureGlimpseAgentWebOptions)
{
Order = -1000;
}
public static void ConfigureGlimpseAgentWebOptions(GlimpseAgentWebOptions options)
{
// Set up IgnoredUris
options.IgnoredUris.Add("^/__browserLink/requestData");
options.IgnoredUris.Add("^/Glimpse");
options.IgnoredUris.Add("^/favicon.ico");
}
}
} | using System;
using Glimpse.Agent.Web.Options;
using Microsoft.Framework.OptionsModel;
namespace Glimpse.Agent.Web
{
public class GlimpseAgentWebOptionsSetup : ConfigureOptions<GlimpseAgentWebOptions>
{
public GlimpseAgentWebOptionsSetup() : base(ConfigureGlimpseAgentWebOptions)
{
Order = -1000;
}
public static void ConfigureGlimpseAgentWebOptions(GlimpseAgentWebOptions options)
{
// Set up IgnoredUris
options.IgnoredUris.AddUri("^/__browserLink/requestData");
options.IgnoredUris.AddUri("^/Glimpse");
options.IgnoredUris.AddUri("^/favicon.ico");
}
}
} |
Fix the test on MySQL, should work now | using System;
using System.Data;
using System.Text;
using NHibernate.Engine;
using NExpression = NHibernate.Expression;
using NHibernate.SqlCommand;
using NHibernate.Type;
using NHibernate.DomainModel;
using NUnit.Framework;
namespace NHibernate.Test.ExpressionTest
{
/// <summary>
/// Summary description for NotExpressionFixture.
/// </summary>
[TestFixture]
public class NotExpressionFixture : BaseExpressionFixture
{
[Test]
public void NotSqlStringTest()
{
ISession session = factory.OpenSession();
NExpression.ICriterion notExpression = NExpression.Expression.Not(NExpression.Expression.Eq("Address", "12 Adress"));
SqlString sqlString = notExpression.ToSqlString(factoryImpl, typeof(Simple), "simple_alias", BaseExpressionFixture.EmptyAliasClasses );
string expectedSql = dialect is Dialect.MySQLDialect ?
"not(simple_alias.address = :simple_alias.address)" :
"not simple_alias.address = :simple_alias.address";
Parameter firstParam = new Parameter( "address", "simple_alias", new SqlTypes.StringSqlType() );
CompareSqlStrings(sqlString, expectedSql, new Parameter[] {firstParam});
session.Close();
}
}
}
| using System;
using System.Data;
using System.Text;
using NHibernate.Engine;
using NExpression = NHibernate.Expression;
using NHibernate.SqlCommand;
using NHibernate.Type;
using NHibernate.DomainModel;
using NUnit.Framework;
namespace NHibernate.Test.ExpressionTest
{
/// <summary>
/// Summary description for NotExpressionFixture.
/// </summary>
[TestFixture]
public class NotExpressionFixture : BaseExpressionFixture
{
[Test]
public void NotSqlStringTest()
{
ISession session = factory.OpenSession();
NExpression.ICriterion notExpression = NExpression.Expression.Not(NExpression.Expression.Eq("Address", "12 Adress"));
SqlString sqlString = notExpression.ToSqlString(factoryImpl, typeof(Simple), "simple_alias", BaseExpressionFixture.EmptyAliasClasses );
string expectedSql = dialect is Dialect.MySQLDialect ?
"not (simple_alias.address = :simple_alias.address)" :
"not simple_alias.address = :simple_alias.address";
Parameter firstParam = new Parameter( "address", "simple_alias", new SqlTypes.StringSqlType() );
CompareSqlStrings(sqlString, expectedSql, new Parameter[] {firstParam});
session.Close();
}
}
}
|
Switch Thomas Rayner over to IWorkAtMicrosoft | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class ThomasRayner : IAmAMicrosoftMVP
{
public string FirstName => "Thomas";
public string LastName => "Rayner";
public string ShortBioOrTagLine => "Senior Security Systems Engineer @ Microsoft";
public string StateOrRegion => "Canada";
public string EmailAddress => "thmsrynr@outlook.com";
public string TwitterHandle => "MrThomasRayner";
public string GitHubHandle => "ThmsRynr";
public string GravatarHash => "";
public GeoPosition Position => new GeoPosition(53.5443890, -113.4909270);
public Uri WebSite => new Uri("https://thomasrayner.ca");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://thomasrayner.ca/feed"); } }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class ThomasRayner : IWorkAtMicrosoft
{
public string FirstName => "Thomas";
public string LastName => "Rayner";
public string ShortBioOrTagLine => "Senior Security Systems Engineer @ Microsoft";
public string StateOrRegion => "Canada";
public string EmailAddress => "thmsrynr@outlook.com";
public string TwitterHandle => "MrThomasRayner";
public string GitHubHandle => "ThmsRynr";
public string GravatarHash => "";
public GeoPosition Position => new GeoPosition(53.5443890, -113.4909270);
public Uri WebSite => new Uri("https://thomasrayner.ca");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://thomasrayner.ca/feed"); } }
}
}
|
Add assemblywide cake namespace imports | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Cake.Hg")]
[assembly: AssemblyDescription("Cake AddIn that extends Cake with Mercurial features")]
[assembly: AssemblyCompany("vCipher")]
[assembly: AssemblyProduct("Cake.Hg")]
// 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("8E7F175A-9805-4FB2-8708-C358FF9F5CB2")]
// 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.0.3.0")]
[assembly: AssemblyFileVersion("0.0.3.0")] | using Cake.Core.Annotations;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Cake.Hg")]
[assembly: AssemblyDescription("Cake AddIn that extends Cake with Mercurial features")]
[assembly: AssemblyCompany("vCipher")]
[assembly: AssemblyProduct("Cake.Hg")]
// 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("8E7F175A-9805-4FB2-8708-C358FF9F5CB2")]
// 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.0.4.0")]
[assembly: AssemblyFileVersion("0.0.4.0")]
// Cake build configuration
[assembly: CakeNamespaceImport("Mercurial")]
[assembly: CakeNamespaceImport("Cake.Hg")]
[assembly: CakeNamespaceImport("Cake.Hg.Aliases")]
[assembly: CakeNamespaceImport("Cake.Hg.Versions")] |
Mark ROM region for Glulx | using System;
using IFVM.Core;
namespace IFVM.Glulx
{
public class GlulxMachine : Machine
{
public GlulxHeader Header { get; }
public GlulxMachine(Memory memory) : base(memory)
{
this.Header = new GlulxHeader(memory);
VerifyChecksum(memory, this.Header.Checksum);
// Initial the memory should have a size equal to ExtStart.
// We must expand it to EndMem.
if (this.Header.ExtStart != memory.Size)
{
throw new InvalidOperationException($"Size expected to be {this.Header.ExtStart}");
}
memory.Expand((int)this.Header.EndMem);
}
private static void VerifyChecksum(Memory memory, uint expectedValue)
{
var scanner = memory.CreateScanner(offset: 0);
var checksum = 0u;
while (scanner.CanReadNextDWord)
{
if (scanner.Offset == 0x20)
{
// Note: We don't include the checksum value from the header.
scanner.SkipDWord();
}
else
{
checksum += scanner.NextDWord();
}
}
if (checksum != expectedValue)
{
throw new InvalidOperationException("Checksum does not match.");
}
}
}
}
| using System;
using IFVM.Core;
namespace IFVM.Glulx
{
public class GlulxMachine : Machine
{
public GlulxHeader Header { get; }
public GlulxMachine(Memory memory) : base(memory)
{
this.Header = new GlulxHeader(memory);
VerifyChecksum(memory, this.Header.Checksum);
// Initial the memory should have a size equal to ExtStart.
// We must expand it to EndMem.
if (this.Header.ExtStart != memory.Size)
{
throw new InvalidOperationException($"Size expected to be {this.Header.ExtStart}");
}
memory.Expand((int)this.Header.EndMem);
memory.AddReadOnlyRegion(0, (int)this.Header.RamStart);
}
private static void VerifyChecksum(Memory memory, uint expectedValue)
{
var scanner = memory.CreateScanner(offset: 0);
var checksum = 0u;
while (scanner.CanReadNextDWord)
{
if (scanner.Offset == 0x20)
{
// Note: We don't include the checksum value from the header.
scanner.SkipDWord();
}
else
{
checksum += scanner.NextDWord();
}
}
if (checksum != expectedValue)
{
throw new InvalidOperationException("Checksum does not match.");
}
}
}
}
|
Order pages by title in dropdown | using System.Collections.Generic;
using System.Linq;
using DirigoEdgeCore.Data.Entities;
using DirigoEdgeCore.Models;
public class RedirectViewModel : DirigoBaseModel
{
public List<Redirect> Redirects;
public List<string> Pages = new List<string>();
public RedirectViewModel()
{
BookmarkTitle = "Configure Redirects";
Redirects = Context.Redirects.ToList();
var pages = Context.ContentPages.Where(x => x.IsActive == true).ToList();
foreach (var page in pages)
{
Pages.Add(NavigationUtils.GetGeneratedUrl(page));
}
}
} | using System.Collections.Generic;
using System.Linq;
using DirigoEdgeCore.Data.Entities;
using DirigoEdgeCore.Models;
public class RedirectViewModel : DirigoBaseModel
{
public List<Redirect> Redirects;
public List<string> Pages = new List<string>();
public RedirectViewModel()
{
BookmarkTitle = "Configure Redirects";
Redirects = Context.Redirects.ToList();
var pages = Context.ContentPages.Where(x => x.IsActive == true).OrderBy(x => x.Title).ToList();
foreach (var page in pages)
{
Pages.Add(NavigationUtils.GetGeneratedUrl(page));
}
}
}
|
Remove other_files message box from the region selector | using System;
using System.IO;
using System.Windows.Forms;
namespace MusicRandomizer
{
public partial class VersionRequestForm : Form
{
public SplatoonRegion chosenRegion;
public VersionRequestForm()
{
InitializeComponent();
}
private void VersionRequestForm_Load(object sender, EventArgs e)
{
}
private void btnSave_Click(object sender, EventArgs e)
{
if (!radNorthAmerica.Checked && !radEurope.Checked && !radJapan.Checked)
{
MessageBox.Show("Please choose a region.");
return;
}
if (Directory.Exists("other_files"))
{
MessageBox.Show("The files inside other_files will be moved to a new folder called cafiine_root.");
}
if (radNorthAmerica.Checked)
{
chosenRegion = SplatoonRegion.NorthAmerica;
}
else if (radEurope.Checked)
{
chosenRegion = SplatoonRegion.Europe;
}
else
{
chosenRegion = SplatoonRegion.Japan;
}
this.Close();
}
}
}
| using System;
using System.IO;
using System.Windows.Forms;
namespace MusicRandomizer
{
public partial class VersionRequestForm : Form
{
public SplatoonRegion chosenRegion;
public VersionRequestForm()
{
InitializeComponent();
}
private void VersionRequestForm_Load(object sender, EventArgs e)
{
}
private void btnSave_Click(object sender, EventArgs e)
{
if (!radNorthAmerica.Checked && !radEurope.Checked && !radJapan.Checked)
{
MessageBox.Show("Please choose a region.");
return;
}
if (radNorthAmerica.Checked)
{
chosenRegion = SplatoonRegion.NorthAmerica;
}
else if (radEurope.Checked)
{
chosenRegion = SplatoonRegion.Europe;
}
else
{
chosenRegion = SplatoonRegion.Japan;
}
this.Close();
}
}
}
|
Allow category to be null in Azure SQL listener | using System.Data;
using System.Data.SqlClient;
using SimpleAzureTraceListener.Listeners.Base;
using SimpleAzureTraceListener.Models;
namespace SimpleAzureTraceListener.Listeners
{
public class AzureSqlTraceListener : AzureTraceListener
{
private readonly string _tableName;
private readonly SqlConnection _connection;
public AzureSqlTraceListener(string applicationName, string sqlConnectionString, string tableName = "TraceLogs")
{
_tableName = tableName;
ApplicationName = applicationName;
_connection = new SqlConnection(sqlConnectionString);
_connection.Open();
}
protected override void SaveMessage(AzureTraceMessage azureTraceMessage)
{
using (var command = _connection.CreateCommand())
{
command.CommandText = string.Format(@"INSERT INTO {0} (ApplicationName, Message, Category, Timestamp) VALUES
(@applicationName, @message, @category, @timeStamp)", _tableName);
command.Parameters.Add(new SqlParameter("applicationName", SqlDbType.NVarChar) { Value = azureTraceMessage.ApplicationName });
command.Parameters.Add(new SqlParameter("message", SqlDbType.NVarChar) { Value = azureTraceMessage.Message });
command.Parameters.Add(new SqlParameter("category", SqlDbType.NVarChar) { Value = azureTraceMessage.Category });
command.Parameters.Add(new SqlParameter("timeStamp", SqlDbType.DateTime2) { Value = azureTraceMessage.Timestamp });
command.ExecuteNonQuery();
}
}
}
} | using System;
using System.Data;
using System.Data.SqlClient;
using SimpleAzureTraceListener.Listeners.Base;
using SimpleAzureTraceListener.Models;
namespace SimpleAzureTraceListener.Listeners
{
public class AzureSqlTraceListener : AzureTraceListener
{
private readonly string _tableName;
private readonly SqlConnection _connection;
public AzureSqlTraceListener(string applicationName, string sqlConnectionString, string tableName = "TraceLogs")
{
_tableName = tableName;
ApplicationName = applicationName;
_connection = new SqlConnection(sqlConnectionString);
_connection.Open();
}
protected override void SaveMessage(AzureTraceMessage azureTraceMessage)
{
using (var command = _connection.CreateCommand())
{
command.CommandText = string.Format(@"INSERT INTO {0} (ApplicationName, Message, Category, Timestamp) VALUES
(@applicationName, @message, @category, @timeStamp)", _tableName);
command.Parameters.Add(new SqlParameter("applicationName", SqlDbType.NVarChar) { Value = azureTraceMessage.ApplicationName });
command.Parameters.Add(new SqlParameter("message", SqlDbType.NVarChar) { Value = azureTraceMessage.Message });
command.Parameters.Add(new SqlParameter("category", SqlDbType.NVarChar) { IsNullable = true, Value = azureTraceMessage.Category ?? (object) DBNull.Value });
command.Parameters.Add(new SqlParameter("timeStamp", SqlDbType.DateTime2) { Value = azureTraceMessage.Timestamp });
command.ExecuteNonQuery();
}
}
}
} |
Hide the blinking console tail on linux. | using SnakeApp.Models;
using System;
using System.Threading.Tasks;
namespace SnakeApp
{
public class GameController
{
public async Task StartNewGame()
{
var game = new Game(80, 25, 5, 100);
game.Start();
ConsoleKeyInfo userInput = new ConsoleKeyInfo();
do
{
userInput = Console.ReadKey(true);
game.ReceiveInput(userInput.Key);
} while (userInput.Key != ConsoleKey.Q);
}
}
}
| using SnakeApp.Models;
using System;
using System.Threading.Tasks;
namespace SnakeApp
{
public class GameController
{
public async Task StartNewGame()
{
PrepareConsole();
var game = new Game(80, 25, 5, 100);
game.Start();
ConsoleKeyInfo userInput = new ConsoleKeyInfo();
do
{
userInput = Console.ReadKey(true);
game.ReceiveInput(userInput.Key);
} while (userInput.Key != ConsoleKey.Q);
RestoreConsole();
}
private void PrepareConsole()
{
// getting the current cursor visibility is not supported on linux, so just hide then restore it
Console.Clear();
Console.CursorVisible = false;
}
private void RestoreConsole()
{
Console.Clear();
Console.CursorVisible = true;
}
}
}
|
Change method callings to default static instance | using System;
namespace PcscDotNet
{
public static class Pcsc<TIPcscProvider> where TIPcscProvider : class, IPcscProvider, new()
{
private static readonly Pcsc _instance = new Pcsc(new TIPcscProvider());
public static Pcsc Instance => _instance;
public static PcscContext CreateContext()
{
return new PcscContext(_instance);
}
public static PcscContext EstablishContext(SCardScope scope)
{
return new PcscContext(_instance, scope);
}
}
} | using System;
namespace PcscDotNet
{
public static class Pcsc<TIPcscProvider> where TIPcscProvider : class, IPcscProvider, new()
{
private static readonly Pcsc _instance = new Pcsc(new TIPcscProvider());
public static Pcsc Instance => _instance;
public static PcscContext CreateContext()
{
return _instance.CreateContext();
}
public static PcscContext EstablishContext(SCardScope scope)
{
return _instance.EstablishContext(scope);
}
}
} |
Add registration options for codeAction request | using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
using Newtonsoft.Json.Linq;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class CodeActionRequest
{
public static readonly
RequestType<CodeActionParams, CodeActionCommand[], object, object> Type =
RequestType<CodeActionParams, CodeActionCommand[], object, object>.Create("textDocument/codeAction");
}
/// <summary>
/// Parameters for CodeActionRequest.
/// </summary>
public class CodeActionParams
{
/// <summary>
/// The document in which the command was invoked.
/// </summary>
public TextDocumentIdentifier TextDocument { get; set; }
/// <summary>
/// The range for which the command was invoked.
/// </summary>
public Range Range { get; set; }
/// <summary>
/// Context carrying additional information.
/// </summary>
public CodeActionContext Context { get; set; }
}
public class CodeActionContext
{
public Diagnostic[] Diagnostics { get; set; }
}
public class CodeActionCommand
{
public string Title { get; set; }
public string Command { get; set; }
public JArray Arguments { get; set; }
}
}
| using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
using Newtonsoft.Json.Linq;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class CodeActionRequest
{
public static readonly
RequestType<CodeActionParams, CodeActionCommand[], object, TextDocumentRegistrationOptions> Type =
RequestType<CodeActionParams, CodeActionCommand[], object, TextDocumentRegistrationOptions>.Create("textDocument/codeAction");
}
/// <summary>
/// Parameters for CodeActionRequest.
/// </summary>
public class CodeActionParams
{
/// <summary>
/// The document in which the command was invoked.
/// </summary>
public TextDocumentIdentifier TextDocument { get; set; }
/// <summary>
/// The range for which the command was invoked.
/// </summary>
public Range Range { get; set; }
/// <summary>
/// Context carrying additional information.
/// </summary>
public CodeActionContext Context { get; set; }
}
public class CodeActionContext
{
public Diagnostic[] Diagnostics { get; set; }
}
public class CodeActionCommand
{
public string Title { get; set; }
public string Command { get; set; }
public JArray Arguments { get; set; }
}
}
|
Move down to highlight the Create methods. | using System.Net.Http;
using MyCouch.Net;
namespace MyCouch.Requests.Factories
{
public class AttachmentHttpRequestFactory :
HttpRequestFactoryBase,
IHttpRequestFactory<GetAttachmentRequest>,
IHttpRequestFactory<PutAttachmentRequest>,
IHttpRequestFactory<DeleteAttachmentRequest>
{
public AttachmentHttpRequestFactory(IConnection connection) : base(connection) { }
protected virtual string GenerateRequestUrl(string docId, string docRev, string attachmentName)
{
return string.Format("{0}/{1}/{2}{3}",
Connection.Address,
docId,
attachmentName,
docRev == null ? string.Empty : string.Concat("?rev=", docRev));
}
public virtual HttpRequest Create(GetAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Get, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
return httpRequest;
}
public virtual HttpRequest Create(PutAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Put, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
httpRequest.SetContent(request.Content, request.ContentType);
return httpRequest;
}
public virtual HttpRequest Create(DeleteAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Delete, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
return httpRequest;
}
}
}
| using System.Net.Http;
using MyCouch.Net;
namespace MyCouch.Requests.Factories
{
public class AttachmentHttpRequestFactory :
HttpRequestFactoryBase,
IHttpRequestFactory<GetAttachmentRequest>,
IHttpRequestFactory<PutAttachmentRequest>,
IHttpRequestFactory<DeleteAttachmentRequest>
{
public AttachmentHttpRequestFactory(IConnection connection) : base(connection) { }
public virtual HttpRequest Create(GetAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Get, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
return httpRequest;
}
public virtual HttpRequest Create(PutAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Put, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
httpRequest.SetContent(request.Content, request.ContentType);
return httpRequest;
}
public virtual HttpRequest Create(DeleteAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Delete, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
return httpRequest;
}
protected virtual string GenerateRequestUrl(string docId, string docRev, string attachmentName)
{
return string.Format("{0}/{1}/{2}{3}",
Connection.Address,
docId,
attachmentName,
docRev == null ? string.Empty : string.Concat("?rev=", docRev));
}
}
}
|
Fix copy and past bug. | using UnityEngine;
using System.Collections;
using Realms.Common.Packet;
using System;
namespace Realms.Server.Packet
{
[Serializable]
public class PlayerHandshakePacket : IPacket
{
/// <summary>
/// Is the connection to the server allowed
/// </summary>
public bool AllowConnection { get; private set; }
/// <summary>
/// If connection is refused, the reason why
/// </summary>
public string ErrorMessage { get; private set; }
/// <summary>
/// Spawn X position
/// </summary>
public float PositionX { get; private set; }
/// <summary>
/// Spawn Y position
/// </summary>
public float PositionY { get; private set; }
/// <summary>
/// Spawn Z position
/// </summary>
public float PositionZ { get; private set; }
/// <summary>
/// Class constructor
/// </summary>
/// <param name="allowConnection"></param>
/// <param name="errorMessage"></param>
public PlayerHandshakePacket(bool allowConnection, string errorMessage, Vector3 spawnPosition) : base(typeof(PlayerHandshakePacket))
{
this.AllowConnection = allowConnection;
this.ErrorMessage = errorMessage;
this.PositionX = spawnPosition.x;
this.PositionX = spawnPosition.y;
this.PositionX = spawnPosition.z;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Vector3 GetPosition()
{
return new Vector3(this.PositionX, this.PositionY, this.PositionZ);
}
}
}
| using UnityEngine;
using System.Collections;
using Realms.Common.Packet;
using System;
namespace Realms.Server.Packet
{
[Serializable]
public class PlayerHandshakePacket : IPacket
{
/// <summary>
/// Is the connection to the server allowed
/// </summary>
public bool AllowConnection { get; private set; }
/// <summary>
/// If connection is refused, the reason why
/// </summary>
public string ErrorMessage { get; private set; }
/// <summary>
/// Spawn X position
/// </summary>
public float PositionX { get; private set; }
/// <summary>
/// Spawn Y position
/// </summary>
public float PositionY { get; private set; }
/// <summary>
/// Spawn Z position
/// </summary>
public float PositionZ { get; private set; }
/// <summary>
/// Class constructor
/// </summary>
/// <param name="allowConnection"></param>
/// <param name="errorMessage"></param>
public PlayerHandshakePacket(bool allowConnection, string errorMessage, Vector3 spawnPosition) : base(typeof(PlayerHandshakePacket))
{
this.AllowConnection = allowConnection;
this.ErrorMessage = errorMessage;
this.PositionX = spawnPosition.x;
this.PositionY = spawnPosition.y;
this.PositionZ = spawnPosition.z;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Vector3 GetPosition()
{
return new Vector3(this.PositionX, this.PositionY, this.PositionZ);
}
}
}
|
Fix failing test due to missing dependency | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Edit.Components.Timelines.Summary;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneEditorSummaryTimeline : EditorClockTestScene
{
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
Add(new SummaryTimeline
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500, 50)
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Components.Timelines.Summary;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneEditorSummaryTimeline : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
private readonly EditorBeatmap editorBeatmap = new EditorBeatmap(new OsuBeatmap());
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
Add(new SummaryTimeline
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500, 50)
});
}
}
}
|
Mark the ExtractTest as EndToEnd. | using org.grobid.core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using Grobid.NET;
using System.Xml.Linq;
using org.apache.log4j;
namespace Grobid.Test
{
public class GrobidTest
{
static GrobidTest()
{
BasicConfigurator.configure();
org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG);
}
[Fact]
public void ExtractTest()
{
var factory = new GrobidFactory(
@"c:\dev\grobid.net\grobid.zip",
@"c:\dev\grobid.net\bin\pdf2xml.exe",
@"c:\temp");
var grobid = factory.Create();
var result = grobid.Extract(@"c:\dev\grobid.net\content\essence-linq.pdf");
result.Should().NotBeEmpty();
Action test = () => XDocument.Parse(result);
test.ShouldNotThrow();
}
[Fact]
public void Test()
{
var x = GrobidModels.NAMES_HEADER;
x.name().Should().Be("NAMES_HEADER");
x.toString().Should().Be("name/header");
}
}
}
| using org.grobid.core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using Grobid.NET;
using System.Xml.Linq;
using org.apache.log4j;
namespace Grobid.Test
{
public class GrobidTest
{
static GrobidTest()
{
BasicConfigurator.configure();
org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG);
}
[Fact]
[Trait("Test", "EndToEnd")]
public void ExtractTest()
{
var factory = new GrobidFactory(
@"c:\dev\grobid.net\grobid.zip",
@"c:\dev\grobid.net\bin\pdf2xml.exe",
@"c:\temp");
var grobid = factory.Create();
var result = grobid.Extract(@"c:\dev\grobid.net\content\essence-linq.pdf");
result.Should().NotBeEmpty();
Action test = () => XDocument.Parse(result);
test.ShouldNotThrow();
}
[Fact]
public void Test()
{
var x = GrobidModels.NAMES_HEADER;
x.name().Should().Be("NAMES_HEADER");
x.toString().Should().Be("name/header");
}
}
}
|
Add registration options for documentHighlight request | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public enum DocumentHighlightKind
{
Text = 1,
Read = 2,
Write = 3
}
public class DocumentHighlight
{
public Range Range { get; set; }
public DocumentHighlightKind Kind { get; set; }
}
public class DocumentHighlightRequest
{
public static readonly
RequestType<TextDocumentPositionParams, DocumentHighlight[], object, object> Type =
RequestType<TextDocumentPositionParams, DocumentHighlight[], object, object>.Create("textDocument/documentHighlight");
}
}
| //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public enum DocumentHighlightKind
{
Text = 1,
Read = 2,
Write = 3
}
public class DocumentHighlight
{
public Range Range { get; set; }
public DocumentHighlightKind Kind { get; set; }
}
public class DocumentHighlightRequest
{
public static readonly
RequestType<TextDocumentPositionParams, DocumentHighlight[], object, TextDocumentRegistrationOptions> Type =
RequestType<TextDocumentPositionParams, DocumentHighlight[], object, TextDocumentRegistrationOptions>.Create("textDocument/documentHighlight");
}
}
|
Put obstaclenetworking setup in the right place. | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpinnerActivator : MonoBehaviour
{
public bool boostEnabled;
public GameObject boost;
private void Start()
{
boost.GetComponent<BoostPadForce>().boostEnabled = false;
boost.GetComponent<BoostPad>().lightDisabled();
GetComponent<ObstacleNetworking>().ActivateFromServer += ActivateBoost;
GetComponent<ObstacleNetworking>().DeactivateFromServer += DeactivateBoost;
}
void OnCollisionEnter(Collision col)
{
if (boostEnabled == true)
{
ActivateBoost();
GetComponent<ObstacleNetworking>().ActivateFromServer();
}
else if (boostEnabled == false)
{
DeactivateBoost();
GetComponent<ObstacleNetworking>().DeactivateFromServer();
}
}
void ActivateBoost()
{
boost.GetComponent<BoostPadForce>().boostEnabled = false;
boost.GetComponent<BoostPad>().lightDisabled();
boostEnabled = false;
}
void DeactivateBoost()
{
boost.GetComponent<BoostPadForce>().boostEnabled = true;
boost.GetComponent<BoostPad>().lightEnabled();
boostEnabled = true;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class SpinnerActivator : MonoBehaviour
{
public bool boostEnabled;
public GameObject boost;
private void Start()
{
boost.GetComponent<BoostPadForce>().boostEnabled = false;
boost.GetComponent<BoostPad>().lightDisabled();
}
private void Awake()
{
GetComponent<ObstacleNetworking>().ActivateFromServer += ActivateBoost;
GetComponent<ObstacleNetworking>().DeactivateFromServer += DeactivateBoost;
}
void OnCollisionEnter(Collision col)
{
if (!NetworkManager.singleton.isNetworkActive || NetworkServer.connections.Count > 0)
{
//Host only
if (boostEnabled == false)
{
ActivateBoost();
GetComponent<ObstacleNetworking>().ActivateFromServer();
}
else if (boostEnabled == true)
{
DeactivateBoost();
GetComponent<ObstacleNetworking>().DeactivateFromServer();
}
}
}
void DeactivateBoost()
{
boost.GetComponent<BoostPadForce>().boostEnabled = false;
boost.GetComponent<BoostPad>().lightDisabled();
boostEnabled = false;
}
void ActivateBoost()
{
boost.GetComponent<BoostPadForce>().boostEnabled = true;
boost.GetComponent<BoostPad>().lightEnabled();
boostEnabled = true;
}
}
|
Remove some hints, function name is clear enough | using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Networking;
public static class UnityUtils
{
/// <summary>
/// Is any of the keys UP?
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public static bool IsAnyKeyUp(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyUp(key))
return true;
}
return false;
}
/// <summary>
/// Is any of the keys DOWN?
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public static bool IsAnyKeyDown(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyDown(key))
return true;
}
return false;
}
/// <summary>
/// Detect headless mode (which has graphicsDeviceType Null)
/// </summary>
/// <returns></returns>
public static bool IsHeadless()
{
return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null;
}
public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component
{
output = null;
GameObject foundObject = ClientScene.FindLocalObject(targetNetId);
if (foundObject == null)
return false;
output = foundObject.GetComponent<T>();
if (output == null)
return false;
return true;
}
}
| using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Networking;
public static class UnityUtils
{
public static bool IsAnyKeyUp(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyUp(key))
return true;
}
return false;
}
public static bool IsAnyKeyDown(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyDown(key))
return true;
}
return false;
}
/// <summary>
/// Detect headless mode (which has graphicsDeviceType Null)
/// </summary>
/// <returns></returns>
public static bool IsHeadless()
{
return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null;
}
public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component
{
output = null;
GameObject foundObject = ClientScene.FindLocalObject(targetNetId);
if (foundObject == null)
return false;
output = foundObject.GetComponent<T>();
if (output == null)
return false;
return true;
}
}
|
Add view elements for resending Confirm code | <h1 class="heading-xlarge">Enter your security code</h1>
<form method="post">
@Html.AntiForgeryToken()
<fieldset>
<legend class="visuallyhidden">Enter your security code</legend>
<div class="form-group">
<label class="form-label-bold" for="SecurityCode">Enter security code</label>
<input autofocus="autofocus" aria-required="true" class="form-control" id="SecurityCode" name="SecurityCode">
</div>
<div class="form-group">
<label class="form-label-bold" for="Password">Password</label>
<input type="password" aria-required="true" autocomplete="off" class="form-control" id="Password" name="Password">
</div>
</fieldset>
<button type="submit" class="button">Continue</button>
</form> | @model SFA.DAS.EmployerUsers.Web.Models.OrchestratorResponse<SFA.DAS.EmployerUsers.Web.Models.ConfirmChangeEmailViewModel>
<h1 class="heading-xlarge">Enter your security code</h1>
<form method="post">
@Html.AntiForgeryToken()
<fieldset>
<legend class="visuallyhidden">Enter your security code</legend>
<div class="form-group">
<label class="form-label-bold" for="SecurityCode">Enter security code</label>
<input autofocus="autofocus" aria-required="true" class="form-control" id="SecurityCode" name="SecurityCode">
</div>
<div class="form-group">
<label class="form-label-bold" for="Password">Password</label>
<input type="password" aria-required="true" autocomplete="off" class="form-control" id="Password" name="Password">
</div>
</fieldset>
<button type="submit" class="button">Continue</button>
</form>
@if (Model.Data.SecurityCode != null)
{
<div class="form-group">
<h2 class="heading-medium">Not received your security code?</h2>
<p>You can <a href="@Url.Action("ResendActivation")">request another security code.</a> </p>
</div>
} |
Test for properties column filtering | using System;
using System.Collections.Generic;
using System.Text;
namespace Serilog.Sinks.MSSqlServer.Tests
{
class TestPropertiesColumnFiltering
{
}
}
| using Dapper;
using FluentAssertions;
using System.Data.SqlClient;
using Xunit;
namespace Serilog.Sinks.MSSqlServer.Tests
{
[Collection("LogTest")]
public class TestPropertiesColumnFiltering
{
internal class PropertiesColumns
{
public string Properties { get; set; }
}
[Fact]
public void FilteredProperties()
{
// arrange
var columnOptions = new ColumnOptions();
columnOptions.Properties.PropertiesFilter = (propName) => propName == "A";
Log.Logger = new LoggerConfiguration()
.WriteTo.MSSqlServer
(
connectionString: DatabaseFixture.LogEventsConnectionString,
tableName: DatabaseFixture.LogTableName,
columnOptions: columnOptions,
autoCreateSqlTable: true
)
.CreateLogger();
// act
Log.Logger
.ForContext("A", "AValue")
.ForContext("B", "BValue")
.Information("Logging message");
Log.CloseAndFlush();
// assert
using (var conn = new SqlConnection(DatabaseFixture.LogEventsConnectionString))
{
var logEvents = conn.Query<PropertiesColumns>($"SELECT Properties from {DatabaseFixture.LogTableName}");
logEvents.Should().Contain(e => e.Properties.Contains("AValue"));
logEvents.Should().NotContain(e => e.Properties.Contains("BValue"));
}
}
}
}
|
Make sure SQL Server tests don't run in parallel | // Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Data.SqlClient;
using Openchain.Tests;
namespace Openchain.SqlServer.Tests
{
public class SqlServerStorageEngineTests : BaseStorageEngineTests
{
private readonly int instanceId;
public SqlServerStorageEngineTests()
{
Random rnd = new Random();
this.instanceId = rnd.Next(0, int.MaxValue);
SqlServerStorageEngine engine = new SqlServerStorageEngine("Data Source=.;Initial Catalog=Openchain;Integrated Security=True", this.instanceId, TimeSpan.FromSeconds(10));
engine.OpenConnection().Wait();
SqlCommand command = engine.Connection.CreateCommand();
command.CommandText = @"
DELETE FROM [Openchain].[RecordMutations];
DELETE FROM [Openchain].[Records];
DELETE FROM [Openchain].[Transactions];
";
command.ExecuteNonQuery();
this.Store = engine;
}
}
}
| // Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Data.SqlClient;
using Openchain.Tests;
using Xunit;
namespace Openchain.SqlServer.Tests
{
[Collection("SQL Server Tests")]
public class SqlServerStorageEngineTests : BaseStorageEngineTests
{
private readonly int instanceId;
public SqlServerStorageEngineTests()
{
SqlServerStorageEngine engine = new SqlServerStorageEngine("Data Source=.;Initial Catalog=Openchain;Integrated Security=True", 1, TimeSpan.FromSeconds(10));
engine.OpenConnection().Wait();
SqlCommand command = engine.Connection.CreateCommand();
command.CommandText = @"
DELETE FROM [Openchain].[RecordMutations];
DELETE FROM [Openchain].[Records];
DELETE FROM [Openchain].[Transactions];
";
command.ExecuteNonQuery();
this.Store = engine;
}
}
}
|
Use ShapeFactory as base class | // Copyright (c) Wiesław Šoltés. 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.Text;
using System.Threading.Tasks;
using Test2d;
namespace Test2d
{
/// <summary>
///
/// </summary>
public class RoslynScriptGlobals
{
/// <summary>
///
/// </summary>
public EditorContext Context;
}
}
| // Copyright (c) Wiesław Šoltés. 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.Text;
using System.Threading.Tasks;
using Test2d;
namespace Test2d
{
/// <summary>
///
/// </summary>
public class RoslynScriptGlobals : ShapeFactory
{
}
}
|
Abort key handling if SDL2 passes us an unknown key | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Input.StateChanges;
using osu.Framework.Input.States;
using osu.Framework.Platform;
using osu.Framework.Statistics;
using Veldrid;
using TKKey = osuTK.Input.Key;
namespace osu.Framework.Input.Handlers.Keyboard
{
public class Sdl2KeyboardHandler : InputHandler
{
private readonly KeyboardState lastKeyboardState = new KeyboardState();
private readonly KeyboardState thisKeyboardState = new KeyboardState();
public override bool IsActive => true;
public override int Priority => 0;
public override bool Initialize(GameHost host)
{
if (!(host.Window is Window window))
return false;
Enabled.BindValueChanged(e =>
{
if (e.NewValue)
{
window.KeyDown += handleKeyboardEvent;
window.KeyUp += handleKeyboardEvent;
}
else
{
window.KeyDown -= handleKeyboardEvent;
window.KeyUp -= handleKeyboardEvent;
}
}, true);
return true;
}
private void handleKeyboardEvent(KeyEvent keyEvent)
{
thisKeyboardState.Keys.SetPressed((TKKey)keyEvent.Key, keyEvent.Down);
PendingInputs.Enqueue(new KeyboardKeyInput(thisKeyboardState.Keys, lastKeyboardState.Keys));
lastKeyboardState.Keys.SetPressed((TKKey)keyEvent.Key, keyEvent.Down);
FrameStatistics.Increment(StatisticsCounterType.KeyEvents);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Input.StateChanges;
using osu.Framework.Input.States;
using osu.Framework.Platform;
using osu.Framework.Statistics;
using Veldrid;
using TKKey = osuTK.Input.Key;
namespace osu.Framework.Input.Handlers.Keyboard
{
public class Sdl2KeyboardHandler : InputHandler
{
private readonly KeyboardState lastKeyboardState = new KeyboardState();
private readonly KeyboardState thisKeyboardState = new KeyboardState();
public override bool IsActive => true;
public override int Priority => 0;
public override bool Initialize(GameHost host)
{
if (!(host.Window is Window window))
return false;
Enabled.BindValueChanged(e =>
{
if (e.NewValue)
{
window.KeyDown += handleKeyboardEvent;
window.KeyUp += handleKeyboardEvent;
}
else
{
window.KeyDown -= handleKeyboardEvent;
window.KeyUp -= handleKeyboardEvent;
}
}, true);
return true;
}
private void handleKeyboardEvent(KeyEvent keyEvent)
{
if (keyEvent.Key == Key.Unknown)
return;
thisKeyboardState.Keys.SetPressed((TKKey)keyEvent.Key, keyEvent.Down);
PendingInputs.Enqueue(new KeyboardKeyInput(thisKeyboardState.Keys, lastKeyboardState.Keys));
lastKeyboardState.Keys.SetPressed((TKKey)keyEvent.Key, keyEvent.Down);
FrameStatistics.Increment(StatisticsCounterType.KeyEvents);
}
}
}
|
Fix formatting on queued sender | using CertiPay.Common.Logging;
using CertiPay.Common.WorkQueue;
using System.Threading;
using System.Threading.Tasks;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Sends notifications to the background worker queue for async processing and retries
/// </summary>
public partial class QueuedSender :
INotificationSender<SMSNotification>,
INotificationSender<EmailNotification>
{
private static readonly ILog Log = LogManager.GetLogger<QueuedSender>();
private readonly IQueueManager _queue;
public QueuedSender(IQueueManager queue)
{
this._queue = queue;
}
public async Task SendAsync(EmailNotification notification)
{
await SendAsync(notification, CancellationToken.None);
}
public async Task SendAsync(EmailNotification notification, CancellationToken token)
{
using (Log.Timer("QueuedSender.SendAsync", context: notification))
{
await _queue.Enqueue(EmailNotification.QueueName, notification);
}
}
public async Task SendAsync(SMSNotification notification)
{
await SendAsync(notification, CancellationToken.None);
}
public async Task SendAsync(SMSNotification notification, CancellationToken token)
{
using (Log.Timer("QueuedSender.SendAsync", context: notification))
{
await _queue.Enqueue(SMSNotification.QueueName, notification);
}
}
}
} | using CertiPay.Common.Logging;
using CertiPay.Common.WorkQueue;
using System.Threading;
using System.Threading.Tasks;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Sends notifications to the background worker queue for async processing and retries
/// </summary>
public partial class QueuedSender :
INotificationSender<SMSNotification>,
INotificationSender<EmailNotification>
{
private static readonly ILog Log = LogManager.GetLogger<QueuedSender>();
private readonly IQueueManager _queue;
public QueuedSender(IQueueManager queue)
{
this._queue = queue;
}
public async Task SendAsync(EmailNotification notification)
{
await SendAsync(notification, CancellationToken.None);
}
public async Task SendAsync(EmailNotification notification, CancellationToken token)
{
using (Log.Timer("QueuedSender.SendAsync", context: notification))
{
await _queue.Enqueue(EmailNotification.QueueName, notification);
}
}
public async Task SendAsync(SMSNotification notification)
{
await SendAsync(notification, CancellationToken.None);
}
public async Task SendAsync(SMSNotification notification, CancellationToken token)
{
using (Log.Timer("QueuedSender.SendAsync", context: notification))
{
await _queue.Enqueue(SMSNotification.QueueName, notification);
}
}
}
} |
Rename Control_DragAndDrop_UsingDragAndDropUsingScriptBehavior test to Control_DragAndDrop_UsingDomEvents | using NUnit.Framework;
namespace Atata.Tests
{
public class ControlTests : UITestFixture
{
[Test]
public void Control_DragAndDrop_UsingDragAndDropUsingScriptBehavior()
{
Go.To<DragAndDropPage>().
DropContainer.Items.Should.BeEmpty().
DragItems.Items.Should.HaveCount(2).
DragItems[x => x.Content == "Drag item 1"].DragAndDropTo(x => x.DropContainer).
DragItems[0].DragAndDropTo(x => x.DropContainer).
DropContainer.Items.Should.HaveCount(2).
DragItems.Items.Should.BeEmpty().
DropContainer[1].Content.Should.Equal("Drag item 2");
}
}
}
| using NUnit.Framework;
namespace Atata.Tests
{
public class ControlTests : UITestFixture
{
[Test]
public void Control_DragAndDrop_UsingDomEvents()
{
Go.To<DragAndDropPage>().
DropContainer.Items.Should.BeEmpty().
DragItems.Items.Should.HaveCount(2).
DragItems[x => x.Content == "Drag item 1"].DragAndDropTo(x => x.DropContainer).
DragItems[0].DragAndDropTo(x => x.DropContainer).
DropContainer.Items.Should.HaveCount(2).
DragItems.Items.Should.BeEmpty().
DropContainer[1].Content.Should.Equal("Drag item 2");
}
}
}
|
Refactor Divide Integers Operation to use GetValujes and CloneWithValues | namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DivideIntegerIntegerOperation : IBinaryOperation<int, int, int>
{
public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2)
{
Tensor<int> result = new Tensor<int>();
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 DivideIntegerIntegerOperation : IBinaryOperation<int, int, int>
{
public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2)
{
int[] values1 = tensor1.GetValues();
int l = values1.Length;
int value2 = tensor2.GetValue();
int[] newvalues = new int[l];
for (int k = 0; k < l; k++)
newvalues[k] = values1[k] / value2;
return tensor1.CloneWithNewValues(newvalues);
}
}
}
|
Set max connections per server to 1024 by default. | // Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
using AppBrix.Configuration;
using System;
using System.Linq;
using System.Threading;
namespace AppBrix.Web.Client.Configuration
{
public sealed class WebClientConfig : IConfig
{
#region Construction
/// <summary>
/// Creates a new instance of <see cref="WebClientConfig"/> with default values for the properties.
/// </summary>
public WebClientConfig()
{
this.MaxConnectionsPerServer = 128;
this.RequestTimeout = Timeout.InfiniteTimeSpan;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the timeout used when making HTTP requests.
/// </summary>
public int MaxConnectionsPerServer { get; set; }
/// <summary>
/// Gets or sets the timeout used when making HTTP requests.
/// </summary>
public TimeSpan RequestTimeout { get; set; }
#endregion
}
}
| // Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
using AppBrix.Configuration;
using System;
using System.Linq;
using System.Threading;
namespace AppBrix.Web.Client.Configuration
{
public sealed class WebClientConfig : IConfig
{
#region Construction
/// <summary>
/// Creates a new instance of <see cref="WebClientConfig"/> with default values for the properties.
/// </summary>
public WebClientConfig()
{
this.MaxConnectionsPerServer = 1024;
this.RequestTimeout = Timeout.InfiniteTimeSpan;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the timeout used when making HTTP requests.
/// </summary>
public int MaxConnectionsPerServer { get; set; }
/// <summary>
/// Gets or sets the timeout used when making HTTP requests.
/// </summary>
public TimeSpan RequestTimeout { get; set; }
#endregion
}
}
|
Enable default mapped span results for Razor. | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal sealed class RazorSpanMappingServiceWrapper : ISpanMappingService
{
private readonly IRazorSpanMappingService _razorSpanMappingService;
public RazorSpanMappingServiceWrapper(IRazorSpanMappingService razorSpanMappingService)
{
_razorSpanMappingService = razorSpanMappingService ?? throw new ArgumentNullException(nameof(razorSpanMappingService));
}
public async Task<ImmutableArray<MappedSpanResult>> MapSpansAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken)
{
var razorSpans = await _razorSpanMappingService.MapSpansAsync(document, spans, cancellationToken).ConfigureAwait(false);
var roslynSpans = new MappedSpanResult[razorSpans.Length];
for (var i = 0; i < razorSpans.Length; i++)
{
var razorSpan = razorSpans[i];
roslynSpans[i] = new MappedSpanResult(razorSpan.FilePath, razorSpan.LinePositionSpan, razorSpan.Span);
}
return roslynSpans.ToImmutableArray();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal sealed class RazorSpanMappingServiceWrapper : ISpanMappingService
{
private readonly IRazorSpanMappingService _razorSpanMappingService;
public RazorSpanMappingServiceWrapper(IRazorSpanMappingService razorSpanMappingService)
{
_razorSpanMappingService = razorSpanMappingService ?? throw new ArgumentNullException(nameof(razorSpanMappingService));
}
public async Task<ImmutableArray<MappedSpanResult>> MapSpansAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken)
{
var razorSpans = await _razorSpanMappingService.MapSpansAsync(document, spans, cancellationToken).ConfigureAwait(false);
var roslynSpans = new MappedSpanResult[razorSpans.Length];
for (var i = 0; i < razorSpans.Length; i++)
{
var razorSpan = razorSpans[i];
if (razorSpan.FilePath == null)
{
// Unmapped location
roslynSpans[i] = default;
}
else
{
roslynSpans[i] = new MappedSpanResult(razorSpan.FilePath, razorSpan.LinePositionSpan, razorSpan.Span);
}
}
return roslynSpans.ToImmutableArray();
}
}
}
|
Set more specific return type to enable application/atom+xml response formatting. | using System.Linq;
using System.Web.Http;
using System.Web.Http.OData;
using NuGet.Lucene.Web.Models;
using NuGet.Lucene.Web.Util;
namespace NuGet.Lucene.Web.Controllers
{
/// <summary>
/// OData provider for Lucene based NuGet package repository.
/// </summary>
public class PackagesODataController : ODataController
{
public ILucenePackageRepository Repository { get; set; }
public IMirroringPackageRepository MirroringRepository { get; set; }
[Queryable]
public IQueryable<ODataPackage> Get()
{
return Repository.LucenePackages.Select(p => p.AsDataServicePackage()).AsQueryable();
}
public object Get([FromODataUri] string id, [FromODataUri] string version)
{
SemanticVersion semanticVersion;
if (!SemanticVersion.TryParse(version, out semanticVersion))
{
return BadRequest("Invalid version");
}
if (string.IsNullOrWhiteSpace(id))
{
return BadRequest("Invalid package id");
}
var package = MirroringRepository.FindPackage(id, semanticVersion);
return package == null ? (object)NotFound() : package.AsDataServicePackage();
}
}
}
| using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.OData;
using NuGet.Lucene.Web.Models;
using NuGet.Lucene.Web.Util;
namespace NuGet.Lucene.Web.Controllers
{
/// <summary>
/// OData provider for Lucene based NuGet package repository.
/// </summary>
public class PackagesODataController : ODataController
{
public ILucenePackageRepository Repository { get; set; }
public IMirroringPackageRepository MirroringRepository { get; set; }
[Queryable]
public IQueryable<ODataPackage> Get()
{
return Repository.LucenePackages.Select(p => p.AsDataServicePackage()).AsQueryable();
}
public IHttpActionResult Get([FromODataUri] string id, [FromODataUri] string version)
{
SemanticVersion semanticVersion;
if (!SemanticVersion.TryParse(version, out semanticVersion))
{
return BadRequest("Invalid version");
}
if (string.IsNullOrWhiteSpace(id))
{
return BadRequest("Invalid package id");
}
var package = MirroringRepository.FindPackage(id, semanticVersion);
return package == null ? (IHttpActionResult)NotFound() : Ok(package.AsDataServicePackage());
}
}
}
|
Correct basic client config test | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading;
using Lokad.Cqrs.Build.Client;
using Lokad.Cqrs.Build.Engine;
using Lokad.Cqrs.Core.Dispatch.Events;
using Microsoft.WindowsAzure;
using NUnit.Framework;
using System.Linq;
namespace Lokad.Cqrs
{
[TestFixture]
public sealed class BasicClientConfigurationTests
{
[DataContract]
public sealed class Message : Define.Command
{
}
// ReSharper disable InconsistentNaming
[Test]
public void Test()
{
var dev = AzureStorage.CreateConfigurationForDev();
WipeAzureAccount.Fast(s => s.StartsWith("test-"), dev);
var events = new Subject<ISystemEvent>();
var b = new CqrsEngineBuilder();
b.Azure(c => c.AddAzureProcess(dev, "test-publish",container => { }));
b.Advanced.RegisterObserver(events);
var engine = b.Build();
var source = new CancellationTokenSource();
engine.Start(source.Token);
var builder = new CqrsClientBuilder();
builder.Azure(c => c.AddAzureSender(dev, "test-publish"));
var client = builder.Build();
client.Sender.SendOne(new Message());
using (engine)
using (events.OfType<EnvelopeAcked>().Subscribe(e => source.Cancel()))
{
source.Token.WaitHandle.WaitOne(5000);
source.Cancel();
}
}
}
} | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading;
using Lokad.Cqrs.Build.Client;
using Lokad.Cqrs.Build.Engine;
using Lokad.Cqrs.Core.Dispatch.Events;
using Microsoft.WindowsAzure;
using NUnit.Framework;
using System.Linq;
namespace Lokad.Cqrs
{
[TestFixture]
public sealed class BasicClientConfigurationTests
{
[DataContract]
public sealed class Message : Define.Command
{
}
// ReSharper disable InconsistentNaming
[Test]
public void Test()
{
var dev = AzureStorage.CreateConfigurationForDev();
WipeAzureAccount.Fast(s => s.StartsWith("test-"), dev);
var events = new Subject<ISystemEvent>();
var b = new CqrsEngineBuilder();
b.Azure(c => c.AddAzureProcess(dev, "test-publish",HandlerComposer.Empty));
b.Advanced.RegisterObserver(events);
var engine = b.Build();
var source = new CancellationTokenSource();
engine.Start(source.Token);
var builder = new CqrsClientBuilder();
builder.Azure(c => c.AddAzureSender(dev, "test-publish"));
var client = builder.Build();
client.Sender.SendOne(new Message());
using (engine)
using (events.OfType<EnvelopeAcked>().Subscribe(e => source.Cancel()))
{
source.Token.WaitHandle.WaitOne(5000);
source.Cancel();
}
}
}
} |
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0. | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.2.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Configuration 3.2.0")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.2.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Configuration 3.2.0")]
|
Add Fsm variable for text/initials | using UnityEngine;
using System;
using HutongGames.PlayMaker;
using TooltipAttribute = HutongGames.PlayMaker.TooltipAttribute;
using BCP.SimpleJSON;
/// <summary>
/// Custom PlayMaker action for MPF that sends a Trigger BCP command to MPF.
/// </summary>
[ActionCategory("BCP")]
[Tooltip("Sends 'text_input_high_score_complete' Trigger BCP command to MPF.")]
public class SendBCPInputHighScoreComplete : FsmStateAction
{
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("The text initials of the high score player to send to MPF")]
public string text;
/// <summary>
/// Resets this instance to default values.
/// </summary>
public override void Reset()
{
text = null;
}
/// <summary>
/// Called when the state becomes active. Sends the BCP Trigger command to MPF.
/// </summary>
public override void OnEnter()
{
BcpMessage message = BcpMessage.TriggerMessage("text_input_high_score_complete");
message.Parameters["text"] = new JSONString(text);
BcpServer.Instance.Send(message);
Finish();
}
}
| using UnityEngine;
using System;
using HutongGames.PlayMaker;
using TooltipAttribute = HutongGames.PlayMaker.TooltipAttribute;
using BCP.SimpleJSON;
/// <summary>
/// Custom PlayMaker action for MPF that sends a Trigger BCP command to MPF.
/// </summary>
[ActionCategory("BCP")]
[Tooltip("Sends 'text_input_high_score_complete' Trigger BCP command to MPF.")]
public class SendBCPInputHighScoreComplete : FsmStateAction
{
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("The variable containing text initials of the high score player to send to MPF")]
public FsmString text;
/// <summary>
/// Resets this instance to default values.
/// </summary>
public override void Reset()
{
text = null;
}
/// <summary>
/// Called when the state becomes active. Sends the BCP Trigger command to MPF.
/// </summary>
public override void OnEnter()
{
BcpMessage message = BcpMessage.TriggerMessage("text_input_high_score_complete");
message.Parameters["text"] = new JSONString(text.Value);
BcpServer.Instance.Send(message);
Finish();
}
}
|
Remove old points from back | using Nito;
using System.Collections;
using System.Net.NetworkInformation;
using UnityEngine;
namespace TrailAdvanced.PointSource {
public abstract class AbstractPointSource : MonoBehaviour {
public int maxPoints = 1000;
protected Deque<Vector3> points;
protected int minimumFreeCapacity = 10;
public Deque<Vector3> GetPoints() {
return points;
}
protected virtual void Start() {
points = new Deque<Vector3>(maxPoints);
}
protected virtual void Update() {
int count = points.Count - (points.Capacity - minimumFreeCapacity);
if (count > 0) {
points.RemoveRange(0, count);
}
}
}
} | using Nito;
using System.Collections;
using System.Net.NetworkInformation;
using UnityEngine;
namespace TrailAdvanced.PointSource {
public abstract class AbstractPointSource : MonoBehaviour {
public int maxPoints = 1000;
protected Deque<Vector3> points;
protected int minimumFreeCapacity = 10;
public Deque<Vector3> GetPoints() {
return points;
}
protected virtual void Start() {
points = new Deque<Vector3>(maxPoints);
}
protected virtual void Update() {
int count = points.Count - (points.Capacity - minimumFreeCapacity);
if (count > 0) {
points.RemoveRange(points.Count - count, count);
}
}
}
}
|
Reduce the date size for the email subject | namespace Pigeon.Pipelines
{
using System;
using Sitecore.Diagnostics;
public class SetEmailSubject:PigeonPipelineProcessor
{
public override void Process(PigeonPipelineArgs args)
{
Assert.IsNotNull(args,"args != null");
args.Subject = $"[Pigeon] {System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName()} {Environment.MachineName} - Date Range: {args.StartDateTime:O} -> {args.EndDateTime:O}";
}
}
} | namespace Pigeon.Pipelines
{
using System;
using Sitecore.Diagnostics;
public class SetEmailSubject:PigeonPipelineProcessor
{
public override void Process(PigeonPipelineArgs args)
{
Assert.IsNotNull(args,"args != null");
args.Subject = $"[Pigeon] {System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName()} {Environment.MachineName} - Date Range: {args.StartDateTime:G} -> {args.EndDateTime:G}";
}
}
} |
Fix bug with IB instrument addition window | // -----------------------------------------------------------------------
// <copyright file="AddInstrumentInteractiveBrokersWindow.xaml.cs" company="">
// Copyright 2016 Alexander Soffronow Pagonidis
// </copyright>
// -----------------------------------------------------------------------
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using NLog;
using QDMSServer.ViewModels;
using System;
using System.Windows;
using System.Windows.Input;
namespace QDMSServer
{
/// <summary>
/// Interaction logic for AddInstrumentInteractiveBrokersWindow.xaml
/// </summary>
public partial class AddInstrumentInteractiveBrokersWindow : MetroWindow
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public AddInstrumentInteractiveBrokersWindow()
{
try
{
ViewModel = new AddInstrumentIbViewModel(DialogCoordinator.Instance);
}
catch (Exception ex)
{
Hide();
_logger.Log(LogLevel.Error, ex.Message);
return;
}
DataContext = ViewModel;
InitializeComponent();
Show();
}
private void CloseBtn_Click(object sender, RoutedEventArgs e)
{
Hide();
}
private void DXWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (ViewModel != null)
{
ViewModel.Dispose();
}
}
private void SymbolTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
ViewModel.Search.Execute(null);
}
public AddInstrumentIbViewModel ViewModel { get; set; }
}
} | // -----------------------------------------------------------------------
// <copyright file="AddInstrumentInteractiveBrokersWindow.xaml.cs" company="">
// Copyright 2016 Alexander Soffronow Pagonidis
// </copyright>
// -----------------------------------------------------------------------
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using NLog;
using QDMSServer.ViewModels;
using System;
using System.Windows;
using System.Windows.Input;
namespace QDMSServer
{
/// <summary>
/// Interaction logic for AddInstrumentInteractiveBrokersWindow.xaml
/// </summary>
public partial class AddInstrumentInteractiveBrokersWindow : MetroWindow
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public AddInstrumentInteractiveBrokersWindow()
{
try
{
ViewModel = new AddInstrumentIbViewModel(DialogCoordinator.Instance);
}
catch (Exception ex)
{
Hide();
_logger.Log(LogLevel.Error, ex.Message);
return;
}
DataContext = ViewModel;
InitializeComponent();
ShowDialog();
}
private void CloseBtn_Click(object sender, RoutedEventArgs e)
{
Hide();
}
private void DXWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (ViewModel != null)
{
ViewModel.Dispose();
}
}
private void SymbolTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
ViewModel.Search.Execute(null);
}
public AddInstrumentIbViewModel ViewModel { get; set; }
}
} |
Simplify VoidResult to a value type | namespace StyleCop.Analyzers.Helpers
{
using System.Threading.Tasks;
internal static class SpecializedTasks
{
internal static Task CompletedTask { get; } = Task.FromResult(default(VoidResult));
private sealed class VoidResult
{
private VoidResult()
{
}
}
}
}
| namespace StyleCop.Analyzers.Helpers
{
using System.Threading.Tasks;
internal static class SpecializedTasks
{
internal static Task CompletedTask { get; } = Task.FromResult(default(VoidResult));
private struct VoidResult
{
}
}
}
|
Change port of urls in multi tenant admin | using System.Web.Mvc;
using Orchard.Environment.Configuration;
namespace Orchard.MultiTenancy.Extensions {
public static class UrlHelperExtensions {
public static string Tenant(this UrlHelper urlHelper, ShellSettings tenantShellSettings) {
return string.Format(
"http://{0}/{1}",
!string.IsNullOrEmpty(tenantShellSettings.RequestUrlHost)
? tenantShellSettings.RequestUrlHost
: urlHelper.RequestContext.HttpContext.Request.Headers["Host"],
tenantShellSettings.RequestUrlPrefix);
}
}
} | using System.Web.Mvc;
using Orchard.Environment.Configuration;
namespace Orchard.MultiTenancy.Extensions {
public static class UrlHelperExtensions {
public static string Tenant(this UrlHelper urlHelper, ShellSettings tenantShellSettings) {
//info: (heskew) might not keep the port insertion around beyond...
var port = string.Empty;
string host = urlHelper.RequestContext.HttpContext.Request.Headers["Host"];
if(host.Contains(":"))
port = host.Substring(host.IndexOf(":"));
return string.Format(
"http://{0}/{1}",
!string.IsNullOrEmpty(tenantShellSettings.RequestUrlHost)
? tenantShellSettings.RequestUrlHost + port : host,
tenantShellSettings.RequestUrlPrefix);
}
}
} |
Add SetComparison to the default build | namespace DeepEquals
{
using System.Collections;
public class DeepComparison
{
public static IEqualityComparer CreateComparer()
{
return new ComparisonComparer(Create());
}
public static CompositeComparison Create()
{
var root = new CompositeComparison();
root.AddRange(
new DefaultComparison(),
new EnumComparison(),
new ListComparison(root),
new ComplexObjectComparison(root));
return root;
}
}
}
| namespace DeepEquals
{
using System.Collections;
public class DeepComparison
{
public static IEqualityComparer CreateComparer()
{
return new ComparisonComparer(Create());
}
public static CompositeComparison Create()
{
var root = new CompositeComparison();
root.AddRange(
new DefaultComparison(),
new EnumComparison(),
new SetComparison(root),
new ListComparison(root),
new ComplexObjectComparison(root));
return root;
}
}
}
|
Update the docs here, too. | using System.Collections.Generic;
using System.Threading.Tasks;
namespace SparkPost
{
public interface IRecipientLists
{
/// <summary>
/// Creates a recipient list.
/// </summary>
/// <param name="recipientList">The properties of the recipientList to create.</param>
/// <returns>The response from the API.</returns>
Task<SendRecipientListsResponse> Create(RecipientList recipientList);
/// <summary>
/// Retrieves an email transmission.
/// </summary>
/// <param name="recipientListsId">The id of the transmission to retrieve.</param>
/// <returns>The response from the API.</returns>
Task<RetrieveRecipientListsResponse> Retrieve(string recipientListsId);
}
} | using System.Collections.Generic;
using System.Threading.Tasks;
namespace SparkPost
{
public interface IRecipientLists
{
/// <summary>
/// Creates a recipient list.
/// </summary>
/// <param name="recipientList">The properties of the recipientList to create.</param>
/// <returns>The response from the API.</returns>
Task<SendRecipientListsResponse> Create(RecipientList recipientList);
/// <summary>
/// Retrieves a recipient list.
/// </summary>
/// <param name="recipientListsId">The id of the recipient list to retrieve.</param>
/// <returns>The response from the API.</returns>
Task<RetrieveRecipientListsResponse> Retrieve(string recipientListsId);
}
} |
Use DetectIsJson string extension as opposed to a horrible try/catch | @model dynamic
@using Umbraco.Web.Templates
@{
var embedValue = string.Empty;
try {
embedValue = Model.value.preview;
} catch(Exception ex) {
embedValue = Model.value;
}
}
<div class="video-wrapper">
@Html.Raw(embedValue)
</div>
| @model dynamic
@using Umbraco.Web.Templates
@{
string embedValue = Convert.ToString(Model.value);
embedValue = embedValue.DetectIsJson() ? Model.value.preview : Model.value;
}
<div class="video-wrapper">
@Html.Raw(embedValue)
</div>
|
Fix `AsNonNull` not working on release configuration | // 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace osu.Framework.Extensions.ObjectExtensions
{
/// <summary>
/// Extensions that apply to all objects.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
/// </summary>
/// <remarks>
/// This should only be used when an assertion or other handling is not a reasonable alternative.
/// </remarks>
/// <param name="obj">The nullable object.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
public static T AsNonNull<T>(this T? obj)
where T : class
{
Debug.Assert(obj != null);
return obj;
}
/// <summary>
/// If the given object is null.
/// </summary>
public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);
/// <summary>
/// <c>true</c> if the given object is not null, <c>false</c> otherwise.
/// </summary>
public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
}
}
| // 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
namespace osu.Framework.Extensions.ObjectExtensions
{
/// <summary>
/// Extensions that apply to all objects.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
/// </summary>
/// <remarks>
/// This should only be used when an assertion or other handling is not a reasonable alternative.
/// </remarks>
/// <param name="obj">The nullable object.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
public static T AsNonNull<T>(this T? obj)
where T : class
{
Trace.Assert(obj != null);
Debug.Assert(obj != null);
return obj;
}
/// <summary>
/// If the given object is null.
/// </summary>
public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);
/// <summary>
/// <c>true</c> if the given object is not null, <c>false</c> otherwise.
/// </summary>
public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
}
}
|
Update delete signature to use only id | using System.Collections.Generic;
using DapperTesting.Core.Model;
namespace DapperTesting.Core.Data
{
public interface IUserRepository
{
void Create(User user);
void Delete(User user);
User Get(int id);
User Get(string email);
List<User> GetAll();
void Update(User user);
}
}
| using System.Collections.Generic;
using DapperTesting.Core.Model;
namespace DapperTesting.Core.Data
{
public interface IUserRepository
{
void Create(User user);
void Delete(int id);
User Get(int id);
User Get(string email);
List<User> GetAll();
void Update(User user);
}
}
|
Use static import for repeated EditorGUI.* calls | using UnityEditor;
using UnityEngine;
namespace Alensia.Core.I18n
{
[CustomPropertyDrawer(typeof(TranslatableText))]
public class TranslatableTextPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var text = property.FindPropertyRelative("_text");
var textKey = property.FindPropertyRelative("_textKey");
EditorGUI.BeginProperty(position, label, text);
var xMin = position.xMin;
position.height = EditorGUIUtility.singleLineHeight;
EditorGUI.BeginChangeCheck();
var textValue = EditorGUI.TextField(position, label, text.stringValue);
if (EditorGUI.EndChangeCheck())
{
text.stringValue = textValue;
}
EditorGUI.EndProperty();
position.xMin = xMin;
position.yMin += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
EditorGUI.BeginProperty(position, label, textKey);
position.height = EditorGUIUtility.singleLineHeight;
EditorGUI.BeginChangeCheck();
var textKeyValue = EditorGUI.TextField(
position, $"{property.displayName} (I18n Key)", textKey.stringValue);
if (EditorGUI.EndChangeCheck())
{
textKey.stringValue = textKeyValue;
}
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
const int rows = 2;
return base.GetPropertyHeight(property, label) * rows +
(rows - 1) * EditorGUIUtility.standardVerticalSpacing;
}
}
} | using UnityEditor;
using UnityEngine;
using static UnityEditor.EditorGUI;
namespace Alensia.Core.I18n
{
[CustomPropertyDrawer(typeof(TranslatableText))]
public class TranslatableTextPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var text = property.FindPropertyRelative("_text");
var textKey = property.FindPropertyRelative("_textKey");
BeginProperty(position, label, text);
var xMin = position.xMin;
position.height = EditorGUIUtility.singleLineHeight;
BeginChangeCheck();
var textValue = TextField(position, label, text.stringValue);
if (EndChangeCheck())
{
text.stringValue = textValue;
}
EndProperty();
position.xMin = xMin;
position.yMin += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
BeginProperty(position, label, textKey);
position.height = EditorGUIUtility.singleLineHeight;
BeginChangeCheck();
var textKeyValue = TextField(
position, $"{property.displayName} (I18n Key)", textKey.stringValue);
if (EndChangeCheck())
{
textKey.stringValue = textKeyValue;
}
EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
const int rows = 2;
return base.GetPropertyHeight(property, label) * rows +
(rows - 1) * EditorGUIUtility.standardVerticalSpacing;
}
}
} |
Move TestEnvironmentSetUpFixture into project root namespace | using ImplicitNullability.Plugin.Tests;
using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
[assembly: RequiresSTA]
namespace ImplicitNullability.Plugin.Tests
{
[ZoneDefinition]
public interface IImplicitNullabilityTestEnvironmentZone : ITestsZone, IRequire<PsiFeatureTestZone>, IRequire<IImplicitNullabilityZone>
{
}
[ZoneMarker]
public class ZoneMarker : IRequire<IImplicitNullabilityTestEnvironmentZone>
{
}
}
// ReSharper disable once CheckNamespace
[SetUpFixture]
public class TestEnvironmentSetUpFixture : ExtensionTestEnvironmentAssembly<IImplicitNullabilityTestEnvironmentZone>
{
}
| using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
[assembly: RequiresSTA]
namespace ImplicitNullability.Plugin.Tests
{
[ZoneDefinition]
public interface IImplicitNullabilityTestEnvironmentZone : ITestsZone, IRequire<PsiFeatureTestZone>, IRequire<IImplicitNullabilityZone>
{
}
[ZoneMarker]
public class ZoneMarker : IRequire<IImplicitNullabilityTestEnvironmentZone>
{
}
[SetUpFixture]
public class TestEnvironmentSetUpFixture : ExtensionTestEnvironmentAssembly<IImplicitNullabilityTestEnvironmentZone>
{
}
}
|
Add a 60 sec pause before SQL Server connection | using System.Data;
using System.Threading;
using Evolve.Driver;
using Xunit;
namespace Evolve.Core.Test.Driver
{
public class CoreReflectionBasedDriverTest
{
[Fact(DisplayName = "MicrosoftDataSqliteDriver_works")]
public void MicrosoftDataSqliteDriver_works()
{
var driver = new CoreMicrosoftDataSqliteDriver(TestContext.DriverResourcesDepsFile, TestContext.NugetPackageFolder);
var cnn = driver.CreateConnection("Data Source=:memory:");
cnn.Open();
Assert.True(cnn.State == ConnectionState.Open);
}
[Fact(DisplayName = "NpgsqlDriver_works")]
public void NpgsqlDriver_works()
{
var driver = new CoreNpgsqlDriver(TestContext.DriverResourcesDepsFile, TestContext.NugetPackageFolder);
var cnn = driver.CreateConnection($"Server=127.0.0.1;Port=5432;Database=my_database;User Id=postgres;Password={TestContext.PgPassword};");
cnn.Open();
Assert.True(cnn.State == ConnectionState.Open);
}
[Fact(DisplayName = "SqlClientDriver_works")]
public void SqlClientDriver_works()
{
Thread.Sleep(30000);
var driver = new CoreSqlClientDriver(TestContext.DriverResourcesDepsFile, TestContext.NugetPackageFolder);
var cnn = driver.CreateConnection("Server=127.0.0.1;Database=master;User Id=sa;Password=Password12!;");
cnn.Open();
Assert.True(cnn.State == ConnectionState.Open);
}
}
}
| using System.Data;
using System.Threading;
using Evolve.Driver;
using Xunit;
namespace Evolve.Core.Test.Driver
{
public class CoreReflectionBasedDriverTest
{
[Fact(DisplayName = "MicrosoftDataSqliteDriver_works")]
public void MicrosoftDataSqliteDriver_works()
{
var driver = new CoreMicrosoftDataSqliteDriver(TestContext.DriverResourcesDepsFile, TestContext.NugetPackageFolder);
var cnn = driver.CreateConnection("Data Source=:memory:");
cnn.Open();
Assert.True(cnn.State == ConnectionState.Open);
}
[Fact(DisplayName = "NpgsqlDriver_works")]
public void NpgsqlDriver_works()
{
var driver = new CoreNpgsqlDriver(TestContext.DriverResourcesDepsFile, TestContext.NugetPackageFolder);
var cnn = driver.CreateConnection($"Server=127.0.0.1;Port=5432;Database=my_database;User Id=postgres;Password={TestContext.PgPassword};");
cnn.Open();
Assert.True(cnn.State == ConnectionState.Open);
}
[Fact(DisplayName = "SqlClientDriver_works")]
public void SqlClientDriver_works()
{
Thread.Sleep(60000);
var driver = new CoreSqlClientDriver(TestContext.DriverResourcesDepsFile, TestContext.NugetPackageFolder);
var cnn = driver.CreateConnection("Server=127.0.0.1;Database=master;User Id=sa;Password=Password12!;");
cnn.Open();
Assert.True(cnn.State == ConnectionState.Open);
}
}
}
|
Fix for nullable doubles in entities | using System;
using Newtonsoft.Json.Linq;
namespace Chronological
{
public class DataType
{
public string TimeSeriesInsightsType { get; }
internal DataType(string dataType)
{
TimeSeriesInsightsType = dataType;
}
internal JProperty ToJProperty()
{
return new JProperty("type", TimeSeriesInsightsType);
}
internal static DataType FromType(Type type)
{
switch (type)
{
case Type doubleType when doubleType == typeof(double):
return Double;
case Type stringType when stringType == typeof(string):
return String;
case Type dateTimeType when dateTimeType == typeof(DateTime):
return DateTime;
case Type boolType when boolType == typeof(bool) || boolType == typeof(bool?):
return Boolean;
default:
//Todo: Better exceptions
throw new Exception("Unexpected Type");
}
}
public static DataType Double => new DataType("Double");
public static DataType String => new DataType("String");
public static DataType DateTime => new DataType("DateTime");
public static DataType Boolean => new DataType("Boolean");
}
}
| using System;
using Newtonsoft.Json.Linq;
namespace Chronological
{
public class DataType
{
public string TimeSeriesInsightsType { get; }
internal DataType(string dataType)
{
TimeSeriesInsightsType = dataType;
}
internal JProperty ToJProperty()
{
return new JProperty("type", TimeSeriesInsightsType);
}
internal static DataType FromType(Type type)
{
switch (type)
{
case Type doubleType when doubleType == typeof(double) || doubleType == typeof(double?):
return Double;
case Type stringType when stringType == typeof(string):
return String;
case Type dateTimeType when dateTimeType == typeof(DateTime):
return DateTime;
case Type boolType when boolType == typeof(bool) || boolType == typeof(bool?):
return Boolean;
default:
//Todo: Better exceptions
throw new Exception("Unexpected Type");
}
}
public static DataType Double => new DataType("Double");
public static DataType String => new DataType("String");
public static DataType DateTime => new DataType("DateTime");
public static DataType Boolean => new DataType("Boolean");
}
}
|
Make interface test more interesting | using System;
interface IFlyable
{
void Fly();
string Name { get; }
}
class Bird : IFlyable
{
public Bird() { }
public string Name => "Bird";
public void Fly()
{
Console.WriteLine("Chirp");
}
}
class Plane : IFlyable
{
public Plane() { }
public string Name => "Plane";
public void Fly()
{
Console.WriteLine("Nnneeaoowww");
}
}
static class Program
{
public static IFlyable[] GetBirdInstancesAndPlaneInstancesMixed()
{
return new IFlyable[]
{
new Bird(),
new Plane()
};
}
public static void Main(string[] Args)
{
var items = GetBirdInstancesAndPlaneInstancesMixed();
for (int i = 0; i < items.Length; i++)
{
Console.Write(items[i].Name + ": ");
items[i].Fly();
}
}
}
| using System;
interface IFlyable
{
void Fly();
string Name { get; }
}
class Bird : IFlyable
{
public Bird()
{
Name = "Bird";
}
public string Name { get; private set; }
public void Fly()
{
Console.WriteLine("Chirp");
}
}
class Plane : IFlyable
{
public Plane() { }
public string Name => "Plane";
public void Fly()
{
Console.WriteLine("Nnneeaoowww");
}
}
static class Program
{
public static IFlyable[] GetBirdInstancesAndPlaneInstancesMixed()
{
return new IFlyable[]
{
new Bird(),
new Plane()
};
}
public static void Main(string[] Args)
{
var items = GetBirdInstancesAndPlaneInstancesMixed();
for (int i = 0; i < items.Length; i++)
{
Console.Write(items[i].Name + ": ");
items[i].Fly();
}
}
}
|
Update binding redirects for 0.3.0 builds | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell;
// Add binding redirects for each assembly we ship in VS. This is required so that these assemblies show
// up in the Load context, which means that we can use ServiceHub and other nice things.
//
// The versions here need to match what the build is producing. If you change the version numbers
// for the Blazor assemblies, this needs to change as well.
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.AspNetCore.Blazor.AngleSharp",
GenerateCodeBase = true,
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.9.9.0",
NewVersion = "0.9.9.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.AspNetCore.Blazor.Razor.Extensions",
GenerateCodeBase = true,
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.2.0.0",
NewVersion = "0.2.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.VisualStudio.LanguageServices.Blazor",
GenerateCodeBase = true,
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.2.0.0",
NewVersion = "0.2.0.0")]
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell;
// Add binding redirects for each assembly we ship in VS. This is required so that these assemblies show
// up in the Load context, which means that we can use ServiceHub and other nice things.
//
// The versions here need to match what the build is producing. If you change the version numbers
// for the Blazor assemblies, this needs to change as well.
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.AspNetCore.Blazor.AngleSharp",
GenerateCodeBase = true,
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.9.9.0",
NewVersion = "0.9.9.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.AspNetCore.Blazor.Razor.Extensions",
GenerateCodeBase = true,
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.3.0.0",
NewVersion = "0.3.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.VisualStudio.LanguageServices.Blazor",
GenerateCodeBase = true,
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.3.0.0",
NewVersion = "0.3.0.0")]
|
Use cross platform compatible paths for debug run. | using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace IronAHK
{
partial class Program
{
const bool debug =
#if DEBUG
true
#else
false
#endif
;
[Conditional("DEBUG"), DllImport("kernel32.dll")]
static extern void AllocConsole();
[Conditional("DEBUG")]
static void Start(ref string[] args)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
AllocConsole();
args = new[] { string.Format("..{0}..{0}..{0}Tests{0}Code{0}isolated.ahk", Path.DirectorySeparatorChar), "/out", "test.exe" };
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace IronAHK
{
partial class Program
{
const bool debug =
#if DEBUG
true
#else
false
#endif
;
[Conditional("DEBUG"), DllImport("kernel32.dll")]
static extern void AllocConsole();
[Conditional("DEBUG")]
static void Start(ref string[] args)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
AllocConsole();
const string source = "..{0}..{0}..{0}Tests{0}Code{0}isolated.ahk";
const string binary = "test.exe";
args = string.Format(source + " --out " + binary, Path.DirectorySeparatorChar).Split(' ');
}
}
}
|
Remove weird vestigial `Current` reimplementation | // 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.Bindables;
using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Skinning
{
public class LegacyScoreCounter : GameplayScoreCounter, ISkinnableComponent
{
private readonly ISkin skin;
protected override double RollingDuration => 1000;
protected override Easing RollingEasing => Easing.Out;
public new Bindable<double> Current { get; } = new Bindable<double>();
public LegacyScoreCounter(ISkin skin)
: base(6)
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
this.skin = skin;
// base class uses int for display, but externally we bind to ScoreProcessor as a double for now.
Current.BindValueChanged(v => base.Current.Value = (int)v.NewValue);
Scale = new Vector2(0.96f);
Margin = new MarginPadding(10);
}
protected sealed override OsuSpriteText CreateSpriteText() => new LegacySpriteText(skin, LegacyFont.Score)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
};
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Skinning
{
public class LegacyScoreCounter : GameplayScoreCounter, ISkinnableComponent
{
private readonly ISkin skin;
protected override double RollingDuration => 1000;
protected override Easing RollingEasing => Easing.Out;
public LegacyScoreCounter(ISkin skin)
: base(6)
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
this.skin = skin;
Scale = new Vector2(0.96f);
Margin = new MarginPadding(10);
}
protected sealed override OsuSpriteText CreateSpriteText() => new LegacySpriteText(skin, LegacyFont.Score)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
};
}
}
|
Use full URI rather than CURIE for property type | using System.Collections.Generic;
using BrightstarDB.EntityFramework;
namespace BrightstarDB.Samples.EntityFramework.FoafCore
{
[Entity("http://xmlns.com/foaf/0.1/Person")]
public interface IPerson
{
[Identifier("http://www.brightstardb.com/people/")]
string Id { get; }
[PropertyType("foaf:nick")]
string Nickname { get; set; }
[PropertyType("foaf:name")]
string Name { get; set; }
[PropertyType("foaf:Organization")]
string Organisation { get; set; }
[PropertyType("foaf:knows")]
ICollection<IPerson> Knows { get; set; }
[InversePropertyType("foaf:knows")]
ICollection<IPerson> KnownBy { get; set; }
}
}
| using System.Collections.Generic;
using BrightstarDB.EntityFramework;
namespace BrightstarDB.Samples.EntityFramework.FoafCore
{
[Entity("http://xmlns.com/foaf/0.1/Person")]
public interface IPerson
{
[Identifier("http://www.brightstardb.com/people/")]
string Id { get; }
[PropertyType("http://xmlns.com/foaf/0.1/nick")]
string Nickname { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/name")]
string Name { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/Organization")]
string Organisation { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/knows")]
ICollection<IPerson> Knows { get; set; }
[InversePropertyType("http://xmlns.com/foaf/0.1/knows")]
ICollection<IPerson> KnownBy { get; set; }
}
}
|
Test broken by QueryWrapper.ShouldContain issue | namespace Nancy.Testing.Tests
{
using System.IO;
using System.Linq;
using System.Text;
using Nancy;
using Nancy.Tests;
using Xunit;
public class BrowserResponseBodyWrapperFixture
{
[Fact]
public void Should_contain_response_body()
{
// Given
var body = new BrowserResponseBodyWrapper(new Response
{
Contents = stream =>
{
var writer = new StreamWriter(stream);
writer.Write("This is the content");
writer.Flush();
}
});
var content = Encoding.ASCII.GetBytes("This is the content");
// When
var result = body.SequenceEqual(content);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_querywrapper_for_css_selector_match()
{
// Given
var body = new BrowserResponseBodyWrapper(new Response
{
Contents = stream =>
{
var writer = new StreamWriter(stream);
writer.Write("<div>Outer and <div id='#bar'>inner</div></div>");
writer.Flush();
}
});
// When
var result = body["#bar"];
// Then
#if __MonoCS__
AssertExtensions.ShouldContain(result, "inner", System.StringComparison.OrdinalIgnoreCase);
#else
result.ShouldContain("inner");
#endif
}
}
} | namespace Nancy.Testing.Tests
{
using System.IO;
using System.Linq;
using System.Text;
using Nancy;
using Nancy.Tests;
using Xunit;
public class BrowserResponseBodyWrapperFixture
{
[Fact]
public void Should_contain_response_body()
{
// Given
var body = new BrowserResponseBodyWrapper(new Response
{
Contents = stream =>
{
var writer = new StreamWriter(stream);
writer.Write("This is the content");
writer.Flush();
}
});
var content = Encoding.ASCII.GetBytes("This is the content");
// When
var result = body.SequenceEqual(content);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_querywrapper_for_css_selector_match()
{
// Given
var body = new BrowserResponseBodyWrapper(new Response
{
Contents = stream =>
{
var writer = new StreamWriter(stream);
writer.Write("<div>Outer and <div id='bar'>inner</div></div>");
writer.Flush();
}
});
// When
var result = body["#bar"];
// Then
#if __MonoCS__
AssertExtensions.ShouldContain(result, "inner", System.StringComparison.OrdinalIgnoreCase);
#else
result.ShouldContain("inner");
#endif
}
}
} |
Add new test for String.SubstringRightSafe | #region Using
using System;
using NUnit.Framework;
#endregion
namespace PortableExtensions.Testing
{
[TestFixture]
public partial class StringExTest
{
[TestCase]
public void SubstringRightSafeTestCase()
{
var actual = "testabc".SubstringRightSafe( 3 );
Assert.AreEqual( "abc", actual );
actual = "testabc".SubstringRightSafe( 300 );
Assert.AreEqual( "testabc", actual );
}
[TestCase]
[ExpectedException( typeof ( ArgumentNullException ) )]
public void SubstringRightSafeTestCaseNullCheck()
{
var actual = StringEx.SubstringRight( null, 5 );
}
}
} | #region Using
using System;
using NUnit.Framework;
#endregion
namespace PortableExtensions.Testing
{
[TestFixture]
public partial class StringExTest
{
[TestCase]
public void SubstringRightSafeTestCase()
{
var actual = "testabc".SubstringRightSafe( 3 );
Assert.AreEqual( "abc", actual );
actual = "testabc".SubstringRightSafe( 300 );
Assert.AreEqual( "testabc", actual );
actual = "".SubstringRightSafe(300);
Assert.AreEqual("", actual);
}
[TestCase]
[ExpectedException( typeof ( ArgumentNullException ) )]
public void SubstringRightSafeTestCaseNullCheck()
{
var actual = StringEx.SubstringRight( null, 5 );
}
}
}
|
Change - Consolidated sub-expressions unit-tests. | using Newtonsoft.Json.Linq;
using Xunit;
using DevLab.JmesPath.Expressions;
using DevLab.JmesPath.Utils;
namespace jmespath.net.tests.Expressions
{
public class JmesPathSubExpressionTest
{
[Fact]
public void JmesPathSubExpression_identifier()
{
const string json = "{\"foo\": {\"bar\": \"baz\"}}";
var token = JToken.Parse(json);
var expr = new JmesPathIdentifier("foo");
var sub = new JmesPathIdentifier("bar");
var combined = new JmesPathSubExpression(expr, sub);
var result = combined.Transform(token);
Assert.Equal("\"baz\"", result.AsString());
}
}
} | using Newtonsoft.Json.Linq;
using Xunit;
using DevLab.JmesPath.Expressions;
using DevLab.JmesPath.Utils;
namespace jmespath.net.tests.Expressions
{
public class JmesPathSubExpressionTest
{
/*
* http://jmespath.org/specification.html#subexpressions
*
* search(foo.bar, {"foo": {"bar": "value"}}) -> "value"
* search(foo."bar", {"foo": {"bar": "value"}}) -> "value"
* search(foo.bar, {"foo": {"baz": "value"}}) -> null
* search(foo.bar.baz, {"foo": {"bar": {"baz": "value"}}}) -> "value"
*
*/
[Fact]
public void JmesPathSubExpression_Transform()
{
JmesPathSubExpression_Transform(new[] {"foo", "bar"}, "{\"foo\": {\"bar\": \"value\" }}", "\"value\"");
JmesPathSubExpression_Transform(new[] { "foo", "bar" }, "{\"foo\": {\"bar\": \"value\" }}", "\"value\"");
JmesPathSubExpression_Transform(new[] { "foo", "bar" }, "{\"foo\": {\"baz\": \"value\" }}", null);
JmesPathSubExpression_Transform(new[] { "foo", "bar", "baz" }, "{\"foo\": {\"bar\": { \"baz\": \"value\" }}}", "\"value\"");
}
public void JmesPathSubExpression_Transform(string[] expressions, string input, string expected)
{
JmesPathExpression expression = null;
foreach (var identifier in expressions)
{
JmesPathExpression ident = new JmesPathIdentifier(identifier);
expression = expression != null
? new JmesPathSubExpression(expression, ident)
: ident
;
}
var token = JToken.Parse(input);
var result = expression.Transform(token);
var actual = result?.AsString();
Assert.Equal(expected, actual);
}
}
} |
Add triple variant of Zip as IEnumerable<> extension | using System.Collections.Generic;
using WalletWasabi.Crypto.Groups;
namespace System.Linq
{
public static class Extensions
{
public static GroupElement Sum(this IEnumerable<GroupElement> groupElements) =>
groupElements.Aggregate(GroupElement.Infinity, (ge, acc) => ge + acc);
}
}
| using System.Collections.Generic;
using WalletWasabi.Helpers;
using WalletWasabi.Crypto.Groups;
namespace System.Linq
{
public static class Extensions
{
public static GroupElement Sum(this IEnumerable<GroupElement> groupElements) =>
groupElements.Aggregate(GroupElement.Infinity, (ge, acc) => ge + acc);
public static IEnumerable<TResult> Zip<TFirst, TSecond, TThird, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, IEnumerable<TThird> third, Func<TFirst, TSecond, TThird, TResult> resultSelector)
{
Guard.NotNull(nameof(first), first);
Guard.NotNull(nameof(second), second);
Guard.NotNull(nameof(third), third);
Guard.NotNull(nameof(resultSelector), resultSelector);
using var e1 = first.GetEnumerator();
using var e2 = second.GetEnumerator();
using var e3 = third.GetEnumerator();
while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext())
{
yield return resultSelector(e1.Current, e2.Current, e3.Current);
}
}
}
}
|
Fix Slowest() and Fastest() extension methods | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="MeasurementGroupExtensions.cs" company="Catel development team">
// Copyright (c) 2008 - 2016 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.BenchmarkCombiner
{
using System.Linq;
public static class MeasurementGroupExtensions
{
public static VersionMeasurements Slowest(this MeasurementGroup group)
{
var ordered = group.Measurements.OrderBy(x => x.AverageNanoSeconds);
return ordered.LastOrDefault();
}
public static VersionMeasurements Fastest(this MeasurementGroup group)
{
var ordered = group.Measurements.OrderBy(x => x.AverageNanoSeconds);
return ordered.FirstOrDefault();
}
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="MeasurementGroupExtensions.cs" company="Catel development team">
// Copyright (c) 2008 - 2016 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.BenchmarkCombiner
{
using System.Linq;
public static class MeasurementGroupExtensions
{
public static VersionMeasurements Slowest(this MeasurementGroup group)
{
var ordered = group.Measurements.OrderBy(x => x.AverageNanoSecondsPerOperation);
return ordered.LastOrDefault();
}
public static VersionMeasurements Fastest(this MeasurementGroup group)
{
var ordered = group.Measurements.OrderBy(x => x.AverageNanoSecondsPerOperation);
return ordered.FirstOrDefault();
}
}
} |
Fix model position translation for header views. | using System;
using System.Linq;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Widget;
using Toggl.Joey.UI.Adapters;
using ListFragment = Android.Support.V4.App.ListFragment;
namespace Toggl.Joey.UI.Fragments
{
public class RecentTimeEntriesListFragment : ListFragment
{
public override void OnViewCreated (View view, Bundle savedInstanceState)
{
base.OnViewCreated (view, savedInstanceState);
var headerView = new View (Activity);
int headerWidth = (int) TypedValue.ApplyDimension (ComplexUnitType.Dip, 6, Resources.DisplayMetrics);
headerView.SetMinimumHeight (headerWidth);
ListView.AddHeaderView (headerView);
ListAdapter = new RecentTimeEntriesAdapter ();
}
public override void OnListItemClick (ListView l, View v, int position, long id)
{
var headerAdapter = l.Adapter as HeaderViewListAdapter;
RecentTimeEntriesAdapter adapter = null;
if (headerAdapter != null)
adapter = headerAdapter.WrappedAdapter as RecentTimeEntriesAdapter;
if (adapter == null)
return;
var model = adapter.GetModel (position);
if (model == null)
return;
model.Continue ();
}
}
}
| using System;
using System.Linq;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Widget;
using Toggl.Joey.UI.Adapters;
using ListFragment = Android.Support.V4.App.ListFragment;
namespace Toggl.Joey.UI.Fragments
{
public class RecentTimeEntriesListFragment : ListFragment
{
public override void OnViewCreated (View view, Bundle savedInstanceState)
{
base.OnViewCreated (view, savedInstanceState);
var headerView = new View (Activity);
int headerWidth = (int) TypedValue.ApplyDimension (ComplexUnitType.Dip, 6, Resources.DisplayMetrics);
headerView.SetMinimumHeight (headerWidth);
ListView.AddHeaderView (headerView);
ListAdapter = new RecentTimeEntriesAdapter ();
}
public override void OnListItemClick (ListView l, View v, int position, long id)
{
RecentTimeEntriesAdapter adapter = null;
if (l.Adapter is HeaderViewListAdapter) {
var headerAdapter = (HeaderViewListAdapter)l.Adapter;
adapter = headerAdapter.WrappedAdapter as RecentTimeEntriesAdapter;
// Adjust the position by taking into account the fact that we've got headers
position -= headerAdapter.HeadersCount;
} else if (l.Adapter is RecentTimeEntriesAdapter) {
adapter = (RecentTimeEntriesAdapter)l.Adapter;
}
if (adapter == null)
return;
var model = adapter.GetModel (position);
if (model == null)
return;
model.Continue ();
}
}
}
|
Change putMessage function to prevent double serialization. | using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
namespace AzureStorage.Queue
{
public class AzureQueue<T> : IAzureQueue<T> where T : class
{
private readonly CloudQueue _queue;
public AzureQueue(string conectionString, string queueName)
{
queueName = queueName.ToLower();
var storageAccount = CloudStorageAccount.Parse(conectionString);
var queueClient = storageAccount.CreateCloudQueueClient();
_queue = queueClient.GetQueueReference(queueName);
_queue.CreateIfNotExistsAsync().Wait();
}
public Task PutMessageAsync(T itm)
{
var msg = Newtonsoft.Json.JsonConvert.SerializeObject(itm);
return _queue.AddMessageAsync(new CloudQueueMessage(msg));
}
public async Task<AzureQueueMessage<T>> GetMessageAsync()
{
var msg = await _queue.GetMessageAsync();
if (msg == null)
return null;
await _queue.DeleteMessageAsync(msg);
return AzureQueueMessage<T>.Create(Newtonsoft.Json.JsonConvert.DeserializeObject<T>(msg.AsString), msg);
}
public Task ProcessMessageAsync(AzureQueueMessage<T> token)
{
return _queue.DeleteMessageAsync(token.Token);
}
public Task ClearAsync()
{
return _queue.ClearAsync();
}
}
}
| using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
namespace AzureStorage.Queue
{
public class AzureQueue<T> : IAzureQueue<T> where T : class
{
private readonly CloudQueue _queue;
public AzureQueue(string conectionString, string queueName)
{
queueName = queueName.ToLower();
var storageAccount = CloudStorageAccount.Parse(conectionString);
var queueClient = storageAccount.CreateCloudQueueClient();
_queue = queueClient.GetQueueReference(queueName);
_queue.CreateIfNotExistsAsync().Wait();
}
public Task PutMessageAsync(T itm)
{
var msg = itm.ToString();
return _queue.AddMessageAsync(new CloudQueueMessage(msg));
}
public async Task<AzureQueueMessage<T>> GetMessageAsync()
{
var msg = await _queue.GetMessageAsync();
if (msg == null)
return null;
await _queue.DeleteMessageAsync(msg);
return AzureQueueMessage<T>.Create(Newtonsoft.Json.JsonConvert.DeserializeObject<T>(msg.AsString), msg);
}
public Task ProcessMessageAsync(AzureQueueMessage<T> token)
{
return _queue.DeleteMessageAsync(token.Token);
}
public Task ClearAsync()
{
return _queue.ClearAsync();
}
}
}
|
Fix bug with edit/view non-domain users with enabled domain integration | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace Bonobo.Git.Server
{
public class UsernameUrl
{
//to allow support for email addresses as user names, only encode/decode user name if it is not an email address
private static Regex _isEmailRegEx = new Regex(
@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$",
RegexOptions.Compiled);
public static string Encode(string username)
{
var nameParts = username.Split('\\');
if ( nameParts.Count() == 2 && !_isEmailRegEx.IsMatch(username) )
{
return nameParts[1] + "@" + nameParts[0];
}
return username;
}
public static string Decode(string username)
{
var nameParts = username.Split('@');
if ( (nameParts.Count() == 2 && !_isEmailRegEx.IsMatch(username) ) ||
String.Equals(ConfigurationManager.AppSettings["ActiveDirectoryIntegration"], "true", StringComparison.InvariantCultureIgnoreCase))
{
return nameParts[1] + "\\" + nameParts[0];
}
return username;
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace Bonobo.Git.Server
{
public class UsernameUrl
{
//to allow support for email addresses as user names, only encode/decode user name if it is not an email address
private static Regex _isEmailRegEx = new Regex(
@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$",
RegexOptions.Compiled);
public static string Encode(string username)
{
var nameParts = username.Split('\\');
if ( nameParts.Count() == 2 && !_isEmailRegEx.IsMatch(username) )
{
return nameParts[1] + "@" + nameParts[0];
}
return username;
}
public static string Decode(string username)
{
var nameParts = username.Split('@');
if ( (nameParts.Count() == 2) && (!_isEmailRegEx.IsMatch(username) ||
(String.Equals(ConfigurationManager.AppSettings["ActiveDirectoryIntegration"], "true", StringComparison.InvariantCultureIgnoreCase))))
{
return nameParts[1] + "\\" + nameParts[0];
}
return username;
}
}
} |
Fix wrong namespace beeing used in TitanTest | using Titan.Sharecode;
using Xunit;
namespace TitanTest
{
public class ShareCodeDecoderTest
{
[Fact]
public void TestDecoder()
{
if(ShareCode.Decode("CSGO-727c4-5oCG3-PurVX-sJkdn-LsXfE").MatchID == 3208347562318757960)
{
Assert.True(true, "The decoded Match ID is 3208347562318757960");
}
else
{
Assert.True(false);
}
}
}
} | using Titan.MatchID.Sharecode;
using Xunit;
namespace TitanTest
{
public class ShareCodeDecoderTest
{
[Fact]
public void TestDecoder()
{
if(ShareCode.Decode("CSGO-727c4-5oCG3-PurVX-sJkdn-LsXfE").MatchID == 3208347562318757960)
{
Assert.True(true, "The decoded Match ID is 3208347562318757960");
}
else
{
Assert.True(false);
}
}
}
} |
Handle "null" data values from Lassie API | using Eurofurence.App.Server.Services.Abstractions.Lassie;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace Eurofurence.App.Server.Services.Lassie
{
public class LassieApiClient : ILassieApiClient
{
private class DataResponseWrapper<T>
{
public T[] Data { get; set; }
}
private LassieConfiguration _configuration;
public LassieApiClient(LassieConfiguration configuration)
{
_configuration = configuration;
}
public async Task<LostAndFoundResponse[]> QueryLostAndFoundDbAsync(string command = "lostandfound")
{
var outgoingQuery = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("apikey", _configuration.ApiKey),
new KeyValuePair<string, string>("request", "lostandfounddb"),
new KeyValuePair<string, string>("command", command)
};
using (var client = new HttpClient())
{
var response = await client.PostAsync(_configuration.BaseApiUrl, new FormUrlEncodedContent(outgoingQuery));
var content = await response.Content.ReadAsStringAsync();
var dataResponse = JsonConvert.DeserializeObject<DataResponseWrapper<LostAndFoundResponse>>(content,
new JsonSerializerSettings() { DateTimeZoneHandling = DateTimeZoneHandling.Local });
return dataResponse.Data;
}
}
}
} | using Eurofurence.App.Server.Services.Abstractions.Lassie;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace Eurofurence.App.Server.Services.Lassie
{
public class LassieApiClient : ILassieApiClient
{
private class DataResponseWrapper<T>
{
public T[] Data { get; set; }
}
private LassieConfiguration _configuration;
public LassieApiClient(LassieConfiguration configuration)
{
_configuration = configuration;
}
public async Task<LostAndFoundResponse[]> QueryLostAndFoundDbAsync(string command = "lostandfound")
{
var outgoingQuery = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("apikey", _configuration.ApiKey),
new KeyValuePair<string, string>("request", "lostandfounddb"),
new KeyValuePair<string, string>("command", command)
};
using (var client = new HttpClient())
{
var response = await client.PostAsync(_configuration.BaseApiUrl, new FormUrlEncodedContent(outgoingQuery));
var content = await response.Content.ReadAsStringAsync();
var dataResponse = JsonConvert.DeserializeObject<DataResponseWrapper<LostAndFoundResponse>>(content,
new JsonSerializerSettings() { DateTimeZoneHandling = DateTimeZoneHandling.Local });
return dataResponse.Data ?? new LostAndFoundResponse[0];
}
}
}
} |
Add unit tests for enum access token grant type read and write. | namespace TraktApiSharp.Tests.Enums
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Enums;
[TestClass]
public class TraktAccessTokenGrantTypeTests
{
[TestMethod]
public void TestTraktAccessTokenGrantTypeHasMembers()
{
typeof(TraktAccessTokenGrantType).GetEnumNames().Should().HaveCount(3)
.And.Contain("AuthorizationCode", "RefreshToken", "Unspecified");
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeGetAsString()
{
TraktAccessTokenGrantType.AuthorizationCode.AsString().Should().Be("authorization_code");
TraktAccessTokenGrantType.RefreshToken.AsString().Should().Be("refresh_token");
TraktAccessTokenGrantType.Unspecified.AsString().Should().NotBeNull().And.BeEmpty();
}
}
}
| namespace TraktApiSharp.Tests.Enums
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using TraktApiSharp.Enums;
[TestClass]
public class TraktAccessTokenGrantTypeTests
{
class TestObject
{
[JsonConverter(typeof(TraktAccessTokenGrantTypeConverter))]
public TraktAccessTokenGrantType Value { get; set; }
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeHasMembers()
{
typeof(TraktAccessTokenGrantType).GetEnumNames().Should().HaveCount(3)
.And.Contain("AuthorizationCode", "RefreshToken", "Unspecified");
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeGetAsString()
{
TraktAccessTokenGrantType.AuthorizationCode.AsString().Should().Be("authorization_code");
TraktAccessTokenGrantType.RefreshToken.AsString().Should().Be("refresh_token");
TraktAccessTokenGrantType.Unspecified.AsString().Should().NotBeNull().And.BeEmpty();
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeWriteAndReadJson_AuthorizationCode()
{
var obj = new TestObject { Value = TraktAccessTokenGrantType.AuthorizationCode };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktAccessTokenGrantType.AuthorizationCode);
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeWriteAndReadJson_RefreshToken()
{
var obj = new TestObject { Value = TraktAccessTokenGrantType.RefreshToken };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktAccessTokenGrantType.RefreshToken);
}
[TestMethod]
public void TestTraktAccessTokenGrantTypeWriteAndReadJson_Unspecified()
{
var obj = new TestObject { Value = TraktAccessTokenGrantType.Unspecified };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktAccessTokenGrantType.Unspecified);
}
}
}
|
Add more complex array test to hello app | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AttributeRouting;
namespace NServiceMVC.Examples.HelloWorld.Controllers
{
public class ArraySampleController : ServiceController
{
//
// GET: /ArraySample/
[GET("arraysample/string/list")]
public List<string> StringList()
{
return new List<string>() { "one", "two", "three" };
}
[GET("arraysample/string/enumerable")]
public IEnumerable<string> StringEnumerable()
{
return new List<string>() { "one", "two", "three" };
}
[GET("arraysample/string/array")]
public string[] StringArray()
{
return new string[] { "one", "two", "three" };
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AttributeRouting;
namespace NServiceMVC.Examples.HelloWorld.Controllers
{
public class ArraySampleController : ServiceController
{
//
// GET: /ArraySample/
[GET("arraysample/string/list")]
public List<string> StringList()
{
return new List<string>() { "one", "two", "three" };
}
[GET("arraysample/string/enumerable")]
public IEnumerable<string> StringEnumerable()
{
return new List<string>() { "one", "two", "three" };
}
[GET("arraysample/string/array")]
public string[] StringArray()
{
return new string[] { "one", "two", "three" };
}
[GET("arraysample/hello/{name}")]
public List<Models.HelloResponse> HelloList(string name)
{
return new List<Models.HelloResponse>() {
new Models.HelloResponse() { GreetingType = "Hello", Name = name },
new Models.HelloResponse() { GreetingType = "Bonjour", Name = name },
new Models.HelloResponse() { GreetingType = "¡Hola", Name = name },
new Models.HelloResponse() { GreetingType = "こんにちは", Name = name },
new Models.HelloResponse() { GreetingType = "שלום", Name = name },
new Models.HelloResponse() { GreetingType = "привет", Name = name },
new Models.HelloResponse() { GreetingType = "Hallå", Name = name },
};
}
}
}
|
Make the MVC content verification test explicitly pass the framework | using Xunit;
namespace Microsoft.TemplateEngine.Cli.UnitTests
{
public class PrecedenceSelectionTests : EndToEndTestBase
{
[Theory(DisplayName = nameof(VerifyTemplateContent))]
[InlineData("mvc", "MvcNoAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -au individual", "MvcIndAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -f netcoreapp1.0", "MvcNoAuthTest.json", "MvcFramework10Test.json")]
[InlineData("mvc -au individual -f netcoreapp1.0", "MvcIndAuthTest.json", "MvcFramework10Test.json")]
[InlineData("mvc -f netcoreapp1.1", "MvcNoAuthTest.json", "MvcFramework11Test.json")]
[InlineData("mvc -au individual -f netcoreapp1.1", "MvcIndAuthTest.json", "MvcFramework11Test.json")]
[InlineData("mvc -f netcoreapp2.0", "MvcNoAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -au individual -f netcoreapp2.0", "MvcIndAuthTest.json", "MvcFramework20Test.json")]
public void VerifyTemplateContent(string args, params string[] scripts)
{
Run(args, scripts);
}
}
}
| using Xunit;
namespace Microsoft.TemplateEngine.Cli.UnitTests
{
public class PrecedenceSelectionTests : EndToEndTestBase
{
[Theory(DisplayName = nameof(VerifyTemplateContent))]
[InlineData("mvc -f netcoreapp2.0", "MvcNoAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -au individual -f netcoreapp2.0", "MvcIndAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -f netcoreapp1.0", "MvcNoAuthTest.json", "MvcFramework10Test.json")]
[InlineData("mvc -au individual -f netcoreapp1.0", "MvcIndAuthTest.json", "MvcFramework10Test.json")]
[InlineData("mvc -f netcoreapp1.1", "MvcNoAuthTest.json", "MvcFramework11Test.json")]
[InlineData("mvc -au individual -f netcoreapp1.1", "MvcIndAuthTest.json", "MvcFramework11Test.json")]
[InlineData("mvc -f netcoreapp2.0", "MvcNoAuthTest.json", "MvcFramework20Test.json")]
[InlineData("mvc -au individual -f netcoreapp2.0", "MvcIndAuthTest.json", "MvcFramework20Test.json")]
public void VerifyTemplateContent(string args, params string[] scripts)
{
Run(args, scripts);
}
}
}
|
Fix bug where property names were always named the p1 name. | namespace Microsoft.ApplicationInsights.Extensibility.AggregateMetrics
{
using System.Globalization;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
internal static class MetricTelemetryExtensions
{
internal static void AddProperties(this MetricTelemetry metricTelemetry, MetricsBag metricsBag, string p1Name, string p2Name, string p3Name)
{
if (metricsBag.Property1 != null)
{
metricTelemetry.Properties[p1Name] = metricsBag.Property1;
}
if (metricsBag.Property2 != null)
{
metricTelemetry.Properties[p1Name] = metricsBag.Property2;
}
if (metricsBag.Property3 != null)
{
metricTelemetry.Properties[p1Name] = metricsBag.Property3;
}
}
internal static MetricTelemetry CreateDerivedMetric(this MetricTelemetry metricTelemetry, string nameSuffix, double value)
{
var derivedTelemetry = new MetricTelemetry(string.Format(CultureInfo.InvariantCulture, "{0}_{1}", metricTelemetry.Name, nameSuffix), value)
{
Timestamp = metricTelemetry.Timestamp
};
derivedTelemetry.Context.GetInternalContext().SdkVersion = metricTelemetry.Context.GetInternalContext().SdkVersion;
return derivedTelemetry;
}
}
} | namespace Microsoft.ApplicationInsights.Extensibility.AggregateMetrics
{
using System.Globalization;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
internal static class MetricTelemetryExtensions
{
internal static void AddProperties(this MetricTelemetry metricTelemetry, MetricsBag metricsBag, string p1Name, string p2Name, string p3Name)
{
if (metricsBag.Property1 != null)
{
metricTelemetry.Properties[p1Name] = metricsBag.Property1;
}
if (metricsBag.Property2 != null)
{
metricTelemetry.Properties[p2Name] = metricsBag.Property2;
}
if (metricsBag.Property3 != null)
{
metricTelemetry.Properties[p3Name] = metricsBag.Property3;
}
}
internal static MetricTelemetry CreateDerivedMetric(this MetricTelemetry metricTelemetry, string nameSuffix, double value)
{
var derivedTelemetry = new MetricTelemetry(string.Format(CultureInfo.InvariantCulture, "{0}_{1}", metricTelemetry.Name, nameSuffix), value)
{
Timestamp = metricTelemetry.Timestamp
};
derivedTelemetry.Context.GetInternalContext().SdkVersion = metricTelemetry.Context.GetInternalContext().SdkVersion;
return derivedTelemetry;
}
}
} |
Add unit test to save and VALIDATE file in given non-en-US culture. | using ClosedXML.Excel;
using NUnit.Framework;
using System.IO;
namespace ClosedXML_Tests.Excel.Saving
{
[TestFixture]
public class SavingTests
{
[Test]
public void CanSuccessfullySaveFileMultipleTimes()
{
using (var wb = new XLWorkbook())
{
var sheet = wb.Worksheets.Add("TestSheet");
var memoryStream = new MemoryStream();
wb.SaveAs(memoryStream, true);
for (int i = 1; i <= 3; i++)
{
sheet.Cell(i, 1).Value = "test" + i;
wb.SaveAs(memoryStream, true);
}
memoryStream.Close();
memoryStream.Dispose();
}
}
}
}
| using ClosedXML.Excel;
using NUnit.Framework;
using System.Globalization;
using System.IO;
using System.Threading;
namespace ClosedXML_Tests.Excel.Saving
{
[TestFixture]
public class SavingTests
{
[Test]
public void CanSuccessfullySaveFileMultipleTimes()
{
using (var wb = new XLWorkbook())
{
var sheet = wb.Worksheets.Add("TestSheet");
var memoryStream = new MemoryStream();
wb.SaveAs(memoryStream, true);
for (int i = 1; i <= 3; i++)
{
sheet.Cell(i, 1).Value = "test" + i;
wb.SaveAs(memoryStream, true);
}
memoryStream.Close();
memoryStream.Dispose();
}
}
[Test]
public void CanSaveAndValidateFileInAnotherCulture()
{
string[] cultures = new string[] { "it", "de-AT" };
foreach (var culture in cultures)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture);
using (var wb = new XLWorkbook())
{
var memoryStream = new MemoryStream();
var ws = wb.Worksheets.Add("Sheet1");
wb.SaveAs(memoryStream, true);
}
}
}
}
}
|
Fix font not loading in initial dialogue | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class DatingSimDialogueController : MonoBehaviour
{
public float introTextDelay;
[Tooltip("If set to >0 will slow down or speed up text advance to complete it in this time")]
public float introTextForceCompletionTime;
private TMP_Text textComp;
private AdvancingText textPlayer;
private float defaultTextSpeed;
void Start()
{
textComp = GetComponent<TMP_Text>();
textPlayer = GetComponent<AdvancingText>();
defaultTextSpeed = textPlayer.getAdvanceSpeed();
SetDialogue(DatingSimHelper.getSelectedCharacter().getLocalizedIntroDialogue());
if (introTextForceCompletionTime > 0f)
{
float newSpeed = textPlayer.getTotalVisibleChars() / introTextForceCompletionTime;
textPlayer.setAdvanceSpeed(newSpeed);
}
textPlayer.enabled = false;
Invoke("EnableTextPlayer", introTextDelay);
}
void EnableTextPlayer()
{
textPlayer.enabled = true;
}
public void resetDialogueSpeed()
{
textPlayer.setAdvanceSpeed(defaultTextSpeed);
}
public void SetDialogue(string str)
{
textComp.text = str;
textComp.maxVisibleCharacters = 0;
textPlayer.resetAdvance();
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class DatingSimDialogueController : MonoBehaviour
{
public float introTextDelay;
[Tooltip("If set to >0 will slow down or speed up text advance to complete it in this time")]
public float introTextForceCompletionTime;
private TMP_Text textComp;
private AdvancingText textPlayer;
private float defaultTextSpeed;
void Start()
{
textComp = GetComponent<TMP_Text>();
textPlayer = GetComponent<AdvancingText>();
defaultTextSpeed = textPlayer.getAdvanceSpeed();
SetDialogue(DatingSimHelper.getSelectedCharacter().getLocalizedIntroDialogue());
textPlayer.enabled = false;
Invoke("EnableTextPlayer", introTextDelay);
}
void OnFontLocalized()
{
if (introTextForceCompletionTime > 0f)
{
float newSpeed = textPlayer.getTotalVisibleChars() / introTextForceCompletionTime;
textPlayer.setAdvanceSpeed(newSpeed);
}
}
void EnableTextPlayer()
{
textPlayer.enabled = true;
}
public void resetDialogueSpeed()
{
textPlayer.setAdvanceSpeed(defaultTextSpeed);
}
public void SetDialogue(string str)
{
textComp.text = str;
textComp.maxVisibleCharacters = 0;
textPlayer.resetAdvance();
}
}
|
Convert to new Visual Studio project types | // Copyright (c) SimControl e.U. - Wilhelm Medetz. See LICENSE.txt in the project root for more information.
#if false
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
// TODO: CR
namespace SimControl.Reactive
{
//public class ObservedState: INotifyPropertyChanged
//{
// public string Name { get; internal set; }
// public string Type { get; internal set; }
// public bool IsActive { get; internal set; }
// public IEnumerable<ObservedState> Children { get; internal set; }
// public event PropertyChangedEventHandler PropertyChanged;
//}
//interface IStateMachineObserver: INotifyPropertyChanged
//{
// ExecutionStateValue ExecutionState { get; }
// IDictionary<string, ObservedState> States { get; }
//}
//public class StateMachineObserver: IStateMachineObserver
//{
// public ExecutionStateValue ExecutionState
// {
// get { throw new NotImplementedException(); }
// }
// public IDictionary<string, ObservedState> States
// {
// get { throw new NotImplementedException(); }
// }
// public event PropertyChangedEventHandler PropertyChanged;
//}
}
#endif | // Copyright (c) SimControl e.U. - Wilhelm Medetz. See LICENSE.txt in the project root for more information.
#if false
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
// TODO: CR
namespace SimControl.Reactive
{
//public class ObservedState: INotifyPropertyChanged
//{
// public string Name { get; internal set; }
// public string Type { get; internal set; }
// public bool IsActive { get; internal set; }
// public IEnumerable<ObservedState> Children { get; internal set; }
// public event PropertyChangedEventHandler PropertyChanged;
//}
//interface IStateMachineObserver: INotifyPropertyChanged
//{
// ExecutionStateValue ExecutionState { get; }
// IDictionary<string, ObservedState> States { get; }
//}
//public class StateMachineObserver: IStateMachineObserver
//{
// public ExecutionStateValue ExecutionState
// {
// get { throw new NotImplementedException(); }
// }
// public IDictionary<string, ObservedState> States
// {
// get { throw new NotImplementedException(); }
// }
// public event PropertyChangedEventHandler PropertyChanged;
//}
}
#endif
|
Fix overlined playlist test scene not working | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Online.Multiplayer;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Multi;
using osu.Game.Tests.Beatmaps;
using osuTK;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneOverlinedPlaylist : MultiplayerTestScene
{
protected override bool UseOnlineAPI => true;
public TestSceneOverlinedPlaylist()
{
Add(new DrawableRoomPlaylist(false, false)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500),
});
}
[SetUp]
public new void Setup() => Schedule(() =>
{
Room.RoomID.Value = 7;
for (int i = 0; i < 10; i++)
{
Room.Playlist.Add(new PlaylistItem
{
ID = i,
Beatmap = { Value = new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo },
Ruleset = { Value = new OsuRuleset().RulesetInfo }
});
}
});
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Online.Multiplayer;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Multi;
using osu.Game.Tests.Beatmaps;
using osuTK;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneOverlinedPlaylist : MultiplayerTestScene
{
protected override bool UseOnlineAPI => true;
public TestSceneOverlinedPlaylist()
{
Add(new DrawableRoomPlaylist(false, false)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500),
Items = { BindTarget = Room.Playlist }
});
}
[SetUp]
public new void Setup() => Schedule(() =>
{
Room.RoomID.Value = 7;
for (int i = 0; i < 10; i++)
{
Room.Playlist.Add(new PlaylistItem
{
ID = i,
Beatmap = { Value = new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo },
Ruleset = { Value = new OsuRuleset().RulesetInfo }
});
}
});
}
}
|
Fix not setting custom scheme response status text correctly | using System.IO;
using System.Net;
using System.Text;
using CefSharp;
using TweetLib.Browser.Interfaces;
using TweetLib.Browser.Request;
namespace TweetDuck.Browser.Adapters {
internal sealed class CefSchemeResourceVisitor : ISchemeResourceVisitor<IResourceHandler> {
public static CefSchemeResourceVisitor Instance { get; } = new CefSchemeResourceVisitor();
private static readonly SchemeResource.Status FileIsEmpty = new SchemeResource.Status(HttpStatusCode.NoContent, "File is empty.");
private CefSchemeResourceVisitor() {}
public IResourceHandler Status(SchemeResource.Status status) {
var handler = CreateHandler(Encoding.UTF8.GetBytes(status.Message));
handler.StatusCode = (int) status.Code;
return handler;
}
public IResourceHandler File(SchemeResource.File file) {
byte[] contents = file.Contents;
if (contents.Length == 0) {
return Status(FileIsEmpty); // FromByteArray crashes CEF internals with no contents
}
var handler = CreateHandler(contents);
handler.MimeType = Cef.GetMimeType(file.Extension);
return handler;
}
private static ResourceHandler CreateHandler(byte[] bytes) {
var handler = ResourceHandler.FromStream(new MemoryStream(bytes), autoDisposeStream: true);
handler.Headers.Set("Access-Control-Allow-Origin", "*");
return handler;
}
}
}
| using System;
using System.IO;
using System.Net;
using CefSharp;
using TweetLib.Browser.Interfaces;
using TweetLib.Browser.Request;
namespace TweetDuck.Browser.Adapters {
internal sealed class CefSchemeResourceVisitor : ISchemeResourceVisitor<IResourceHandler> {
public static CefSchemeResourceVisitor Instance { get; } = new CefSchemeResourceVisitor();
private static readonly SchemeResource.Status FileIsEmpty = new SchemeResource.Status(HttpStatusCode.NoContent, "File is empty.");
private CefSchemeResourceVisitor() {}
public IResourceHandler Status(SchemeResource.Status status) {
var handler = CreateHandler(Array.Empty<byte>());
handler.StatusCode = (int) status.Code;
handler.StatusText = status.Message;
return handler;
}
public IResourceHandler File(SchemeResource.File file) {
byte[] contents = file.Contents;
if (contents.Length == 0) {
return Status(FileIsEmpty); // FromByteArray crashes CEF internals with no contents
}
var handler = CreateHandler(contents);
handler.MimeType = Cef.GetMimeType(file.Extension);
return handler;
}
private static ResourceHandler CreateHandler(byte[] bytes) {
return ResourceHandler.FromStream(new MemoryStream(bytes), autoDisposeStream: true);
}
}
}
|
Fix for Deserialization of complex objects | using System;
using CQRS.Light.Contracts;
using Newtonsoft.Json;
namespace CQRS.Light.Core
{
public class JsonSerializationStrategy : ISerializationStrategy
{
public string Serialize(object @object)
{
return JsonConvert.SerializeObject(@object);
}
public object Deserialize(string serializedObject, Type objectType)
{
return JsonConvert.DeserializeObject(serializedObject, objectType);
}
}
} | using System;
using CQRS.Light.Contracts;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace CQRS.Light.Core
{
public class JsonSerializationStrategy : ISerializationStrategy
{
private readonly JsonSerializerSettings deserializeSettings = new JsonSerializerSettings() { ContractResolver = new JsonSerializationContractResolver() };
public string Serialize(object @object)
{
return JsonConvert.SerializeObject(@object);
}
public object Deserialize(string serializedObject, Type objectType)
{
return JsonConvert.DeserializeObject(serializedObject, objectType, deserializeSettings);
}
}
internal class JsonSerializationContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Select(p => base.CreateProperty(p, memberSerialization))
.Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Select(f => base.CreateProperty(f, memberSerialization)))
.ToList();
props.ForEach(p => { p.Writable = true; p.Readable = true; });
return props;
}
}
} |
Support loading bitmaps from resources. | // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using OmniXaml.TypeConversion;
using Perspex.Media.Imaging;
namespace Perspex.Markup.Xaml.Converters
{
public class BitmapTypeConverter : ITypeConverter
{
public bool CanConvertFrom(IXamlTypeConverterContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public bool CanConvertTo(IXamlTypeConverterContext context, Type destinationType)
{
return false;
}
public object ConvertFrom(IXamlTypeConverterContext context, CultureInfo culture, object value)
{
return new Bitmap((string)value);
}
public object ConvertTo(IXamlTypeConverterContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
}
} | // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using OmniXaml.TypeConversion;
using Perspex.Media.Imaging;
using Perspex.Platform;
namespace Perspex.Markup.Xaml.Converters
{
public class BitmapTypeConverter : ITypeConverter
{
public bool CanConvertFrom(IXamlTypeConverterContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public bool CanConvertTo(IXamlTypeConverterContext context, Type destinationType)
{
return false;
}
public object ConvertFrom(IXamlTypeConverterContext context, CultureInfo culture, object value)
{
var uri = new Uri((string)value, UriKind.RelativeOrAbsolute);
var scheme = uri.IsAbsoluteUri ? uri.Scheme : "file";
switch (scheme)
{
case "file":
return new Bitmap((string)value);
case "resource":
var assets = PerspexLocator.Current.GetService<IAssetLoader>();
return new Bitmap(assets.Open(uri));
default:
throw new NotSupportedException($"Unsupported bitmap URI scheme: {uri.Scheme}.");
}
}
public object ConvertTo(IXamlTypeConverterContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.