Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add more logic to the custom action. | using System;
using Microsoft.Deployment.WindowsInstaller;
namespace Wix.CustomActions
{
using System.IO;
public class CustomActions
{
[CustomAction]
public static ActionResult CloseIt(Session session)
{
try
{
const string fileFullPath = @"c:\KensCustomAction.txt";
if (!File.Exists(fileFullPath))
File.Create(fileFullPath);
File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now));
session.Log("Close DotTray!");
}
catch (Exception ex)
{
session.Log("ERROR in custom action CloseIt {0}", ex.ToString());
return ActionResult.Failure;
}
return ActionResult.Success;
}
}
}
| using System;
using Microsoft.Deployment.WindowsInstaller;
namespace Wix.CustomActions
{
using System.IO;
using System.Diagnostics;
public class CustomActions
{
[CustomAction]
public static ActionResult CloseIt(Session session)
{
try
{
Debugger.Launch();
const string fileFullPath = @"c:\KensCustomAction.txt";
if (!File.Exists(fileFullPath))
File.Create(fileFullPath);
File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now));
session.Log("Close DotTray!");
}
catch (Exception ex)
{
session.Log("ERROR in custom action CloseIt {0}", ex.ToString());
return ActionResult.Failure;
}
return ActionResult.Success;
}
}
}
|
Initialize android test library on contructor | using UnityEngine;
namespace com.adjust.sdk.test
{
public class TestFactoryAndroid : ITestFactory
{
private string _baseUrl;
private AndroidJavaObject ajoTestLibrary;
private CommandListenerAndroid onCommandReceivedListener;
public TestFactoryAndroid(string baseUrl)
{
_baseUrl = baseUrl;
CommandExecutor commandExecutor = new CommandExecutor(this, baseUrl);
onCommandReceivedListener = new CommandListenerAndroid(commandExecutor);
}
public void StartTestSession()
{
TestApp.Log("TestFactory -> StartTestSession()");
if (ajoTestLibrary == null)
{
ajoTestLibrary = new AndroidJavaObject(
"com.adjust.testlibrary.TestLibrary",
_baseUrl,
onCommandReceivedListener);
}
TestApp.Log("TestFactory -> calling testLib.startTestSession()");
ajoTestLibrary.Call("startTestSession", TestApp.CLIENT_SDK);
}
public void AddInfoToSend(string key, string paramValue)
{
if (ajoTestLibrary == null)
{
return;
}
ajoTestLibrary.Call("addInfoToSend", key, paramValue);
}
public void SendInfoToServer(string basePath)
{
if (ajoTestLibrary == null)
{
return;
}
ajoTestLibrary.Call("sendInfoToServer", basePath);
}
public void AddTest(string testName)
{
if (ajoTestLibrary == null) {
return;
}
ajoTestLibrary.Call("addTest", testName);
}
public void AddTestDirectory(string testDirectory)
{
if (ajoTestLibrary == null)
{
return;
}
ajoTestLibrary.Call("addTestDirectory", testDirectory);
}
}
}
| using UnityEngine;
namespace com.adjust.sdk.test
{
public class TestFactoryAndroid : ITestFactory
{
private string _baseUrl;
private AndroidJavaObject ajoTestLibrary;
private CommandListenerAndroid onCommandReceivedListener;
public TestFactoryAndroid(string baseUrl)
{
_baseUrl = baseUrl;
CommandExecutor commandExecutor = new CommandExecutor(this, baseUrl);
onCommandReceivedListener = new CommandListenerAndroid(commandExecutor);
ajoTestLibrary = new AndroidJavaObject(
"com.adjust.testlibrary.TestLibrary",
_baseUrl,
onCommandReceivedListener);
}
public void StartTestSession()
{
ajoTestLibrary.Call("startTestSession", TestApp.CLIENT_SDK);
}
public void AddInfoToSend(string key, string paramValue)
{
ajoTestLibrary.Call("addInfoToSend", key, paramValue);
}
public void SendInfoToServer(string basePath)
{
ajoTestLibrary.Call("sendInfoToServer", basePath);
}
public void AddTest(string testName)
{
ajoTestLibrary.Call("addTest", testName);
}
public void AddTestDirectory(string testDirectory)
{
ajoTestLibrary.Call("addTestDirectory", testDirectory);
}
}
}
|
Adjust output directory in script | #addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "Default"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Default").Does (() =>
{
const string sln = "./../Vibrate.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Default")
.Does (() =>
{
NuGetPack ("./../Vibrate.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
BasePath = "./",
});
});
RunTarget (TARGET);
| #addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "Default"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Default").Does (() =>
{
const string sln = "./../Vibrate.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Default")
.Does (() =>
{
NuGetPack ("./../Vibrate.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./../",
BasePath = "./",
});
});
RunTarget (TARGET);
|
Add commission as Employee Pay Type | using System.Collections.Generic;
namespace CertiPay.Payroll.Common
{
/// <summary>
/// Describes how an employee pay is calculated
/// </summary>
public enum EmployeePayType : byte
{
/// <summary>
/// Employee earns a set salary per period of time, i.e. $70,000 yearly
/// </summary>
Salary = 1,
/// <summary>
/// Employee earns a given amount per hour of work, i.e. $10 per hour
/// </summary>
Hourly = 2
}
public static class EmployeePayTypes
{
public static IEnumerable<EmployeePayType> Values()
{
yield return EmployeePayType.Salary;
yield return EmployeePayType.Hourly;
}
}
} | using System.Collections.Generic;
namespace CertiPay.Payroll.Common
{
/// <summary>
/// Describes how an employee pay is calculated
/// </summary>
public enum EmployeePayType : byte
{
/// <summary>
/// Employee earns a set salary per period of time, i.e. $70,000 yearly
/// </summary>
Salary = 1,
/// <summary>
/// Employee earns a given amount per hour of work, i.e. $10 per hour
/// </summary>
Hourly = 2,
/// <summary>
/// Employee earns a flat rate based on sales or project completion
/// </summary>
Commission = 3
}
public static class EmployeePayTypes
{
public static IEnumerable<EmployeePayType> Values()
{
yield return EmployeePayType.Salary;
yield return EmployeePayType.Hourly;
yield return EmployeePayType.Commission;
}
}
} |
Update controller for request validation | using System.Web.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;
using ValidateRequestExample.Filters;
namespace ValidateRequestExample.Controllers
{
public class IncomingController : TwilioController
{
[ValidateTwilioRequest]
public ActionResult Voice(string from)
{
var response = new TwilioResponse();
const string message = "Thanks for calling! " +
"Your phone number is {0}. I got your call because of Twilio's webhook. " +
"Goodbye!";
response.Say(string.Format(message, from));
response.Hangup();
return TwiML(response);
}
[ValidateTwilioRequest]
public ActionResult Message(string body)
{
var response = new TwilioResponse();
response.Say($"Your text to me was {body.Length} characters long. Webhooks are neat :)");
response.Hangup();
return TwiML(response);
}
}
}
| using System.Web.Mvc;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;
using ValidateRequestExample.Filters;
namespace ValidateRequestExample.Controllers
{
public class IncomingController : TwilioController
{
[ValidateTwilioRequest]
public ActionResult Voice(string from)
{
var message = "Thanks for calling! " +
$"Your phone number is {from}. " +
"I got your call because of Twilio's webhook. " +
"Goodbye!";
var response = new VoiceResponse();
response.Say(string.Format(message, from));
response.Hangup();
return TwiML(response);
}
[ValidateTwilioRequest]
public ActionResult Message(string body)
{
var message = $"Your text to me was {body.Length} characters long. " +
"Webhooks are neat :)";
var response = new MessagingResponse();
response.Message(new Message(message));
return TwiML(response);
}
}
}
|
Fix test for NotNullOrEmpty passing check. | using System;
using NUnit.Framework;
using DevTyr.Gullap;
namespace DevTyr.Gullap.Tests.With_Guard.For_NotNullOrEmpty
{
[TestFixture]
public class When_argument_is_not_null
{
[Test]
public void Should_pass ()
{
Guard.NotNullOrEmpty ("", null);
Assert.Pass ();
}
}
}
| using System;
using NUnit.Framework;
using DevTyr.Gullap;
namespace DevTyr.Gullap.Tests.With_Guard.For_NotNullOrEmpty
{
[TestFixture]
public class When_argument_is_not_null_or_empty
{
[Test]
public void Should_pass ()
{
Guard.NotNullOrEmpty ("Test", null);
Assert.Pass ();
}
}
}
|
Remove EnableCors attribute from controller | using BankService.Domain.Contracts;
using BankService.Domain.Models;
using Microsoft.AspNet.Cors;
using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
namespace BankService.Api.Controllers
{
[EnableCors("MyPolicy")]
[Route("api/accountHolders")]
public class AccountHolderController : Controller
{
private readonly IAccountHolderRepository accountHolderRepository;
private readonly ICachedAccountHolderRepository cachedAccountHolderRepository;
public AccountHolderController(IAccountHolderRepository repository, ICachedAccountHolderRepository cachedRepository)
{
this.accountHolderRepository = repository;
this.cachedAccountHolderRepository = cachedRepository;
}
[HttpGet]
public IEnumerable<AccountHolder> Get()
{
return this.accountHolderRepository.GetWithLimit(100);
}
[HttpGet("{id}")]
public AccountHolder Get(string id)
{
var accountHolder = this.cachedAccountHolderRepository.Get(id);
if (accountHolder != null)
{
return accountHolder;
}
accountHolder = this.accountHolderRepository.GetById(id);
this.cachedAccountHolderRepository.Set(accountHolder);
return accountHolder;
}
}
}
| using BankService.Domain.Contracts;
using BankService.Domain.Models;
using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
namespace BankService.Api.Controllers
{
[Route("api/accountHolders")]
public class AccountHolderController : Controller
{
private readonly IAccountHolderRepository accountHolderRepository;
private readonly ICachedAccountHolderRepository cachedAccountHolderRepository;
public AccountHolderController(IAccountHolderRepository repository, ICachedAccountHolderRepository cachedRepository)
{
this.accountHolderRepository = repository;
this.cachedAccountHolderRepository = cachedRepository;
}
[HttpGet]
public IEnumerable<AccountHolder> Get()
{
return this.accountHolderRepository.GetWithLimit(100);
}
[HttpGet("{id}")]
public AccountHolder Get(string id)
{
var accountHolder = this.cachedAccountHolderRepository.Get(id);
if (accountHolder != null)
{
return accountHolder;
}
accountHolder = this.accountHolderRepository.GetById(id);
this.cachedAccountHolderRepository.Set(accountHolder);
return accountHolder;
}
}
}
|
Hide UserId by Editing in KendoGrid PopUp | namespace VotingSystem.Web.Areas.User.ViewModels
{
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using VotingSystem.Models;
using VotingSystem.Web.Infrastructure.Mapping;
using AutoMapper;
public class UserPollsViewModel : IMapFrom<Poll>, IHaveCustomMappings
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[HiddenInput(DisplayValue = false)]
public string Author { get; set; }
public bool IsPublic { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string UserId { get; set; }
public void CreateMappings(AutoMapper.IConfiguration configuration)
{
configuration.CreateMap<Poll, UserPollsViewModel>()
.ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName));
}
}
} | namespace VotingSystem.Web.Areas.User.ViewModels
{
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using VotingSystem.Models;
using VotingSystem.Web.Infrastructure.Mapping;
using AutoMapper;
public class UserPollsViewModel : IMapFrom<Poll>, IHaveCustomMappings
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[HiddenInput(DisplayValue = false)]
public string Author { get; set; }
public bool IsPublic { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
[HiddenInput(DisplayValue = false)]
public string UserId { get; set; }
public void CreateMappings(AutoMapper.IConfiguration configuration)
{
configuration.CreateMap<Poll, UserPollsViewModel>()
.ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName));
}
}
} |
Fix test to work in any timezone | using Harvest.Net.Models;
using System;
using System.Linq;
using Xunit;
namespace Harvest.Net.Tests
{
public class TimeTrackingFacts : FactBase, IDisposable
{
DayEntry _todelete = null;
[Fact]
public void Daily_ReturnsResult()
{
var result = Api.Daily();
Assert.NotNull(result);
Assert.NotNull(result.DayEntries);
Assert.NotNull(result.Projects);
Assert.Equal(DateTime.Now.Date, result.ForDay);
}
[Fact]
public void Daily_ReturnsCorrectResult()
{
var result = Api.Daily(286857409);
Assert.NotNull(result);
Assert.Equal(1m, result.DayEntry.Hours);
Assert.Equal(new DateTime(2014, 12, 19), result.DayEntry.SpentAt);
}
[Fact]
public void CreateDaily_CreatesAnEntry()
{
var result = Api.CreateDaily(DateTime.Now.Date, GetTestId(TestId.ProjectId), GetTestId(TestId.TaskId), 2);
_todelete = result.DayEntry;
Assert.Equal(2m, result.DayEntry.Hours);
Assert.Equal(GetTestId(TestId.ProjectId), result.DayEntry.ProjectId);
Assert.Equal(GetTestId(TestId.TaskId), result.DayEntry.TaskId);
}
public void Dispose()
{
if (_todelete != null)
Api.DeleteDaily(_todelete.Id);
}
}
}
| using Harvest.Net.Models;
using System;
using System.Linq;
using Xunit;
namespace Harvest.Net.Tests
{
public class TimeTrackingFacts : FactBase, IDisposable
{
DayEntry _todelete = null;
[Fact]
public void Daily_ReturnsResult()
{
var result = Api.Daily();
Assert.NotNull(result);
Assert.NotNull(result.DayEntries);
Assert.NotNull(result.Projects);
// The test harvest account is in EST, but Travis CI runs in different timezones
Assert.Equal(TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Utc, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")).Date, result.ForDay);
}
[Fact]
public void Daily_ReturnsCorrectResult()
{
var result = Api.Daily(286857409);
Assert.NotNull(result);
Assert.Equal(1m, result.DayEntry.Hours);
Assert.Equal(new DateTime(2014, 12, 19), result.DayEntry.SpentAt);
}
[Fact]
public void CreateDaily_CreatesAnEntry()
{
var result = Api.CreateDaily(DateTime.Now.Date, GetTestId(TestId.ProjectId), GetTestId(TestId.TaskId), 2);
_todelete = result.DayEntry;
Assert.Equal(2m, result.DayEntry.Hours);
Assert.Equal(GetTestId(TestId.ProjectId), result.DayEntry.ProjectId);
Assert.Equal(GetTestId(TestId.TaskId), result.DayEntry.TaskId);
}
public void Dispose()
{
if (_todelete != null)
Api.DeleteDaily(_todelete.Id);
}
}
}
|
Use the aspnet core built-in GetDisplayUrl method. | using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using System.Text;
namespace Abp.AspNetCore.EntityHistory
{
/// <summary>
/// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
/// </summary>
public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
{
[CanBeNull]
public override string Reason
{
get
{
if (OverridedValue != null)
{
return OverridedValue.Reason;
}
// TODO: Use back HttpContextAccessor.HttpContext?.Request.GetDisplayUrl()
// after moved to net core 3.0
// see https://github.com/aspnet/AspNetCore/issues/2718#issuecomment-482347489
return GetDisplayUrl(HttpContextAccessor.HttpContext?.Request);
}
}
protected IHttpContextAccessor HttpContextAccessor { get; }
private const string SchemeDelimiter = "://";
public HttpRequestEntityChangeSetReasonProvider(
IHttpContextAccessor httpContextAccessor,
IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
) : base(reasonOverrideScopeProvider)
{
HttpContextAccessor = httpContextAccessor;
}
private string GetDisplayUrl(HttpRequest request)
{
if (request == null)
{
Logger.Debug("Unable to get URL from HttpRequest, fallback to null");
return null;
}
var scheme = request.Scheme ?? string.Empty;
var host = request.Host.Value ?? string.Empty;
var pathBase = request.PathBase.Value ?? string.Empty;
var path = request.Path.Value ?? string.Empty;
var queryString = request.QueryString.Value ?? string.Empty;
// PERF: Calculate string length to allocate correct buffer size for StringBuilder.
var length = scheme.Length + SchemeDelimiter.Length + host.Length
+ pathBase.Length + path.Length + queryString.Length;
return new StringBuilder(length)
.Append(scheme)
.Append(SchemeDelimiter)
.Append(host)
.Append(pathBase)
.Append(path)
.Append(queryString)
.ToString();
}
}
}
| using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using System.Text;
using Microsoft.AspNetCore.Http.Extensions;
namespace Abp.AspNetCore.EntityHistory
{
/// <summary>
/// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
/// </summary>
public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
{
[CanBeNull]
public override string Reason => OverridedValue != null
? OverridedValue.Reason
: HttpContextAccessor.HttpContext?.Request.GetDisplayUrl();
protected IHttpContextAccessor HttpContextAccessor { get; }
private const string SchemeDelimiter = "://";
public HttpRequestEntityChangeSetReasonProvider(
IHttpContextAccessor httpContextAccessor,
IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
) : base(reasonOverrideScopeProvider)
{
HttpContextAccessor = httpContextAccessor;
}
}
}
|
Fix unit of work ctor param | using System;
using System.Data.Entity;
using PhotoLife.Data.Contracts;
namespace PhotoLife.Data
{
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext dbContext;
public UnitOfWork(DbContext context)
{
if (context == null)
{
throw new ArgumentNullException("Context cannot be null");
}
this.dbContext = context;
}
public void Dispose()
{
}
public void Commit()
{
this.dbContext.SaveChanges();
}
}
}
| using System;
using PhotoLife.Data.Contracts;
namespace PhotoLife.Data
{
public class UnitOfWork : IUnitOfWork
{
private readonly IPhotoLifeEntities dbContext;
public UnitOfWork(IPhotoLifeEntities context)
{
if (context == null)
{
throw new ArgumentNullException("Context cannot be null");
}
this.dbContext = context;
}
public void Dispose()
{
}
public void Commit()
{
this.dbContext.SaveChanges();
}
}
}
|
Scale up and down in demo | namespace Worker.Scalable
{
using King.Service;
using System.Diagnostics;
using System.Threading.Tasks;
public class ScalableTask : IDynamicRuns
{
public int MaximumPeriodInSeconds
{
get { return 30; }
}
public int MinimumPeriodInSeconds
{
get { return 20; }
}
public Task<bool> Run()
{
Trace.TraceInformation("Scalable Task Running.");
return Task.FromResult(true);
}
}
} | namespace Worker.Scalable
{
using King.Service;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
public class ScalableTask : IDynamicRuns
{
public int MaximumPeriodInSeconds
{
get
{
return 30;
}
}
public int MinimumPeriodInSeconds
{
get
{
return 20;
}
}
public Task<bool> Run()
{
var random = new Random();
var workWasDone = (random.Next() % 2) == 0;
Trace.TraceInformation("Work was done: {0}", workWasDone);
return Task.FromResult(workWasDone);
}
}
} |
Add filter property to trending shows request. | namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base.Get;
using Objects.Basic;
using Objects.Get.Shows.Common;
internal class TraktShowsTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingShow>, TraktTrendingShow>
{
internal TraktShowsTrendingRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "shows/trending{?extended,page,limit}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
| namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base;
using Base.Get;
using Objects.Basic;
using Objects.Get.Shows.Common;
internal class TraktShowsTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingShow>, TraktTrendingShow>
{
internal TraktShowsTrendingRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "shows/trending{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
internal TraktShowFilter Filter { get; set; }
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
|
Access dos not support such join syntax. | using System;
using System.Linq;
using LinqToDB;
using NUnit.Framework;
namespace Tests.UserTests
{
[TestFixture]
public class Issue1556Tests : TestBase
{
[Test]
public void Issue1556Test([DataSources(ProviderName.Sybase, ProviderName.OracleNative)] string context)
{
using (var db = GetDataContext(context))
{
AreEqual(
from p in db.Parent
from c in db.Child
where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID)
select new { p, c }
,
db.Parent
.InnerJoin(db.Child,
(p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID),
(p,c) => new { p, c }));
}
}
}
}
| using System;
using System.Linq;
using LinqToDB;
using NUnit.Framework;
namespace Tests.UserTests
{
[TestFixture]
public class Issue1556Tests : TestBase
{
[Test]
public void Issue1556Test(
[DataSources(ProviderName.Sybase, ProviderName.OracleNative, ProviderName.Access)] string context)
{
using (var db = GetDataContext(context))
{
AreEqual(
from p in db.Parent
from c in db.Child
where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID)
select new { p, c }
,
db.Parent
.InnerJoin(db.Child,
(p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID),
(p,c) => new { p, c }));
}
}
}
}
|
Fix integration tests for tracing | using System.Net.Http;
using System.Threading.Tasks;
using Anemonis.MicrosoftOffice.AddinHost.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace Anemonis.MicrosoftOffice.AddinHost.IntegrationTests
{
[TestClass]
public sealed class RequestTracingMiddlewareTests
{
[TestMethod]
public async Task Trace()
{
var loggerMock = new Mock<Serilog.ILogger>(MockBehavior.Strict);
loggerMock.Setup(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<object[]>()));
var builder = new WebHostBuilder()
.ConfigureServices(sc => sc
.AddSingleton(loggerMock.Object)
.AddSingleton<RequestTracingMiddleware, RequestTracingMiddleware>())
.Configure(ab => ab
.UseMiddleware<RequestTracingMiddleware>());
using (var server = new TestServer(builder))
{
using (var client = server.CreateClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, server.BaseAddress);
var response = await client.SendAsync(request);
}
}
loggerMock.Verify(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<object[]>()), Times.Exactly(1));
}
}
} | using System.Net.Http;
using System.Threading.Tasks;
using Anemonis.MicrosoftOffice.AddinHost.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace Anemonis.MicrosoftOffice.AddinHost.IntegrationTests
{
[TestClass]
public sealed class RequestTracingMiddlewareTests
{
[TestMethod]
public async Task Trace()
{
var loggerMock = new Mock<Serilog.ILogger>(MockBehavior.Strict);
loggerMock.Setup(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>()));
var builder = new WebHostBuilder()
.ConfigureServices(sc => sc
.AddSingleton(loggerMock.Object)
.AddSingleton<RequestTracingMiddleware, RequestTracingMiddleware>())
.Configure(ab => ab
.UseMiddleware<RequestTracingMiddleware>());
using (var server = new TestServer(builder))
{
using (var client = server.CreateClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, server.BaseAddress);
var response = await client.SendAsync(request);
}
}
loggerMock.Verify(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(1));
}
}
} |
Access always to list of branches | using GRA.Domain.Service;
using GRA.Controllers.ViewModel.ParticipatingBranches;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace GRA.Controllers
{
public class ParticipatingBranchesController : Base.UserController
{
private readonly SiteService _siteService;
public static string Name { get { return "ParticipatingBranches"; } }
public ParticipatingBranchesController(ServiceFacade.Controller context,
SiteService siteService)
: base(context)
{
_siteService = siteService ?? throw new ArgumentNullException(nameof(siteService));
}
public async Task<IActionResult> Index()
{
var site = await GetCurrentSiteAsync();
if(await _siteLookupService.GetSiteSettingBoolAsync(site.Id,
SiteSettingKey.Users.ShowLinkToParticipatingBranches))
{
var viewModel = new ParticipatingBranchesViewModel
{
Systems = await _siteService.GetSystemList()
};
return View(nameof(Index), viewModel);
}
else
{
return StatusCode(404);
}
}
}
}
| using GRA.Domain.Service;
using GRA.Controllers.ViewModel.ParticipatingBranches;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace GRA.Controllers
{
public class ParticipatingBranchesController : Base.UserController
{
private readonly SiteService _siteService;
public static string Name { get { return "ParticipatingBranches"; } }
public ParticipatingBranchesController(ServiceFacade.Controller context,
SiteService siteService)
: base(context)
{
_siteService = siteService ?? throw new ArgumentNullException(nameof(siteService));
}
public async Task<IActionResult> Index()
{
var site = await GetCurrentSiteAsync();
var viewModel = new ParticipatingBranchesViewModel
{
Systems = await _siteService.GetSystemList()
};
return View(nameof(Index), viewModel);
}
}
}
|
Fix wind Degree not using the right name for the json file | using System;
namespace OpenWeatherMap.Standard.Models
{
/// <summary>
/// wind model
/// </summary>
[Serializable]
public class Wind : BaseModel
{
private float speed, gust;
private int deg;
/// <summary>
/// wind speed
/// </summary>
public float Speed
{
get => speed;
set => SetProperty(ref speed, value);
}
/// <summary>
/// wind degree
/// </summary>
public int Degree
{
get => deg;
set => SetProperty(ref deg, value);
}
/// <summary>
/// gust
/// </summary>
public float Gust
{
get => gust;
set => SetProperty(ref gust, value);
}
}
}
| using Newtonsoft.Json;
using System;
namespace OpenWeatherMap.Standard.Models
{
/// <summary>
/// wind model
/// </summary>
[Serializable]
public class Wind : BaseModel
{
private float speed, gust;
private int deg;
/// <summary>
/// wind speed
/// </summary>
public float Speed
{
get => speed;
set => SetProperty(ref speed, value);
}
/// <summary>
/// wind degree
/// </summary>
[JsonProperty("deg")]
public int Degree
{
get => deg;
set => SetProperty(ref deg, value);
}
/// <summary>
/// gust
/// </summary>
public float Gust
{
get => gust;
set => SetProperty(ref gust, value);
}
}
}
|
Use the user profile as scan entry point instead of drives like in Windows | using RepoZ.Api.IO;
using System;
using System.Linq;
namespace RepoZ.Api.Mac.IO
{
public class MacDriveEnumerator : IPathProvider
{
public string[] GetPaths()
{
return System.IO.DriveInfo.GetDrives()
.Where(d => d.DriveType == System.IO.DriveType.Fixed)
.Where(p => !p.RootDirectory.FullName.StartsWith("/private", StringComparison.OrdinalIgnoreCase))
.Select(d => d.RootDirectory.FullName)
.ToArray();
}
}
} | using RepoZ.Api.IO;
using System;
using System.Linq;
namespace RepoZ.Api.Mac.IO
{
public class MacDriveEnumerator : IPathProvider
{
public string[] GetPaths()
{
return new string[] { Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) };
}
}
} |
Set the default parser to the Penguin Parser as it has better error reporting and is faster | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sprache;
using System.Text.RegularExpressions;
using KVLib.KeyValues;
namespace KVLib
{
/// <summary>
/// Parser entry point for reading Key Value strings
/// </summary>
public static class KVParser
{
public static IKVParser KV1 = new KeyValues.SpracheKVParser();
/// <summary>
/// Reads a line of text and returns the first Root key in the text
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
///
[Obsolete("Please use KVParser.KV1.Parse()")]
public static KeyValue ParseKeyValueText(string text)
{
return KV1.Parse(text);
}
/// <summary>
/// Reads a blob of text and returns an array of all root keys in the text
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
///
[Obsolete("Please use KVParser.KV1.ParseAll()")]
public static KeyValue[] ParseAllKVRootNodes(string text)
{
return KV1.ParseAll(text);
}
}
public class KeyValueParsingException : Exception
{
public KeyValueParsingException(string message, Exception inner)
: base(message, inner)
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sprache;
using System.Text.RegularExpressions;
using KVLib.KeyValues;
namespace KVLib
{
/// <summary>
/// Parser entry point for reading Key Value strings
/// </summary>
public static class KVParser
{
public static IKVParser KV1 = new KeyValues.PenguinParser();
/// <summary>
/// Reads a line of text and returns the first Root key in the text
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
///
[Obsolete("Please use KVParser.KV1.Parse()")]
public static KeyValue ParseKeyValueText(string text)
{
return KV1.Parse(text);
}
/// <summary>
/// Reads a blob of text and returns an array of all root keys in the text
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
///
[Obsolete("Please use KVParser.KV1.ParseAll()")]
public static KeyValue[] ParseAllKVRootNodes(string text)
{
return KV1.ParseAll(text);
}
}
public class KeyValueParsingException : Exception
{
public KeyValueParsingException(string message, Exception inner)
: base(message, inner)
{
}
}
}
|
Fix nested list item space before to 2 characters GH-14 |
using System;
using System.Linq;
using HtmlAgilityPack;
namespace ReverseMarkdown.Converters
{
public class Li
: ConverterBase
{
public Li(Converter converter)
: base(converter)
{
this.Converter.Register("li", this);
}
public override string Convert(HtmlNode node)
{
string content = this.TreatChildren(node);
string indentation = IndentationFor(node);
string prefix = PrefixFor(node);
return string.Format("{0}{1}{2}" + Environment.NewLine, indentation, prefix, content.Chomp());
}
private string PrefixFor(HtmlNode node)
{
if (node.ParentNode != null && node.ParentNode.Name == "ol")
{
// index are zero based hence add one
int index = node.ParentNode.SelectNodes("./li").IndexOf(node) + 1;
return string.Format("{0}. ",index);
}
else
{
return "- ";
}
}
private string IndentationFor(HtmlNode node)
{
int length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count();
return new string(' ', Math.Max(length-1,0));
}
}
}
|
using System;
using System.Linq;
using HtmlAgilityPack;
namespace ReverseMarkdown.Converters
{
public class Li
: ConverterBase
{
public Li(Converter converter)
: base(converter)
{
this.Converter.Register("li", this);
}
public override string Convert(HtmlNode node)
{
string content = this.TreatChildren(node);
string indentation = IndentationFor(node);
string prefix = PrefixFor(node);
return string.Format("{0}{1}{2}" + Environment.NewLine, indentation, prefix, content.Chomp());
}
private string PrefixFor(HtmlNode node)
{
if (node.ParentNode != null && node.ParentNode.Name == "ol")
{
// index are zero based hence add one
int index = node.ParentNode.SelectNodes("./li").IndexOf(node) + 1;
return string.Format("{0}. ",index);
}
else
{
return "- ";
}
}
private string IndentationFor(HtmlNode node)
{
int length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count();
return new string(' ', Math.Max(length-1,0)*2);
}
}
}
|
Use racial attack bonus to compute current attack. |
namespace DungeonsAndDragons.DOF
{
public class Character
{
public int Level { get; set; }
public int Strength { get; set; }
public int Dexterity { get; set; }
public IWeapon CurrentWeapon { get; set; }
public int StrengthModifier
{
get { return Strength / 2 - 5; }
}
public int DexterityModifier
{
get { return Dexterity / 2 - 5; }
}
public int BaseMeleeAttack
{
get { return Level / 2 + StrengthModifier; }
}
public int BaseRangedAttack
{
get { return Level / 2 + DexterityModifier; }
}
public int CurrentAttack
{
get
{
if (CurrentWeapon.IsMelee)
return BaseMeleeAttack + CurrentWeapon.AttackBonus;
else
return BaseRangedAttack + CurrentWeapon.AttackBonus;
}
}
public void Equip(IWeapon weapon)
{
CurrentWeapon = weapon;
}
public bool Attack(Creature creature, int roll)
{
return CurrentAttack + roll >= creature.ArmorClass;
}
}
}
|
namespace DungeonsAndDragons.DOF
{
public class Character
{
public int Level { get; set; }
public int Strength { get; set; }
public int Dexterity { get; set; }
public IWeapon CurrentWeapon { get; set; }
public int StrengthModifier
{
get { return Strength / 2 - 5; }
}
public int DexterityModifier
{
get { return Dexterity / 2 - 5; }
}
public int BaseMeleeAttack
{
get { return Level / 2 + StrengthModifier; }
}
public int BaseRangedAttack
{
get { return Level / 2 + DexterityModifier; }
}
public int GetCurrentAttack(Creature creature)
{
if (CurrentWeapon.IsMelee)
return BaseMeleeAttack + CurrentWeapon.RacialAttackBonus(creature.Race);
else
return BaseRangedAttack + CurrentWeapon.RacialAttackBonus(creature.Race);
}
public void Equip(IWeapon weapon)
{
CurrentWeapon = weapon;
}
public bool Attack(Creature creature, int roll)
{
return GetCurrentAttack(creature) + roll >= creature.ArmorClass;
}
}
}
|
Add support for `ExpiryCheck` on Issuing `Authorization` | namespace Stripe.Issuing
{
using Newtonsoft.Json;
public class VerificationData : StripeEntity<VerificationData>
{
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("address_line1_check")]
public string AddressLine1Check { get; set; }
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("address_zip_check")]
public string AddressZipCheck { get; set; }
/// <summary>
/// One of <c>success</c>, <c>failure</c>, <c>exempt</c>, or <c>none</c>.
/// </summary>
[JsonProperty("authentication")]
public string Authentication { get; set; }
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("cvc_check")]
public string CvcCheck { get; set; }
}
}
| namespace Stripe.Issuing
{
using Newtonsoft.Json;
public class VerificationData : StripeEntity<VerificationData>
{
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("address_line1_check")]
public string AddressLine1Check { get; set; }
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("address_zip_check")]
public string AddressZipCheck { get; set; }
/// <summary>
/// One of <c>success</c>, <c>failure</c>, <c>exempt</c>, or <c>none</c>.
/// </summary>
[JsonProperty("authentication")]
public string Authentication { get; set; }
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("cvc_check")]
public string CvcCheck { get; set; }
/// <summary>
/// One of <c>match</c>, <c>mismatch</c>, or <c>not_provided</c>.
/// </summary>
[JsonProperty("expiry_check")]
public string ExpiryCheck { get; set; }
}
}
|
Fix trailing slash in Url | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Requests
{
public class Schema
{
public string Url { get; private set; }
public string Base { get; private set; }
public string Path { get; private set; }
public Schema(string url)
{
Url = url.TrimEnd(new char[] { '/' });
var baseAndPath = url.Split('#');
Base = baseAndPath[0];
if (baseAndPath.Length == 2)
{
Path = baseAndPath[1];
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Requests
{
public class Schema
{
public string Url { get; private set; }
public string Base { get; private set; }
public string Path { get; private set; }
public Schema(string url)
{
Url = url.TrimEnd(new char[] { '/' });
var baseAndPath = Url.Split('#');
Base = baseAndPath[0];
if (baseAndPath.Length == 2)
{
Path = baseAndPath[1];
}
}
}
}
|
Add a quick little demo of using a function from the shared class library to ConsoleApp1 | using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int x = ClassLibrary1.Class1.ReturnFive();
Console.WriteLine("Hello World!");
}
}
}
| using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Quick little demo of using a function from the shared class library
int x = ClassLibrary1.Class1.ReturnFive();
System.Diagnostics.Debug.Assert(x == 5);
Console.WriteLine("Hello World!");
}
}
}
|
Add link to org chart | @model IEnumerable<Unit>
<div class="page-header">
<h1>Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Name)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var unit in Model)
{
<tr>
<td>@Html.DisplayFor(s => unit)</td>
<td>@Html.DisplayFor(s => unit.UIC)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { unit.Id })
@Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id })
</td>
</tr>
}
</tbody>
</table>
| @model IEnumerable<Unit>
<div class="page-header">
<h1>Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Name)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var unit in Model)
{
<tr>
<td>@Html.DisplayFor(s => unit)</td>
<td>@Html.DisplayFor(s => unit.UIC)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { unit.Id })
@Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id })
@Html.ActionLink("Org Chart", "Details", new { unit.Id })
</td>
</tr>
}
</tbody>
</table>
|
Allow settings to be passed as well | using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace Meraki {
public partial class MerakiClient {
private readonly HttpClient _client;
private readonly UrlFormatProvider _formatter = new UrlFormatProvider();
public MerakiClient(IOptions<MerakiClientSettings> options) {
_client = new HttpClient(new HttpClientHandler()) {
BaseAddress = new Uri(options.Value.Address)
};
_client.DefaultRequestHeaders.Add("X-Cisco-Meraki-API-Key", options.Value.Key);
_client.DefaultRequestHeaders.Add("Accept-Type", "application/json");
}
private string Url(FormattableString formattable) => formattable.ToString(_formatter);
public Task<HttpResponseMessage> SendAsync(HttpMethod method, string uri) {
return SendAsync(new HttpRequestMessage(method, uri));
}
internal Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) {
return _client.SendAsync(request);
}
internal async Task<T> GetAsync<T>(string uri) {
var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(content);
}
public async Task<string> GetAsync(string uri) {
var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
var content = await response.Content.ReadAsStringAsync();
return content;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace Meraki {
public partial class MerakiClient {
private readonly HttpClient _client;
private readonly UrlFormatProvider _formatter = new UrlFormatProvider();
public MerakiClient(IOptions<MerakiClientSettings> options)
: this(options.Value) {
}
public MerakiClient(MerakiClientSettings settings) {
_client = new HttpClient(new HttpClientHandler()) {
BaseAddress = new Uri(settings.Address)
};
_client.DefaultRequestHeaders.Add("X-Cisco-Meraki-API-Key", settings.Key);
_client.DefaultRequestHeaders.Add("Accept-Type", "application/json");
}
private string Url(FormattableString formattable) => formattable.ToString(_formatter);
public Task<HttpResponseMessage> SendAsync(HttpMethod method, string uri) => SendAsync(new HttpRequestMessage(method, uri));
internal Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) => _client.SendAsync(request);
internal async Task<T> GetAsync<T>(string uri) {
var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(content);
}
public async Task<string> GetAsync(string uri) {
var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
var content = await response.Content.ReadAsStringAsync();
return content;
}
}
} |
Create exec engine on load and pass context to script | using System;
using System.Collections.Generic;
using System.Linq;
using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScriptGo)]
public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
{
public ContentRef<PythonScript> Script { get; set; }
[DontSerialize]
private PythonExecutionEngine _engine;
protected PythonExecutionEngine Engine
{
get { return _engine; }
}
protected virtual float Delta
{
get { return Time.MsPFMult * Time.TimeMult; }
}
public void OnInit(InitContext context)
{
if (!Script.IsAvailable) return;
_engine = new PythonExecutionEngine(Script.Res.Content);
_engine.SetVariable("gameObject", GameObj);
if (_engine.HasMethod("start"))
_engine.CallMethod("start");
}
public void OnUpdate()
{
if (_engine.HasMethod("update"))
_engine.CallMethod("update", Delta);
}
public void OnShutdown(ShutdownContext context)
{
if (context == ShutdownContext.Deactivate)
{
GameObj.DisposeLater();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Duality;
using RockyTV.Duality.Plugins.IronPython.Resources;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScriptGo)]
public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
{
public ContentRef<PythonScript> Script { get; set; }
[DontSerialize]
private PythonExecutionEngine _engine;
protected PythonExecutionEngine Engine
{
get { return _engine; }
}
protected virtual float Delta
{
get { return Time.MsPFMult * Time.TimeMult; }
}
public void OnInit(InitContext context)
{
if (!Script.IsAvailable) return;
if (context == InitContext.Loaded)
{
_engine = new PythonExecutionEngine(Script.Res.Content);
_engine.SetVariable("gameObject", GameObj);
}
if (_engine.HasMethod("start"))
_engine.CallMethod("start", context);
}
public void OnUpdate()
{
if (_engine.HasMethod("update"))
_engine.CallMethod("update", Delta);
}
public void OnShutdown(ShutdownContext context)
{
if (context == ShutdownContext.Deactivate)
{
GameObj.DisposeLater();
}
}
}
}
|
Add smoke test to Status controller | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace SFA.DAS.EmployerUsers.Api.Controllers
{
[RoutePrefix("api/status")]
public class StatusController : ApiController
{
[Route("")]
public IHttpActionResult Index()
{
// Do some Infrastructre work here to smoke out any issues.
return Ok();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using SFA.DAS.EmployerUsers.Api.Orchestrators;
namespace SFA.DAS.EmployerUsers.Api.Controllers
{
[RoutePrefix("api/status")]
public class StatusController : ApiController
{
private readonly UserOrchestrator _orchestrator;
public StatusController(UserOrchestrator orchestrator)
{
_orchestrator = orchestrator;
}
[Route("")]
public async Task <IHttpActionResult> Index()
{
try
{
// Do some Infrastructre work here to smoke out any issues.
var users = await _orchestrator.UsersIndex(1, 1);
return Ok();
}
catch (Exception e)
{
return InternalServerError(e);
}
}
}
}
|
Break build to test TeamCity. | namespace Siftables
{
public partial class MainWindowView
{
public MainWindowView()
{
InitializeComponent();
}
}
}
| namespace Siftables
{
public partial class MainWindowView
{
public MainWindowView()
{
InitializeComponent();
DoSomething();
}
}
}
|
Fix spelling error in summary comment. | namespace Fixie
{
using Internal;
using Internal.Expressions;
/// <summary>
/// Subclass Discovery to customize test discovery rules.
///
/// The default discovery rules are applied to a test assembly whenever the test
/// assembly includes no such subclass.
///
/// By defualt,
///
/// <para>A class is a test class if its name ends with "Tests".</para>
///
/// <para>All public methods in a test class are test methods.</para>
/// </summary>
public class Discovery
{
public Discovery()
{
Config = new Configuration();
Classes = new ClassExpression(Config);
Methods = new MethodExpression(Config);
Parameters = new ParameterSourceExpression(Config);
}
/// <summary>
/// The current state describing the discovery rules. This state can be manipulated through
/// the other properties on Discovery.
/// </summary>
internal Configuration Config { get; }
/// <summary>
/// Defines the set of conditions that describe which classes are test classes.
/// </summary>
public ClassExpression Classes { get; }
/// <summary>
/// Defines the set of conditions that describe which test class methods are test methods,
/// and what order to run them in.
/// </summary>
public MethodExpression Methods { get; }
/// <summary>
/// Defines the set of parameter sources, which provide inputs to parameterized test methods.
/// </summary>
public ParameterSourceExpression Parameters { get; }
}
} | namespace Fixie
{
using Internal;
using Internal.Expressions;
/// <summary>
/// Subclass Discovery to customize test discovery rules.
///
/// The default discovery rules are applied to a test assembly whenever the test
/// assembly includes no such subclass.
///
/// By default,
///
/// <para>A class is a test class if its name ends with "Tests".</para>
///
/// <para>All public methods in a test class are test methods.</para>
/// </summary>
public class Discovery
{
public Discovery()
{
Config = new Configuration();
Classes = new ClassExpression(Config);
Methods = new MethodExpression(Config);
Parameters = new ParameterSourceExpression(Config);
}
/// <summary>
/// The current state describing the discovery rules. This state can be manipulated through
/// the other properties on Discovery.
/// </summary>
internal Configuration Config { get; }
/// <summary>
/// Defines the set of conditions that describe which classes are test classes.
/// </summary>
public ClassExpression Classes { get; }
/// <summary>
/// Defines the set of conditions that describe which test class methods are test methods,
/// and what order to run them in.
/// </summary>
public MethodExpression Methods { get; }
/// <summary>
/// Defines the set of parameter sources, which provide inputs to parameterized test methods.
/// </summary>
public ParameterSourceExpression Parameters { get; }
}
} |
Use stable version of JQueryMobile. | using System.Web.UI;
using IntelliFactory.WebSharper;
namespace IntelliFactory.WebSharper.JQuery.Mobile.Resources
{
[IntelliFactory.WebSharper.Core.Attributes.Require(typeof(IntelliFactory.WebSharper.JQuery.Resources.JQuery))]
public class JQueryMobile : IntelliFactory.WebSharper.Core.Resources.BaseResource
{
public JQueryMobile() : base("http://code.jquery.com/mobile/1.2.0-alpha.1",
"/jquery.mobile-1.2.0-alpha.1.min.js",
"/jquery.mobile-1.2.0-alpha.1.min.css") {}
}
}
| using System.Web.UI;
using IntelliFactory.WebSharper;
namespace IntelliFactory.WebSharper.JQuery.Mobile.Resources
{
[IntelliFactory.WebSharper.Core.Attributes.Require(typeof(IntelliFactory.WebSharper.JQuery.Resources.JQuery))]
public class JQueryMobile : IntelliFactory.WebSharper.Core.Resources.BaseResource
{
public JQueryMobile() : base("http://code.jquery.com/mobile/1.1.1",
"/jquery.mobile-1.1.1.min.js",
"/jquery.mobile-1.1.1.min.css") {}
}
}
|
Disable parallel execution for tests | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FakeHttpContext.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FakeHttpContext.Tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bdcb2164-56db-4f8c-8e7d-58c36a7408ca")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
// 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("FakeHttpContext.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FakeHttpContext.Tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bdcb2164-56db-4f8c-8e7d-58c36a7408ca")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Replace test with test stub | #region Usings
using NUnit.Framework;
#endregion
namespace UnitTests
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
Assert.True(true);
}
}
} | #region Usings
using NUnit.Framework;
using WebApplication.Controllers;
#endregion
namespace UnitTests
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
var controller = new HabitController();
Assert.True(true);
}
}
} |
Make sure there is only one MobileServiceClient | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using Microsoft.WindowsAzure.MobileServices;
namespace MyDriving.AzureClient
{
public class AzureClient : IAzureClient
{
const string DefaultMobileServiceUrl = "https://mydriving.azurewebsites.net";
IMobileServiceClient client;
string mobileServiceUrl;
public IMobileServiceClient Client => client ?? (client = CreateClient());
IMobileServiceClient CreateClient()
{
client = new MobileServiceClient(DefaultMobileServiceUrl, new AuthHandler())
{
SerializerSettings = new MobileServiceJsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
CamelCasePropertyNames = true
}
};
return client;
}
}
} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using Microsoft.WindowsAzure.MobileServices;
namespace MyDriving.AzureClient
{
public class AzureClient : IAzureClient
{
const string DefaultMobileServiceUrl = "https://mydriving.azurewebsites.net";
static IMobileServiceClient client;
public IMobileServiceClient Client => client ?? (client = CreateClient());
IMobileServiceClient CreateClient()
{
client = new MobileServiceClient(DefaultMobileServiceUrl, new AuthHandler())
{
SerializerSettings = new MobileServiceJsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
CamelCasePropertyNames = true
}
};
return client;
}
}
} |
Correct feature attribute to indicate dependency. | using Lombiq.HelpfulExtensions.Extensions.SiteTexts.Services;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Data.Migration;
using OrchardCore.Modules;
namespace Lombiq.HelpfulExtensions.Extensions.SiteTexts;
[Feature(FeatureIds.SiteTexts)]
public class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IDataMigration, Migrations>();
services.AddScoped<ISiteTextService, SiteTextService>();
}
}
[Feature("OrchardCore.ContentLocalization")]
public class ContentLocalizationStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.RemoveImplementations<ISiteTextService>();
services.AddScoped<ISiteTextService, ContentLocalizationSiteTextService>();
}
}
| using Lombiq.HelpfulExtensions.Extensions.SiteTexts.Services;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Data.Migration;
using OrchardCore.Modules;
namespace Lombiq.HelpfulExtensions.Extensions.SiteTexts;
[Feature(FeatureIds.SiteTexts)]
public class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IDataMigration, Migrations>();
services.AddScoped<ISiteTextService, SiteTextService>();
}
}
[RequireFeatures("OrchardCore.ContentLocalization")]
public class ContentLocalizationStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.RemoveImplementations<ISiteTextService>();
services.AddScoped<ISiteTextService, ContentLocalizationSiteTextService>();
}
}
|
Create Label failing due to null Color & ExternalID being sent to API | using Newtonsoft.Json;
namespace Clubhouse.io.net.Entities.Labels
{
public class ClubhouseCreateLabelParams
{
[JsonProperty(PropertyName = "color")]
public string Color { get; set; }
[JsonProperty(PropertyName = "external_id")]
public string ExternalID { get; set; }
[JsonProperty(PropertyName = "name", Required = Required.Always)]
public string Name { get; set; }
}
}
| using Newtonsoft.Json;
namespace Clubhouse.io.net.Entities.Labels
{
public class ClubhouseCreateLabelParams
{
[JsonProperty(PropertyName = "color", NullValueHandling = NullValueHandling.Ignore)]
public string Color { get; set; }
[JsonProperty(PropertyName = "external_id", NullValueHandling = NullValueHandling.Ignore)]
public string ExternalID { get; set; }
[JsonProperty(PropertyName = "name", Required = Required.Always)]
public string Name { get; set; }
}
}
|
Add DocumentDb connection to main kotori config | using System.Collections.Generic;
namespace KotoriCore.Configuration
{
/// <summary>
/// Kotori main configuration.
/// </summary>
public class Kotori
{
/// <summary>
/// Gets or sets the instance.
/// </summary>
/// <value>The instance.</value>
public string Instance { get; set; }
/// <summary>
/// GEts or sets the version of kotori server.
/// </summary>
/// <value>The version.</value>
public string Version { get; set; }
/// <summary>
/// Gets or sets the master keys.
/// </summary>
/// <value>The master keys.</value>
public IEnumerable<MasterKey> MasterKeys { get; set; }
}
}
| using System.Collections.Generic;
namespace KotoriCore.Configuration
{
/// <summary>
/// Kotori main configuration.
/// </summary>
public class Kotori
{
/// <summary>
/// Gets or sets the instance.
/// </summary>
/// <value>The instance.</value>
public string Instance { get; set; }
/// <summary>
/// GEts or sets the version of kotori server.
/// </summary>
/// <value>The version.</value>
public string Version { get; set; }
/// <summary>
/// Gets or sets the master keys.
/// </summary>
/// <value>The master keys.</value>
public IEnumerable<MasterKey> MasterKeys { get; set; }
/// <summary>
/// Gets or sets the document db connection string.
/// </summary>
/// <value>The document db.</value>
public DocumentDb DocumentDb { get; set; }
}
}
|
Change because lqr support was added to the Linux and macOS build. | // Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// 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 ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Magick.NET.Tests
{
public partial class MagickNETTests
{
[TestClass]
public class TheDelegatesProperty
{
[TestMethod]
public void ShouldReturnAllDelegates()
{
var delegates = MagickNET.Delegates; // Cannot detect difference between macOS and Linux build at the moment
#if WINDOWS_BUILD
Assert.AreEqual("cairo flif freetype gslib heic jng jp2 jpeg lcms lqr openexr pangocairo png ps raw rsvg tiff webp xml zlib", delegates);
#else
Assert.AreEqual("fontconfig freetype heic jng jp2 jpeg lcms openexr png raw tiff webp xml zlib", delegates);
#endif
}
}
}
} | // Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// 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 ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Magick.NET.Tests
{
public partial class MagickNETTests
{
[TestClass]
public class TheDelegatesProperty
{
[TestMethod]
public void ShouldReturnAllDelegates()
{
var delegates = MagickNET.Delegates; // Cannot detect difference between macOS and Linux build at the moment
#if WINDOWS_BUILD
Assert.AreEqual("cairo flif freetype gslib heic jng jp2 jpeg lcms lqr openexr pangocairo png ps raw rsvg tiff webp xml zlib", delegates);
#else
Assert.AreEqual("fontconfig freetype heic jng jp2 jpeg lcms lqr openexr png raw tiff webp xml zlib", delegates);
#endif
}
}
}
} |
Fix mono bug in the FontHelper class | using System;
using System.Drawing;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
}
}
| using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[Test]
public void MakeFont_FontName_ValidFont()
{
using (var sourceFont = SystemFonts.DefaultFont)
{
using (var returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name))
{
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
}
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// use Times New Roman
foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
{
using (var sourceFont = new Font(family, 10f, FontStyle.Regular))
{
using (var returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold))
{
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
}
}
break;
}
}
}
}
|
Increase test wait times (appveyor be slow) | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new TestAudioCollectionManager();
var threadExecutionFinished = new ManualResetEventSlim();
var updateLoopStarted = new ManualResetEventSlim();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++)
manager.AddItem(new TestingAdjustableAudioComponent());
// in a separate thread start processing the queue
var thread = new Thread(() =>
{
while (!manager.IsDisposed)
{
manager.Update();
updateLoopStarted.Set();
}
threadExecutionFinished.Set();
});
thread.Start();
Assert.IsTrue(updateLoopStarted.Wait(1000));
Assert.DoesNotThrow(() => manager.Dispose());
Assert.IsTrue(threadExecutionFinished.Wait(1000));
}
private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent>
{
public new bool IsDisposed => base.IsDisposed;
}
private class TestingAdjustableAudioComponent : AdjustableAudioComponent
{
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new TestAudioCollectionManager();
var threadExecutionFinished = new ManualResetEventSlim();
var updateLoopStarted = new ManualResetEventSlim();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++)
manager.AddItem(new TestingAdjustableAudioComponent());
// in a separate thread start processing the queue
var thread = new Thread(() =>
{
while (!manager.IsDisposed)
{
manager.Update();
updateLoopStarted.Set();
}
threadExecutionFinished.Set();
});
thread.Start();
Assert.IsTrue(updateLoopStarted.Wait(10000));
Assert.DoesNotThrow(() => manager.Dispose());
Assert.IsTrue(threadExecutionFinished.Wait(10000));
}
private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent>
{
public new bool IsDisposed => base.IsDisposed;
}
private class TestingAdjustableAudioComponent : AdjustableAudioComponent
{
}
}
}
|
Fix unit test so it does unprotecting and padding | using NUnit.Framework;
using SecretSplitting;
namespace ElectronicCash.Tests
{
[TestFixture]
class SecretSplittingTests
{
private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);
[Test]
public void OnSplit_OriginalMessageShouldBeRecoverable()
{
_splitter.SplitSecretBetweenTwoPeople();
var r = _splitter.R;
var s = _splitter.S;
var m = Helpers.ExclusiveOr(r, s);
Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message));
}
[Test]
public void OnSecretSplit_FlagsShouldBeTrue()
{
var splitter = new SecretSplittingProvider(Message, RandBytes);
splitter.SplitSecretBetweenTwoPeople();
Assert.IsTrue(splitter.IsRProtected);
Assert.IsTrue(splitter.IsSProtected);
Assert.IsTrue(splitter.IsSecretMessageProtected);
}
}
}
| using NUnit.Framework;
using SecretSplitting;
namespace ElectronicCash.Tests
{
[TestFixture]
class SecretSplittingTests
{
private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);
private const int Padding = 16;
[Test]
public void OnSplit_OriginalMessageShouldBeRecoverable()
{
_splitter.SplitSecretBetweenTwoPeople();
Helpers.ToggleMemoryProtection(_splitter);
var r = _splitter.R;
var s = _splitter.S;
var m = Helpers.ExclusiveOr(r, s);
var toPad = Message;
Helpers.PadArrayToMultipleOf(ref toPad, Padding);
Helpers.ToggleMemoryProtection(_splitter);
Assert.AreEqual(Helpers.GetString(toPad), Helpers.GetString(m));
}
[Test]
public void OnSecretSplit_FlagsShouldBeTrue()
{
var splitter = new SecretSplittingProvider(Message, RandBytes);
splitter.SplitSecretBetweenTwoPeople();
Assert.IsTrue(splitter.IsRProtected);
Assert.IsTrue(splitter.IsSProtected);
Assert.IsTrue(splitter.IsSecretMessageProtected);
}
}
}
|
Fix string comparison for URL history | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using XHRTool.XHRLogic.Common;
namespace XHRTool.UI.WPF.ViewModels
{
[Serializable]
public class UrlHistoryModel
{
public UrlHistoryModel(string url, string verb)
{
Url = url;
Verb = verb;
}
public string Url { get; set; }
public string Verb { get; set; }
}
public class UrlHistoryModelEqualityComparer : IEqualityComparer<UrlHistoryModel>
{
public bool Equals(UrlHistoryModel x, UrlHistoryModel y)
{
return x.Url.Equals(y.Url) && x.Verb.Equals(y.Verb);
}
public int GetHashCode(UrlHistoryModel obj)
{
return (obj.Verb.GetHashCode() + obj.Url.GetHashCode()) / 2;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using XHRTool.XHRLogic.Common;
namespace XHRTool.UI.WPF.ViewModels
{
[Serializable]
public class UrlHistoryModel
{
public UrlHistoryModel(string url, string verb)
{
Url = url;
Verb = verb;
}
public string Url { get; set; }
public string Verb { get; set; }
}
public class UrlHistoryModelEqualityComparer : IEqualityComparer<UrlHistoryModel>
{
public bool Equals(UrlHistoryModel x, UrlHistoryModel y)
{
return x.Url.Equals(y.Url, StringComparison.OrdinalIgnoreCase) && x.Verb.Equals(y.Verb, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(UrlHistoryModel obj)
{
return (obj.Verb.GetHashCode() + obj.Url.GetHashCode()) / 2;
}
}
}
|
Fix BillingDetails on PaymentMethod creation to have the right params | namespace Stripe
{
using Newtonsoft.Json;
public class BillingDetailsOptions : INestedOptions
{
[JsonProperty("address")]
public AddressOptions Address { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("line1")]
public string Line1 { get; set; }
[JsonProperty("line2")]
public string Line2 { get; set; }
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
}
| namespace Stripe
{
using Newtonsoft.Json;
public class BillingDetailsOptions : INestedOptions
{
[JsonProperty("address")]
public AddressOptions Address { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("phone")]
public string Phone { get; set; }
}
}
|
Add test for loading spinner with box | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics.UserInterface;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneLoadingSpinner : OsuGridTestScene
{
public TestSceneLoadingSpinner()
: base(2, 2)
{
LoadingSpinner loading;
Cell(0).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(1).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.White,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(2).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Gray,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(3).AddRange(new Drawable[]
{
loading = new LoadingSpinner()
});
Scheduler.AddDelayed(() => loading.ToggleVisibility(), 200, true);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics.UserInterface;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneLoadingSpinner : OsuGridTestScene
{
public TestSceneLoadingSpinner()
: base(2, 2)
{
LoadingSpinner loading;
Cell(0).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(1).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.White,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner(true)
});
loading.Show();
Cell(2).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Gray,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(3).AddRange(new Drawable[]
{
loading = new LoadingSpinner()
});
Scheduler.AddDelayed(() => loading.ToggleVisibility(), 200, true);
}
}
}
|
Fix U4-2711 add Null Check to ToXMl method | using System.Xml;
namespace umbraco.editorControls.imagecropper
{
public class DataTypeData : umbraco.cms.businesslogic.datatype.DefaultData
{
public DataTypeData(umbraco.cms.businesslogic.datatype.BaseDataType DataType) : base(DataType) { }
public override XmlNode ToXMl(XmlDocument data)
{
if (Value.ToString() != "") {
XmlDocument xd = new XmlDocument();
xd.LoadXml(Value.ToString());
return data.ImportNode(xd.DocumentElement, true);
} else {
return base.ToXMl(data);
}
}
}
} | using System.Xml;
namespace umbraco.editorControls.imagecropper
{
public class DataTypeData : umbraco.cms.businesslogic.datatype.DefaultData
{
public DataTypeData(umbraco.cms.businesslogic.datatype.BaseDataType DataType) : base(DataType) { }
public override XmlNode ToXMl(XmlDocument data)
{
if (Value!=null && Value.ToString() != "") {
XmlDocument xd = new XmlDocument();
xd.LoadXml(Value.ToString());
return data.ImportNode(xd.DocumentElement, true);
} else {
return base.ToXMl(data);
}
}
}
} |
Use two shift registers with two bar graphs and an collection | using System;
using System.Threading.Tasks;
using Treehopper;
using Treehopper.Libraries.Displays;
namespace LedShiftRegisterDemo
{
class Program
{
static void Main(string[] args)
{
App().Wait();
}
static async Task App()
{
var board = await ConnectionService.Instance.GetFirstDeviceAsync();
await board.ConnectAsync();
Console.WriteLine("Connected to " + board);
var driver = new LedShiftRegister(board.Spi, board.Pins[5], board.Pwm1);
driver.Brightness = 0.01;
var bar = new BarGraph(driver.Leds);
while (!Console.KeyAvailable)
{
for (int i = 1; i < 10; i++)
{
bar.Value = i / 10.0;
await Task.Delay(50);
}
for (int i = 10; i >= 0; i--)
{
bar.Value = i / 10.0;
await Task.Delay(50);
}
await Task.Delay(100);
}
board.Disconnect();
}
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using Treehopper;
using Treehopper.Libraries.Displays;
namespace LedShiftRegisterDemo
{
class Program
{
static void Main(string[] args)
{
App().Wait();
}
static async Task App()
{
var board = await ConnectionService.Instance.GetFirstDeviceAsync();
await board.ConnectAsync();
Console.WriteLine("Connected to " + board);
var driver = new LedShiftRegister(board.Spi, board.Pins[9], board.Pwm1, LedShiftRegister.LedChannelCount.SixteenChannel, 0.1);
var driver2 = new LedShiftRegister(driver, LedShiftRegister.LedChannelCount.SixteenChannel);
driver.Brightness = 0.01;
var leds = driver.Leds.Concat(driver2.Leds);
var ledSet1 = leds.Take(8).Concat(leds.Skip(16).Take(8)).ToList();
var ledSet2 = leds.Skip(8).Take(8).Reverse().Concat(leds.Skip(24).Take(8).Reverse()).ToList();
var bar1 = new BarGraph(ledSet1);
var bar2 = new BarGraph(ledSet2);
var collection = new LedDisplayCollection();
collection.Add(bar1);
collection.Add(bar2);
while (!Console.KeyAvailable)
{
for (int i = 1; i < 16; i++)
{
bar1.Value = i / 16.0;
bar2.Value = i / 16.0;
await collection.Flush();
await Task.Delay(10);
}
await Task.Delay(100);
for (int i = 16; i >= 0; i--)
{
bar1.Value = i / 16.0;
bar2.Value = i / 16.0;
await collection.Flush();
await Task.Delay(10);
}
await Task.Delay(100);
}
board.Disconnect();
}
}
}
|
Add test for authorization requirement in TraktUserListLikeRequest | namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
[TestClass]
public class TraktUserListLikeRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsNotAbstract()
{
typeof(TraktUserListLikeRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSealed()
{
typeof(TraktUserListLikeRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSubclassOfATraktNoContentBodylessPostByIdRequest()
{
typeof(TraktUserListLikeRequest).IsSubclassOf(typeof(ATraktNoContentBodylessPostByIdRequest)).Should().BeTrue();
}
}
}
| namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Requests;
[TestClass]
public class TraktUserListLikeRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsNotAbstract()
{
typeof(TraktUserListLikeRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSealed()
{
typeof(TraktUserListLikeRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSubclassOfATraktNoContentBodylessPostByIdRequest()
{
typeof(TraktUserListLikeRequest).IsSubclassOf(typeof(ATraktNoContentBodylessPostByIdRequest)).Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestHasAuthorizationRequired()
{
var request = new TraktUserListLikeRequest(null);
request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
}
}
}
|
Refresh interface list on change | using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Common
{
public partial class InterfaceSelectorComboBox : ComboBox
{
public InterfaceSelectorComboBox()
{
InitializeComponent();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface iface in interfaces)
{
UnicastIPAddressInformationCollection addresses = iface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation address in addresses)
{
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
Items.Add(address.Address.ToString());
}
}
}
}
}
| using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Common
{
public partial class InterfaceSelectorComboBox : ComboBox
{
public InterfaceSelectorComboBox()
{
InitializeComponent();
Initalize();
NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
private void Initalize()
{
if (InvokeRequired)
{
BeginInvoke((MethodInvoker)Initalize);
return;
}
Items.Clear();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface iface in interfaces)
{
UnicastIPAddressInformationCollection addresses = iface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation address in addresses)
{
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
Items.Add(address.Address.ToString());
}
}
}
private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
Initalize();
}
private void NetworkChange_NetworkAddressChanged(object sender, System.EventArgs e)
{
Initalize();
}
}
}
|
Correct error message in thread test | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using NUnit.Framework;
namespace MaxMind.MaxMindDb.Test
{
[TestFixture]
public class ThreadingTest
{
[Test]
public void TestParallelFor()
{
var reader = new MaxMindDbReader("..\\..\\TestData\\GeoLite2-City.mmdb", FileAccessMode.MemoryMapped);
var count = 0;
var ipsAndResults = new Dictionary<IPAddress, string>();
var rand = new Random();
while(count < 10000)
{
var ip = new IPAddress(rand.Next(int.MaxValue));
var resp = reader.Find(ip);
if (resp != null)
{
ipsAndResults.Add(ip, resp.ToString());
count++;
}
}
var ips = ipsAndResults.Keys.ToArray();
Parallel.For(0, ips.Length, (i) =>
{
var ipAddress = ips[i];
var result = reader.Find(ipAddress);
var resultString = result.ToString();
var expectedString = ipsAndResults[ipAddress];
if(resultString != expectedString)
throw new Exception(string.Format("Non-matching zip. Expected {0}, found {1}", expectedString, resultString));
});
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using NUnit.Framework;
namespace MaxMind.MaxMindDb.Test
{
[TestFixture]
public class ThreadingTest
{
[Test]
public void TestParallelFor()
{
var reader = new MaxMindDbReader("..\\..\\TestData\\GeoLite2-City.mmdb", FileAccessMode.MemoryMapped);
var count = 0;
var ipsAndResults = new Dictionary<IPAddress, string>();
var rand = new Random();
while(count < 10000)
{
var ip = new IPAddress(rand.Next(int.MaxValue));
var resp = reader.Find(ip);
if (resp != null)
{
ipsAndResults.Add(ip, resp.ToString());
count++;
}
}
var ips = ipsAndResults.Keys.ToArray();
Parallel.For(0, ips.Length, (i) =>
{
var ipAddress = ips[i];
var result = reader.Find(ipAddress);
var resultString = result.ToString();
var expectedString = ipsAndResults[ipAddress];
if(resultString != expectedString)
throw new Exception(string.Format("Non-matching result. Expected {0}, found {1}", expectedString, resultString));
});
}
}
} |
Fix conversion from Xamarin Forms color to native color | using Xamarin.Forms;
#if __ANDROID__
using NativePoint = Android.Graphics.PointF;
using NativeColor = Android.Graphics.Color;
#elif __IOS__
using NativePoint = CoreGraphics.CGPoint;
#elif NETFX_CORE
using NativePoint = Windows.Foundation.Point;
#endif
#if NETFX_CORE
using NativeColor = Windows.UI.Color;
#endif
namespace Esri.ArcGISRuntime.Toolkit.Xamarin.Forms.Internal
{
internal static class ExtensionMethods
{
internal static NativeColor ToNativeColor(this Color color)
{
#if NETFX_CORE
return NativeColor.FromArgb((byte)color.A, (byte)color.R, (byte)color.G, (byte)color.B);
#elif __ANDROID__
return NativeColor.Argb((int)color.A, (int)color.R, (int)color.G, (int)color.B);
#endif
}
internal static Color ToXamarinFormsColor(this NativeColor color)
{
return Color.FromRgba(color.R, color.G, color.B, color.A);
}
}
}
| using Xamarin.Forms;
#if __ANDROID__
using NativePoint = Android.Graphics.PointF;
using NativeColor = Android.Graphics.Color;
#elif __IOS__
using NativePoint = CoreGraphics.CGPoint;
#elif NETFX_CORE
using NativePoint = Windows.Foundation.Point;
#endif
#if NETFX_CORE
using NativeColor = Windows.UI.Color;
#endif
namespace Esri.ArcGISRuntime.Toolkit.Xamarin.Forms.Internal
{
internal static class ExtensionMethods
{
internal static NativeColor ToNativeColor(this Color color)
{
var a = (byte)(255 * color.A);
var r = (byte)(255 * color.R);
var g = (byte)(255 * color.G);
var b = (byte)(255 * color.B);
#if NETFX_CORE
return NativeColor.FromArgb(a, r, g, b);
#elif __ANDROID__
return NativeColor.Argb(a, r, g, b);
#endif
}
internal static Color ToXamarinFormsColor(this NativeColor color)
{
return Color.FromRgba(color.R, color.G, color.B, color.A);
}
}
}
|
Tweak initialization for email notification | using System;
using System.Collections.Generic;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Represents an email notification sent a user, employee, or administrator
/// </summary>
public class EmailNotification : Notification
{
public static String QueueName { get { return "EmailNotifications"; } }
/// <summary>
/// Who the email notification should be FROM
/// </summary>
public String FromAddress { get; set; }
/// <summary>
/// A list of email addresses to CC
/// </summary>
public ICollection<String> CC { get; set; }
/// <summary>
/// A list of email addresses to BCC
/// </summary>
public ICollection<String> BCC { get; set; }
/// <summary>
/// The subject line of the email
/// </summary>
public String Subject { get; set; }
/// <summary>
/// Any attachments to the email in the form of URLs to download
/// </summary>
public ICollection<Attachment> Attachments { get; set; }
public EmailNotification()
{
this.Recipients = new List<String>();
this.Attachments = new List<Attachment>();
this.CC = new List<String>();
this.BCC = new List<String>();
}
/// <summary>
/// A file may be attached to the email notification by providing a URL to download
/// the file (will be downloaded by the sending process) and a filename
/// </summary>
public class Attachment
{
public String Filename { get; set; }
public String Uri { get; set; }
}
}
} | using System;
using System.Collections.Generic;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Represents an email notification sent a user, employee, or administrator
/// </summary>
public class EmailNotification : Notification
{
public static String QueueName { get { return "EmailNotifications"; } }
/// <summary>
/// Who the email notification should be FROM
/// </summary>
public String FromAddress { get; set; }
/// <summary>
/// A list of email addresses to CC
/// </summary>
public ICollection<String> CC { get; set; } = new List<String>();
/// <summary>
/// A list of email addresses to BCC
/// </summary>
public ICollection<String> BCC { get; set; } = new List<String>();
/// <summary>
/// The subject line of the email
/// </summary>
public String Subject { get; set; }
/// <summary>
/// Any attachments to the email in the form of URLs to download
/// </summary>
public ICollection<Attachment> Attachments { get; set; } = new List<Attachment>();
/// <summary>
/// A file may be attached to the email notification by providing a URL to download
/// the file (will be downloaded by the sending process) and a filename
/// </summary>
public class Attachment
{
public String Filename { get; set; }
public String Uri { get; set; }
}
}
} |
Remove duplicae null check, simplified state check | using Avalonia.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace WalletWasabi.Gui.Converters
{
public class WindowStateAfterSartJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(WindowState);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
// If minimized, then go with Maximized, because at start it shouldn't run with minimized.
var value = reader.Value as string;
if (string.IsNullOrWhiteSpace(value))
{
return WindowState.Maximized;
}
if (value is null)
{
return WindowState.Maximized;
}
string windowStateString = value.Trim();
if (WindowState.Normal.ToString().Equals(windowStateString, StringComparison.OrdinalIgnoreCase)
|| "normal".Equals(windowStateString, StringComparison.OrdinalIgnoreCase)
|| "norm".Equals(windowStateString, StringComparison.OrdinalIgnoreCase))
{
return WindowState.Normal;
}
else
{
return WindowState.Maximized;
}
}
catch
{
return WindowState.Maximized;
}
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((WindowState)value).ToString());
}
}
}
| using Avalonia.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace WalletWasabi.Gui.Converters
{
public class WindowStateAfterSartJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(WindowState);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
// If minimized, then go with Maximized, because at start it shouldn't run with minimized.
var value = reader.Value as string;
if (string.IsNullOrWhiteSpace(value))
{
return WindowState.Maximized;
}
var windowStateString = value.Trim();
return windowStateString.StartsWith("norm", StringComparison.OrdinalIgnoreCase)
? WindowState.Normal
: WindowState.Maximized;
}
catch
{
return WindowState.Maximized;
}
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((WindowState)value).ToString());
}
}
}
|
Add logging to webjob start and end | using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Data;
using SFA.DAS.EmployerFinance.Interfaces;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ExpireFundsJob
{
private readonly IMessageSession _messageSession;
private readonly ICurrentDateTime _currentDateTime;
private readonly IEmployerAccountRepository _accountRepository;
public ExpireFundsJob(
IMessageSession messageSession,
ICurrentDateTime currentDateTime,
IEmployerAccountRepository accountRepository)
{
_messageSession = messageSession;
_currentDateTime = currentDateTime;
_accountRepository = accountRepository;
}
public async Task Run(
[TimerTrigger("0 0 0 28 * *")] TimerInfo timer,
ILogger logger)
{
var now = _currentDateTime.Now;
var accounts = await _accountRepository.GetAllAccounts();
var commands = accounts.Select(a => new ExpireAccountFundsCommand { AccountId = a.Id });
var tasks = commands.Select(c =>
{
var sendOptions = new SendOptions();
sendOptions.RequireImmediateDispatch();
sendOptions.SetMessageId($"{nameof(ExpireAccountFundsCommand)}-{now.Year}-{now.Month}-{c.AccountId}");
return _messageSession.Send(c, sendOptions);
});
await Task.WhenAll(tasks);
}
}
} | using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Data;
using SFA.DAS.EmployerFinance.Interfaces;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ExpireFundsJob
{
private readonly IMessageSession _messageSession;
private readonly ICurrentDateTime _currentDateTime;
private readonly IEmployerAccountRepository _accountRepository;
public ExpireFundsJob(
IMessageSession messageSession,
ICurrentDateTime currentDateTime,
IEmployerAccountRepository accountRepository)
{
_messageSession = messageSession;
_currentDateTime = currentDateTime;
_accountRepository = accountRepository;
}
public async Task Run(
[TimerTrigger("0 0 0 28 * *")] TimerInfo timer,
ILogger logger)
{
logger.LogInformation($"Starting {nameof(ExpireFundsJob)}");
var now = _currentDateTime.Now;
var accounts = await _accountRepository.GetAllAccounts();
var commands = accounts.Select(a => new ExpireAccountFundsCommand { AccountId = a.Id });
var tasks = commands.Select(c =>
{
var sendOptions = new SendOptions();
sendOptions.RequireImmediateDispatch();
sendOptions.SetMessageId($"{nameof(ExpireAccountFundsCommand)}-{now.Year}-{now.Month}-{c.AccountId}");
return _messageSession.Send(c, sendOptions);
});
await Task.WhenAll(tasks);
logger.LogInformation($"{nameof(ExpireFundsJob)} completed.");
}
}
} |
Add text to fullscreen test. | using System;
using System.Collections.Generic;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.InputLib;
namespace Tests.DisplayTests
{
class FullscreenTest : IAgateTest
{
public string Name
{
get { return "Full Screen"; }
}
public string Category
{
get { return "Display"; }
}
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup(args))
{
setup.InitializeAll();
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateFullScreen("Hello World", 640, 480);
Surface mySurface = new Surface("jellybean.png");
// Run the program while the window is open.
while (Display.CurrentWindow.IsClosed == false &&
Keyboard.Keys[KeyCode.Escape] == false)
{
Display.BeginFrame();
Display.Clear(Color.DarkGreen);
mySurface.Draw(Mouse.X, Mouse.Y);
Display.EndFrame();
Core.KeepAlive();
}
}
}
}
} | using System;
using System.Collections.Generic;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.InputLib;
namespace Tests.DisplayTests
{
class FullscreenTest : IAgateTest
{
public string Name
{
get { return "Full Screen"; }
}
public string Category
{
get { return "Display"; }
}
string text = "Press Esc or Tilde to exit." + Environment.NewLine + "Starting Text";
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup(args))
{
setup.InitializeAll();
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateFullScreen("Hello World", 640, 480);
Surface mySurface = new Surface("jellybean.png");
Keyboard.KeyDown += new InputEventHandler(Keyboard_KeyDown);
FontSurface font = FontSurface.AgateSans14;
// Run the program while the window is open.
while (Display.CurrentWindow.IsClosed == false &&
Keyboard.Keys[KeyCode.Escape] == false &&
Keyboard.Keys[KeyCode.Tilde] == false)
{
Display.BeginFrame();
Display.Clear(Color.DarkGreen);
font.DrawText(text);
mySurface.Draw(Mouse.X, Mouse.Y);
Display.EndFrame();
Core.KeepAlive();
}
}
}
void Keyboard_KeyDown(InputEventArgs e)
{
text += e.KeyString;
}
}
} |
Extend PlayerTags to accept name or entityID | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Frenetic.TagHandlers;
using Frenetic.TagHandlers.Objects;
using Voxalia.ServerGame.TagSystem.TagObjects;
using Voxalia.ServerGame.ServerMainSystem;
using Voxalia.ServerGame.EntitySystem;
using Voxalia.Shared;
namespace Voxalia.ServerGame.TagSystem.TagBases
{
class PlayerTagBase : TemplateTags
{
Server TheServer;
// <--[tag]
// @Base player[<TextTag>]
// @Group Entities
// @ReturnType PlayerTag
// @Returns the player with the given name.
// -->
public PlayerTagBase(Server tserver)
{
Name = "player";
TheServer = tserver;
}
public override string Handle(TagData data)
{
string pname = data.GetModifier(0).ToLower();
foreach (PlayerEntity player in TheServer.Players)
{
if (player.Name.ToLower() == pname)
{
return new PlayerTag(player).Handle(data.Shrink());
}
}
return new TextTag("{NULL}").Handle(data.Shrink());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Frenetic.TagHandlers;
using Frenetic.TagHandlers.Objects;
using Voxalia.ServerGame.TagSystem.TagObjects;
using Voxalia.ServerGame.ServerMainSystem;
using Voxalia.ServerGame.EntitySystem;
using Voxalia.Shared;
namespace Voxalia.ServerGame.TagSystem.TagBases
{
class PlayerTagBase : TemplateTags
{
Server TheServer;
// <--[tag]
// @Base player[<TextTag>]
// @Group Entities
// @ReturnType PlayerTag
// @Returns the player with the given name.
// -->
public PlayerTagBase(Server tserver)
{
Name = "player";
TheServer = tserver;
}
public override string Handle(TagData data)
{
string pname = data.GetModifier(0).ToLower();
long pid;
if (long.TryParse(pname, out pid))
{
foreach (PlayerEntity player in TheServer.Players)
{
if (player.EID == pid)
{
return new PlayerTag(player).Handle(data.Shrink());
}
}
}
else
{
foreach (PlayerEntity player in TheServer.Players)
{
if (player.Name.ToLower() == pname)
{
return new PlayerTag(player).Handle(data.Shrink());
}
}
}
return new TextTag("{NULL}").Handle(data.Shrink());
}
}
}
|
Create server side API for single multiple answer question | using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
|
Fix PubSub converter attribute in protobuf | // Copyright 2020, Google LLC
//
// 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
//
// https://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.
// TODO: Generate this file!
// This file contains partial classes for all event data messages, to apply
// the converter attributes to them.
namespace Google.Events.Protobuf.Cloud.PubSub.V1
{
[CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<PubsubMessage>))]
public partial class PubsubMessage { }
}
| // Copyright 2020, Google LLC
//
// 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
//
// https://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.
// TODO: Generate this file!
// This file contains partial classes for all event data messages, to apply
// the converter attributes to them.
namespace Google.Events.Protobuf.Cloud.PubSub.V1
{
[CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<MessagePublishedData>))]
public partial class MessagePublishedData { }
}
|
Make the system respect the Target ConnectionString Provider designation. | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using PPTail.Entities;
using PPTail.Interfaces;
namespace PPTail
{
public class Program
{
public static void Main(string[] args)
{
(var argsAreValid, var argumentErrrors) = args.ValidateArguments();
if (argsAreValid)
{
var (sourceConnection, targetConnection, templateConnection) = args.ParseArguments();
var settings = (null as ISettings).Create(sourceConnection, targetConnection, templateConnection);
var templates = (null as IEnumerable<Template>).Create(templateConnection);
var container = (null as IServiceCollection).Create(settings, templates);
var serviceProvider = container.BuildServiceProvider();
// TODO: Move data load here -- outside of the build process
//var contentRepos = serviceProvider.GetServices<IContentRepository>();
//var contentRepo = contentRepos.First(); // TODO: Implement properly
var siteBuilder = serviceProvider.GetService<ISiteBuilder>();
var sitePages = siteBuilder.Build();
// TODO: Change this to use the named provider specified in the input args
var outputRepo = serviceProvider.GetService<Interfaces.IOutputRepository>();
outputRepo.Save(sitePages);
}
else
{
// TODO: Display argument errors to user
throw new NotImplementedException();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using PPTail.Entities;
using PPTail.Interfaces;
using PPTail.Extensions;
namespace PPTail
{
public class Program
{
const string _connectionStringProviderKey = "Provider";
public static void Main(string[] args)
{
(var argsAreValid, var argumentErrrors) = args.ValidateArguments();
if (argsAreValid)
{
var (sourceConnection, targetConnection, templateConnection) = args.ParseArguments();
var settings = (null as ISettings).Create(sourceConnection, targetConnection, templateConnection);
var templates = (null as IEnumerable<Template>).Create(templateConnection);
var container = (null as IServiceCollection).Create(settings, templates);
var serviceProvider = container.BuildServiceProvider();
// Generate the website pages
var siteBuilder = serviceProvider.GetService<ISiteBuilder>();
var sitePages = siteBuilder.Build();
// Store the resulting output
var outputRepoInstanceName = settings.TargetConnection.GetConnectionStringValue(_connectionStringProviderKey);
var outputRepo = serviceProvider.GetNamedService<IOutputRepository>(outputRepoInstanceName);
outputRepo.Save(sitePages);
}
else
{
// TODO: Display argument errors to user
throw new NotImplementedException();
}
}
}
}
|
Check assemblies reference System.Net.Http v4.0 | using System.IO;
using System.Reflection;
using NUnit.Framework;
public class GitHubAssemblyTests
{
[Theory]
public void GitHub_Assembly_Should_Not_Reference_DesignTime_Assembly(string assemblyFile)
{
var asm = Assembly.LoadFrom(assemblyFile);
foreach (var referencedAssembly in asm.GetReferencedAssemblies())
{
Assert.That(referencedAssembly.Name, Does.Not.EndWith(".DesignTime"),
"DesignTime assemblies should be embedded not referenced");
}
}
[DatapointSource]
string[] GitHubAssemblies => Directory.GetFiles(AssemblyDirectory, "GitHub.*.dll");
string AssemblyDirectory => Path.GetDirectoryName(GetType().Assembly.Location);
}
| using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
public class GitHubAssemblyTests
{
[Theory]
public void GitHub_Assembly_Should_Not_Reference_DesignTime_Assembly(string assemblyFile)
{
var asm = Assembly.LoadFrom(assemblyFile);
foreach (var referencedAssembly in asm.GetReferencedAssemblies())
{
Assert.That(referencedAssembly.Name, Does.Not.EndWith(".DesignTime"),
"DesignTime assemblies should be embedded not referenced");
}
}
[Theory]
public void GitHub_Assembly_Should_Not_Reference_System_Net_Http_Above_4_0(string assemblyFile)
{
var asm = Assembly.LoadFrom(assemblyFile);
foreach (var referencedAssembly in asm.GetReferencedAssemblies())
{
if (referencedAssembly.Name == "System.Net.Http")
{
Assert.That(referencedAssembly.Version, Is.EqualTo(new Version("4.0.0.0")));
}
}
}
[DatapointSource]
string[] GitHubAssemblies => Directory.GetFiles(AssemblyDirectory, "GitHub.*.dll");
string AssemblyDirectory => Path.GetDirectoryName(GetType().Assembly.Location);
}
|
Add unit test for annual calendar | using System;
using Quartz.Impl.Calendar;
using Xunit;
namespace Quartz.DynamoDB.Tests
{
/// <summary>
/// Tests the DynamoCalendar serialisation for all quartz derived calendar types.
/// </summary>
public class CalendarSerialisationTests
{
[Fact]
[Trait("Category", "Unit")]
public void BaseCalendarDescription()
{
BaseCalendar cal = new BaseCalendar() { Description = "Hi mum" };
var sut = new DynamoCalendar("test", cal);
var serialised = sut.ToDynamo();
var deserialised = new DynamoCalendar(serialised);
Assert.Equal(sut.Description, deserialised.Description);
}
}
}
| using System;
using Quartz.Impl.Calendar;
using Xunit;
namespace Quartz.DynamoDB.Tests
{
/// <summary>
/// Tests the DynamoCalendar serialisation for all quartz derived calendar types.
/// </summary>
public class CalendarSerialisationTests
{
/// <summary>
/// Tests that the description property of the base calendar type serialises and deserialises correctly.
/// </summary>
/// <returns>The calendar description.</returns>
[Fact]
[Trait("Category", "Unit")]
public void BaseCalendarDescription()
{
BaseCalendar cal = new BaseCalendar() { Description = "Hi mum" };
var sut = new DynamoCalendar("test", cal);
var serialised = sut.ToDynamo();
var deserialised = new DynamoCalendar(serialised);
Assert.Equal(sut.Description, deserialised.Description);
}
/// <summary>
/// Tests that the excluded days property of the annual calendar serialises and deserialises correctly.
/// </summary>
[Fact]
[Trait("Category", "Unit")]
public void Annual()
{
var importantDate = new DateTime(2015, 04, 02);
AnnualCalendar cal = new AnnualCalendar();
cal.SetDayExcluded(DateTime.Today, true);
cal.SetDayExcluded(importantDate, true);
var sut = new DynamoCalendar("test", cal);
var serialised = sut.ToDynamo();
var deserialised = new DynamoCalendar(serialised);
Assert.True(((AnnualCalendar)deserialised.Calendar).IsDayExcluded(DateTime.Today));
Assert.True(((AnnualCalendar)deserialised.Calendar).IsDayExcluded(importantDate));
}
}
}
|
Debug try catch added to values controller | using KitKare.Data.Models;
using KitKare.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper.QueryableExtensions;
using KitKare.Server.ViewModels;
namespace KitKare.Server.Controllers
{
public class ValuesController : ApiController
{
private IRepository<User> users;
public ValuesController(IRepository<User> users)
{
this.users = users;
}
// GET api/values
public IEnumerable<string> Get()
{
var user = this.users.All().ProjectTo<ProfileViewModel>().FirstOrDefault();
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
| using KitKare.Data.Models;
using KitKare.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper.QueryableExtensions;
using KitKare.Server.ViewModels;
namespace KitKare.Server.Controllers
{
public class ValuesController : ApiController
{
private IRepository<User> users;
public ValuesController(IRepository<User> users)
{
this.users = users;
}
// GET api/values
public IEnumerable<string> Get()
{
try
{
var user = this.users.All().ProjectTo<ProfileViewModel>().FirstOrDefault();
return new string[] { "value1", "value2" };
}
catch (Exception e)
{
return new string[] { e.Message };
}
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
|
Change property types to better match up with Boo syntax | using System.Collections.Generic;
namespace Casper {
public class MSBuild : TaskBase {
public string WorkingDirectory { get; set; }
public string ProjectFile { get; set; }
public string[] Targets { get; set; }
public IDictionary<string, string> Properties { get; set; }
public override void Execute() {
List<string> args = new List<string>();
if (null != ProjectFile) {
args.Add(ProjectFile);
}
if (null != Targets) {
args.Add("/t:" + string.Join(";", Targets));
}
if (null != Properties) {
foreach (var entry in Properties) {
args.Add("/p:" + entry.Key + "=" + entry.Value);
}
}
var exec = new Exec {
WorkingDirectory = WorkingDirectory,
Executable = "xbuild",
Arguments = string.Join(" ", args),
};
exec.Execute();
}
}
}
| using System.Collections.Generic;
using System.Collections;
namespace Casper {
public class MSBuild : TaskBase {
public string WorkingDirectory { get; set; }
public string ProjectFile { get; set; }
public IList Targets { get; set; }
public IDictionary Properties { get; set; }
public override void Execute() {
List<string> args = new List<string>();
if (null != ProjectFile) {
args.Add(ProjectFile);
}
if (null != Targets) {
args.Add("/t:" + string.Join(";", Targets));
}
if (null != Properties) {
foreach (var propertyName in Properties.Keys) {
args.Add("/p:" + propertyName + "=" + Properties[propertyName]);
}
}
var exec = new Exec {
WorkingDirectory = WorkingDirectory,
Executable = "xbuild",
Arguments = string.Join(" ", args),
};
exec.Execute();
}
}
}
|
Enable all kernels except FAT. | using System;
using System.Collections.Generic;
namespace Cosmos.TestRunner.Core
{
public static class TestKernelSets
{
public static IEnumerable<Type> GetStableKernelTypes()
{
yield return typeof(VGACompilerCrash.Kernel);
////yield return typeof(Cosmos.Compiler.Tests.Encryption.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Bcl.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.SingleEchoTest.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel);
//yield return typeof(SimpleStructsAndArraysTest.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Exceptions.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.LinqTests.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.MethodTests.Kernel);
yield return typeof(Cosmos.Kernel.Tests.Fat.Kernel);
////yield return typeof(FrotzKernel.Kernel);
}
}
}
| using System;
using System.Collections.Generic;
namespace Cosmos.TestRunner.Core
{
public static class TestKernelSets
{
public static IEnumerable<Type> GetStableKernelTypes()
{
yield return typeof(VGACompilerCrash.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Encryption.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Bcl.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SingleEchoTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel);
yield return typeof(SimpleStructsAndArraysTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Exceptions.Kernel);
yield return typeof(Cosmos.Compiler.Tests.LinqTests.Kernel);
yield return typeof(Cosmos.Compiler.Tests.MethodTests.Kernel);
//yield return typeof(Cosmos.Kernel.Tests.Fat.Kernel);
//yield return typeof(FrotzKernel.Kernel);
}
}
}
|
Fix bug in Statement DTO mapper that expected bucket code to always have a value - it can be null. | using System;
using BudgetAnalyser.Engine.BankAccount;
using BudgetAnalyser.Engine.Budget;
using JetBrains.Annotations;
namespace BudgetAnalyser.Engine.Statement.Data
{
[AutoRegisterWithIoC]
internal partial class Mapper_TransactionDto_Transaction
{
private readonly IAccountTypeRepository accountRepo;
private readonly IBudgetBucketRepository bucketRepo;
private readonly ITransactionTypeRepository transactionTypeRepo;
public Mapper_TransactionDto_Transaction([NotNull] IAccountTypeRepository accountRepo, [NotNull] IBudgetBucketRepository bucketRepo, [NotNull] ITransactionTypeRepository transactionTypeRepo)
{
if (accountRepo == null) throw new ArgumentNullException(nameof(accountRepo));
if (bucketRepo == null) throw new ArgumentNullException(nameof(bucketRepo));
if (transactionTypeRepo == null) throw new ArgumentNullException(nameof(transactionTypeRepo));
this.accountRepo = accountRepo;
this.bucketRepo = bucketRepo;
this.transactionTypeRepo = transactionTypeRepo;
}
partial void ToDtoPostprocessing(ref TransactionDto dto, Transaction model)
{
dto.Account = model.Account.Name;
dto.BudgetBucketCode = model.BudgetBucket.Code;
dto.TransactionType = model.TransactionType.Name;
}
partial void ToModelPostprocessing(TransactionDto dto, ref Transaction model)
{
// TODO do these need to be added to the repo here?
model.Account = this.accountRepo.GetByKey(dto.Account);
model.BudgetBucket = this.bucketRepo.GetByCode(dto.BudgetBucketCode);
model.TransactionType = this.transactionTypeRepo.GetOrCreateNew(dto.TransactionType);
}
}
} | using System;
using BudgetAnalyser.Engine.BankAccount;
using BudgetAnalyser.Engine.Budget;
using JetBrains.Annotations;
namespace BudgetAnalyser.Engine.Statement.Data
{
[AutoRegisterWithIoC]
internal partial class Mapper_TransactionDto_Transaction
{
private readonly IAccountTypeRepository accountRepo;
private readonly IBudgetBucketRepository bucketRepo;
private readonly ITransactionTypeRepository transactionTypeRepo;
public Mapper_TransactionDto_Transaction([NotNull] IAccountTypeRepository accountRepo, [NotNull] IBudgetBucketRepository bucketRepo, [NotNull] ITransactionTypeRepository transactionTypeRepo)
{
if (accountRepo == null) throw new ArgumentNullException(nameof(accountRepo));
if (bucketRepo == null) throw new ArgumentNullException(nameof(bucketRepo));
if (transactionTypeRepo == null) throw new ArgumentNullException(nameof(transactionTypeRepo));
this.accountRepo = accountRepo;
this.bucketRepo = bucketRepo;
this.transactionTypeRepo = transactionTypeRepo;
}
partial void ToDtoPostprocessing(ref TransactionDto dto, Transaction model)
{
dto.Account = model.Account.Name;
dto.BudgetBucketCode = model.BudgetBucket?.Code;
dto.TransactionType = model.TransactionType.Name;
}
partial void ToModelPostprocessing(TransactionDto dto, ref Transaction model)
{
// TODO do these need to be added to the repo here?
model.Account = this.accountRepo.GetByKey(dto.Account);
model.BudgetBucket = this.bucketRepo.GetByCode(dto.BudgetBucketCode);
model.TransactionType = this.transactionTypeRepo.GetOrCreateNew(dto.TransactionType);
}
}
} |
Improve text control black list | using System.Collections.Generic;
namespace JetBrains.ReSharper.Plugins.PresentationAssistant
{
public static class ActionIdBlacklist
{
private static readonly HashSet<string> ActionIds = new HashSet<string>
{
// These are the only actions that should be hidden
"TextControl.Backspace",
"TextControl.Delete",
"TextControl.Cut",
"TextControl.Paste",
"TextControl.Copy",
// Used when code completion window is visible
"TextControl.Up", "TextControl.Down",
"TextControl.PageUp", "TextControl.PageDown",
// If camel humps are enabled in the editor
"TextControl.PreviousWord",
"TextControl.PreviousWord.Selection",
"TextControl.NextWord",
"TextControl.NextWord.Selection",
// VS commands, not R# commands
"Edit.Up", "Edit.Down", "Edit.Left", "Edit.Right", "Edit.PageUp", "Edit.PageDown",
// Make sure we don't try to show the presentation assistant popup just as we're
// killing the popups
PresentationAssistantAction.ActionId
};
public static bool IsBlacklisted(string actionId)
{
return ActionIds.Contains(actionId);
}
}
} | using System.Collections.Generic;
namespace JetBrains.ReSharper.Plugins.PresentationAssistant
{
public static class ActionIdBlacklist
{
private static readonly HashSet<string> ActionIds = new HashSet<string>
{
// These are the only actions that should be hidden
"TextControl.Backspace",
"TextControl.Delete",
"TextControl.Cut",
"TextControl.Paste",
"TextControl.Copy",
"TextControl.Left", "TextControl.Right",
"TextControl.Left.Selection", "TextControl.Right.Selection",
"TextControl.Up", "TextControl.Down",
"TextControl.Up.Selection", "TextControl.Down.Selection",
"TextControl.Home", "TextControl.End",
"TextControl.Home.Selection", "TextControl.End.Selection",
"TextControl.PageUp", "TextControl.PageDown",
"TextControl.PageUp.Selection", "TextControl.PageDown.Selection",
"TextControl.PreviousWord", "TextControl.NextWord",
"TextControl.PreviousWord.Selection", "TextControl.NextWord.Selection",
// VS commands, not R# commands
"Edit.Up", "Edit.Down", "Edit.Left", "Edit.Right", "Edit.PageUp", "Edit.PageDown",
// Make sure we don't try to show the presentation assistant popup just as we're
// killing the popups
PresentationAssistantAction.ActionId
};
public static bool IsBlacklisted(string actionId)
{
return ActionIds.Contains(actionId);
}
}
} |
Remove doc_values fielddata format for strings | using System.Runtime.Serialization;
namespace Nest
{
public enum StringFielddataFormat
{
[EnumMember(Value = "paged_bytes")]
PagedBytes,
[EnumMember(Value = "doc_values")]
DocValues,
[EnumMember(Value = "disabled")]
Disabled
}
}
| using System.Runtime.Serialization;
namespace Nest
{
public enum StringFielddataFormat
{
[EnumMember(Value = "paged_bytes")]
PagedBytes,
[EnumMember(Value = "disabled")]
Disabled
}
}
|
Simplify the code that ensures a birthday is in the future. | using System;
using Humanizer;
namespace Repack
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Usage: repack [date]");
Console.WriteLine("Prints how long it is until your birthday.");
Console.WriteLine("If you don't supply your birthday, it uses mine.");
DateTime birthDay = GetBirthday(args);
Console.WriteLine();
var span = GetSpan(birthDay);
Console.WriteLine("{0} until your birthday", span.Humanize());
}
private static TimeSpan GetSpan(DateTime birthDay)
{
if (birthDay < DateTime.Now)
{
if (birthDay.Year < DateTime.Now.Year)
{
return GetSpan(new DateTime(DateTime.Now.Year, birthDay.Month, birthDay.Day));
}
else
{
return GetSpan(new DateTime(DateTime.Now.Year + 1, birthDay.Month, birthDay.Day));
}
}
var span = birthDay - DateTime.Now;
return span;
}
private static DateTime GetBirthday(string[] args)
{
string day = null;
if (args != null && args.Length > 0)
{
day = args[0];
}
return GetBirthday(day);
}
private static DateTime GetBirthday(string day)
{
DateTime parsed;
if (DateTime.TryParse(day, out parsed))
{
return parsed;
}
else
{
return new DateTime(DateTime.Now.Year, 8, 20);
}
}
}
} | using System;
using Humanizer;
namespace Repack
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Usage: repack [date]");
Console.WriteLine("Prints how long it is until your birthday.");
Console.WriteLine("If you don't supply your birthday, it uses mine.");
DateTime birthDay = GetBirthday(args);
Console.WriteLine();
var span = GetSpan(birthDay);
Console.WriteLine("{0} until your birthday", span.Humanize());
}
private static TimeSpan GetSpan(DateTime birthDay)
{
var span = birthDay - DateTime.Now;
if (span.Days < 0)
{
// If the supplied birthday has already happened, then find the next one that will occur.
int years = span.Days / -365;
span = span.Add(TimeSpan.FromDays((years + 1) * 365));
}
return span;
}
private static DateTime GetBirthday(string[] args)
{
string day = null;
if (args != null && args.Length > 0)
{
day = args[0];
}
return GetBirthday(day);
}
private static DateTime GetBirthday(string day)
{
DateTime parsed;
if (DateTime.TryParse(day, out parsed))
{
return parsed;
}
else
{
return new DateTime(DateTime.Now.Year, 8, 20);
}
}
}
} |
Add new command option "skipDetect" | using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Builder
{
public class Options
{
[Option('a', "buildDir", Required = true, HelpText = "")]
public string BuildDir { get; set; }
[Option('b', "buildArtifactsCacheDir", Required = false, HelpText = "")]
public string BuildArtifactsCacheDir { get; set; }
[Option('o', "buildpackOrder", Required = false, HelpText = "")]
public string BuildpackOrder { get; set; }
[Option('e', "buildpacksDir", Required = false, HelpText = "")]
public string BuildpacksDir { get; set; }
[Option('c', "outputBuildArtifactsCache", Required = false, HelpText = "")]
public string OutputBuildArtifactsCache { get; set; }
[Option('d', "outputDroplet", Required = true, HelpText = "")]
public string OutputDroplet { get; set; }
[Option('m', "outputMetadata", Required = true, HelpText = "")]
public string OutputMetadata { get; set; }
[Option('s', "skipCertVerify", Required = false, HelpText = "")]
public string SkipCertVerify { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
}
| using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Builder
{
public class Options
{
[Option('a', "buildDir", Required = true, HelpText = "")]
public string BuildDir { get; set; }
[Option('b', "buildArtifactsCacheDir", Required = false, HelpText = "")]
public string BuildArtifactsCacheDir { get; set; }
[Option('o', "buildpackOrder", Required = false, HelpText = "")]
public string BuildpackOrder { get; set; }
[Option('e', "buildpacksDir", Required = false, HelpText = "")]
public string BuildpacksDir { get; set; }
[Option('c', "outputBuildArtifactsCache", Required = false, HelpText = "")]
public string OutputBuildArtifactsCache { get; set; }
[Option('d', "outputDroplet", Required = true, HelpText = "")]
public string OutputDroplet { get; set; }
[Option('m', "outputMetadata", Required = true, HelpText = "")]
public string OutputMetadata { get; set; }
[Option('s', "skipCertVerify", Required = false, HelpText = "")]
public string SkipCertVerify { get; set; }
[Option('k', "skipDetect", Required = false, HelpText = "")]
public string skipDetect { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
}
|
Use `Array.Empty` instead of constructed list | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using Realms;
using Realms.Schema;
#nullable enable
namespace osu.Game.Database
{
public class EmptyRealmSet<T> : IRealmCollection<T>
{
private static List<T> emptySet => new List<T>();
public IEnumerator<T> GetEnumerator()
{
return emptySet.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)emptySet).GetEnumerator();
}
public int Count => emptySet.Count;
public T this[int index] => emptySet[index];
public event NotifyCollectionChangedEventHandler? CollectionChanged
{
add => throw new NotImplementedException();
remove => throw new NotImplementedException();
}
public event PropertyChangedEventHandler? PropertyChanged
{
add => throw new NotImplementedException();
remove => throw new NotImplementedException();
}
public int IndexOf(object item)
{
return emptySet.IndexOf((T)item);
}
public bool Contains(object item)
{
return emptySet.Contains((T)item);
}
public IRealmCollection<T> Freeze()
{
throw new NotImplementedException();
}
public IDisposable SubscribeForNotifications(NotificationCallbackDelegate<T> callback)
{
throw new NotImplementedException();
}
public bool IsValid => throw new NotImplementedException();
public Realm Realm => throw new NotImplementedException();
public ObjectSchema ObjectSchema => throw new NotImplementedException();
public bool IsFrozen => throw new NotImplementedException();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using Realms;
using Realms.Schema;
#nullable enable
namespace osu.Game.Database
{
public class EmptyRealmSet<T> : IRealmCollection<T>
{
private IList<T> emptySet => Array.Empty<T>();
public IEnumerator<T> GetEnumerator() => emptySet.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => emptySet.GetEnumerator();
public int Count => emptySet.Count;
public T this[int index] => emptySet[index];
public int IndexOf(object item) => emptySet.IndexOf((T)item);
public bool Contains(object item) => emptySet.Contains((T)item);
public event NotifyCollectionChangedEventHandler? CollectionChanged
{
add => throw new NotImplementedException();
remove => throw new NotImplementedException();
}
public event PropertyChangedEventHandler? PropertyChanged
{
add => throw new NotImplementedException();
remove => throw new NotImplementedException();
}
public IRealmCollection<T> Freeze() => throw new NotImplementedException();
public IDisposable SubscribeForNotifications(NotificationCallbackDelegate<T> callback) => throw new NotImplementedException();
public bool IsValid => throw new NotImplementedException();
public Realm Realm => throw new NotImplementedException();
public ObjectSchema ObjectSchema => throw new NotImplementedException();
public bool IsFrozen => throw new NotImplementedException();
}
}
|
Fix System.Reflection.Context test to run on Desktop | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Reflection.Context
{
public class CustomReflectionContextTests
{
[Fact]
public void InstantiateContext_Throws()
{
Assert.Throws<PlatformNotSupportedException>(() => new DerivedContext());
}
private class DerivedContext : CustomReflectionContext { }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Reflection.Context
{
public class CustomReflectionContextTests
{
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void InstantiateContext_Throws()
{
Assert.Throws<PlatformNotSupportedException>(() => new DerivedContext());
}
private class DerivedContext : CustomReflectionContext { }
}
}
|
Add support for LF record separator | using System;
using System.Collections.Generic;
using Arkivverket.Arkade.Util;
namespace Arkivverket.Arkade.Core.Addml.Definitions
{
public class Separator
{
private static readonly Dictionary<string, string> SpecialSeparators = new Dictionary<string, string>
{
{"CRLF", "\r\n"}
};
public static readonly Separator CRLF = new Separator("CRLF");
private readonly string _name;
private readonly string _separator;
public Separator(string separator)
{
Assert.AssertNotNullOrEmpty("separator", separator);
_name = separator;
_separator = Convert(separator);
}
public string Get()
{
return _separator;
}
public override string ToString()
{
return _name;
}
protected bool Equals(Separator other)
{
return string.Equals(_name, other._name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Separator) obj);
}
public override int GetHashCode()
{
return _name?.GetHashCode() ?? 0;
}
private string Convert(string s)
{
return SpecialSeparators.ContainsKey(s) ? SpecialSeparators[s] : s;
}
internal int GetLength()
{
return _separator.Length;
}
}
} | using System;
using System.Collections.Generic;
using Arkivverket.Arkade.Util;
namespace Arkivverket.Arkade.Core.Addml.Definitions
{
public class Separator
{
private static readonly Dictionary<string, string> SpecialSeparators = new Dictionary<string, string>
{
{"CRLF", "\r\n"},
{"LF", "\n"}
};
public static readonly Separator CRLF = new Separator("CRLF");
private readonly string _name;
private readonly string _separator;
public Separator(string separator)
{
Assert.AssertNotNullOrEmpty("separator", separator);
_name = separator;
_separator = Convert(separator);
}
public string Get()
{
return _separator;
}
public override string ToString()
{
return _name;
}
protected bool Equals(Separator other)
{
return string.Equals(_name, other._name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Separator) obj);
}
public override int GetHashCode()
{
return _name?.GetHashCode() ?? 0;
}
private string Convert(string s)
{
return SpecialSeparators.ContainsKey(s) ? SpecialSeparators[s] : s;
}
internal int GetLength()
{
return _separator.Length;
}
}
} |
Send the current song index as nullable | using Espera.Core;
using Espera.Core.Management;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
namespace Espera.Services
{
public static class MobileHelper
{
public static async Task<byte[]> CompressContentAsync(byte[] content)
{
using (var targetStream = new MemoryStream())
{
using (var stream = new GZipStream(targetStream, CompressionMode.Compress))
{
await stream.WriteAsync(content, 0, content.Length);
}
return targetStream.ToArray();
}
}
public static JObject SerializePlaylist(Playlist playlist)
{
return JObject.FromObject(new
{
name = playlist.Name,
current = playlist.CurrentSongIndex.Value.ToString(),
songs = playlist.Select(x => new
{
artist = x.Song.Artist,
title = x.Song.Title,
source = x.Song is LocalSong ? "local" : "youtube",
guid = x.Guid
})
});
}
public static JObject SerializeSongs(IEnumerable<LocalSong> songs)
{
return JObject.FromObject(new
{
songs = songs
.Select(s => new
{
album = s.Album,
artist = s.Artist,
duration = s.Duration.TotalSeconds,
genre = s.Genre,
title = s.Title,
guid = s.Guid
})
});
}
}
} | using Espera.Core;
using Espera.Core.Management;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
namespace Espera.Services
{
public static class MobileHelper
{
public static async Task<byte[]> CompressContentAsync(byte[] content)
{
using (var targetStream = new MemoryStream())
{
using (var stream = new GZipStream(targetStream, CompressionMode.Compress))
{
await stream.WriteAsync(content, 0, content.Length);
}
return targetStream.ToArray();
}
}
public static JObject SerializePlaylist(Playlist playlist)
{
return JObject.FromObject(new
{
name = playlist.Name,
current = playlist.CurrentSongIndex.Value,
songs = playlist.Select(x => new
{
artist = x.Song.Artist,
title = x.Song.Title,
source = x.Song is LocalSong ? "local" : "youtube",
guid = x.Guid
})
});
}
public static JObject SerializeSongs(IEnumerable<LocalSong> songs)
{
return JObject.FromObject(new
{
songs = songs
.Select(s => new
{
album = s.Album,
artist = s.Artist,
duration = s.Duration.TotalSeconds,
genre = s.Genre,
title = s.Title,
guid = s.Guid
})
});
}
}
} |
Make concat add to the eof array | using SubMapper.EnumerableMapping;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SubMapper.EnumerableMapping.Adders
{
public static partial class PartialEnumerableMappingExtensions
{
public static PartialEnumerableMapping<TSubA, TSubB, IEnumerable<TSubIItem>, TSubJ, TSubIItem>
WithArrayConcatAdder<TSubA, TSubB, TSubJ, TSubIItem>(
this PartialEnumerableMapping<TSubA, TSubB, IEnumerable<TSubIItem>, TSubJ, TSubIItem> source)
where TSubJ : new()
where TSubIItem : new()
{
source.WithAdder((bc, b) => new[] { b }.Concat(bc ?? new TSubIItem[] { }).ToArray());
return source;
}
}
}
| using SubMapper.EnumerableMapping;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SubMapper.EnumerableMapping.Adders
{
public static partial class PartialEnumerableMappingExtensions
{
public static PartialEnumerableMapping<TSubA, TSubB, IEnumerable<TSubIItem>, TSubJ, TSubIItem>
WithArrayConcatAdder<TSubA, TSubB, TSubJ, TSubIItem>(
this PartialEnumerableMapping<TSubA, TSubB, IEnumerable<TSubIItem>, TSubJ, TSubIItem> source)
where TSubJ : new()
where TSubIItem : new()
{
source.WithAdder((bc, b) => (bc ?? new TSubIItem[] { }).Concat(new[] { b }).ToArray());
return source;
}
}
}
|
Use the new factory for Typesetting context | using CSharpMath.Apple;
namespace CSharpMath.Ios
{
static class IosMathLabels
{
public static AppleLatexView LatexView(string latex)
{
var typesettingContext = AppleTypesetters.CreateTypesettingContext()
var view = new AppleLatexView();
view.SetLatex(latex);
return view;
}
}
} | using CSharpMath.Apple;
namespace CSharpMath.Ios
{
static class IosMathLabels
{
public static AppleLatexView LatexView(string latex)
{
var typesettingContext = AppleTypesetters.CreateLatinMath();
var view = new AppleLatexView(typesettingContext);
view.SetLatex(latex);
return view;
}
}
} |
Correct default serialization strategy to `Default` | using System;
using UnityEngine;
namespace FullSerializer {
/// <summary>
/// Enables some top-level customization of Full Serializer.
/// </summary>
public static class fsConfig {
/// <summary>
/// The attributes that will force a field or property to be serialized.
/// </summary>
public static Type[] SerializeAttributes = new[] { typeof(SerializeField), typeof(fsPropertyAttribute) };
/// <summary>
/// The attributes that will force a field or property to *not* be serialized.
/// </summary>
public static Type[] IgnoreSerializeAttributes = new[] { typeof(NonSerializedAttribute), typeof(fsIgnoreAttribute) };
/// <summary>
/// The default member serialization.
/// </summary>
public static fsMemberSerialization DefaultMemberSerialization {
get {
return _defaultMemberSerialization;
}
set {
_defaultMemberSerialization = value;
fsMetaType.ClearCache();
}
}
private static fsMemberSerialization _defaultMemberSerialization = fsMemberSerialization.OptOut;
}
} | using System;
using UnityEngine;
namespace FullSerializer {
/// <summary>
/// Enables some top-level customization of Full Serializer.
/// </summary>
public static class fsConfig {
/// <summary>
/// The attributes that will force a field or property to be serialized.
/// </summary>
public static Type[] SerializeAttributes = new[] { typeof(SerializeField), typeof(fsPropertyAttribute) };
/// <summary>
/// The attributes that will force a field or property to *not* be serialized.
/// </summary>
public static Type[] IgnoreSerializeAttributes = new[] { typeof(NonSerializedAttribute), typeof(fsIgnoreAttribute) };
/// <summary>
/// The default member serialization.
/// </summary>
public static fsMemberSerialization DefaultMemberSerialization {
get {
return _defaultMemberSerialization;
}
set {
_defaultMemberSerialization = value;
fsMetaType.ClearCache();
}
}
private static fsMemberSerialization _defaultMemberSerialization = fsMemberSerialization.Default;
}
} |
Improve argument exception message of scrobble post. | namespace TraktApiSharp.Objects.Post.Scrobbles
{
using Newtonsoft.Json;
using System;
public abstract class TraktScrobblePost : IValidatable
{
[JsonProperty(PropertyName = "progress")]
public float Progress { get; set; }
[JsonProperty(PropertyName = "app_version")]
public string AppVersion { get; set; }
[JsonProperty(PropertyName = "app_date")]
public string AppDate { get; set; }
public void Validate()
{
if (Progress.CompareTo(0.0f) < 0)
throw new ArgumentException("progress value not valid");
if (Progress.CompareTo(100.0f) > 0)
throw new ArgumentException("progress value not valid");
}
}
}
| namespace TraktApiSharp.Objects.Post.Scrobbles
{
using Newtonsoft.Json;
using System;
public abstract class TraktScrobblePost : IValidatable
{
[JsonProperty(PropertyName = "progress")]
public float Progress { get; set; }
[JsonProperty(PropertyName = "app_version")]
public string AppVersion { get; set; }
[JsonProperty(PropertyName = "app_date")]
public string AppDate { get; set; }
public void Validate()
{
if (Progress.CompareTo(0.0f) < 0 || Progress.CompareTo(100.0f) > 0)
throw new ArgumentException("progress value not valid - value must be between 0 and 100");
}
}
}
|
Add default request header to Payments API httpClient to look for version 2. Since removing the SecureHttpClient from PaymentEventsApiClient this header was lost. This only matters for data locks as that is the only controller action split by api version at present | using System.Net.Http;
using SFA.DAS.CommitmentPayments.WebJob.Configuration;
using SFA.DAS.Http;
using SFA.DAS.Http.TokenGenerators;
using SFA.DAS.NLog.Logger.Web.MessageHandlers;
using SFA.DAS.Provider.Events.Api.Client;
using SFA.DAS.Provider.Events.Api.Client.Configuration;
using StructureMap;
namespace SFA.DAS.CommitmentPayments.WebJob.DependencyResolution
{
internal class PaymentsRegistry : Registry
{
public PaymentsRegistry()
{
For<PaymentEventsApi>().Use(c => c.GetInstance<CommitmentPaymentsConfiguration>().PaymentEventsApi);
For<IPaymentsEventsApiConfiguration>().Use(c => c.GetInstance<PaymentEventsApi>());
For<IPaymentsEventsApiClient>().Use<PaymentsEventsApiClient>().Ctor<HttpClient>().Is(c => CreateClient(c));
}
private HttpClient CreateClient(IContext context)
{
var config = context.GetInstance<CommitmentPaymentsConfiguration>().PaymentEventsApi;
HttpClient httpClient = new HttpClientBuilder()
.WithBearerAuthorisationHeader(new AzureActiveDirectoryBearerTokenGenerator(config))
.WithHandler(new RequestIdMessageRequestHandler())
.WithHandler(new SessionIdMessageRequestHandler())
.WithDefaultHeaders()
.Build();
return httpClient;
}
}
}
| using System.Net.Http;
using SFA.DAS.CommitmentPayments.WebJob.Configuration;
using SFA.DAS.Http;
using SFA.DAS.Http.TokenGenerators;
using SFA.DAS.NLog.Logger.Web.MessageHandlers;
using SFA.DAS.Provider.Events.Api.Client;
using SFA.DAS.Provider.Events.Api.Client.Configuration;
using StructureMap;
namespace SFA.DAS.CommitmentPayments.WebJob.DependencyResolution
{
internal class PaymentsRegistry : Registry
{
public PaymentsRegistry()
{
For<PaymentEventsApi>().Use(c => c.GetInstance<CommitmentPaymentsConfiguration>().PaymentEventsApi);
For<IPaymentsEventsApiConfiguration>().Use(c => c.GetInstance<PaymentEventsApi>());
For<IPaymentsEventsApiClient>().Use<PaymentsEventsApiClient>().Ctor<HttpClient>().Is(c => CreateClient(c));
}
private HttpClient CreateClient(IContext context)
{
var config = context.GetInstance<CommitmentPaymentsConfiguration>().PaymentEventsApi;
HttpClient httpClient = new HttpClientBuilder()
.WithBearerAuthorisationHeader(new AzureActiveDirectoryBearerTokenGenerator(config))
.WithHandler(new RequestIdMessageRequestHandler())
.WithHandler(new SessionIdMessageRequestHandler())
.WithDefaultHeaders()
.Build();
httpClient.DefaultRequestHeaders.Add("api-version", "2");
return httpClient;
}
}
}
|
Add extra tests and missing TestClass attribute. | // Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// 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.Drawing;
using ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Magick.NET.SystemDrawing.Tests
{
public partial class MagickImageFactoryTests
{
public partial class TheCreateMethod
{
[TestMethod]
public void ShouldCreateImageFromBitmap()
{
using (var bitmap = new Bitmap(Files.SnakewarePNG))
{
var factory = new MagickImageFactory();
using (var image = factory.Create(bitmap))
{
Assert.AreEqual(286, image.Width);
Assert.AreEqual(67, image.Height);
Assert.AreEqual(MagickFormat.Png, image.Format);
}
}
}
}
}
} | // Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// 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.Drawing;
using ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Magick.NET.SystemDrawing.Tests
{
public partial class MagickImageFactoryTests
{
[TestClass]
public partial class TheCreateMethod
{
[TestMethod]
public void ShouldThrowExceptionWhenBitmapIsNull()
{
var factory = new MagickImageFactory();
ExceptionAssert.Throws<ArgumentNullException>("bitmap", () => factory.Create((Bitmap)null));
}
[TestMethod]
public void ShouldCreateImageFromBitmap()
{
using (var bitmap = new Bitmap(Files.SnakewarePNG))
{
var factory = new MagickImageFactory();
using (var image = factory.Create(bitmap))
{
Assert.AreEqual(286, image.Width);
Assert.AreEqual(67, image.Height);
Assert.AreEqual(MagickFormat.Png, image.Format);
}
}
}
}
}
} |
Make comment say that 0x001 is RTLD_LOCAL + RTLD_LAZY | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Runtime.InteropServices;
namespace osu.Framework.Platform.Linux.Native
{
public static class Library
{
[DllImport("libdl.so", EntryPoint = "dlopen")]
private static extern IntPtr dlopen(string filename, int flags);
public static void LoadLazyLocal(string filename)
{
dlopen(filename, 0x001); // RTLD_LOCAL + RTLD_NOW
}
public static void LoadNowLocal(string filename)
{
dlopen(filename, 0x002); // RTLD_LOCAL + RTLD_NOW
}
public static void LoadLazyGlobal(string filename)
{
dlopen(filename, 0x101); // RTLD_GLOBAL + RTLD_LAZY
}
public static void LoadNowGlobal(string filename)
{
dlopen(filename, 0x102); // RTLD_GLOBAL + RTLD_NOW
}
}
} | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Runtime.InteropServices;
namespace osu.Framework.Platform.Linux.Native
{
public static class Library
{
[DllImport("libdl.so", EntryPoint = "dlopen")]
private static extern IntPtr dlopen(string filename, int flags);
public static void LoadLazyLocal(string filename)
{
dlopen(filename, 0x001); // RTLD_LOCAL + RTLD_LAZY
}
public static void LoadNowLocal(string filename)
{
dlopen(filename, 0x002); // RTLD_LOCAL + RTLD_NOW
}
public static void LoadLazyGlobal(string filename)
{
dlopen(filename, 0x101); // RTLD_GLOBAL + RTLD_LAZY
}
public static void LoadNowGlobal(string filename)
{
dlopen(filename, 0x102); // RTLD_GLOBAL + RTLD_NOW
}
}
} |
Fix error when unserializing json object | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace PogoLocationFeeder.Helper
{
public class JsonSerializerSettingsCultureInvariant : JsonSerializerSettings
{
public JsonSerializerSettingsCultureInvariant()
{
Culture = CultureInfo.InvariantCulture;
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PogoLocationFeeder.Helper
{
public class JsonSerializerSettingsCultureInvariant : JsonSerializerSettings
{
public JsonSerializerSettingsCultureInvariant()
{
Culture = CultureInfo.InvariantCulture;
Converters = new List<JsonConverter> { new DoubleConverter()};
}
}
public class DoubleConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(double) || objectType == typeof(double?));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Float || token.Type == JTokenType.Integer)
{
return token.ToObject<double>();
}
if (token.Type == JTokenType.String)
{
var match = Regex.Match(token.ToString(), @"(1?\-?\d+\.?\d*)");
if (match.Success)
{
return Double.Parse(match.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
}
return Double.Parse(token.ToString(),
System.Globalization.CultureInfo.InvariantCulture);
}
if (token.Type == JTokenType.Null && objectType == typeof(double?))
{
return null;
}
throw new JsonSerializationException("Unexpected token type: " +
token.Type.ToString());
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
|
Add filter property to most anticipated shows request. | namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base.Get;
using Objects.Basic;
using Objects.Get.Shows.Common;
internal class TraktShowsMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedShow>, TraktMostAnticipatedShow>
{
internal TraktShowsMostAnticipatedRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "shows/anticipated{?extended,page,limit}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
| namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base;
using Base.Get;
using Objects.Basic;
using Objects.Get.Shows.Common;
internal class TraktShowsMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedShow>, TraktMostAnticipatedShow>
{
internal TraktShowsMostAnticipatedRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "shows/anticipated{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
internal TraktShowFilter Filter { get; set; }
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
|
Add dots to experiment names so they can be enabled as feature flags. | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
public bool ReturnValue = false;
[ImportingConstructor]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => ReturnValue;
}
internal static class WellKnownExperimentNames
{
public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
public const string RoslynInlineRenameFile = "Roslyn.FileRename";
// Syntactic LSP experiment treatments.
public const string SyntacticExp_LiveShareTagger_Remote = "RoslynLsp_Tagger";
public const string SyntacticExp_LiveShareTagger_TextMate = "RoslynTextMate_Tagger";
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
public bool ReturnValue = false;
[ImportingConstructor]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => ReturnValue;
}
internal static class WellKnownExperimentNames
{
public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
public const string RoslynInlineRenameFile = "Roslyn.FileRename";
// Syntactic LSP experiment treatments.
public const string SyntacticExp_LiveShareTagger_Remote = "Roslyn.LspTagger";
public const string SyntacticExp_LiveShareTagger_TextMate = "Roslyn.TextMateTagger";
}
}
|
Add spotlighted beatmaps filter to beatmap listing | // 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.ComponentModel;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Overlays.BeatmapListing
{
public enum SearchGeneral
{
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralRecommended))]
[Description("Recommended difficulty")]
Recommended,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralConverts))]
[Description("Include converted beatmaps")]
Converts,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFollows))]
[Description("Subscribed mappers")]
Follows,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFeaturedArtists))]
[Description("Featured artists")]
FeaturedArtists
}
}
| // 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.ComponentModel;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Overlays.BeatmapListing
{
public enum SearchGeneral
{
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralRecommended))]
[Description("Recommended difficulty")]
Recommended,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralConverts))]
[Description("Include converted beatmaps")]
Converts,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFollows))]
[Description("Subscribed mappers")]
Follows,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralSpotlights))]
Spotlights,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFeaturedArtists))]
[Description("Featured artists")]
FeaturedArtists
}
}
|
Call the correct implementation if IMessageHandler.ProcessMessage method | using System;
using Shuttle.Core.Infrastructure;
namespace Shuttle.Esb
{
public class DefaultMessageHandlerInvoker : IMessageHandlerInvoker
{
public MessageHandlerInvokeResult Invoke(IPipelineEvent pipelineEvent)
{
Guard.AgainstNull(pipelineEvent, "pipelineEvent");
var state = pipelineEvent.Pipeline.State;
var bus = state.GetServiceBus();
var message = state.GetMessage();
var handler = bus.Configuration.MessageHandlerFactory.GetHandler(message);
if (handler == null)
{
return MessageHandlerInvokeResult.InvokeFailure();
}
try
{
var transportMessage = state.GetTransportMessage();
var messageType = message.GetType();
var contextType = typeof (HandlerContext<>).MakeGenericType(messageType);
var method = handler.GetType().GetMethod("ProcessMessage", new[] {contextType});
if (method == null)
{
throw new ProcessMessageMethodMissingException(string.Format(
EsbResources.ProcessMessageMethodMissingException,
handler.GetType().FullName,
messageType.FullName));
}
var handlerContext = Activator.CreateInstance(contextType, bus, transportMessage, message, state.GetActiveState());
method.Invoke(handler, new[] {handlerContext});
}
finally
{
bus.Configuration.MessageHandlerFactory.ReleaseHandler(handler);
}
return MessageHandlerInvokeResult.InvokedHandler(handler);
}
}
} | using System;
using System.Linq;
using Shuttle.Core.Infrastructure;
namespace Shuttle.Esb
{
public class DefaultMessageHandlerInvoker : IMessageHandlerInvoker
{
public MessageHandlerInvokeResult Invoke(IPipelineEvent pipelineEvent)
{
Guard.AgainstNull(pipelineEvent, "pipelineEvent");
var state = pipelineEvent.Pipeline.State;
var bus = state.GetServiceBus();
var message = state.GetMessage();
var handler = bus.Configuration.MessageHandlerFactory.GetHandler(message);
if (handler == null)
{
return MessageHandlerInvokeResult.InvokeFailure();
}
try
{
var transportMessage = state.GetTransportMessage();
var messageType = message.GetType();
var interfaceType = typeof(IMessageHandler<>).MakeGenericType(messageType);
var method = handler.GetType().GetInterfaceMap(interfaceType).TargetMethods.SingleOrDefault();
if (method == null)
{
throw new ProcessMessageMethodMissingException(string.Format(
EsbResources.ProcessMessageMethodMissingException,
handler.GetType().FullName,
messageType.FullName));
}
var contextType = typeof(HandlerContext<>).MakeGenericType(messageType);
var handlerContext = Activator.CreateInstance(contextType, bus, transportMessage, message, state.GetActiveState());
method.Invoke(handler, new[] {handlerContext});
}
finally
{
bus.Configuration.MessageHandlerFactory.ReleaseHandler(handler);
}
return MessageHandlerInvokeResult.InvokedHandler(handler);
}
}
} |
Remove get all with dynamic clause. SHould be handeled by user in own class. Otherwise forced to use FastCRUD | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper.FastCrud;
using Dapper.FastCrud.Configuration.StatementOptions.Builders;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public abstract partial class Repository<TSession, TEntity, TPk>
where TEntity : class, IEntity<TPk>
where TSession : ISession
{
public IEnumerable<TEntity> GetAll(ISession session = null)
{
return GetAllAsync(session).Result;
}
public async Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null)
{
if (session != null)
{
return await session.FindAsync<TEntity>();
}
using (var uow = Factory.CreateSession<TSession>())
{
return await uow.FindAsync<TEntity>();
}
}
protected async Task<IEnumerable<TEntity>> GetAllAsync(ISession session, Action<IRangedBatchSelectSqlSqlStatementOptionsOptionsBuilder<TEntity>> statement)
{
if (session != null)
{
return await session.FindAsync(statement);
}
using (var uow = Factory.CreateSession<TSession>())
{
return await uow.FindAsync(statement);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper.FastCrud;
using Dapper.FastCrud.Configuration.StatementOptions.Builders;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public abstract partial class Repository<TSession, TEntity, TPk>
where TEntity : class, IEntity<TPk>
where TSession : ISession
{
public IEnumerable<TEntity> GetAll(ISession session = null)
{
return GetAllAsync(session).Result;
}
public async Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null)
{
if (session != null)
{
return await session.FindAsync<TEntity>();
}
using (var uow = Factory.CreateSession<TSession>())
{
return await uow.FindAsync<TEntity>();
}
}
}
}
|
Add more arango specific attributes. | using System;
namespace Arango.Client
{
[AttributeUsage(AttributeTargets.Property)]
public class ArangoProperty : Attribute
{
public string Alias { get; set; }
public bool Serializable { get; set; }
public ArangoProperty()
{
Serializable = true;
}
}
}
| using System;
namespace Arango.Client
{
[AttributeUsage(AttributeTargets.Property)]
public class ArangoProperty : Attribute
{
public bool Serializable { get; set; }
public bool Identity { get; set; }
public bool Key { get; set; }
public bool Revision { get; set; }
public bool From { get; set; }
public bool To { get; set; }
public string Alias { get; set; }
public ArangoProperty()
{
Serializable = true;
Identity = false;
Key = false;
Revision = false;
From = false;
To = false;
}
}
}
|
Allow NON_BOUNDED value to be used as constructor parameter. | using System;
using System.Collections.Concurrent;
using System.Threading;
namespace Serilog.Sinks.PeriodicBatching
{
class BoundedConcurrentQueue<T>
{
const int NON_BOUNDED = -1;
readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
readonly int _queueLimit;
int _counter;
public BoundedConcurrentQueue()
{
_queueLimit = NON_BOUNDED;
}
public BoundedConcurrentQueue(int queueLimit)
{
if (queueLimit <= 0)
throw new ArgumentOutOfRangeException(nameof(queueLimit), "queue limit must be positive");
_queueLimit = queueLimit;
}
public int Count => _queue.Count;
public bool TryDequeue(out T item)
{
if (_queueLimit == NON_BOUNDED)
return _queue.TryDequeue(out item);
var result = false;
try
{ }
finally // prevent state corrupt while aborting
{
if (_queue.TryDequeue(out item))
{
Interlocked.Decrement(ref _counter);
result = true;
}
}
return result;
}
public bool TryEnqueue(T item)
{
if (_queueLimit == NON_BOUNDED)
{
_queue.Enqueue(item);
return true;
}
var result = true;
try
{ }
finally
{
if (Interlocked.Increment(ref _counter) <= _queueLimit)
{
_queue.Enqueue(item);
}
else
{
Interlocked.Decrement(ref _counter);
result = false;
}
}
return result;
}
}
}
| using System;
using System.Collections.Concurrent;
using System.Threading;
namespace Serilog.Sinks.PeriodicBatching
{
class BoundedConcurrentQueue<T>
{
const int NON_BOUNDED = -1;
readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
readonly int _queueLimit;
int _counter;
public BoundedConcurrentQueue()
: this(NON_BOUNDED) { }
public BoundedConcurrentQueue(int queueLimit)
{
if (queueLimit <= 0 && queueLimit != NON_BOUNDED)
throw new ArgumentOutOfRangeException(nameof(queueLimit), $"Queue limit must be positive, or {NON_BOUNDED} (to indicate unlimited).");
_queueLimit = queueLimit;
}
public int Count => _queue.Count;
public bool TryDequeue(out T item)
{
if (_queueLimit == NON_BOUNDED)
return _queue.TryDequeue(out item);
var result = false;
try
{ }
finally // prevent state corrupt while aborting
{
if (_queue.TryDequeue(out item))
{
Interlocked.Decrement(ref _counter);
result = true;
}
}
return result;
}
public bool TryEnqueue(T item)
{
if (_queueLimit == NON_BOUNDED)
{
_queue.Enqueue(item);
return true;
}
var result = true;
try
{ }
finally
{
if (Interlocked.Increment(ref _counter) <= _queueLimit)
{
_queue.Enqueue(item);
}
else
{
Interlocked.Decrement(ref _counter);
result = false;
}
}
return result;
}
}
}
|
Send proper 401 for access denied | using System.Web;
using System.Web.UI;
namespace Unicorn.ControlPanel
{
public class AccessDenied : IControlPanelControl
{
public void Render(HtmlTextWriter writer)
{
writer.Write("<h2>Access Denied</h2>");
writer.Write("<p>You need to <a href=\"/sitecore/admin/login.aspx?ReturnUrl={0}\">sign in to Sitecore as an administrator</a> to use the Unicorn control panel.</p>", HttpUtility.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery));
}
}
}
| using System.Web;
using System.Web.UI;
namespace Unicorn.ControlPanel
{
public class AccessDenied : IControlPanelControl
{
public void Render(HtmlTextWriter writer)
{
writer.Write("<h2>Access Denied</h2>");
writer.Write("<p>You need to <a href=\"/sitecore/admin/login.aspx?ReturnUrl={0}\">sign in to Sitecore as an administrator</a> to use the Unicorn control panel.</p>", HttpUtility.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery));
HttpContext.Current.Response.TrySkipIisCustomErrors = true;
HttpContext.Current.Response.StatusCode = 401;
}
}
}
|
Remove this last piece of hardcodedness | using System;
namespace KnckoutBindingGenerater
{
public class KnockoutProxy
{
private readonly string m_ViewModelName;
private readonly string m_PrimitiveObservables;
private readonly string m_MethodProxies;
private readonly string m_CollectionObservables;
const string c_ViewModelTemplate = @"
var {0}ProxyObject = function() {{
{1}
{2}
{3}
}}
window.{4} = new {0}ProxyObject();
ko.applyBindings({4});
";
public KnockoutProxy(string viewModelName, string primitiveObservables, string methodProxies, string collectionObservables)
{
m_ViewModelName = viewModelName;
m_PrimitiveObservables = primitiveObservables;
m_MethodProxies = methodProxies;
m_CollectionObservables = collectionObservables;
}
public string KnockoutViewModel
{
get
{
return String.Format(c_ViewModelTemplate,
m_ViewModelName,
m_PrimitiveObservables,
m_MethodProxies,
m_CollectionObservables,
ViewModelInstanceName);
}
}
public string ViewModelInstanceName
{
get { return "kevin"; }
}
}
} | using System;
namespace KnckoutBindingGenerater
{
public class KnockoutProxy
{
private readonly string m_ViewModelName;
private readonly string m_PrimitiveObservables;
private readonly string m_MethodProxies;
private readonly string m_CollectionObservables;
const string c_ViewModelTemplate = @"
var {0}ProxyObject = function() {{
{1}
{2}
{3}
}}
window.{4} = new {0}ProxyObject();
ko.applyBindings({4});
";
public KnockoutProxy(string viewModelName, string primitiveObservables, string methodProxies, string collectionObservables)
{
m_ViewModelName = viewModelName;
m_PrimitiveObservables = primitiveObservables;
m_MethodProxies = methodProxies;
m_CollectionObservables = collectionObservables;
}
public string KnockoutViewModel
{
get
{
return String.Format(c_ViewModelTemplate,
m_ViewModelName,
m_PrimitiveObservables,
m_MethodProxies,
m_CollectionObservables,
ViewModelInstanceName);
}
}
public string ViewModelInstanceName
{
get { return String.Format("{0}ProxyObjectInstance", m_ViewModelName); }
}
}
} |
Access operator for array is now "item" | using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;
namespace Reni.FeatureTest.Reference
{
[TestFixture]
[ArrayElementType]
[TargetSet(@"
text: 'abcdefghijklmnopqrstuvwxyz';
pointer: ((text type >>)*1) array_reference instance (text);
(pointer >> 7) dump_print;
(pointer >> 0) dump_print;
(pointer >> 11) dump_print;
(pointer >> 11) dump_print;
(pointer >> 14) dump_print;
", "hallo")]
public sealed class ArrayReferenceByInstance : CompilerTest {}
} | using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;
namespace Reni.FeatureTest.Reference
{
[TestFixture]
[ArrayElementType]
[TargetSet(@"
text: 'abcdefghijklmnopqrstuvwxyz';
pointer: ((text type item)*1) array_reference instance (text);
pointer item(7) dump_print;
pointer item(0) dump_print;
pointer item(11) dump_print;
pointer item(11) dump_print;
pointer item(14) dump_print;
", "hallo")]
public sealed class ArrayReferenceByInstance : CompilerTest {}
} |
Add missing client method to interface | using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.CommitmentsV2.Api.Types.Requests;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
namespace SFA.DAS.CommitmentsV2.Api.Client
{
public interface ICommitmentsApiClient
{
Task<bool> HealthCheck();
Task<AccountLegalEntityResponse> GetLegalEntity(long accountLegalEntityId, CancellationToken cancellationToken = default);
// To be removed latter
Task<string> SecureCheck();
Task<string> SecureEmployerCheck();
Task<string> SecureProviderCheck();
Task<CreateCohortResponse> CreateCohort(CreateCohortRequest request, CancellationToken cancellationToken = default);
Task<UpdateDraftApprenticeshipResponse> UpdateDraftApprenticeship(long cohortId, long apprenticeshipId, UpdateDraftApprenticeshipRequest request, CancellationToken cancellationToken = default);
}
}
| using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.CommitmentsV2.Api.Types.Requests;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
namespace SFA.DAS.CommitmentsV2.Api.Client
{
public interface ICommitmentsApiClient
{
Task<bool> HealthCheck();
Task<AccountLegalEntityResponse> GetLegalEntity(long accountLegalEntityId, CancellationToken cancellationToken = default);
// To be removed latter
Task<string> SecureCheck();
Task<string> SecureEmployerCheck();
Task<string> SecureProviderCheck();
Task<CreateCohortResponse> CreateCohort(CreateCohortRequest request, CancellationToken cancellationToken = default);
Task<UpdateDraftApprenticeshipResponse> UpdateDraftApprenticeship(long cohortId, long apprenticeshipId, UpdateDraftApprenticeshipRequest request, CancellationToken cancellationToken = default);
Task<GetCohortResponse> GetCohort(long cohortId, CancellationToken cancellationToken = default);
}
}
|
Create const for targetdir key | using Subtle.Model;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
namespace Subtle.Registry
{
[RunInstaller(true)]
public partial class Installer : System.Configuration.Install.Installer
{
public Installer()
{
InitializeComponent();
}
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
if (!Context.Parameters.ContainsKey("targetdir"))
{
throw new InstallException("Missing 'targetdir' parameter");
}
var targetDir = Context.Parameters["targetdir"].TrimEnd(Path.DirectorySeparatorChar);
RegistryHelper.SetShellCommands(
FileTypes.VideoTypes,
Path.Combine(targetDir, "Subtle.exe"),
Path.Combine(targetDir, "Subtle.ico"));
}
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
//RegistryHelper.DeleteShellCommands(FileTypes.VideoTypes);
}
}
} | using Subtle.Model;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
namespace Subtle.Registry
{
[RunInstaller(true)]
public partial class Installer : System.Configuration.Install.Installer
{
private const string TargetDirKey = "targetdir";
public Installer()
{
InitializeComponent();
}
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
if (!Context.Parameters.ContainsKey(TargetDirKey))
{
throw new InstallException($"Missing '{TargetDirKey}' parameter");
}
var targetDir = Context.Parameters[TargetDirKey].TrimEnd(Path.DirectorySeparatorChar);
RegistryHelper.SetShellCommands(
FileTypes.VideoTypes,
Path.Combine(targetDir, "Subtle.exe"),
Path.Combine(targetDir, "Subtle.ico"));
}
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
//RegistryHelper.DeleteShellCommands(FileTypes.VideoTypes);
}
}
} |
Allow `HidePopover()` to be called directly on popover containers | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
#nullable enable
namespace osu.Framework.Extensions
{
public static class PopoverExtensions
{
/// <summary>
/// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover);
/// <summary>
/// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null);
private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target)
{
var popoverContainer = origin.FindClosestParent<PopoverContainer>()
?? throw new InvalidOperationException($"Cannot show or hide a popover without a parent {nameof(PopoverContainer)} in the hierarchy");
popoverContainer.SetTarget(target);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
#nullable enable
namespace osu.Framework.Extensions
{
public static class PopoverExtensions
{
/// <summary>
/// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover);
/// <summary>
/// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null);
private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target)
{
var popoverContainer = origin as PopoverContainer
?? origin.FindClosestParent<PopoverContainer>()
?? throw new InvalidOperationException($"Cannot show or hide a popover without a parent {nameof(PopoverContainer)} in the hierarchy");
popoverContainer.SetTarget(target);
}
}
}
|
Add NextLine to execution context | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Roton.Emulation
{
internal class ExecuteCodeContext : ICodeSeekable
{
private ICodeSeekable _instructionSource;
public ExecuteCodeContext(int index, ICodeSeekable instructionSource, string name)
{
_instructionSource = instructionSource;
this.Index = index;
this.Name = name;
}
public Actor Actor
{
get;
set;
}
public int CommandsExecuted
{
get;
set;
}
public bool Died
{
get;
set;
}
public bool Finished
{
get;
set;
}
public int Index
{
get;
set;
}
public int Instruction
{
get { return _instructionSource.Instruction; }
set { _instructionSource.Instruction = value; }
}
public string Message
{
get;
set;
}
public bool Moved
{
get;
set;
}
public string Name
{
get;
set;
}
public int PreviousInstruction
{
get;
set;
}
public bool Repeat
{
get;
set;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Roton.Emulation
{
internal class ExecuteCodeContext : ICodeSeekable
{
private ICodeSeekable _instructionSource;
public ExecuteCodeContext(int index, ICodeSeekable instructionSource, string name)
{
_instructionSource = instructionSource;
this.Index = index;
this.Name = name;
}
public Actor Actor
{
get;
set;
}
public int CommandsExecuted
{
get;
set;
}
public bool Died
{
get;
set;
}
public bool Finished
{
get;
set;
}
public int Index
{
get;
set;
}
public int Instruction
{
get { return _instructionSource.Instruction; }
set { _instructionSource.Instruction = value; }
}
public string Message
{
get;
set;
}
public bool Moved
{
get;
set;
}
public string Name
{
get;
set;
}
public bool NextLine
{
get;
set;
}
public int PreviousInstruction
{
get;
set;
}
public bool Repeat
{
get;
set;
}
}
}
|
Fix victory delegate clearing in stage | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YuukaWaterController : MonoBehaviour {
public int requiredCompletion = 3;
int completionCounter = 0;
public delegate void VictoryAction();
public static event VictoryAction OnVictory;
public void Notify() {
completionCounter++;
if (completionCounter >= requiredCompletion) {
MicrogameController.instance.setVictory(true, true);
OnVictory();
}
}
private void OnDestroy() {
OnVictory = null;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YuukaWaterController : MonoBehaviour {
public int requiredCompletion = 3;
int completionCounter = 0;
public delegate void VictoryAction();
public static event VictoryAction OnVictory;
private void Awake()
{
OnVictory = null;
}
public void Notify() {
completionCounter++;
if (completionCounter >= requiredCompletion) {
MicrogameController.instance.setVictory(true, true);
OnVictory();
}
}
}
|
Change sitemap.xml to reference requested host | #r "Newtonsoft.Json"
using System;
using Red_Folder.WebCrawl;
using Red_Folder.WebCrawl.Data;
using Red_Folder.Logging;
using Newtonsoft.Json;
public static void Run(string request, out object outputDocument, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {crawlRequest.Id}");
var azureLogger = new AzureLogger(log);
var crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request);
var crawler = new Crawler(crawlRequest, azureLogger);
crawler.AddUrl("https://www.red-folder.com/sitemap.xml");
var crawlResult = crawler.Crawl();
outputDocument = crawlResult;
}
public class AzureLogger : ILogger
{
private TraceWriter _log;
public AzureLogger(TraceWriter log)
{
_log = log;
}
public void Info(string message)
{
_log.Info(message);
}
}
| #r "Newtonsoft.Json"
using System;
using Red_Folder.WebCrawl;
using Red_Folder.WebCrawl.Data;
using Red_Folder.Logging;
using Newtonsoft.Json;
public static void Run(string request, out object outputDocument, TraceWriter log)
{
var crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request);
log.Info($"C# Queue trigger function processed: {crawlRequest.Id}");
var azureLogger = new AzureLogger(log);
var crawler = new Crawler(crawlRequest, azureLogger);
crawler.AddUrl($"{crawlRequest.Host}/sitemap.xml");
var crawlResult = crawler.Crawl();
outputDocument = crawlResult;
}
public class AzureLogger : ILogger
{
private TraceWriter _log;
public AzureLogger(TraceWriter log)
{
_log = log;
}
public void Info(string message)
{
_log.Info(message);
}
}
|
Fix bug with querying ProductPrices in SampleAPI case study | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SampleProject.Domain.Products;
using SampleProject.Domain.SharedKernel;
namespace SampleProject.Application.Orders.PlaceCustomerOrder
{
public static class ProductPriceProvider
{
public static async Task<List<ProductPriceData>> GetAllProductPrices(IDbConnection connection)
{
var productPrices = await connection.QueryAsync<ProductPriceResponse>("SELECT " +
$"[ProductPrice].ProductId AS [{nameof(ProductPriceResponse.ProductId)}], " +
$"[ProductPrice].Value AS [{nameof(ProductPriceResponse.Value)}], " +
$"[ProductPrice].Currency AS [{nameof(ProductPriceResponse.Currency)}] " +
"FROM orders.v_ProductPrices AS [ProductPrice]");
return productPrices.AsList()
.Select(x => new ProductPriceData(
new ProductId(x.ProductId),
MoneyValue.Of(x.Value, x.Currency)))
.ToList();
}
private sealed class ProductPriceResponse
{
public Guid ProductId { get; set; }
public decimal Value { get; set; }
public string Currency { get; set; }
}
}
} | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SampleProject.Domain.Products;
using SampleProject.Domain.SharedKernel;
namespace SampleProject.Application.Orders.PlaceCustomerOrder
{
public static class ProductPriceProvider
{
public static async Task<List<ProductPriceData>> GetAllProductPrices(IDbConnection connection)
{
var productPrices = await connection.QueryAsync<ProductPriceResponse>("SELECT " +
$"[ProductPrice].ProductId AS [{nameof(ProductPriceResponse.ProductId)}], " +
$"[ProductPrice].Value AS [{nameof(ProductPriceResponse.Value)}], " +
$"[ProductPrice].Currency AS [{nameof(ProductPriceResponse.Currency)}] " +
"FROM orders.ProductPrices AS [ProductPrice]");
return productPrices.AsList()
.Select(x => new ProductPriceData(
new ProductId(x.ProductId),
MoneyValue.Of(x.Value, x.Currency)))
.ToList();
}
private sealed class ProductPriceResponse
{
public Guid ProductId { get; set; }
public decimal Value { get; set; }
public string Currency { get; set; }
}
}
} |
Reduce potential value updates when setting localisablestring | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Configuration;
using osu.Framework.IO.Stores;
namespace osu.Framework.Localisation
{
public partial class LocalisationManager
{
private class LocalisedBindableString : Bindable<string>, ILocalisedBindableString
{
private readonly IBindable<IResourceStore<string>> storage = new Bindable<IResourceStore<string>>();
private LocalisableString text;
public LocalisedBindableString(IBindable<IResourceStore<string>> storage)
{
this.storage.BindTo(storage);
this.storage.BindValueChanged(_ => updateValue(), true);
}
private void updateValue()
{
string newText = text.Text;
if (text.ShouldLocalise && storage.Value != null)
newText = storage.Value.Get(newText);
if (text.Args != null && !string.IsNullOrEmpty(newText))
{
try
{
newText = string.Format(newText, text.Args);
}
catch (FormatException)
{
// Prevent crashes if the formatting fails. The string will be in a non-formatted state.
}
}
Value = newText;
}
LocalisableString ILocalisedBindableString.Original
{
set
{
text = value;
updateValue();
}
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Configuration;
using osu.Framework.IO.Stores;
namespace osu.Framework.Localisation
{
public partial class LocalisationManager
{
private class LocalisedBindableString : Bindable<string>, ILocalisedBindableString
{
private readonly IBindable<IResourceStore<string>> storage = new Bindable<IResourceStore<string>>();
private LocalisableString text;
public LocalisedBindableString(IBindable<IResourceStore<string>> storage)
{
this.storage.BindTo(storage);
this.storage.BindValueChanged(_ => updateValue(), true);
}
private void updateValue()
{
string newText = text.Text;
if (text.ShouldLocalise && storage.Value != null)
newText = storage.Value.Get(newText);
if (text.Args != null && !string.IsNullOrEmpty(newText))
{
try
{
newText = string.Format(newText, text.Args);
}
catch (FormatException)
{
// Prevent crashes if the formatting fails. The string will be in a non-formatted state.
}
}
Value = newText;
}
LocalisableString ILocalisedBindableString.Original
{
set
{
if (text == value)
return;
text = value;
updateValue();
}
}
}
}
}
|
Create server side API for single multiple answer question | using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
/// <summary>
/// Adding single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
}
}
|
Add filter property to trending movies request. | namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
using Base.Get;
using Objects.Basic;
using Objects.Get.Movies.Common;
internal class TraktMoviesTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingMovie>, TraktTrendingMovie>
{
internal TraktMoviesTrendingRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "movies/trending{?extended,page,limit}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
| namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
using Base;
using Base.Get;
using Objects.Basic;
using Objects.Get.Movies.Common;
internal class TraktMoviesTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingMovie>, TraktTrendingMovie>
{
internal TraktMoviesTrendingRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "movies/trending{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
internal TraktMovieFilter Filter { get; set; }
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.