Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add correlationId to fix startup of the EAS web application. Copied from specific branch
using System; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Dapper; using SFA.DAS.EAS.Domain.Configuration; using SFA.DAS.EAS.Domain.Data.Repositories; using SFA.DAS.EAS.Domain.Models.UserProfile; using SFA.DAS.Sql.Client; using SFA.DAS.NLog.Logger; namespace SFA.DAS.EAS.Infrastructure.Data { public class UserRepository : BaseRepository, IUserRepository { private readonly Lazy<EmployerAccountsDbContext> _db; public UserRepository(EmployerApprenticeshipsServiceConfiguration configuration, ILog logger, Lazy<EmployerAccountsDbContext> db) : base(configuration.DatabaseConnectionString, logger) { _db = db; } public Task Upsert(User user) { return WithConnection(c => { var parameters = new DynamicParameters(); parameters.Add("@email", user.Email, DbType.String); parameters.Add("@userRef", new Guid(user.UserRef), DbType.Guid); parameters.Add("@firstName", user.FirstName, DbType.String); parameters.Add("@lastName", user.LastName, DbType.String); return c.ExecuteAsync( sql: "[employer_account].[UpsertUser] @userRef, @email, @firstName, @lastName", param: parameters, commandType: CommandType.Text); }); } } }
using System; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Dapper; using SFA.DAS.EAS.Domain.Configuration; using SFA.DAS.EAS.Domain.Data.Repositories; using SFA.DAS.EAS.Domain.Models.UserProfile; using SFA.DAS.Sql.Client; using SFA.DAS.NLog.Logger; namespace SFA.DAS.EAS.Infrastructure.Data { public class UserRepository : BaseRepository, IUserRepository { private readonly Lazy<EmployerAccountsDbContext> _db; public UserRepository(EmployerApprenticeshipsServiceConfiguration configuration, ILog logger, Lazy<EmployerAccountsDbContext> db) : base(configuration.DatabaseConnectionString, logger) { _db = db; } public Task Upsert(User user) { return WithConnection(c => { var parameters = new DynamicParameters(); parameters.Add("@email", user.Email, DbType.String); parameters.Add("@userRef", new Guid(user.UserRef), DbType.Guid); parameters.Add("@firstName", user.FirstName, DbType.String); parameters.Add("@lastName", user.LastName, DbType.String); parameters.Add("@correlationId", null, DbType.String); return c.ExecuteAsync( sql: "[employer_account].[UpsertUser] @userRef, @email, @firstName, @lastName, @correlationId", param: parameters, commandType: CommandType.Text); }); } } }
Change namespace for helper extension method to Amazon.Lambda.TestUtilities to make it more discover able when writing tests.
using Amazon.Lambda.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; namespace Amazon.Lambda.AspNetCoreServer { /// <summary> /// Helper extensions for APIGatewayProxyFunction /// </summary> public static class APIGatewayProxyFunctionExtensions { /// <summary> /// An overload of FunctionHandlerAsync to allow working with the typed API Gateway event classes. Implemented as an extension /// method to avoid confusion of using it as the function handler for the Lambda function. /// </summary> /// <param name="function"></param> /// <param name="request"></param> /// <param name="lambdaContext"></param> /// <returns></returns> public static async Task<APIGatewayProxyResponse> FunctionHandlerAsync(this APIGatewayProxyFunction function, APIGatewayProxyRequest request, ILambdaContext lambdaContext) { ILambdaSerializer serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer(); var requestStream = new MemoryStream(); serializer.Serialize<APIGatewayProxyRequest>(request, requestStream); requestStream.Position = 0; var responseStream = await function.FunctionHandlerAsync(requestStream, lambdaContext); var response = serializer.Deserialize<APIGatewayProxyResponse>(responseStream); return response; } } }
using Amazon.Lambda.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.AspNetCoreServer; namespace Amazon.Lambda.TestUtilities { /// <summary> /// Extension methods for APIGatewayProxyFunction to make it easier to write tests /// </summary> public static class APIGatewayProxyFunctionExtensions { /// <summary> /// An overload of FunctionHandlerAsync to allow working with the typed API Gateway event classes. Implemented as an extension /// method to avoid confusion of using it as the function handler for the Lambda function. /// </summary> /// <param name="function"></param> /// <param name="request"></param> /// <param name="lambdaContext"></param> /// <returns></returns> public static async Task<APIGatewayProxyResponse> FunctionHandlerAsync(this APIGatewayProxyFunction function, APIGatewayProxyRequest request, ILambdaContext lambdaContext) { ILambdaSerializer serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer(); var requestStream = new MemoryStream(); serializer.Serialize<APIGatewayProxyRequest>(request, requestStream); requestStream.Position = 0; var responseStream = await function.FunctionHandlerAsync(requestStream, lambdaContext); var response = serializer.Deserialize<APIGatewayProxyResponse>(responseStream); return response; } } }
Expand and add comment for ShouldIgnore.
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.NamingStyles { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpNamingStyleDiagnosticAnalyzer : NamingStyleDiagnosticAnalyzerBase<SyntaxKind> { protected override ImmutableArray<SyntaxKind> SupportedSyntaxKinds { get; } = ImmutableArray.Create( SyntaxKind.VariableDeclarator, SyntaxKind.ForEachStatement, SyntaxKind.CatchDeclaration, SyntaxKind.SingleVariableDesignation, SyntaxKind.LocalFunctionStatement, SyntaxKind.Parameter, SyntaxKind.TypeParameter); // Parameters of positional record declarations should be ignored because they also // considered properties, and that naming style makes more sense protected override bool ShouldIgnore(ISymbol symbol) => (symbol.IsKind(SymbolKind.Parameter) && IsParameterOfRecordDeclaration(symbol.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax())) || !symbol.CanBeReferencedByName; private static bool IsParameterOfRecordDeclaration(SyntaxNode? node) => node is ParameterSyntax { Parent: ParameterListSyntax { Parent: RecordDeclarationSyntax } }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.NamingStyles { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpNamingStyleDiagnosticAnalyzer : NamingStyleDiagnosticAnalyzerBase<SyntaxKind> { protected override ImmutableArray<SyntaxKind> SupportedSyntaxKinds { get; } = ImmutableArray.Create( SyntaxKind.VariableDeclarator, SyntaxKind.ForEachStatement, SyntaxKind.CatchDeclaration, SyntaxKind.SingleVariableDesignation, SyntaxKind.LocalFunctionStatement, SyntaxKind.Parameter, SyntaxKind.TypeParameter); protected override bool ShouldIgnore(ISymbol symbol) { if (symbol.IsKind(SymbolKind.Parameter) && symbol.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is ParameterSyntax { Parent: ParameterListSyntax { Parent: RecordDeclarationSyntax } }) { // Parameters of positional record declarations should be ignored because they also // considered properties, and that naming style makes more sense return true; } if (!symbol.CanBeReferencedByName) { // Explicit interface implementation falls into here, as they don't own their names // Two symbols are involved here, and symbol.ExplicitInterfaceImplementations only applies for one return true; } return false; } } }
Create method for overload operator + and -
using System; namespace FractionCalculator.Class { public struct Fraction { private long numerator; private long denominator; public Fraction(long numerator, long denominator) : this() { this.Numerator = numerator; this.Denominator = denominator; } public long Denominator { get { return this.denominator; } set { if (value <= 0) throw new DivideByZeroException("Denominator cannot be zero or negative"); this.denominator = value; } } public long Numerator { get { return this.numerator; } set { if (value <= 0) throw new ArgumentException("numerator", "Numerator cannot be zero or negative!"); this.numerator = value; } } public override string ToString() { return string.Format(); } } }
using System; namespace FractionCalculator.Class { public struct Fraction { private long numerator; private long denominator; public Fraction(long numerator, long denominator) : this() { this.Numerator = numerator; this.Denominator = denominator; } public long Denominator { get { return this.denominator; } set { if (value <= 0) throw new DivideByZeroException("Denominator cannot be zero or negative"); this.denominator = value; } } public long Numerator { get { return this.numerator; } set { if (value <= 0) throw new ArgumentException("numerator", "Numerator cannot be zero or negative!"); this.numerator = value; } } public static Fraction operator +(Fraction fraction1, Fraction fraction2) { return new Fraction(fraction1.Numerator + fraction2.Numerator, fraction1.Denominator + fraction2.Denominator); } public static Fraction operator -(Fraction fraction1, Fraction fraction2) { return new Fraction(fraction1.Numerator - fraction2.Numerator, fraction1.Denominator - fraction2.Denominator); } //public override string ToString() //{ // return string.Format(); //} } }
Fix email sender to 'vote on'
using Microsoft.AspNet.Identity; using SendGrid; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading.Tasks; using System.Web; namespace VotingApplication.Web.Api.Services { public class SendMailEmailSender : IMailSender { private NetworkCredential credentials; private string hostEmail; public SendMailEmailSender(NetworkCredential credentials, string hostEmail) { this.credentials = credentials; this.hostEmail = hostEmail; } public Task SendMail(string to, string subject, string message) { SendGridMessage mail = new SendGridMessage(); mail.From = new MailAddress(this.hostEmail, "Voting App"); mail.AddTo(to); mail.Subject = subject; mail.Html = message; var transportWeb = new SendGrid.Web(this.credentials); return transportWeb.DeliverAsync(mail); } } }
using SendGrid; using System.Net; using System.Net.Mail; using System.Threading.Tasks; namespace VotingApplication.Web.Api.Services { public class SendMailEmailSender : IMailSender { private NetworkCredential credentials; private string hostEmail; public SendMailEmailSender(NetworkCredential credentials, string hostEmail) { this.credentials = credentials; this.hostEmail = hostEmail; } public Task SendMail(string to, string subject, string message) { SendGridMessage mail = new SendGridMessage(); mail.From = new MailAddress(this.hostEmail, "Vote On"); mail.AddTo(to); mail.Subject = subject; mail.Html = message; var transportWeb = new SendGrid.Web(this.credentials); return transportWeb.DeliverAsync(mail); } } }
Boost priority of NavigateTo when running in OOP server.
// 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.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.NavigateTo; namespace Microsoft.CodeAnalysis.Remote { internal partial class CodeAnalysisService : IRemoteNavigateToSearchService { public async Task<SerializableNavigateToSearchResult[]> SearchDocumentAsync( DocumentId documentId, string searchPattern) { var solution = await GetSolutionAsync().ConfigureAwait(false); var project = solution.GetDocument(documentId); var result = await AbstractNavigateToSearchService.SearchDocumentInCurrentProcessAsync( project, searchPattern, CancellationToken).ConfigureAwait(false); return Convert(result); } public async Task<SerializableNavigateToSearchResult[]> SearchProjectAsync( ProjectId projectId, string searchPattern) { var solution = await GetSolutionAsync().ConfigureAwait(false); var project = solution.GetProject(projectId); var result = await AbstractNavigateToSearchService.SearchProjectInCurrentProcessAsync( project, searchPattern, CancellationToken).ConfigureAwait(false); return Convert(result); } private SerializableNavigateToSearchResult[] Convert( ImmutableArray<INavigateToSearchResult> result) { return result.Select(SerializableNavigateToSearchResult.Dehydrate).ToArray(); } } }
// 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.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.NavigateTo; namespace Microsoft.CodeAnalysis.Remote { internal partial class CodeAnalysisService : IRemoteNavigateToSearchService { public async Task<SerializableNavigateToSearchResult[]> SearchDocumentAsync( DocumentId documentId, string searchPattern) { using (UserOperationBooster.Boost()) { var solution = await GetSolutionAsync().ConfigureAwait(false); var project = solution.GetDocument(documentId); var result = await AbstractNavigateToSearchService.SearchDocumentInCurrentProcessAsync( project, searchPattern, CancellationToken).ConfigureAwait(false); return Convert(result); } } public async Task<SerializableNavigateToSearchResult[]> SearchProjectAsync( ProjectId projectId, string searchPattern) { using (UserOperationBooster.Boost()) { var solution = await GetSolutionAsync().ConfigureAwait(false); var project = solution.GetProject(projectId); var result = await AbstractNavigateToSearchService.SearchProjectInCurrentProcessAsync( project, searchPattern, CancellationToken).ConfigureAwait(false); return Convert(result); } } private SerializableNavigateToSearchResult[] Convert( ImmutableArray<INavigateToSearchResult> result) { return result.Select(SerializableNavigateToSearchResult.Dehydrate).ToArray(); } } }
Update tag button container markup
@model IEnumerable<Tag> @{ ViewBag.Title = "Tag Index"; } <h2>Tag Index</h2> @if (User.Identity.IsAuthenticated) { <p> <a asp-action="Create">Create new Tag</a> </p> } <h3>@Model.Count() tags</h3> <ul class="tag-buttons"> @Html.Partial("_TagButtons", Model) </ul>
@model IEnumerable<Tag> @{ ViewBag.Title = "Tag Index"; } <h2>Tag Index</h2> @if (User.Identity.IsAuthenticated) { <p> <a asp-action="Create">Create new Tag</a> </p> } <h3>@Model.Count() tags</h3> <div> @Html.Partial("_TagButtons", Model) </div>
Fix bug in properties and event detection
using System; namespace Terrajobst.Pns.Scanner { public struct PnsResult { public static readonly PnsResult DoesNotThrow = new PnsResult(-1); private PnsResult(int level) { Level = level; } public static PnsResult ThrowsAt(int level) { return new PnsResult(level); } public PnsResult Combine(PnsResult other) { if (!Throws) return other; return ThrowsAt(Math.Min(Level, other.Level)); } public bool Throws => Level >= 0; public int Level { get; } public override string ToString() { return Level.ToString(); } } }
using System; namespace Terrajobst.Pns.Scanner { public struct PnsResult { public static readonly PnsResult DoesNotThrow = new PnsResult(-1); private PnsResult(int level) { Level = level; } public static PnsResult ThrowsAt(int level) { return new PnsResult(level); } public PnsResult Combine(PnsResult other) { if (!Throws) return other; if (!other.Throws) return this; return ThrowsAt(Math.Min(Level, other.Level)); } public bool Throws => Level >= 0; public int Level { get; } public override string ToString() { return Level.ToString(); } } }
Abort test if test container exists.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Lokad.Cqrs.Properties; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.StorageClient; using NUnit.Framework; namespace Lokad.Cqrs.Feature.TapeStorage { [TestFixture] public class BlobTapeStorageTests : TapeStorageTests { const string ContainerName = "blob-tape-test"; CloudBlobClient _cloudBlobClient; ISingleThreadTapeWriterFactory _writerFactory; ITapeReaderFactory _readerFactory; protected override void SetUp() { CloudStorageAccount.SetConfigurationSettingPublisher( (configName, configSetter) => configSetter((string) Settings.Default[configName])); var cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString"); _cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient(); _writerFactory = new BlobTapeWriterFactory(_cloudBlobClient, ContainerName); _writerFactory.Init(); _readerFactory = new BlobTapeReaderFactory(_cloudBlobClient, ContainerName); } protected override void TearDown() { _cloudBlobClient.GetContainerReference(ContainerName).Delete(); } protected override TestConfiguration GetConfiguration() { return new TestConfiguration { Name = "test", WriterFactory = _writerFactory, ReaderFactory = _readerFactory }; } } }
using System; using Lokad.Cqrs.Properties; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.StorageClient; using NUnit.Framework; namespace Lokad.Cqrs.Feature.TapeStorage { [TestFixture] public class BlobTapeStorageTests : TapeStorageTests { const string ContainerName = "blob-tape-test"; CloudBlobClient _cloudBlobClient; ISingleThreadTapeWriterFactory _writerFactory; ITapeReaderFactory _readerFactory; protected override void SetUp() { CloudStorageAccount.SetConfigurationSettingPublisher( (configName, configSetter) => configSetter((string) Settings.Default[configName])); var cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString"); _cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient(); try { _cloudBlobClient.GetContainerReference(ContainerName).FetchAttributes(); throw new InvalidOperationException("Container '" + ContainerName + "' already exists!"); } catch (StorageClientException e) { if (e.ErrorCode != StorageErrorCode.ResourceNotFound) throw new InvalidOperationException("Container '" + ContainerName + "' already exists!"); } _writerFactory = new BlobTapeWriterFactory(_cloudBlobClient, ContainerName); _writerFactory.Init(); _readerFactory = new BlobTapeReaderFactory(_cloudBlobClient, ContainerName); } protected override void TearDown() { _cloudBlobClient.GetContainerReference(ContainerName).Delete(); } protected override TestConfiguration GetConfiguration() { return new TestConfiguration { Name = "test", WriterFactory = _writerFactory, ReaderFactory = _readerFactory }; } } }
Fix startup problem on windows
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Steeltoe.Extensions.Configuration.CloudFoundry; namespace CloudFoundry { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() // Lab01 - Lab04 Start .AddCloudFoundry() // Lab01 - Lab04 End .Build(); } }
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Steeltoe.Extensions.Configuration.CloudFoundry; namespace CloudFoundry { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) { // Lab01 - Lab04 Start var configuration = new ConfigurationBuilder().AddCommandLine(args).Build(); // Lab01 - Lab04 End return WebHost.CreateDefaultBuilder(args) // Lab01 - Lab04 Start .UseConfiguration(configuration) // Lab01 - Lab04 End .UseStartup<Startup>() // Lab01 - Lab04 Start .AddCloudFoundry() // Lab01 - Lab04 End .Build(); } } }
Fix Roslyn compiler issues when the same file is being used for multiple target platforms (and might result in a class without methods)
using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpDox.Build.Roslyn.MethodVisitors; namespace SharpDox.Build.Roslyn.Parser.ProjectParser { internal class MethodCallParser : BaseParser { internal MethodCallParser(ParserOptions parserOptions) : base(parserOptions) { } internal void ParseMethodCalls() { var namespaces = ParserOptions.SDRepository.GetAllNamespaces(); foreach (var sdNamespace in namespaces) { foreach (var sdType in sdNamespace.Types) { foreach (var sdMethod in sdType.Methods) { HandleOnItemParseStart(sdMethod.Name); var fileId = ParserOptions.CodeSolution.GetDocumentIdsWithFilePath(sdMethod.Region.FilePath).Single(); var file = ParserOptions.CodeSolution.GetDocument(fileId); var syntaxTree = file.GetSyntaxTreeAsync().Result; if (file.Project.Language == "C#") { var methodVisitor = new CSharpMethodVisitor(ParserOptions.SDRepository, sdMethod, sdType, file); var methodSyntaxNode = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>() .Single(m => m.Span.Start == sdMethod.Region.Start && m.Span.End == sdMethod.Region.End); methodVisitor.Visit(methodSyntaxNode); } else if (file.Project.Language == "VBNET") { } } } } } } }
using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpDox.Build.Roslyn.MethodVisitors; namespace SharpDox.Build.Roslyn.Parser.ProjectParser { internal class MethodCallParser : BaseParser { internal MethodCallParser(ParserOptions parserOptions) : base(parserOptions) { } internal void ParseMethodCalls() { var namespaces = ParserOptions.SDRepository.GetAllNamespaces(); foreach (var sdNamespace in namespaces) { foreach (var sdType in sdNamespace.Types) { foreach (var sdMethod in sdType.Methods) { HandleOnItemParseStart(sdMethod.Name); var fileId = ParserOptions.CodeSolution.GetDocumentIdsWithFilePath(sdMethod.Region.FilePath).FirstOrDefault(); var file = ParserOptions.CodeSolution.GetDocument(fileId); var syntaxTree = file.GetSyntaxTreeAsync().Result; if (file.Project.Language == "C#") { var methodVisitor = new CSharpMethodVisitor(ParserOptions.SDRepository, sdMethod, sdType, file); var methodSyntaxNode = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>() .FirstOrDefault(m => m.Span.Start == sdMethod.Region.Start && m.Span.End == sdMethod.Region.End); if (methodSyntaxNode != null) { methodVisitor.Visit(methodSyntaxNode); } } else if (file.Project.Language == "VBNET") { } } } } } } }
Change exception to proper class
using OrienteeringToolWPF.Model; using OrienteeringToolWPF.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrienteeringToolWPF.DAO { public static class CompetitorHelper { public static List<Competitor> CompetitorsJoinedWhereRelayId(long RelayId) { var db = DatabaseUtils.GetDatabase(); dynamic resultsAlias, punchAlias; var CompetitorList = (List<Competitor>)db.Competitors.FindAllByRelayId(RelayId) .LeftJoin(db.Results, out resultsAlias) .On(db.Results.Chip == db.Competitors.Chip) .LeftJoin(db.Punches, out punchAlias) .On(db.Punches.Chip == db.Competitors.Chip) .With(resultsAlias) .With(punchAlias); foreach (var competitor in CompetitorList) { var punches = (List<Punch>)competitor.Punches; try { punches?.Sort(); Punch.CalculateDeltaStart(ref punches, competitor.Result.StartTime); Punch.CalculateDeltaPrevious(ref punches); } catch (ArgumentNullException) { } competitor.Punches = punches; } return CompetitorList; } } }
using OrienteeringToolWPF.Model; using OrienteeringToolWPF.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrienteeringToolWPF.DAO { public static class CompetitorHelper { public static List<Competitor> CompetitorsJoinedWhereRelayId(long RelayId) { var db = DatabaseUtils.GetDatabase(); dynamic resultsAlias, punchAlias; var CompetitorList = (List<Competitor>)db.Competitors.FindAllByRelayId(RelayId) .LeftJoin(db.Results, out resultsAlias) .On(db.Results.Chip == db.Competitors.Chip) .LeftJoin(db.Punches, out punchAlias) .On(db.Punches.Chip == db.Competitors.Chip) .With(resultsAlias) .With(punchAlias); foreach (var competitor in CompetitorList) { var punches = (List<Punch>)competitor.Punches; try { punches?.Sort(); Punch.CalculateDeltaStart(ref punches, competitor.Result.StartTime); Punch.CalculateDeltaPrevious(ref punches); } catch (NullReferenceException) { } competitor.Punches = punches; } return CompetitorList; } } }
Remove fat arrow getter because of appveyor .net version support
using LiveScoreUpdateSystem.Data.Models.Contracts; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Security.Claims; using System.Threading.Tasks; namespace LiveScoreUpdateSystem.Data.Models { public class User : IdentityUser, IDeletable, IAuditable, IDataModel { public DateTime? CreatedOn { get; set; } public DateTime? ModifiedOn { get; set; } public bool IsDeleted { get; set; } public DateTime? DeletedOn { get; set; } Guid IDataModel.Id => throw new NotImplementedException(); public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } }
using LiveScoreUpdateSystem.Data.Models.Contracts; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Security.Claims; using System.Threading.Tasks; namespace LiveScoreUpdateSystem.Data.Models { public class User : IdentityUser, IDeletable, IAuditable, IDataModel { public DateTime? CreatedOn { get; set; } public DateTime? ModifiedOn { get; set; } public bool IsDeleted { get; set; } public DateTime? DeletedOn { get; set; } Guid IDataModel.Id { get; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } }
Fix for Unknown status display
@model Vehicle @switch(Model.Status) { case Vehicle.VehicleStatus.FMC: <span class="label label-success">FMC</span> return; case Vehicle.VehicleStatus.NMC: <span class="label label-danger">NMC</span> return; default: <span class="label label-warning">@Model</span> return; }
@model Vehicle @switch(Model.Status) { case Vehicle.VehicleStatus.FMC: <span class="label label-success">FMC</span> return; case Vehicle.VehicleStatus.NMC: <span class="label label-danger">NMC</span> return; case Vehicle.VehicleStatus.Unknown: <span class="label label-warning">Unknown</span> return; }
Fix bug: incorrectly determines the center of the top
using System.Windows.Controls.Primitives; namespace SharpGraphEditor.Controls.GraphElements { /// <summary> /// Логика взаимодействия для VertexControl.xaml /// </summary> public partial class VertexControl : Thumb { public VertexControl() { InitializeComponent(); } } }
using System.Windows.Controls.Primitives; namespace SharpGraphEditor.Controls.GraphElements { /// <summary> /// Логика взаимодействия для VertexControl.xaml /// </summary> public partial class VertexControl : Thumb { public VertexControl() { InitializeComponent(); SizeChanged += (_, __) => { var centerX = ActualWidth / 2; var centerY = ActualHeight / 2; Margin = new System.Windows.Thickness(-centerX, -centerY, centerX, centerY); }; } } }
Set endpoint routing in responsive sample web app
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Responsive { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add responsive services. services.AddDetection(); // Add framework services. services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseDetection(); app.UseRouting(); app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute()); } } }
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Responsive { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add responsive services. services.AddDetection(); // Add framework services. services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseDetection(); app.UseRouting(); app.UseEndpoints( endpoints => { endpoints.MapControllerRoute( "default", "{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute( "areas", "{area:exists}/{controller=Home}/{action=Index}/{id?}" ); }); } } }
Rename setup blob => setup files
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; namespace CodeComb.AspNet.Upload.Models { public static class ModelBuilderExtensions { public static ModelBuilder SetupBlob(this ModelBuilder self) { return self.Entity<File>(e => { e.HasIndex(x => x.Time); e.HasIndex(x => x.FileName); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; namespace CodeComb.AspNet.Upload.Models { public static class ModelBuilderExtensions { public static ModelBuilder SetupFiles(this ModelBuilder self) { return self.Entity<File>(e => { e.HasIndex(x => x.Time); e.HasIndex(x => x.FileName); }); } } }
Change classe accessibility to internal
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Xamarin.Forms.GoogleMaps { public static class GeoConstants { public const double EarthRadiusKm = 6371; public const double EarthCircumferenceKm = EarthRadiusKm * 2 * Math.PI; public const double MetersPerMile = 1609.344; public const double MetersPerKilometer = 1000.0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Xamarin.Forms.GoogleMaps { internal static class GeoConstants { public const double EarthRadiusKm = 6371; public const double EarthCircumferenceKm = EarthRadiusKm * 2 * Math.PI; public const double MetersPerMile = 1609.344; public const double MetersPerKilometer = 1000.0; } }
Update NotificationSettingsVM for LiveTiles settings
using CodeHub.Services; using GalaSoft.MvvmLight; namespace CodeHub.ViewModels.Settings { public class NofiticationSettingsViewModel : ObservableObject { private bool _isToastEnabled = SettingsService.Get<bool>(SettingsKeys.IsToastEnabled); public bool IsToastEnabled { get => _isToastEnabled; set { if (_isToastEnabled != value) { _isToastEnabled = value; SettingsService.Save(SettingsKeys.IsToastEnabled, value); RaisePropertyChanged(); } } } public NofiticationSettingsViewModel() { } } }
using CodeHub.Services; using GalaSoft.MvvmLight; namespace CodeHub.ViewModels.Settings { public class NofiticationSettingsViewModel : ObservableObject { private bool _isToastEnabled = SettingsService.Get<bool>(SettingsKeys.IsToastEnabled); private bool _isLiveTilesEnabled = SettingsService.Get<bool>(SettingsKeys.IsLiveTilesEnabled); private bool _isLiveTilesBadgeEnabled = SettingsService.Get<bool>(SettingsKeys.IsLiveTilesBadgeEnabled); private bool _isLiveTileUpdateAllBadgesEnabled = SettingsService.Get<bool>(SettingsKeys.IsLiveTileUpdateAllBadgesEnabled); public bool IsToastEnabled { get => _isToastEnabled; set { if (_isToastEnabled != value) { _isToastEnabled = value; SettingsService.Save(SettingsKeys.IsToastEnabled, value); RaisePropertyChanged(() => IsToastEnabled); } } } public bool IsLiveTilesEnabled { get => _isLiveTilesEnabled; set { if (_isLiveTilesEnabled != value) { _isLiveTilesEnabled = value; SettingsService.Save(SettingsKeys.IsLiveTilesEnabled, value); RaisePropertyChanged(() => IsLiveTilesEnabled); } if (!value && IsLiveTilesBadgeEnabled) { IsLiveTilesBadgeEnabled = false; } } } public bool IsLiveTilesBadgeEnabled { get => _isLiveTilesBadgeEnabled; set { if (_isLiveTilesBadgeEnabled != value) { _isLiveTilesBadgeEnabled = value; SettingsService.Save(SettingsKeys.IsLiveTilesBadgeEnabled, value); RaisePropertyChanged(() => IsLiveTilesBadgeEnabled); } if (!value && IsAllBadgesUpdateEnabled) { IsAllBadgesUpdateEnabled = false; } } } public bool IsAllBadgesUpdateEnabled { get => _isLiveTilesEnabled; set { if (_isLiveTileUpdateAllBadgesEnabled != value) { _isLiveTileUpdateAllBadgesEnabled = value; SettingsService.Save(SettingsKeys.IsLiveTileUpdateAllBadgesEnabled, value); RaisePropertyChanged(() => IsAllBadgesUpdateEnabled); } } } public NofiticationSettingsViewModel() { } } }
Update settings with username and conference ids
// Helpers/Settings.cs using Refractored.Xam.Settings; using Refractored.Xam.Settings.Abstractions; namespace CodeCamp.Helpers { /// <summary> /// This is the Settings static class that can be used in your Core solution or in any /// of your client applications. All settings are laid out the same exact way with getters /// and setters. /// </summary> public static class Settings { private static ISettings AppSettings { get { return CrossSettings.Current; } } #region Setting Constants private const string SettingsKey = "settings_key"; private static readonly string SettingsDefault = string.Empty; #endregion public static string GeneralSettings { get { return AppSettings.GetValueOrDefault(SettingsKey, SettingsDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(SettingsKey, value)) AppSettings.Save(); } } } }
// Helpers/Settings.cs using Refractored.Xam.Settings; using Refractored.Xam.Settings.Abstractions; namespace CodeCamp.Helpers { /// <summary> /// This is the Settings static class that can be used in your Core solution or in any /// of your client applications. All settings are laid out the same exact way with getters /// and setters. /// </summary> public static class Settings { private static ISettings AppSettings { get { return CrossSettings.Current; } } #region Setting Constants private const string UsernameKey = "username_key"; private static readonly string UsernameDefault = string.Empty; private const string MasterConferenceKey = "masterconference_key"; private static readonly int MasterConferenceDefault = -1; private const string ConferenceKey = "conference_key"; private static readonly int ConferenceDefault = -1; #endregion public static string UsernameSettings { get { return AppSettings.GetValueOrDefault(UsernameKey, UsernameDefault); } set { if (AppSettings.AddOrUpdateValue(UsernameKey, value)) AppSettings.Save(); } } public static int MasterConference { get { return AppSettings.GetValueOrDefault(MasterConferenceKey, MasterConferenceDefault); } set { if (AppSettings.AddOrUpdateValue(MasterConferenceKey, value)) AppSettings.Save(); } } public static int Conference { get { return AppSettings.GetValueOrDefault(ConferenceKey, ConferenceDefault); } set { if (AppSettings.AddOrUpdateValue(ConferenceKey, value)) AppSettings.Save(); } } } }
Revert "Fixing bad default path."
using System; using System.IO; using System.Collections.Generic; namespace CyLR { internal static class CollectionPaths { public static List<string> GetPaths(Arguments arguments) { var paths = new List<string> { @"C:\Windows\System32\config", @"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup", @"C:\Windows\Prefetch", @"C:\Windows\Tasks", @"C:\Windows\SchedLgU.Txt", @"C:\Windows\System32\winevt\logs", @"C:\Windows\System32\drivers\etc\hosts", @"C:\$MFT" }; if (Platform.IsUnixLike()) { paths = new List<string> { "/root/.bash_history", "/var/logs" }; } if (arguments.CollectionFilePath != ".") { if (File.Exists(arguments.CollectionFilePath)) { paths.Clear(); paths.AddRange(File.ReadAllLines(arguments.CollectionFilePath)); } else { Console.WriteLine("Error: Could not find file: {0}", arguments.CollectionFilePath); Console.WriteLine("Exiting"); throw new ArgumentException(); } } return paths; } } }
using System; using System.IO; using System.Collections.Generic; namespace CyLR { internal static class CollectionPaths { public static List<string> GetPaths(Arguments arguments) { var paths = new List<string> { @"C:\Windows\System32\config", @"C:\Windows\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup", @"C:\Windows\Prefetch", @"C:\Windows\Tasks", @"C:\Windows\SchedLgU.Txt", @"C:\Windows\System32\winevt\logs", @"C:\Windows\System32\drivers\etc\hosts", @"C:\$MFT" }; if (Platform.IsUnixLike()) { paths = new List<string> { "/root/.bash_history", "/var/logs" }; } if (arguments.CollectionFilePath != ".") { if (File.Exists(arguments.CollectionFilePath)) { paths.Clear(); paths.AddRange(File.ReadAllLines(arguments.CollectionFilePath)); } else { Console.WriteLine("Error: Could not find file: {0}", arguments.CollectionFilePath); Console.WriteLine("Exiting"); throw new ArgumentException(); } } return paths; } } }
Improve spacing for status messages
@{ var parsedModel = TempData.GetStatusMessageModel(); } @if (parsedModel != null) { <div class="alert alert-@parsedModel.SeverityCSS @(parsedModel.AllowDismiss? "alert-dismissible":"" )" role="alert"> @if (parsedModel.AllowDismiss) { <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> } @if (!string.IsNullOrEmpty(parsedModel.Message)) { @parsedModel.Message } @if (!string.IsNullOrEmpty(parsedModel.Html)) { @Safe.Raw(parsedModel.Html) } </div> }
@{ var parsedModel = TempData.GetStatusMessageModel(); } @if (parsedModel != null) { <div class="alert alert-@parsedModel.SeverityCSS @(parsedModel.AllowDismiss? "alert-dismissible":"" ) mb-5" role="alert"> @if (parsedModel.AllowDismiss) { <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> } @if (!string.IsNullOrEmpty(parsedModel.Message)) { @parsedModel.Message } @if (!string.IsNullOrEmpty(parsedModel.Html)) { @Safe.Raw(parsedModel.Html) } </div> }
Remove unnecessary nesting of `IconButton` and update design a touch
// 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.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Graphics.UserInterface; using osu.Game.Screens.Edit.Timing; using osuTK; using osuTK.Graphics; namespace osu.Game.Screens.Edit.Compose.Components.Timeline { public class TimelineButton : CompositeDrawable { public Action Action; public readonly BindableBool Enabled = new BindableBool(true); public IconUsage Icon { get => button.Icon; set => button.Icon = value; } private readonly TimelineIconButton button; public TimelineButton() { InternalChild = button = new TimelineIconButton { Action = () => Action?.Invoke() }; button.Enabled.BindTo(Enabled); Width = button.Width; } protected override void Update() { base.Update(); button.Size = new Vector2(button.Width, DrawHeight); } private class TimelineIconButton : IconButton { public TimelineIconButton() { Anchor = Anchor.Centre; Origin = Anchor.Centre; IconColour = OsuColour.Gray(0.35f); IconHoverColour = Color4.White; HoverColour = OsuColour.Gray(0.25f); FlashColour = OsuColour.Gray(0.5f); Add(new RepeatingButtonBehaviour(this)); } protected override HoverSounds CreateHoverSounds(HoverSampleSet sampleSet) => new HoverSounds(sampleSet); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays; using osu.Game.Screens.Edit.Timing; namespace osu.Game.Screens.Edit.Compose.Components.Timeline { public class TimelineButton : IconButton { [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { // These are using colourProvider but don't match the design. // Just something to fit until someone implements the updated design. IconColour = colourProvider.Background1; IconHoverColour = colourProvider.Content2; HoverColour = colourProvider.Background1; FlashColour = colourProvider.Content2; Add(new RepeatingButtonBehaviour(this)); } protected override HoverSounds CreateHoverSounds(HoverSampleSet sampleSet) => new HoverSounds(sampleSet); } }
Fix string injection of NAME from ViewBag to ng.constant
<script type="text/javascript"> angular.module("myapp") .constant("WAIT", @ViewBag.WAIT) .constant("NAME", @ViewBag.NAME) ; </script>
<script type="text/javascript"> angular.module("myapp") .constant("WAIT", @ViewBag.WAIT) .constant("NAME", '@ViewBag.NAME') ; </script>
Simplify the response from the server on the agent-server http channel
using Glimpse.Web; using Microsoft.AspNet.Http; using Newtonsoft.Json; using System.IO; using System.Text; using Microsoft.AspNet.Builder; namespace Glimpse.Server.Web { public class HttpChannelReceiver : IMiddlewareResourceComposer { private readonly IServerBroker _messageServerBus; public HttpChannelReceiver(IServerBroker messageServerBus) { _messageServerBus = messageServerBus; } public void Register(IApplicationBuilder appBuilder) { appBuilder.Map("/agent", chuldApp => chuldApp.Run(async context => { var envelope = ReadMessage(context.Request); _messageServerBus.SendMessage(envelope); // TEST CODE ONLY!!!! var response = context.Response; response.Headers.Set("Content-Type", "text/plain"); var data = Encoding.UTF8.GetBytes(envelope.Payload); await response.Body.WriteAsync(data, 0, data.Length); // TEST CODE ONLY!!!! })); } private Message ReadMessage(HttpRequest request) { var reader = new StreamReader(request.Body); var text = reader.ReadToEnd(); var message = JsonConvert.DeserializeObject<Message>(text); return message; } } }
using Glimpse.Web; using Microsoft.AspNet.Http; using Newtonsoft.Json; using System.IO; using System.Text; using Microsoft.AspNet.Builder; namespace Glimpse.Server.Web { public class HttpChannelReceiver : IMiddlewareResourceComposer { private readonly IServerBroker _messageServerBus; public HttpChannelReceiver(IServerBroker messageServerBus) { _messageServerBus = messageServerBus; } public void Register(IApplicationBuilder appBuilder) { appBuilder.Map("/agent", childApp => childApp.Run(async context => { var envelope = ReadMessage(context.Request); _messageServerBus.SendMessage(envelope); // TODO: Really should do something better var response = context.Response; response.Headers.Set("Content-Type", "text/plain"); var data = Encoding.UTF8.GetBytes("OK"); await response.Body.WriteAsync(data, 0, data.Length); })); } private Message ReadMessage(HttpRequest request) { var reader = new StreamReader(request.Body); var text = reader.ReadToEnd(); var message = JsonConvert.DeserializeObject<Message>(text); return message; } } }
Fix problem with missing avatars
using System.Collections.Generic; using JoinRpg.DataModel; using JoinRpg.Domain; using Claim = System.Security.Claims.Claim; using ClaimTypes = System.Security.Claims.ClaimTypes; namespace Joinrpg.Web.Identity { internal static class ClaimInfoBuilder { public static IList<Claim> ToClaimsList(this User dbUser) { return new List<Claim> { new Claim(ClaimTypes.Email, dbUser.Email), new Claim(JoinClaimTypes.DisplayName, dbUser.GetDisplayName()), new Claim(JoinClaimTypes.AvatarId, dbUser.SelectedAvatarId?.ToString()) }; } } }
using System.Collections.Generic; using JoinRpg.DataModel; using JoinRpg.Domain; using Claim = System.Security.Claims.Claim; using ClaimTypes = System.Security.Claims.ClaimTypes; namespace Joinrpg.Web.Identity { internal static class ClaimInfoBuilder { public static IList<Claim> ToClaimsList(this User dbUser) { var claimList = new List<Claim> { new Claim(ClaimTypes.Email, dbUser.Email), new Claim(JoinClaimTypes.DisplayName, dbUser.GetDisplayName()), }; if (dbUser.SelectedAvatarId is not null) { //TODO: When we fix all avatars, it will be not required check claimList.Add(new Claim(JoinClaimTypes.AvatarId, dbUser.SelectedAvatarId?.ToString())); } return claimList; } } }
Read plugin settings from BasePluginsDirectory and all sub-directories
namespace Nubot.Abstractions { using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; public abstract class RobotPluginBase : IRobotPlugin { protected readonly IRobot Robot; protected RobotPluginBase(string pluginName, IRobot robot) { Name = pluginName; Robot = robot; HelpMessages = new List<string>(); } static RobotPluginBase() { ExecutingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); BasePluginsDirectory = Path.Combine(ExecutingDirectory, "plugins"); } public string Name { get; protected set; } public static string ExecutingDirectory { get; private set; } public static string BasePluginsDirectory { get; private set; } public IEnumerable<string> HelpMessages { get; protected set; } public virtual IEnumerable<IPluginSetting> Settings { get { return Enumerable.Empty<IPluginSetting>();} } public virtual string MakeConfigFileName() { var pluginName = Name.Replace(" ", string.Empty); //Bug it is not defined that the plugin is from the root folder var file = string.Format("{0}.config", pluginName); var configFileName = Path.Combine(BasePluginsDirectory, file); return configFileName; } } }
namespace Nubot.Abstractions { using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; public abstract class RobotPluginBase : IRobotPlugin { protected readonly IRobot Robot; protected RobotPluginBase(string pluginName, IRobot robot) { Name = pluginName; Robot = robot; HelpMessages = new List<string>(); } static RobotPluginBase() { ExecutingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); BasePluginsDirectory = Path.Combine(ExecutingDirectory, "plugins"); } public string Name { get; private set; } public static string ExecutingDirectory { get; private set; } public static string BasePluginsDirectory { get; private set; } public IEnumerable<string> HelpMessages { get; protected set; } public virtual IEnumerable<IPluginSetting> Settings { get { return Enumerable.Empty<IPluginSetting>();} } public virtual string MakeConfigFileName() { var pluginName = Name.Replace(" ", string.Empty); var file = string.Format("{0}.config", pluginName); return Directory.GetFiles(BasePluginsDirectory, file, SearchOption.AllDirectories).FirstOrDefault(); } } }
Use newly introduced autofac's SetAutofacLifetimeScope method to pass autofac scope from asp.net core pipeline to owin pipeline
using Autofac; using Autofac.Integration.Owin; using Bit.Owin.Contracts; using Bit.Owin.Middlewares; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Owin; using Owin; using System; using System.Reflection; using System.Threading.Tasks; namespace Bit.OwinCore.Middlewares { public class AspNetCoreAutofacDependencyInjectionMiddlewareConfiguration : IOwinMiddlewareConfiguration { public virtual void Configure(IAppBuilder owinApp) { owinApp.Use<AspNetCoreAutofacDependencyInjectionMiddleware>(); owinApp.Use<AutofacScopeBasedDependencyResolverMiddleware>(); } } public class AspNetCoreAutofacDependencyInjectionMiddleware : OwinMiddleware { public AspNetCoreAutofacDependencyInjectionMiddleware(OwinMiddleware next) : base(next) { } static AspNetCoreAutofacDependencyInjectionMiddleware() { TypeInfo autofacConstantsType = typeof(OwinContextExtensions).GetTypeInfo().Assembly.GetType("Autofac.Integration.Owin.Constants").GetTypeInfo(); FieldInfo owinLifetimeScopeKeyField = autofacConstantsType.GetField("OwinLifetimeScopeKey", BindingFlags.Static | BindingFlags.NonPublic); if (owinLifetimeScopeKeyField == null) throw new InvalidOperationException($"OwinLifetimeScopeKey field could not be found in {nameof(OwinContextExtensions)} "); OwinLifetimeScopeKey = (string)owinLifetimeScopeKeyField.GetValue(null); } private static readonly string OwinLifetimeScopeKey; public override async Task Invoke(IOwinContext context) { HttpContext aspNetCoreContext = (HttpContext)context.Environment["Microsoft.AspNetCore.Http.HttpContext"]; aspNetCoreContext.Items["OwinContext"] = context; ILifetimeScope autofacScope = aspNetCoreContext.RequestServices.GetService<ILifetimeScope>(); context.Set(OwinLifetimeScopeKey, autofacScope); await Next.Invoke(context); } } }
using Autofac; using Autofac.Integration.Owin; using Bit.Owin.Contracts; using Bit.Owin.Middlewares; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Owin; using Owin; using System.Threading.Tasks; namespace Bit.OwinCore.Middlewares { public class AspNetCoreAutofacDependencyInjectionMiddlewareConfiguration : IOwinMiddlewareConfiguration { public virtual void Configure(IAppBuilder owinApp) { owinApp.Use<AspNetCoreAutofacDependencyInjectionMiddleware>(); owinApp.Use<AutofacScopeBasedDependencyResolverMiddleware>(); } } public class AspNetCoreAutofacDependencyInjectionMiddleware : OwinMiddleware { public AspNetCoreAutofacDependencyInjectionMiddleware(OwinMiddleware next) : base(next) { } public override async Task Invoke(IOwinContext context) { HttpContext aspNetCoreContext = (HttpContext)context.Environment["Microsoft.AspNetCore.Http.HttpContext"]; aspNetCoreContext.Items["OwinContext"] = context; ILifetimeScope autofacScope = aspNetCoreContext.RequestServices.GetService<ILifetimeScope>(); context.SetAutofacLifetimeScope(autofacScope); await Next.Invoke(context); } } }
Fix uri templates in season requests.
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Seasons { using Enums; using Objects.Basic; using Objects.Get.Shows.Seasons; using System.Collections.Generic; internal class TraktSeasonCommentsRequest : TraktGetByIdSeasonRequest<TraktPaginationListResult<TraktSeasonComment>, TraktSeasonComment> { internal TraktSeasonCommentsRequest(TraktClient client) : base(client) { } internal TraktCommentSortOrder? Sorting { get; set; } protected override IDictionary<string, object> GetUriPathParameters() { var uriParams = base.GetUriPathParameters(); if (Sorting.HasValue && Sorting.Value != TraktCommentSortOrder.Unspecified) uriParams.Add("sorting", Sorting.Value.AsString()); return uriParams; } protected override string UriTemplate => "shows/{id}/seasons/{season}/comments/{sorting}"; protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Seasons { using Enums; using Objects.Basic; using Objects.Get.Shows.Seasons; using System.Collections.Generic; internal class TraktSeasonCommentsRequest : TraktGetByIdSeasonRequest<TraktPaginationListResult<TraktSeasonComment>, TraktSeasonComment> { internal TraktSeasonCommentsRequest(TraktClient client) : base(client) { } internal TraktCommentSortOrder? Sorting { get; set; } protected override IDictionary<string, object> GetUriPathParameters() { var uriParams = base.GetUriPathParameters(); if (Sorting.HasValue && Sorting.Value != TraktCommentSortOrder.Unspecified) uriParams.Add("sorting", Sorting.Value.AsString()); return uriParams; } protected override string UriTemplate => "shows/{id}/seasons/{season}/comments{/sorting}"; protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
Support `Status` filter when listing Terminal `Reader`s
namespace Stripe.Terminal { using System; using Newtonsoft.Json; public class ReaderListOptions : ListOptions { [JsonProperty("location")] public string Location { get; set; } [Obsolete("This feature has been deprecated and should not be used moving forward.")] [JsonProperty("operator_account")] public string OperatorAccount { get; set; } } }
namespace Stripe.Terminal { using System; using Newtonsoft.Json; public class ReaderListOptions : ListOptions { /// <summary> /// A location ID to filter the response list to only readers at the specific location. /// </summary> [JsonProperty("location")] public string Location { get; set; } /// <summary> /// A status filter to filter readers to only offline or online readers. Possible values /// are <c>offline</c> and <c>online</c>. /// </summary> [JsonProperty("status")] public string Status { get; set; } [Obsolete("This feature has been deprecated and should not be used moving forward.")] [JsonProperty("operator_account")] public string OperatorAccount { get; set; } } }
Add event hub connection property
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.Azure.WebJobs.Description; namespace Microsoft.Azure.WebJobs.ServiceBus { /// <summary> /// Setup an 'trigger' on a parameter to listen on events from an event hub. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Binding] public sealed class EventHubTriggerAttribute : Attribute { /// <summary> /// Create an instance of this attribute. /// </summary> /// <param name="eventHubName">Event hub to listen on for messages. </param> public EventHubTriggerAttribute(string eventHubName) { this.EventHubName = eventHubName; } /// <summary> /// Name of the event hub. /// </summary> public string EventHubName { get; private set; } /// <summary> /// Optional Name of the consumer group. If missing, then use the default name, "$Default" /// </summary> public string ConsumerGroup { get; set; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.Azure.WebJobs.Description; namespace Microsoft.Azure.WebJobs.ServiceBus { /// <summary> /// Setup an 'trigger' on a parameter to listen on events from an event hub. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Binding] public sealed class EventHubTriggerAttribute : Attribute { /// <summary> /// Create an instance of this attribute. /// </summary> /// <param name="eventHubName">Event hub to listen on for messages. </param> public EventHubTriggerAttribute(string eventHubName) { this.EventHubName = eventHubName; } /// <summary> /// Name of the event hub. /// </summary> public string EventHubName { get; private set; } /// <summary> /// Optional Name of the consumer group. If missing, then use the default name, "$Default" /// </summary> public string ConsumerGroup { get; set; } /// <summary> /// Optional connection name. If missing, tries to use a registered event hub receiver. /// </summary> public string Connection { get; set; } } }
Throw an exception if the Redis connection is not open
using System; using System.Threading.Tasks; using System.Web.Mvc; using BookSleeve; using SignalR; namespace Compilify.Web.EndPoints { public class ExecuteEndPoint : PersistentConnection { /// <summary> /// Handle messages sent by the client.</summary> protected override Task OnReceivedAsync(string connectionId, string data) { var redis = DependencyResolver.Current.GetService<RedisConnection>(); var command = new ExecuteCommand { ClientId = connectionId, Code = data }; var message = Convert.ToBase64String(command.GetBytes()); redis.Lists.AddLast(0, "queue:execute", message); return Send(new { status = "ok" }); } } }
using System; using System.Threading.Tasks; using System.Web.Mvc; using BookSleeve; using SignalR; namespace Compilify.Web.EndPoints { public class ExecuteEndPoint : PersistentConnection { /// <summary> /// Handle messages sent by the client.</summary> protected override Task OnReceivedAsync(string connectionId, string data) { var redis = DependencyResolver.Current.GetService<RedisConnection>(); if (redis.State != RedisConnectionBase.ConnectionState.Open) { throw new InvalidOperationException("RedisConnection state is " + redis.State); } var command = new ExecuteCommand { ClientId = connectionId, Code = data }; var message = Convert.ToBase64String(command.GetBytes()); redis.Lists.AddLast(0, "queue:execute", message); return Send(new { status = "ok" }); } } }
Remove protocol from licenses view.
using System.Diagnostics; using System.Windows.Input; using Norma.Models; using Norma.ViewModels.Internal; using Prism.Commands; namespace Norma.ViewModels { internal class LibraryViewModel : ViewModel { private readonly Library _library; public string Name => _library.Name; public string Url => _library.Url; public string License => _library.License; public LibraryViewModel(Library library) { _library = library; } #region OpenHyperlinkCommand private ICommand _openHyperlinkCommand; public ICommand OpenHyperlinkCommand => _openHyperlinkCommand ?? (_openHyperlinkCommand = new DelegateCommand(OpenHyperlink)); private void OpenHyperlink() => Process.Start(Url); #endregion } }
using System.Diagnostics; using System.Windows.Input; using Norma.Models; using Norma.ViewModels.Internal; using Prism.Commands; namespace Norma.ViewModels { internal class LibraryViewModel : ViewModel { private readonly Library _library; public string Name => _library.Name; public string Url => _library.Url.Replace("https://", "").Replace("http://", ""); public string License => _library.License; public LibraryViewModel(Library library) { _library = library; } #region OpenHyperlinkCommand private ICommand _openHyperlinkCommand; public ICommand OpenHyperlinkCommand => _openHyperlinkCommand ?? (_openHyperlinkCommand = new DelegateCommand(OpenHyperlink)); private void OpenHyperlink() => Process.Start(_library.Url); #endregion } }
Set OpenCoffee as default test type
using System; using System.ComponentModel; namespace CoffeeFilter.UITests.Shared { public static class UITestsHelpers { public static string XTCApiKey { get; } = "024b0d715a7e9c22388450cf0069cb19"; public static TestType SelectedTest { get; set; } public enum TestType { NoConnection, ParseError, OpenCoffee, ClosedCoffee, NoLocations, UserMoved } } public static class TestTypeExtensions { public static string ToFriendlyString(this UITestsHelpers.TestType me) { switch(me) { case UITestsHelpers.TestType.NoConnection: return "No Internet Connection"; case UITestsHelpers.TestType.ParseError: return "Parse Error"; case UITestsHelpers.TestType.OpenCoffee: return "Open Coffee Locations"; case UITestsHelpers.TestType.ClosedCoffee: return "Closed Coffee Locations"; case UITestsHelpers.TestType.NoLocations: return "No Locations Around"; case UITestsHelpers.TestType.UserMoved: return "User Moved and Refreshed"; } return string.Empty; } } }
using System; using System.ComponentModel; namespace CoffeeFilter.UITests.Shared { public static class UITestsHelpers { public static string XTCApiKey { get; } = "024b0d715a7e9c22388450cf0069cb19"; public static TestType SelectedTest { get; set; } public enum TestType { OpenCoffee = 0, NoConnection, ParseError, ClosedCoffee, NoLocations, UserMoved } } public static class TestTypeExtensions { public static string ToFriendlyString(this UITestsHelpers.TestType me) { switch(me) { case UITestsHelpers.TestType.NoConnection: return "No Internet Connection"; case UITestsHelpers.TestType.ParseError: return "Parse Error"; case UITestsHelpers.TestType.OpenCoffee: return "Open Coffee Locations"; case UITestsHelpers.TestType.ClosedCoffee: return "Closed Coffee Locations"; case UITestsHelpers.TestType.NoLocations: return "No Locations Around"; case UITestsHelpers.TestType.UserMoved: return "User Moved and Refreshed"; } return string.Empty; } } }
Add using when creating a memorystream
using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; using CompaniesHouse.Response.Document; using CompaniesHouse.UriBuilders; using FluentAssertions; using Moq; using NUnit.Framework; namespace CompaniesHouse.Tests.CompaniesHouseDocumentClientTests { [TestFixture] public class CompaniesHouseDocumentClientTests { private CompaniesHouseClientResponse<DocumentDownload> _result; private const string ExpectedMediaType = "application/pdf"; private const string ExpectedContent = "test pdf"; private const string DocumentId = "wibble"; [SetUp] public async Task GivenAClient_WhenDownloadingDocument() { var requestUri = new Uri($"https://document-api.companieshouse.gov.uk/document/{DocumentId}/content"); var stubHttpMessageHandler = new StubHttpMessageHandler(requestUri, ExpectedContent, ExpectedMediaType); var mockUriBuilder = new Mock<IDocumentUriBuilder>(); mockUriBuilder.Setup(x => x.WithContent()).Returns(mockUriBuilder.Object); mockUriBuilder.Setup(x => x.Build(DocumentId)).Returns(requestUri.ToString()); _result = await new CompaniesHouseDocumentClient(new HttpClient(stubHttpMessageHandler), mockUriBuilder.Object).DownloadDocumentAsync(DocumentId); } [Test] public void ThenDocumentContentIsCorrect() { var memoryStream = new MemoryStream(); _result.Data.Content.CopyToAsync(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); new StreamReader(memoryStream).ReadToEnd().Should().Be(ExpectedContent); } } }
using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; using CompaniesHouse.Response.Document; using CompaniesHouse.UriBuilders; using FluentAssertions; using Moq; using NUnit.Framework; namespace CompaniesHouse.Tests.CompaniesHouseDocumentClientTests { [TestFixture] public class CompaniesHouseDocumentClientTests { private CompaniesHouseClientResponse<DocumentDownload> _result; private const string ExpectedMediaType = "application/pdf"; private const string ExpectedContent = "test pdf"; private const string DocumentId = "wibble"; [SetUp] public async Task GivenAClient_WhenDownloadingDocument() { var requestUri = new Uri($"https://document-api.companieshouse.gov.uk/document/{DocumentId}/content"); var stubHttpMessageHandler = new StubHttpMessageHandler(requestUri, ExpectedContent, ExpectedMediaType); var mockUriBuilder = new Mock<IDocumentUriBuilder>(); mockUriBuilder.Setup(x => x.WithContent()).Returns(mockUriBuilder.Object); mockUriBuilder.Setup(x => x.Build(DocumentId)).Returns(requestUri.ToString()); _result = await new CompaniesHouseDocumentClient(new HttpClient(stubHttpMessageHandler), mockUriBuilder.Object).DownloadDocumentAsync(DocumentId); } [Test] public void ThenDocumentContentIsCorrect() { using var memoryStream = new MemoryStream(); _result.Data.Content.CopyToAsync(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); new StreamReader(memoryStream).ReadToEnd().Should().Be(ExpectedContent); } } }
Comment out some test code that no longer works due to API changes in UE
using System; using System.Runtime.InteropServices; using Klawr.ClrHost.Managed; using Klawr.ClrHost.Interfaces; using Klawr.ClrHost.Managed.SafeHandles; namespace Klawr.UnrealEngine { public class TestActor : AActorScriptObject { public TestActor(long instanceID, UObjectHandle nativeObject) : base(instanceID, nativeObject) { Console.WriteLine("TestActor()"); } public override void BeginPlay() { Console.WriteLine("BeginPlay()"); var world = K2_GetWorld(); var worldClass = UWorld.StaticClass(); bool isWorldClass = world.IsA(worldClass); var anotherWorldClass = (UClass)typeof(UWorld); bool isSameClass = worldClass == anotherWorldClass; bool isWorldClassDerivedFromObjectClass = worldClass.IsChildOf(UObject.StaticClass()); world.Dispose(); } public override void Tick(float deltaTime) { Console.WriteLine("Tick()"); } public override void Destroy() { Console.WriteLine("Destroy()"); } } }
using System; using System.Runtime.InteropServices; using Klawr.ClrHost.Managed; using Klawr.ClrHost.Interfaces; using Klawr.ClrHost.Managed.SafeHandles; namespace Klawr.UnrealEngine { // NOTE: IScriptObject should probably be considered deprecated in favor of UKlawrScriptComponent public class TestActor : AActorScriptObject { public TestActor(long instanceID, UObjectHandle nativeObject) : base(instanceID, nativeObject) { Console.WriteLine("TestActor()"); } public override void BeginPlay() { Console.WriteLine("BeginPlay()"); // FIXME: AActor::K2_GetWorld() is no more, and AActor::GetWorld() is not exposed to // Blueprints at all... may need to expose UObject::GetWorld() manually. /* var world = K2_GetWorld(); var worldClass = UWorld.StaticClass(); bool isWorldClass = world.IsA(worldClass); var anotherWorldClass = (UClass)typeof(UWorld); bool isSameClass = worldClass == anotherWorldClass; bool isWorldClassDerivedFromObjectClass = worldClass.IsChildOf(UObject.StaticClass()); world.Dispose(); */ } public override void Tick(float deltaTime) { Console.WriteLine("Tick()"); } public override void Destroy() { Console.WriteLine("Destroy()"); } } }
Fix issue when the error messages are rendered in Markdown with an Always configuration
using MarkdownLog; using NBi.Core.ResultSet; using NBi.Core.ResultSet.Lookup; using NBi.Core.ResultSet.Lookup.Violation; using NBi.Framework.FailureMessage.Common; using NBi.Framework.FailureMessage.Common.Helper; using NBi.Framework.FailureMessage.Markdown.Helper; using NBi.Framework.Sampling; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Framework.FailureMessage.Markdown { class LookupExistsViolationMessageMarkdown : LookupViolationMessageMarkdown { public LookupExistsViolationMessageMarkdown(IDictionary<string, ISampler<DataRow>> samplers) : base(samplers) { } protected override void RenderAnalysis(LookupViolationCollection violations, IEnumerable<ColumnMetadata> metadata, ISampler<DataRow> sampler, ColumnMappingCollection keyMappings, ColumnMappingCollection valueMappings, MarkdownContainer container) { container.Append("Analysis".ToMarkdownHeader()); var state = violations.Values.Select(x => x.State).First(); container.Append(GetExplanationText(violations, state).ToMarkdownParagraph()); var rows = violations.Values.Where(x => x is LookupExistsViolationInformation) .Cast<LookupExistsViolationInformation>() .SelectMany(x => x.CandidateRows); sampler.Build(rows); var tableHelper = new StandardTableHelperMarkdown(rows, metadata, sampler); tableHelper.Render(container); } } }
using MarkdownLog; using NBi.Core.ResultSet; using NBi.Core.ResultSet.Lookup; using NBi.Core.ResultSet.Lookup.Violation; using NBi.Framework.FailureMessage.Common; using NBi.Framework.FailureMessage.Common.Helper; using NBi.Framework.FailureMessage.Markdown.Helper; using NBi.Framework.Sampling; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Framework.FailureMessage.Markdown { class LookupExistsViolationMessageMarkdown : LookupViolationMessageMarkdown { public LookupExistsViolationMessageMarkdown(IDictionary<string, ISampler<DataRow>> samplers) : base(samplers) { } protected override void RenderAnalysis(LookupViolationCollection violations, IEnumerable<ColumnMetadata> metadata, ISampler<DataRow> sampler, ColumnMappingCollection keyMappings, ColumnMappingCollection valueMappings, MarkdownContainer container) { if (violations.Values.Any()) { container.Append("Analysis".ToMarkdownHeader()); var state = violations.Values.Select(x => x.State).First(); container.Append(GetExplanationText(violations, state).ToMarkdownParagraph()); var rows = violations.Values.Where(x => x is LookupExistsViolationInformation) .Cast<LookupExistsViolationInformation>() .SelectMany(x => x.CandidateRows); sampler.Build(rows); var tableHelper = new StandardTableHelperMarkdown(rows, metadata, sampler); tableHelper.Render(container); } } } }
Fix BillboardWrapper, prevent bb from collecting by GC
using System; namespace Urho { public partial class BillboardSet { public BillboardWrapper GetBillboardSafe (uint index) { unsafe { Billboard* result = BillboardSet_GetBillboard (handle, index); if (result == null) return null; return new BillboardWrapper(result); } } } }
using System; namespace Urho { public partial class BillboardSet { public BillboardWrapper GetBillboardSafe (uint index) { unsafe { Billboard* result = BillboardSet_GetBillboard (handle, index); if (result == null) return null; return new BillboardWrapper(this, result); } } } }
Add new private field for the route handler
using System.Web.Mvc; using System.Web.Routing; namespace RestfulRouting { public abstract class Mapper { protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods) { return new Route(path, new RouteValueDictionary(new { controller, action }), new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }), new MvcRouteHandler()); } } }
using System.Web.Mvc; using System.Web.Routing; namespace RestfulRouting { public abstract class Mapper { private readonly IRouteHandler _routeHandler; protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods) { return new Route(path, new RouteValueDictionary(new { controller, action }), new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }), new MvcRouteHandler()); } } }
Add jsonconverter to extension model
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { /// <summary> /// Encapsulates information about a Contentful Ui Extension /// </summary> public class UiExtension : IContentfulResource { /// <summary> /// Common system managed metadata properties. /// </summary> [JsonProperty("sys")] public SystemProperties SystemProperties { get; set; } /// <summary> /// The source URL for html file for the extension. /// </summary> public string Src { get; set; } /// <summary> /// String representation of the widget, e.g. inline HTML. /// </summary> public string SrcDoc { get; set; } /// <summary> /// The name of the extension /// </summary> public string Name { get; set; } /// <summary> /// The field types for which this extension applies. /// </summary> public List<string> FieldTypes { get; set; } /// <summary> /// Whether or not this is an extension for the Contentful sidebar. /// </summary> public bool Sidebar { get; set; } } }
using Contentful.Core.Configuration; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { /// <summary> /// Encapsulates information about a Contentful Ui Extension /// </summary> [JsonConverter(typeof(ExtensionJsonConverter))] public class UiExtension : IContentfulResource { /// <summary> /// Common system managed metadata properties. /// </summary> [JsonProperty("sys")] public SystemProperties SystemProperties { get; set; } /// <summary> /// The source URL for html file for the extension. /// </summary> public string Src { get; set; } /// <summary> /// String representation of the widget, e.g. inline HTML. /// </summary> public string SrcDoc { get; set; } /// <summary> /// The name of the extension /// </summary> public string Name { get; set; } /// <summary> /// The field types for which this extension applies. /// </summary> public List<string> FieldTypes { get; set; } /// <summary> /// Whether or not this is an extension for the Contentful sidebar. /// </summary> public bool Sidebar { get; set; } } }
Add missing namespace for uwp
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; #if (NETFX || WINDOWS_PHONE) using System.Windows; using System.Windows.Data; using System.Windows.Markup; #elif (NETFX_CORE) using Windows.UI.Xaml; using Windows.UI.Xaml.Data; #elif (XAMARIN) using Xamarin.Forms; #endif namespace ValueConverters { /// <summary> /// Value converters which aggregates the results of a sequence of converters: Converter1 >> Converter2 >> Converter3 /// The output of converter N becomes the input of converter N+1. /// </summary> #if (NETFX || XAMARIN || WINDOWS_PHONE) [ContentProperty(nameof(Converters))] #elif (NETFX_CORE) [ContentProperty(Name = nameof(Converters))] #endif public class ValueConverterGroup : SingletonConverterBase<ValueConverterGroup> { public List<IValueConverter> Converters { get; set; } = new List<IValueConverter>(); protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return this.Converters?.Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture)); } protected override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return this.Converters?.Reverse<IValueConverter>().Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture)); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; #if (NETFX || WINDOWS_PHONE) using System.Windows; using System.Windows.Data; using System.Windows.Markup; #elif (NETFX_CORE) using Windows.UI.Xaml; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Markup; #elif (XAMARIN) using Xamarin.Forms; #endif namespace ValueConverters { /// <summary> /// Value converters which aggregates the results of a sequence of converters: Converter1 >> Converter2 >> Converter3 /// The output of converter N becomes the input of converter N+1. /// </summary> #if (NETFX || XAMARIN || WINDOWS_PHONE) [ContentProperty(nameof(Converters))] #elif (NETFX_CORE) [ContentProperty(Name = nameof(Converters))] #endif public class ValueConverterGroup : SingletonConverterBase<ValueConverterGroup> { public List<IValueConverter> Converters { get; set; } = new List<IValueConverter>(); protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return this.Converters?.Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture)); } protected override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return this.Converters?.Reverse<IValueConverter>().Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture)); } } }
Add a prefix to each log
using Mindscape.Raygun4Net.Utils; namespace Mindscape.Raygun4Net.Logging { public class RaygunLogger : Singleton<RaygunLogger>, IRaygunLogger { public RaygunLogLevel LogLevel { get; set; } public void Error(string message) { Log(RaygunLogLevel.Error, message); } public void Warning(string message) { Log(RaygunLogLevel.Warning, message); } public void Info(string message) { Log(RaygunLogLevel.Info, message); } public void Debug(string message) { Log(RaygunLogLevel.Debug, message); } public void Verbose(string message) { Log(RaygunLogLevel.Verbose, message); } private void Log(RaygunLogLevel level, string message) { if (LogLevel == RaygunLogLevel.None) { return; } if (level <= LogLevel) { System.Diagnostics.Trace.WriteLine(message); } } } }
using Mindscape.Raygun4Net.Utils; namespace Mindscape.Raygun4Net.Logging { public class RaygunLogger : Singleton<RaygunLogger>, IRaygunLogger { private const string RaygunPrefix = "Raygun: "; public RaygunLogLevel LogLevel { get; set; } public void Error(string message) { Log(RaygunLogLevel.Error, message); } public void Warning(string message) { Log(RaygunLogLevel.Warning, message); } public void Info(string message) { Log(RaygunLogLevel.Info, message); } public void Debug(string message) { Log(RaygunLogLevel.Debug, message); } public void Verbose(string message) { Log(RaygunLogLevel.Verbose, message); } private void Log(RaygunLogLevel level, string message) { if (LogLevel == RaygunLogLevel.None) { return; } if (level <= LogLevel) { System.Diagnostics.Trace.WriteLine($"{RaygunPrefix}{message}"); } } } }
Use Socket instead of TcpClient for port scanning Works around ObjectDisposedException on Linux + Mono
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; namespace MultiMiner.Utility.Networking { public class PortScanner { public static List<IPEndPoint> Find(string ipRange, int startingPort, int endingPort, int connectTimeout = 100) { if (startingPort >= endingPort) throw new ArgumentException(); List<IPEndPoint> endpoints = new List<IPEndPoint>(); IEnumerable<IPAddress> ipAddresses = new IPRange(ipRange).GetIPAddresses(); foreach (IPAddress ipAddress in ipAddresses) for (int currentPort = startingPort; currentPort <= endingPort; currentPort++) if (IsPortOpen(ipAddress, currentPort, connectTimeout)) endpoints.Add(new IPEndPoint(ipAddress, currentPort)); return endpoints; } private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout) { bool portIsOpen = false; using (var tcp = new TcpClient()) { IAsyncResult ar = tcp.BeginConnect(ipAddress, currentPort, null, null); using (ar.AsyncWaitHandle) { //Wait connectTimeout ms for connection. if (ar.AsyncWaitHandle.WaitOne(connectTimeout, false)) { try { tcp.EndConnect(ar); portIsOpen = true; //Connect was successful. } catch { //Server refused the connection. } } } } return portIsOpen; } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; namespace MultiMiner.Utility.Networking { public class PortScanner { public static List<IPEndPoint> Find(string ipRange, int startingPort, int endingPort, int connectTimeout = 100) { if (startingPort >= endingPort) throw new ArgumentException(); List<IPEndPoint> endpoints = new List<IPEndPoint>(); IEnumerable<IPAddress> ipAddresses = new IPRange(ipRange).GetIPAddresses(); foreach (IPAddress ipAddress in ipAddresses) for (int currentPort = startingPort; currentPort <= endingPort; currentPort++) if (IsPortOpen(ipAddress, currentPort, connectTimeout)) endpoints.Add(new IPEndPoint(ipAddress, currentPort)); return endpoints; } private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout) { bool portIsOpen = false; //use raw Sockets //using TclClient along with IAsyncResult can lead to ObjectDisposedException on Linux+Mono Socket socket = null; try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false); IAsyncResult result = socket.BeginConnect(ipAddress.ToString(), currentPort, null, null); result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(connectTimeout), true); portIsOpen = socket.Connected; } catch { } finally { if (socket != null) socket.Close(); } return portIsOpen; } } }
Add multiple bing maps keys
namespace TestAppUWP.Samples.Map { public class MapServiceSettings { public static string Token = string.Empty; } }
namespace TestAppUWP.Samples.Map { public class MapServiceSettings { public const string TokenUwp1 = "TokenUwp1"; public const string TokenUwp2 = "TokenUwp2"; public static string SelectedToken = TokenUwp1; } }
Change recognized event handler for eval
using Microsoft.Speech.Recognition; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace lex4all { public static class EngineControl { /// <summary> /// creates engine and sets properties /// </summary> /// <returns> /// the engine used for recognition /// </returns> public static SpeechRecognitionEngine getEngine () { Console.WriteLine("Building recognition engine"); SpeechRecognitionEngine sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US")); // set confidence threshold(s) sre.UpdateRecognizerSetting("CFGConfidenceRejectionThreshold", 0); // add event handlers sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized); Console.WriteLine("Done."); return sre; } /// <summary> /// handles the speech recognized event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { Console.WriteLine("Recognized text: " + e.Result.Text); } } }
using Microsoft.Speech.Recognition; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace lex4all { public static class EngineControl { /// <summary> /// creates engine and sets properties /// </summary> /// <returns> /// the engine used for recognition /// </returns> public static SpeechRecognitionEngine getEngine () { Console.WriteLine("Building recognition engine"); SpeechRecognitionEngine sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US")); // set confidence threshold(s) sre.UpdateRecognizerSetting("CFGConfidenceRejectionThreshold", 0); // add event handlers sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized); Console.WriteLine("Done."); return sre; } /// <summary> /// handles the speech recognized event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { //Console.WriteLine("Recognized text: " + e.Result.Text); } } }
Return completions from all documents
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Text; using OmniSharp.Models; namespace OmniSharp { public partial class OmnisharpController { [HttpPost("autocomplete")] public async Task<IActionResult> AutoComplete([FromBody]Request request) { _workspace.EnsureBufferUpdated(request); var completions = Enumerable.Empty<AutoCompleteResponse>(); var document = _workspace.GetDocument(request.FileName); if (document != null) { var sourceText = await document.GetTextAsync(); var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1)); var model = await document.GetSemanticModelAsync(); var symbols = Recommender.GetRecommendedSymbolsAtPosition(model, position, _workspace); completions = symbols.Select(MakeAutoCompleteResponse); } else { return new HttpNotFoundResult(); } return new ObjectResult(completions); } private AutoCompleteResponse MakeAutoCompleteResponse(ISymbol symbol) { var response = new AutoCompleteResponse(); response.CompletionText = symbol.Name; // TODO: Do something more intelligent here response.DisplayText = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); response.Description = symbol.GetDocumentationCommentXml(); return response; } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Text; using OmniSharp.Models; namespace OmniSharp { public partial class OmnisharpController { [HttpPost("autocomplete")] public async Task<IActionResult> AutoComplete([FromBody]Request request) { _workspace.EnsureBufferUpdated(request); var completions = new List<AutoCompleteResponse>(); var documents = _workspace.GetDocuments(request.FileName); foreach (var document in documents) { var sourceText = await document.GetTextAsync(); var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1)); var model = await document.GetSemanticModelAsync(); var symbols = Recommender.GetRecommendedSymbolsAtPosition(model, position, _workspace); completions.AddRange(symbols.Select(MakeAutoCompleteResponse)); } return new ObjectResult(completions); } private AutoCompleteResponse MakeAutoCompleteResponse(ISymbol symbol) { var response = new AutoCompleteResponse(); response.CompletionText = symbol.Name; // TODO: Do something more intelligent here response.DisplayText = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); response.Description = symbol.GetDocumentationCommentXml(); return response; } } }
Fix auth http services registration
using InfinniPlatform.Http; using InfinniPlatform.IoC; namespace InfinniPlatform.Auth.HttpService.IoC { public class AuthHttpServiceContainerModule<TUser> : IContainerModule where TUser : AppUser { public void Load(IContainerBuilder builder) { builder.RegisterType(typeof(AuthInternalHttpService<>).MakeGenericType(typeof(TUser))) .As<IHttpService>() .SingleInstance(); builder.RegisterType<UserEventHandlerInvoker>() .AsSelf() .SingleInstance(); } } }
using InfinniPlatform.Http; using InfinniPlatform.IoC; namespace InfinniPlatform.Auth.HttpService.IoC { public class AuthHttpServiceContainerModule<TUser> : IContainerModule where TUser : AppUser { public void Load(IContainerBuilder builder) { builder.RegisterType(typeof(AuthInternalHttpService<>).MakeGenericType(typeof(TUser))) .As<IHttpService>() .SingleInstance(); builder.RegisterType(typeof(AuthExternalHttpService<>).MakeGenericType(typeof(TUser))) .As<IHttpService>() .SingleInstance(); builder.RegisterType(typeof(AuthManagementHttpService<>).MakeGenericType(typeof(TUser))) .As<IHttpService>() .SingleInstance(); builder.RegisterType<UserEventHandlerInvoker>() .AsSelf() .SingleInstance(); } } }
Make testcase even more useful
// 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.Containers; using osu.Game.Overlays.Toolbar; using System; using System.Collections.Generic; using osu.Framework.Graphics; using System.Linq; using osu.Framework.MathUtils; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneToolbarRulesetSelector : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(ToolbarRulesetSelector), typeof(ToolbarRulesetTabButton), }; public TestSceneToolbarRulesetSelector() { ToolbarRulesetSelector selector; Add(new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, AutoSizeAxes = Axes.X, Height = Toolbar.HEIGHT, Child = selector = new ToolbarRulesetSelector() }); AddStep("Select random", () => { selector.Current.Value = selector.Items.ElementAt(RNG.Next(selector.Items.Count())); }); } } }
// 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.Containers; using osu.Game.Overlays.Toolbar; using System; using System.Collections.Generic; using osu.Framework.Graphics; using System.Linq; using osu.Framework.MathUtils; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneToolbarRulesetSelector : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(ToolbarRulesetSelector), typeof(ToolbarRulesetTabButton), }; public TestSceneToolbarRulesetSelector() { ToolbarRulesetSelector selector; Add(new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, AutoSizeAxes = Axes.X, Height = Toolbar.HEIGHT, Child = selector = new ToolbarRulesetSelector() }); AddStep("Select random", () => { selector.Current.Value = selector.Items.ElementAt(RNG.Next(selector.Items.Count())); }); AddStep("Toggle disabled state", () => selector.Current.Disabled = !selector.Current.Disabled); } } }
Stop hiding indexer on IList
using System.Collections.Generic; namespace Ical.Net.Interfaces.DataTypes { public interface IPeriodList : IEncodableDataType, IList<IPeriod> { string TzId { get; set; } IPeriod this[int index] { get; set; } void Add(IDateTime dt); void Remove(IDateTime dt); } }
using System.Collections.Generic; namespace Ical.Net.Interfaces.DataTypes { public interface IPeriodList : IEncodableDataType, IList<IPeriod> { string TzId { get; set; } new IPeriod this[int index] { get; set; } void Add(IDateTime dt); void Remove(IDateTime dt); } }
Fix station events system test
using System.Threading.Tasks; using Content.Server.GameObjects.EntitySystems.StationEvents; using NUnit.Framework; using Robust.Shared.GameObjects.Systems; using Robust.Shared.Interfaces.Timing; using Robust.Shared.IoC; namespace Content.IntegrationTests.Tests.StationEvents { [TestFixture] public class StationEventsSystemTest : ContentIntegrationTest { [Test] public async Task Test() { var server = StartServerDummyTicker(); server.Assert(() => { // Idle each event once var stationEventsSystem = EntitySystem.Get<StationEventSystem>(); var dummyFrameTime = (float) IoCManager.Resolve<IGameTiming>().TickPeriod.TotalSeconds; foreach (var stationEvent in stationEventsSystem.StationEvents) { stationEvent.Startup(); stationEvent.Update(dummyFrameTime); stationEvent.Shutdown(); Assert.That(stationEvent.Occurrences == 1); } stationEventsSystem.ResettingCleanup(); foreach (var stationEvent in stationEventsSystem.StationEvents) { Assert.That(stationEvent.Occurrences == 0); } }); await server.WaitIdleAsync(); } } }
using System.Threading.Tasks; using Content.Server.GameObjects.EntitySystems.StationEvents; using NUnit.Framework; using Robust.Shared.GameObjects.Systems; using Robust.Shared.Interfaces.Timing; using Robust.Shared.IoC; namespace Content.IntegrationTests.Tests.StationEvents { [TestFixture] public class StationEventsSystemTest : ContentIntegrationTest { [Test] public async Task Test() { var server = StartServerDummyTicker(); server.Assert(() => { // Idle each event once var stationEventsSystem = EntitySystem.Get<StationEventSystem>(); var dummyFrameTime = (float) IoCManager.Resolve<IGameTiming>().TickPeriod.TotalSeconds; foreach (var stationEvent in stationEventsSystem.StationEvents) { stationEvent.Startup(); stationEvent.Update(dummyFrameTime); stationEvent.Shutdown(); Assert.That(stationEvent.Occurrences == 1); } stationEventsSystem.Reset(); foreach (var stationEvent in stationEventsSystem.StationEvents) { Assert.That(stationEvent.Occurrences == 0); } }); await server.WaitIdleAsync(); } } }
Use plain text for function secrets in Linux Containers
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Script.Config; using static Microsoft.Azure.Web.DataProtection.Constants; namespace Microsoft.Azure.WebJobs.Script.WebHost { public sealed class DefaultKeyValueConverterFactory : IKeyValueConverterFactory { private bool _encryptionSupported; private static readonly PlaintextKeyValueConverter PlaintextValueConverter = new PlaintextKeyValueConverter(FileAccess.ReadWrite); private static ScriptSettingsManager _settingsManager; public DefaultKeyValueConverterFactory(ScriptSettingsManager settingsManager) { _settingsManager = settingsManager; _encryptionSupported = IsEncryptionSupported(); } // In Linux Containers AzureWebsiteLocalEncryptionKey will be set, enabling encryption private static bool IsEncryptionSupported() => _settingsManager.IsAppServiceEnvironment || _settingsManager.GetSetting(AzureWebsiteLocalEncryptionKey) != null; public IKeyValueReader GetValueReader(Key key) { if (key.IsEncrypted) { return new DataProtectionKeyValueConverter(FileAccess.Read); } return PlaintextValueConverter; } public IKeyValueWriter GetValueWriter(Key key) { if (_encryptionSupported) { return new DataProtectionKeyValueConverter(FileAccess.Write); } return PlaintextValueConverter; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Script.Config; using static Microsoft.Azure.Web.DataProtection.Constants; namespace Microsoft.Azure.WebJobs.Script.WebHost { public sealed class DefaultKeyValueConverterFactory : IKeyValueConverterFactory { private readonly bool _encryptionSupported; private static readonly PlaintextKeyValueConverter PlaintextValueConverter = new PlaintextKeyValueConverter(FileAccess.ReadWrite); private static ScriptSettingsManager _settingsManager; public DefaultKeyValueConverterFactory(ScriptSettingsManager settingsManager) { _settingsManager = settingsManager; _encryptionSupported = IsEncryptionSupported(); } private static bool IsEncryptionSupported() { if (_settingsManager.IsLinuxContainerEnvironment) { // TEMP: https://github.com/Azure/azure-functions-host/issues/3035 return false; } return _settingsManager.IsAppServiceEnvironment || _settingsManager.GetSetting(AzureWebsiteLocalEncryptionKey) != null; } public IKeyValueReader GetValueReader(Key key) { if (key.IsEncrypted) { return new DataProtectionKeyValueConverter(FileAccess.Read); } return PlaintextValueConverter; } public IKeyValueWriter GetValueWriter(Key key) { if (_encryptionSupported) { return new DataProtectionKeyValueConverter(FileAccess.Write); } return PlaintextValueConverter; } } }
Remove TestCase cleanup temporarily until context disposal is sorted
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Game.Tests.Visual { public abstract class OsuTestCase : TestCase { public override void RunTest() { Storage storage; using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false)) { storage = host.Storage; host.Run(new OsuTestCaseTestRunner(this)); } // clean up after each run storage.DeleteDirectory(string.Empty); } public class OsuTestCaseTestRunner : OsuGameBase { private readonly OsuTestCase testCase; public OsuTestCaseTestRunner(OsuTestCase testCase) { this.testCase = testCase; } protected override void LoadComplete() { base.LoadComplete(); Add(new TestCaseTestRunner.TestRunner(testCase)); } } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Game.Tests.Visual { public abstract class OsuTestCase : TestCase { public override void RunTest() { using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false)) { host.Run(new OsuTestCaseTestRunner(this)); } // clean up after each run //storage.DeleteDirectory(string.Empty); } public class OsuTestCaseTestRunner : OsuGameBase { private readonly OsuTestCase testCase; public OsuTestCaseTestRunner(OsuTestCase testCase) { this.testCase = testCase; } protected override void LoadComplete() { base.LoadComplete(); Add(new TestCaseTestRunner.TestRunner(testCase)); } } } }
Remove the ListGroups snippet from Monitoring
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using System; using System.Linq; using Xunit; namespace Google.Monitoring.V3 { [Collection(nameof(MonitoringFixture))] public class GroupServiceClientSnippets { private readonly MonitoringFixture _fixture; public GroupServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } /* TODO: Reinstate when ListGroups is present again. [Fact] public void ListGroups() { string projectId = _fixture.ProjectId; // Snippet: ListGroups GroupServiceClient client = GroupServiceClient.Create(); string projectName = MetricServiceClient.FormatProjectName(projectId); IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", ""); foreach (Group group in groups.Take(10)) { Console.WriteLine($"{group.Name}: {group.DisplayName}"); } // End snippet } */ } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using System; using System.Linq; using Xunit; namespace Google.Monitoring.V3 { [Collection(nameof(MonitoringFixture))] public class GroupServiceClientSnippets { private readonly MonitoringFixture _fixture; public GroupServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } /* TODO: Reinstate when ListGroups is present again. [Fact] public void ListGroups() { string projectId = _fixture.ProjectId; // FIXME:Snippet: ListGroups GroupServiceClient client = GroupServiceClient.Create(); string projectName = MetricServiceClient.FormatProjectName(projectId); IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", ""); foreach (Group group in groups.Take(10)) { Console.WriteLine($"{group.Name}: {group.DisplayName}"); } // End snippet } */ } }
Set Android permissions through Assemblyinfo
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Plugin.MediaManager.Android")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Plugin.MediaManager.Android")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Plugin.MediaManager.Android")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Plugin.MediaManager.Android")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: UsesPermission(Android.Manifest.Permission.AccessWifiState)] [assembly: UsesPermission(Android.Manifest.Permission.Internet)] [assembly: UsesPermission(Android.Manifest.Permission.MediaContentControl)] [assembly: UsesPermission(Android.Manifest.Permission.WakeLock)]
Update the Command Help Request Error to get the value
namespace BigEgg.ConsoleExtension.Parameters.Errors { using System; internal class CommandHelpRequestError : Error { public CommandHelpRequestError() : base(ErrorType.CommandHelpRequest, true) { } public string CommandName { get; private set; } public bool Existed { get; set; } public Type CommandType { get; set; } } }
namespace BigEgg.ConsoleExtension.Parameters.Errors { using System; internal class CommandHelpRequestError : Error { public CommandHelpRequestError(string commandName, bool existed, Type commandType) : base(ErrorType.CommandHelpRequest, true) { CommandName = commandName; Existed = existed; CommandType = existed ? commandType : null; } public string CommandName { get; private set; } public bool Existed { get; private set; } public Type CommandType { get; private set; } } }
Simplify statistics in osu ruleset
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Objects; namespace osu.Game.Rulesets.Osu.Beatmaps { public class OsuBeatmap : Beatmap<OsuHitObject> { public override IEnumerable<BeatmapStatistic> GetStatistics() { IEnumerable<HitObject> circles = HitObjects.Where(c => c is HitCircle); IEnumerable<HitObject> sliders = HitObjects.Where(s => s is Slider); IEnumerable<HitObject> spinners = HitObjects.Where(s => s is Spinner); return new[] { new BeatmapStatistic { Name = @"Circle Count", Content = circles.Count().ToString(), Icon = FontAwesome.fa_circle_o }, new BeatmapStatistic { Name = @"Slider Count", Content = sliders.Count().ToString(), Icon = FontAwesome.fa_circle }, new BeatmapStatistic { Name = @"Spinner Count", Content = spinners.Count().ToString(), Icon = FontAwesome.fa_circle } }; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Rulesets.Osu.Objects; namespace osu.Game.Rulesets.Osu.Beatmaps { public class OsuBeatmap : Beatmap<OsuHitObject> { public override IEnumerable<BeatmapStatistic> GetStatistics() { int circles = HitObjects.Count(c => c is HitCircle); int sliders = HitObjects.Count(s => s is Slider); int spinners = HitObjects.Count(s => s is Spinner); return new[] { new BeatmapStatistic { Name = @"Circle Count", Content = circles.ToString(), Icon = FontAwesome.fa_circle_o }, new BeatmapStatistic { Name = @"Slider Count", Content = sliders.ToString(), Icon = FontAwesome.fa_circle }, new BeatmapStatistic { Name = @"Spinner Count", Content = spinners.ToString(), Icon = FontAwesome.fa_circle } }; } } }
Add short desc on main
using System; using System.Collections.Generic; using System.Threading; using Nancy; using Nancy.Hosting.Self; namespace ChildProcessUtil { public class Program { private const string HttpAddress = "http://localhost:"; private static NancyHost host; private static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("usage: ChildProcessUtil.exe serverPort mainProcessId"); return; } StartServer(int.Parse(args[0]), int.Parse(args[1])); } public static void StartServer(int port, int mainProcessId) { var hostConfigs = new HostConfiguration { UrlReservations = new UrlReservations {CreateAutomatically = true} }; var uriString = HttpAddress + port; ProcessModule.ActiveProcesses = new List<int>(); host = new NancyHost(new Uri(uriString), new DefaultNancyBootstrapper(), hostConfigs); host.Start(); new MainProcessWatcher(mainProcessId); Thread.Sleep(Timeout.Infinite); } internal static void StopServer(int port) { host.Stop(); } } }
using System; using System.Collections.Generic; using System.Threading; using Nancy; using Nancy.Hosting.Self; namespace ChildProcessUtil { public class Program { private const string HttpAddress = "http://localhost:"; private static NancyHost host; private static void Main(string[] args) { Console.WriteLine("Child process watcher and automatic killer"); if (args.Length != 2) { Console.WriteLine("usage: ChildProcessUtil.exe serverPort mainProcessId"); return; } StartServer(int.Parse(args[0]), int.Parse(args[1])); } public static void StartServer(int port, int mainProcessId) { var hostConfigs = new HostConfiguration { UrlReservations = new UrlReservations {CreateAutomatically = true} }; var uriString = HttpAddress + port; ProcessModule.ActiveProcesses = new List<int>(); host = new NancyHost(new Uri(uriString), new DefaultNancyBootstrapper(), hostConfigs); host.Start(); new MainProcessWatcher(mainProcessId); Thread.Sleep(Timeout.Infinite); } internal static void StopServer(int port) { host.Stop(); } } }
Rename Raytraced settings Options page to just Cycles.
/** Copyright 2014-2017 Robert McNeel and Associates Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **/ using Rhino; using Rhino.DocObjects; using Rhino.UI; using System; using System.Drawing; namespace RhinoCycles.Settings { public class OptionsDialogPage : Rhino.UI.OptionsDialogPage { public OptionsDialogPage() : base(Localization.LocalizeString("Raytraced settings", 37)) { CollapsibleSectionHolder = new OptionsDialogCollapsibleSectionUIPanel(); } public override object PageControl => CollapsibleSectionHolder; private OptionsDialogCollapsibleSectionUIPanel CollapsibleSectionHolder { get; } } }
/** Copyright 2014-2017 Robert McNeel and Associates Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **/ using Rhino; using Rhino.DocObjects; using Rhino.UI; using System; using System.Drawing; namespace RhinoCycles.Settings { public class OptionsDialogPage : Rhino.UI.OptionsDialogPage { public OptionsDialogPage() : base(Localization.LocalizeString("Cycles", 7)) { CollapsibleSectionHolder = new OptionsDialogCollapsibleSectionUIPanel(); } public override object PageControl => CollapsibleSectionHolder; private OptionsDialogCollapsibleSectionUIPanel CollapsibleSectionHolder { get; } } }
Fix crazy Unix line endings ;)
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; namespace NodaTime.Utility { /// <summary> /// Exception thrown when data read by Noda Time (such as serialized time zone data) is invalid. /// </summary> /// <remarks> /// This type only exists as <c>InvalidDataException</c> doesn't exist in the Portable Class Library. /// Unfortunately, <c>InvalidDataException</c> itself is sealed, so we can't derive from it for the sake /// of backward compatibility. /// </remarks> /// <threadsafety>Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe. /// See the thread safety section of the user guide for more information. /// </threadsafety> #if !PCL [Serializable] #endif // TODO: Derive from IOException instead, like EndOfStreamException does? public class InvalidNodaDataException : Exception { /// <summary> /// Creates an instance with the given message. /// </summary> /// <param name="message">The message for the exception.</param> public InvalidNodaDataException(string message) : base(message) { } } }
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; namespace NodaTime.Utility { /// <summary> /// Exception thrown when data read by Noda Time (such as serialized time zone data) is invalid. /// </summary> /// <remarks> /// This type only exists as <c>InvalidDataException</c> doesn't exist in the Portable Class Library. /// Unfortunately, <c>InvalidDataException</c> itself is sealed, so we can't derive from it for the sake /// of backward compatibility. /// </remarks> /// <threadsafety>Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe. /// See the thread safety section of the user guide for more information. /// </threadsafety> #if !PCL [Serializable] #endif // TODO: Derive from IOException instead, like EndOfStreamException does? public class InvalidNodaDataException : Exception { /// <summary> /// Creates an instance with the given message. /// </summary> /// <param name="message">The message for the exception.</param> public InvalidNodaDataException(string message) : base(message) { } } }
Fix 'yarn audit'. Register the Audit alias
using System; namespace Cake.Yarn { /// <summary> /// Yarn Runner command interface /// </summary> public interface IYarnRunnerCommands { /// <summary> /// execute 'yarn install' with options /// </summary> /// <param name="configure">options when running 'yarn install'</param> IYarnRunnerCommands Install(Action<YarnInstallSettings> configure = null); /// <summary> /// execute 'yarn add' with options /// </summary> /// <param name="configure">options when running 'yarn add'</param> IYarnRunnerCommands Add(Action<YarnAddSettings> configure = null); /// <summary> /// execute 'yarn run' with arguments /// </summary> /// <param name="scriptName">name of the </param> /// <param name="configure">options when running 'yarn run'</param> IYarnRunnerCommands RunScript(string scriptName, Action<YarnRunSettings> configure = null); /// <summary> /// execute 'yarn pack' with options /// </summary> /// <param name="packSettings">options when running 'yarn pack'</param> IYarnRunnerCommands Pack(Action<YarnPackSettings> packSettings = null); /// <summary> /// execute 'yarn version' with options /// </summary> /// <param name="versionSettings">options when running 'yarn version'</param> IYarnRunnerCommands Version(Action<YarnVersionSettings> versionSettings = null); } }
using System; namespace Cake.Yarn { /// <summary> /// Yarn Runner command interface /// </summary> public interface IYarnRunnerCommands { /// <summary> /// execute 'yarn install' with options /// </summary> /// <param name="configure">options when running 'yarn install'</param> IYarnRunnerCommands Install(Action<YarnInstallSettings> configure = null); /// <summary> /// execute 'yarn add' with options /// </summary> /// <param name="configure">options when running 'yarn add'</param> IYarnRunnerCommands Add(Action<YarnAddSettings> configure = null); /// <summary> /// execute 'yarn run' with arguments /// </summary> /// <param name="scriptName">name of the </param> /// <param name="configure">options when running 'yarn run'</param> IYarnRunnerCommands RunScript(string scriptName, Action<YarnRunSettings> configure = null); /// <summary> /// execute 'yarn pack' with options /// </summary> /// <param name="packSettings">options when running 'yarn pack'</param> IYarnRunnerCommands Pack(Action<YarnPackSettings> packSettings = null); /// <summary> /// execute 'yarn version' with options /// </summary> /// <param name="versionSettings">options when running 'yarn version'</param> IYarnRunnerCommands Version(Action<YarnVersionSettings> versionSettings = null); /// <summary> /// execute 'yarn audit' with options /// </summary> /// <param name="auditSettings">options when running 'yarn audit'</param> /// <returns></returns> IYarnRunnerCommands Audit(Action<YarnAuditSettings> auditSettings = null); } }
Use interface, not concrete type, for Unity Fluent extension.
/* Copyright 2014 Jonathan Holland. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Microsoft.Practices.Unity; using Wave.Configuration; using Wave.IoC.Unity; namespace Wave { public static class FluentConfigurationSourceExtensions { public static FluentConfigurationSource UseUnity(this FluentConfigurationSource builder, UnityContainer container) { return builder.UsingContainer(new UnityContainerAdapter(container)); } } }
/* Copyright 2014 Jonathan Holland. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Microsoft.Practices.Unity; using Wave.Configuration; using Wave.IoC.Unity; namespace Wave { public static class FluentConfigurationSourceExtensions { public static FluentConfigurationSource UseUnity(this FluentConfigurationSource builder, IUnityContainer container) { return builder.UsingContainer(new UnityContainerAdapter(container)); } } }
Test with a slightly larger image.
// 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 Xunit; namespace Magick.NET.Tests { public partial class MagickImageTests { public class TheAddNoiseMethod { [Fact] public void ShouldCreateDifferentImagesEachRun() { using (var imageA = new MagickImage(MagickColors.Black, 10, 10)) { using (var imageB = new MagickImage(MagickColors.Black, 10, 10)) { imageA.AddNoise(NoiseType.Random); imageB.AddNoise(NoiseType.Random); Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared)); } } } } } }
// 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 Xunit; namespace Magick.NET.Tests { public partial class MagickImageTests { public class TheAddNoiseMethod { [Fact] public void ShouldCreateDifferentImagesEachRun() { using (var imageA = new MagickImage(MagickColors.Black, 100, 100)) { imageA.AddNoise(NoiseType.Random); using (var imageB = new MagickImage(MagickColors.Black, 100, 100)) { imageB.AddNoise(NoiseType.Random); Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared)); } } } } } }
Add option to yield return a KMSelectable to toggle-interact with.
using System.Collections; using System.Reflection; using UnityEngine; public class CoroutineModComponentSolver : ComponentSolver { public CoroutineModComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller, MethodInfo processMethod, Component commandComponent) : base(bombCommander, bombComponent, ircConnection, canceller) { ProcessMethod = processMethod; CommandComponent = commandComponent; } protected override IEnumerator RespondToCommandInternal(string inputCommand) { IEnumerator responseCoroutine = (IEnumerator)ProcessMethod.Invoke(CommandComponent, new object[] { inputCommand }); if (responseCoroutine == null) { yield break; } yield return "modcoroutine"; while (responseCoroutine.MoveNext()) { yield return responseCoroutine.Current; } } private readonly MethodInfo ProcessMethod = null; private readonly Component CommandComponent = null; }
using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; public class CoroutineModComponentSolver : ComponentSolver { public CoroutineModComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller, MethodInfo processMethod, Component commandComponent) : base(bombCommander, bombComponent, ircConnection, canceller) { ProcessMethod = processMethod; CommandComponent = commandComponent; } protected override IEnumerator RespondToCommandInternal(string inputCommand) { IEnumerator responseCoroutine = (IEnumerator)ProcessMethod.Invoke(CommandComponent, new object[] { inputCommand }); if (responseCoroutine == null) { yield break; } yield return "modcoroutine"; while (responseCoroutine.MoveNext()) { object currentObject = responseCoroutine.Current; if (currentObject.GetType() == typeof(KMSelectable)) { KMSelectable selectable = (KMSelectable)currentObject; if (HeldSelectables.Contains(selectable)) { DoInteractionEnd(selectable); HeldSelectables.Remove(selectable); } else { DoInteractionStart(selectable); HeldSelectables.Add(selectable); } } yield return currentObject; } } private readonly MethodInfo ProcessMethod = null; private readonly Component CommandComponent = null; private readonly List<KMSelectable> HeldSelectables = new List<KMSelectable>(); }
Fix null reference exception when running under Mono
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace AsyncRewriter { /// <summary> /// </summary> /// <remarks> /// http://stackoverflow.com/questions/2961753/how-to-hide-files-generated-by-custom-tool-in-visual-studio /// </remarks> public class RewriteAsync : Microsoft.Build.Utilities.Task { [Required] public ITaskItem[] InputFiles { get; set; } [Required] public ITaskItem OutputFile { get; set; } readonly Rewriter _rewriter; public RewriteAsync() { _rewriter = new Rewriter(new TaskLoggingAdapter(Log)); } public override bool Execute() { var asyncCode = _rewriter.RewriteAndMerge(InputFiles.Select(f => f.ItemSpec).ToArray()); File.WriteAllText(OutputFile.ItemSpec, asyncCode); return true; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace AsyncRewriter { /// <summary> /// </summary> /// <remarks> /// http://stackoverflow.com/questions/2961753/how-to-hide-files-generated-by-custom-tool-in-visual-studio /// </remarks> public class RewriteAsync : Microsoft.Build.Utilities.Task { [Required] public ITaskItem[] InputFiles { get; set; } [Required] public ITaskItem OutputFile { get; set; } readonly Rewriter _rewriter; public RewriteAsync() { _rewriter = Log == null ? new Rewriter() : new Rewriter(new TaskLoggingAdapter(Log)); } public override bool Execute() { var asyncCode = _rewriter.RewriteAndMerge(InputFiles.Select(f => f.ItemSpec).ToArray()); File.WriteAllText(OutputFile.ItemSpec, asyncCode); return true; } } }
Use extension method for WindsorRegistrationHelper.AddServices
using System; using Microsoft.Extensions.DependencyInjection; namespace Castle.Windsor.MsDependencyInjection { public class WindsorServiceProviderFactory : IServiceProviderFactory<IWindsorContainer> { public IWindsorContainer CreateBuilder(IServiceCollection services) { var container = services.GetSingletonServiceOrNull<IWindsorContainer>(); if (container == null) { container = new WindsorContainer(); services.AddSingleton(container); } WindsorRegistrationHelper.AddServices(container, services); return container; } public IServiceProvider CreateServiceProvider(IWindsorContainer containerBuilder) { return containerBuilder.Resolve<IServiceProvider>(); } } }
using System; using Microsoft.Extensions.DependencyInjection; namespace Castle.Windsor.MsDependencyInjection { public class WindsorServiceProviderFactory : IServiceProviderFactory<IWindsorContainer> { public IWindsorContainer CreateBuilder(IServiceCollection services) { var container = services.GetSingletonServiceOrNull<IWindsorContainer>(); if (container == null) { container = new WindsorContainer(); services.AddSingleton(container); } container.AddServices(services); return container; } public IServiceProvider CreateServiceProvider(IWindsorContainer containerBuilder) { return containerBuilder.Resolve<IServiceProvider>(); } } }
Add interface as resharper forgot
using NUnit.Framework; namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers { public class MyDatabaseSettings { public string ConnectionString { get; } = $@"{TestContext.CurrentContext.TestDirectory}\Tests.db"; } }
using NUnit.Framework; namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers { public class MyDatabaseSettings : IMyDatabaseSettings { public string ConnectionString { get; } = $@"Data Source={TestContext.CurrentContext.TestDirectory}\Tests.db;Version=3;New=True;BinaryGUID=False;"; } }
Update the closest known distance.
using System; using System.Collections.Generic; namespace ChamberLib { public interface IModel { object Tag { get; set; } IEnumerable<IMesh> GetMeshes(); void Draw(Matrix world, Matrix view, Matrix projection, IMaterial materialOverride=null, LightingData? lightingOverride=null); IBone Root { get; set; } void SetAmbientLightColor(Vector3 value); void SetEmissiveColor(Vector3 value); void SetDirectionalLight(DirectionalLight light, int index=0); void DisableDirectionalLight(int index); void SetAlpha(float alpha); void SetTexture(ITexture2D texture); void SetBoneTransforms(Matrix[] boneTransforms, IMaterial materialOverride=null); IEnumerable<Triangle> EnumerateTriangles(); } public static class ModelHelper { public static Vector3? IntersectClosest(this IModel model, Ray ray) { Vector3? closest = null; float closestDist = -1; foreach (var tri in model.EnumerateTriangles()) { var p = tri.Intersects(ray); if (!p.HasValue) continue; if (!closest.HasValue) { closest = p; } else { var dist = (p.Value - ray.Position).LengthSquared(); if (dist < closestDist) { closest = p; closestDist = dist; } } } return closest; } } }
using System; using System.Collections.Generic; namespace ChamberLib { public interface IModel { object Tag { get; set; } IEnumerable<IMesh> GetMeshes(); void Draw(Matrix world, Matrix view, Matrix projection, IMaterial materialOverride=null, LightingData? lightingOverride=null); IBone Root { get; set; } void SetAmbientLightColor(Vector3 value); void SetEmissiveColor(Vector3 value); void SetDirectionalLight(DirectionalLight light, int index=0); void DisableDirectionalLight(int index); void SetAlpha(float alpha); void SetTexture(ITexture2D texture); void SetBoneTransforms(Matrix[] boneTransforms, IMaterial materialOverride=null); IEnumerable<Triangle> EnumerateTriangles(); } public static class ModelHelper { public static Vector3? IntersectClosest(this IModel model, Ray ray) { Vector3? closest = null; float closestDist = -1; foreach (var tri in model.EnumerateTriangles()) { var p = tri.Intersects(ray); if (!p.HasValue) continue; if (!closest.HasValue) { closest = p; closestDist = (p.Value - ray.Position).LengthSquared(); } else { var dist = (p.Value - ray.Position).LengthSquared(); if (dist < closestDist) { closest = p; closestDist = dist; } } } return closest; } } }
Make ES mapping configuration Properties setter public
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Diagnostics.EventFlow.Configuration { public class ElasticSearchMappingsConfiguration { public Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor> Properties { get; private set; } public ElasticSearchMappingsConfiguration() { Properties = new Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor>(); } internal ElasticSearchMappingsConfiguration DeepClone() { var other = new ElasticSearchMappingsConfiguration(); foreach (var item in this.Properties) { other.Properties.Add(item.Key, item.Value.DeepClone()); } return other; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Diagnostics.EventFlow.Configuration { public class ElasticSearchMappingsConfiguration { public Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor> Properties { get; set; } public ElasticSearchMappingsConfiguration() { Properties = new Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor>(); } internal ElasticSearchMappingsConfiguration DeepClone() { var other = new ElasticSearchMappingsConfiguration(); foreach (var item in this.Properties) { other.Properties.Add(item.Key, item.Value.DeepClone()); } return other; } } }
Replace CSharpHighlightingTestBase (will be removed in 2016.2 SDK) usage with TestNetFramework4-attribute
using System.IO; using JetBrains.Annotations; using JetBrains.Application.Settings; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.FeaturesTestFramework.Daemon; using JetBrains.ReSharper.Psi; using XmlDocInspections.Plugin.Highlighting; namespace XmlDocInspections.Plugin.Tests.Integrative { public abstract class MissingXmlDocHighlightingTestsBase : CSharpHighlightingTestNet4Base { protected override string RelativeTestDataPath => "Highlighting"; protected override string GetGoldTestDataPath(string fileName) { return base.GetGoldTestDataPath(Path.Combine(GetType().Name, fileName)); } protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile sourceFile) { return highlighting is MissingXmlDocHighlighting; } protected override void DoTestSolution(params string[] fileSet) { ExecuteWithinSettingsTransaction(settingsStore => { RunGuarded(() => MutateSettings(settingsStore)); base.DoTestSolution(fileSet); }); } protected abstract void MutateSettings([NotNull] IContextBoundSettingsStore settingsStore); } }
using System.IO; using JetBrains.Annotations; using JetBrains.Application.Settings; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.FeaturesTestFramework.Daemon; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.TestFramework; using XmlDocInspections.Plugin.Highlighting; namespace XmlDocInspections.Plugin.Tests.Integrative { [TestNetFramework4] public abstract class MissingXmlDocHighlightingTestsBase : CSharpHighlightingTestBase { protected override string RelativeTestDataPath => "Highlighting"; protected override string GetGoldTestDataPath(string fileName) { return base.GetGoldTestDataPath(Path.Combine(GetType().Name, fileName)); } protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile sourceFile) { return highlighting is MissingXmlDocHighlighting; } protected override void DoTestSolution(params string[] fileSet) { ExecuteWithinSettingsTransaction(settingsStore => { RunGuarded(() => MutateSettings(settingsStore)); base.DoTestSolution(fileSet); }); } protected abstract void MutateSettings([NotNull] IContextBoundSettingsStore settingsStore); } }
Modify the companies house verification service to use the config initalised as a constructor parameter
using System; using System.Net; using System.Threading.Tasks; using Microsoft.Azure; using Newtonsoft.Json; using NLog; using SFA.DAS.EmployerApprenticeshipsService.Domain; using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class CompaniesHouseEmployerVerificationService : IEmployerVerificationService { private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); private readonly string _apiKey; public CompaniesHouseEmployerVerificationService(string apiKey) { _apiKey = apiKey; } public async Task<EmployerInformation> GetInformation(string id) { Logger.Info($"GetInformation({id})"); var webClient = new WebClient(); webClient.Headers.Add($"Authorization: Basic {_apiKey}"); try { var result = await webClient.DownloadStringTaskAsync($"https://api.companieshouse.gov.uk/company/{id}"); return JsonConvert.DeserializeObject<EmployerInformation>(result); } catch (WebException ex) { Logger.Error(ex, "There was a problem with the call to Companies House"); } return null; } } }
using System.Net; using System.Threading.Tasks; using Newtonsoft.Json; using NLog; using SFA.DAS.EmployerApprenticeshipsService.Domain; using SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration; using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class CompaniesHouseEmployerVerificationService : IEmployerVerificationService { private readonly EmployerApprenticeshipsServiceConfiguration _configuration; private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); public CompaniesHouseEmployerVerificationService(EmployerApprenticeshipsServiceConfiguration configuration) { _configuration = configuration; } public async Task<EmployerInformation> GetInformation(string id) { Logger.Info($"GetInformation({id})"); var webClient = new WebClient(); webClient.Headers.Add($"Authorization: Basic {_configuration.CompaniesHouse.ApiKey}"); try { var result = await webClient.DownloadStringTaskAsync($"https://api.companieshouse.gov.uk/company/{id}"); return JsonConvert.DeserializeObject<EmployerInformation>(result); } catch (WebException ex) { Logger.Error(ex, "There was a problem with the call to Companies House"); } return null; } } }
Fix spelling error in method name
using AutoMapper; using Esfa.Vacancy.Api.Types; using Esfa.Vacancy.Register.Api; using Esfa.Vacancy.Register.Application.Queries.SearchApprenticeshipVacancies; using FluentAssertions; using NUnit.Framework; namespace Esfa.Vacancy.Register.UnitTests.SearchApprenticeship.Api.GivenSearchApprenticeshipParameters { [TestFixture] public class AndPageNumber { private IMapper _mapper; [SetUp] public void Setup() { var config = AutoMapperConfig.Configure(); _mapper = config.CreateMapper(); } [Test] public void WhenProvided_ThenPopulateRequestWithTheGivenValue() { var expectedPageNumber = 2; var parameters = new SearchApprenticeshipParameters() { PageNumber = expectedPageNumber }; var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters); result.PageNumber.Should().Be(expectedPageNumber); } [Test] public void WhenNotProvided_ThenPoplateRequestWithTheDefaultValue() { var parameters = new SearchApprenticeshipParameters(); var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters); result.PageNumber.Should().Be(1); } } }
using AutoMapper; using Esfa.Vacancy.Api.Types; using Esfa.Vacancy.Register.Api; using Esfa.Vacancy.Register.Application.Queries.SearchApprenticeshipVacancies; using FluentAssertions; using NUnit.Framework; namespace Esfa.Vacancy.Register.UnitTests.SearchApprenticeship.Api.GivenSearchApprenticeshipParameters { [TestFixture] public class AndPageNumber { private IMapper _mapper; [SetUp] public void Setup() { var config = AutoMapperConfig.Configure(); _mapper = config.CreateMapper(); } [Test] public void WhenProvided_ThenPopulateRequestWithTheGivenValue() { var expectedPageNumber = 2; var parameters = new SearchApprenticeshipParameters() { PageNumber = expectedPageNumber }; var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters); result.PageNumber.Should().Be(expectedPageNumber); } [Test] public void WhenNotProvided_ThenPopulateRequestWithTheDefaultValue() { var parameters = new SearchApprenticeshipParameters(); var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters); result.PageNumber.Should().Be(1); } } }
Create one single instance of StringBuilder
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Text; using UnityEngine; namespace HoloToolkit.Unity { public static class TransformExtensions { /// <summary> /// An extension method that will get you the full path to an object. /// </summary> /// <param name="transform">The transform you wish a full path to.</param> /// <param name="delimiter">The delimiter with which each object is delimited in the string.</param> /// <param name="prefix">Prefix with which the full path to the object should start.</param> /// <returns>A delimited string that is the full path to the game object in the hierarchy.</returns> public static string GetFullPath(this Transform transform, string delimiter = ".", string prefix = "/") { StringBuilder stringBuilder = new StringBuilder(); if (transform.parent == null) { stringBuilder.Append(prefix); stringBuilder.Append(transform.name); } else { stringBuilder.Append(transform.parent.GetFullPath(delimiter, prefix)); stringBuilder.Append(delimiter); stringBuilder.Append(transform.name); } return stringBuilder.ToString(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Text; using UnityEngine; namespace HoloToolkit.Unity { public static class TransformExtensions { /// <summary> /// An extension method that will get you the full path to an object. /// </summary> /// <param name="transform">The transform you wish a full path to.</param> /// <param name="delimiter">The delimiter with which each object is delimited in the string.</param> /// <param name="prefix">Prefix with which the full path to the object should start.</param> /// <returns>A delimited string that is the full path to the game object in the hierarchy.</returns> public static string GetFullPath(this Transform transform, string delimiter = ".", string prefix = "/") { StringBuilder stringBuilder = new StringBuilder(); GetFullPath(stringBuilder, transform, delimiter, prefix); return stringBuilder.ToString(); } private static void GetFullPath(StringBuilder stringBuilder, Transform transform, string delimiter = ".", string prefix = "/") { if (transform.parent == null) { stringBuilder.Append(prefix); } else { GetFullPath(stringBuilder, transform.parent, delimiter, prefix); stringBuilder.Append(delimiter); } stringBuilder.Append(transform.name); } } }
Stop webview from reloading when rotated
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using Android.Runtime; using Android.Views; using Android.Webkit; using Android.Widget; namespace webscripthook_android { [Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor)] public class WebActivity : Activity { WebView webView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.KeepScreenOn); Window.RequestFeature(WindowFeatures.NoTitle); SetContentView(Resource.Layout.Web); webView = FindViewById<WebView>(Resource.Id.webView1); webView.Settings.JavaScriptEnabled = true; webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser if (savedInstanceState == null) { webView.LoadUrl(Intent.GetStringExtra("Address")); } } public override void OnBackPressed() { if (webView.CanGoBack()) { webView.GoBack(); } else { base.OnBackPressed(); } } protected override void OnSaveInstanceState (Bundle outState) { base.OnSaveInstanceState(outState); webView.SaveState(outState); } protected override void OnRestoreInstanceState(Bundle savedInstanceState) { base.OnRestoreInstanceState(savedInstanceState); webView.RestoreState(savedInstanceState); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using Android.Runtime; using Android.Views; using Android.Webkit; using Android.Widget; namespace webscripthook_android { [Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize)] public class WebActivity : Activity { WebView webView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.KeepScreenOn); Window.RequestFeature(WindowFeatures.NoTitle); SetContentView(Resource.Layout.Web); webView = FindViewById<WebView>(Resource.Id.webView1); webView.Settings.JavaScriptEnabled = true; webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser if (savedInstanceState == null) { webView.LoadUrl(Intent.GetStringExtra("Address")); } } public override void OnBackPressed() { if (webView.CanGoBack()) { webView.GoBack(); } else { base.OnBackPressed(); } } } }
Fix h1 class to match other views
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel <h1 class="heading-large">Login successful</h1> <form id="mainForm" method="post" action="@Model.ResponseFormUri"> <div id="autoRedirect" style="display: none;">Please wait...</div> @Html.Raw(Model.ResponseFormFields) <div id="manualLoginContainer"> <p>It appears you do not have javascript enabled. Please click the continue button to complete your login.</p> <button type="submit" class="button" autofocus="autofocus">Continue</button> </div> </form> @section scripts { <script> $('#manualLoginContainer').hide(); $('#autoRedirect').show(); $('#mainForm').submit(); </script> }
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel @{ ViewBag.PageID = "authorize-response"; ViewBag.Title = "Login Successful"; ViewBag.HideSigninLink = "true"; } <h1 class="heading-xlarge">Login successful</h1> <form id="mainForm" method="post" action="@Model.ResponseFormUri"> <div id="autoRedirect" style="display: none;">Please wait...</div> @Html.Raw(Model.ResponseFormFields) <div id="manualLoginContainer"> <p>It appears you do not have javascript enabled. Please click the continue button to complete your login.</p> <button type="submit" class="button" autofocus="autofocus">Continue</button> </div> </form> @section scripts { <script> $('#manualLoginContainer').hide(); $('#autoRedirect').show(); $('#mainForm').submit(); </script> }
Store the number of time units per second in a static const value.
using System; namespace FbxSharp { public struct FbxTime { public static readonly FbxTime Infinite = new FbxTime(0x7fffffffffffffffL); public static readonly FbxTime Zero = new FbxTime(0); public FbxTime(long time) { Value = time; } public long Value; public long Get() { return Value; } public double GetSecondDouble() { return Value / 46186158000.0; } public long GetFrameCount() { return Value / 1539538600L; } } }
using System; namespace FbxSharp { public struct FbxTime { public static readonly FbxTime Infinite = new FbxTime(0x7fffffffffffffffL); public static readonly FbxTime Zero = new FbxTime(0); public const long UnitsPerSecond = 46186158000L; public FbxTime(long time) { Value = time; } public long Value; public long Get() { return Value; } public double GetSecondDouble() { return Value / (double)UnitsPerSecond; } public long GetFrameCount() { return Value / 1539538600L; } } }
Add inital response lines in PU-Stub to mimic production PU
using Kentor.PU_Adapter; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace PU_Stub.Controllers { public class SnodController : ApiController { private static readonly IDictionary<string, string> TestPersons; static SnodController() { TestPersons = Kentor.PU_Adapter.TestData.TestPersonsPuData.PuDataList .ToDictionary(p => p.Substring(8, 12)); // index by person number } [HttpGet] public HttpResponseMessage PKNODPLUS(string arg) { System.Threading.Thread.Sleep(30); // Introduce production like latency string result; if (!TestPersons.TryGetValue(arg, out result)) { // Returkod: 0001 = Sökt person saknas i registren result = "13270001 _"; } var resp = new HttpResponseMessage(HttpStatusCode.OK); resp.Content = new StringContent(result, System.Text.Encoding.GetEncoding("ISO-8859-1"), "text/plain"); return resp; } } }
using Kentor.PU_Adapter; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace PU_Stub.Controllers { public class SnodController : ApiController { private static readonly IDictionary<string, string> TestPersons; static SnodController() { TestPersons = Kentor.PU_Adapter.TestData.TestPersonsPuData.PuDataList .ToDictionary(p => p.Substring(8, 12)); // index by person number } [HttpGet] public HttpResponseMessage PKNODPLUS(string arg) { System.Threading.Thread.Sleep(30); // Introduce production like latency string result; if (!TestPersons.TryGetValue(arg, out result)) { // Returkod: 0001 = Sökt person saknas i registren result = "13270001 _"; } result = "0\n0\n1327\n" + result; // add magic initial lines, like production PU does var resp = new HttpResponseMessage(HttpStatusCode.OK); resp.Content = new StringContent(result, System.Text.Encoding.GetEncoding("ISO-8859-1"), "text/plain"); return resp; } } }
Add “using static System.Console” to main
using CIV.Ccs; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var trace = CcsFacade.RandomTrace(processes["Prison"], 450); foreach (var action in trace) { System.Console.WriteLine(action); } } } }
using static System.Console; using CIV.Ccs; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var trace = CcsFacade.RandomTrace(processes["Prison"], 450); foreach (var action in trace) { WriteLine(action); } } } }
Make sure that a plugin is only created once
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using System; using System.IO; using System.Reflection; using Autofac; using Lunet.Core; using Microsoft.Extensions.Logging; namespace Lunet { public class SiteFactory { private readonly ContainerBuilder _containerBuilder; public SiteFactory() { _containerBuilder = new ContainerBuilder(); // Pre-register some type _containerBuilder.RegisterInstance(this); _containerBuilder.RegisterType<LoggerFactory>().As<ILoggerFactory>().SingleInstance(); _containerBuilder.RegisterType<SiteObject>().SingleInstance(); } public ContainerBuilder ContainerBuilder => _containerBuilder; public SiteFactory Register<TPlugin>() where TPlugin : ISitePlugin { Register(typeof(TPlugin)); return this; } public SiteFactory Register(Type pluginType) { if (pluginType == null) throw new ArgumentNullException(nameof(pluginType)); if (!typeof(ISitePlugin).GetTypeInfo().IsAssignableFrom(pluginType)) { throw new ArgumentException("Expecting a plugin type inheriting from ISitePlugin", nameof(pluginType)); } _containerBuilder.RegisterType(pluginType).AsSelf().As<ISitePlugin>(); return this; } public SiteObject Build() { var container = _containerBuilder.Build(); return container.Resolve<SiteObject>(); } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using System; using System.IO; using System.Reflection; using Autofac; using Lunet.Core; using Microsoft.Extensions.Logging; namespace Lunet { public class SiteFactory { private readonly ContainerBuilder _containerBuilder; public SiteFactory() { _containerBuilder = new ContainerBuilder(); // Pre-register some type _containerBuilder.RegisterInstance(this); _containerBuilder.RegisterType<LoggerFactory>().As<ILoggerFactory>().SingleInstance(); _containerBuilder.RegisterType<SiteObject>().SingleInstance(); } public ContainerBuilder ContainerBuilder => _containerBuilder; public SiteFactory Register<TPlugin>() where TPlugin : ISitePlugin { Register(typeof(TPlugin)); return this; } public SiteFactory Register(Type pluginType) { if (pluginType == null) throw new ArgumentNullException(nameof(pluginType)); if (!typeof(ISitePlugin).GetTypeInfo().IsAssignableFrom(pluginType)) { throw new ArgumentException("Expecting a plugin type inheriting from ISitePlugin", nameof(pluginType)); } _containerBuilder.RegisterType(pluginType).SingleInstance().AsSelf().As<ISitePlugin>(); return this; } public SiteObject Build() { var container = _containerBuilder.Build(); return container.Resolve<SiteObject>(); } } }
Change default gamemode from INSTRUCTION to ONE_PLAYER
using UnityEngine; using System.Collections; public class GameStart : MonoBehaviour { static int gameMode = INSTRUCTION; const int INSTRUCTION = -1; const int ONE_PLAYER = 1; const int TWO_PLAYER = 2; /// <summary> /// The game mode of the current game /// </summary> public static int GameMode { get { return gameMode; } set { if(value == ONE_PLAYER || value == TWO_PLAYER || value == INSTRUCTION) { gameMode = value; } } } /// <summary> /// Add the game to the global board and then destroy this (no longer necessary) /// </summary> private void Awake() { if(GameMode == ONE_PLAYER) { gameObject.AddComponent<SinglePlayerGame>(); } else if (GameMode == TWO_PLAYER) { gameObject.AddComponent<Game>(); } else if (GameMode == INSTRUCTION) { gameObject.AddComponent<InstructionGame>(); } Destroy(this); } }
using UnityEngine; using System.Collections; public class GameStart : MonoBehaviour { static int gameMode = ONE_PLAYER; const int INSTRUCTION = -1; const int ONE_PLAYER = 1; const int TWO_PLAYER = 2; /// <summary> /// The game mode of the current game /// </summary> public static int GameMode { get { return gameMode; } set { if(value == ONE_PLAYER || value == TWO_PLAYER || value == INSTRUCTION) { gameMode = value; } } } /// <summary> /// Add the game to the global board and then destroy this (no longer necessary) /// </summary> private void Awake() { if(GameMode == ONE_PLAYER) { gameObject.AddComponent<SinglePlayerGame>(); } else if (GameMode == TWO_PLAYER) { gameObject.AddComponent<Game>(); } else if (GameMode == INSTRUCTION) { gameObject.AddComponent<InstructionGame>(); } Destroy(this); } }
Fix model binding for OData Patch, Post, Put
using Abp.AspNetCore.OData.Controllers; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Web.Models; using AbpODataDemo.People; using Microsoft.AspNet.OData; using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; namespace AbpODataDemo.Controllers { [DontWrapResult] public class PersonsController : AbpODataEntityController<Person>, ITransientDependency { public PersonsController(IRepository<Person> repository) : base(repository) { } public override Task<IActionResult> Delete([FromODataUri] int key) { return base.Delete(key); } public override IQueryable<Person> Get() { return base.Get(); } public override SingleResult<Person> Get([FromODataUri] int key) { return base.Get(key); } public override Task<IActionResult> Patch([FromODataUri] int key, Delta<Person> entity) { return base.Patch(key, entity); } public override Task<IActionResult> Post(Person entity) { return base.Post(entity); } public override Task<IActionResult> Put([FromODataUri] int key, Person update) { return base.Put(key, update); } } }
using Abp.AspNetCore.OData.Controllers; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Web.Models; using AbpODataDemo.People; using Microsoft.AspNet.OData; using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; namespace AbpODataDemo.Controllers { [DontWrapResult] public class PersonsController : AbpODataEntityController<Person>, ITransientDependency { public PersonsController(IRepository<Person> repository) : base(repository) { } public override Task<IActionResult> Delete([FromODataUri] int key) { return base.Delete(key); } public override IQueryable<Person> Get() { return base.Get(); } public override SingleResult<Person> Get([FromODataUri] int key) { return base.Get(key); } public override Task<IActionResult> Patch([FromODataUri] int key, [FromBody] Delta<Person> entity) { return base.Patch(key, entity); } public override Task<IActionResult> Post([FromBody] Person entity) { return base.Post(entity); } public override Task<IActionResult> Put([FromODataUri] int key, [FromBody] Person update) { return base.Put(key, update); } } }
Add PageImage override for Mac and fix title string
/** Copyright 2014-2017 Robert McNeel and Associates Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **/ using Rhino; using Rhino.DocObjects; using Rhino.UI; using RhinoCyclesCore.Core; using System; using System.Drawing; namespace RhinoCycles.Settings { public class OptionsDialogPage : Rhino.UI.OptionsDialogPage { public OptionsDialogPage() : base(Localization.LocalizeString("Cycles", 7)) { CollapsibleSectionHolder = new OptionsDialogCollapsibleSectionUIPanel(); } public override object PageControl => CollapsibleSectionHolder; public override bool ShowApplyButton => false; public override bool ShowDefaultsButton => true; public override void OnDefaults() { RcCore.It.EngineSettings.DefaultSettings(); CollapsibleSectionHolder.UpdateSections(); } private OptionsDialogCollapsibleSectionUIPanel CollapsibleSectionHolder { get; } } }
/** Copyright 2014-2017 Robert McNeel and Associates Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **/ using Rhino; using Rhino.DocObjects; using Rhino.UI; using RhinoCyclesCore.Core; using System; using System.Drawing; namespace RhinoCycles.Settings { public class OptionsDialogPage : Rhino.UI.OptionsDialogPage { public OptionsDialogPage() : base("Cycles") { CollapsibleSectionHolder = new OptionsDialogCollapsibleSectionUIPanel(); } public override object PageControl => CollapsibleSectionHolder; public override bool ShowApplyButton => false; public override bool ShowDefaultsButton => true; public override string LocalPageTitle => Localization.LocalizeString ("Cycles", 7); public override Image PageImage { get { var icon = Properties.Resources.Cycles_viewport_properties; return icon.ToBitmap (); } } public override void OnDefaults() { RcCore.It.EngineSettings.DefaultSettings(); CollapsibleSectionHolder.UpdateSections(); } private OptionsDialogCollapsibleSectionUIPanel CollapsibleSectionHolder { get; } } }
Update funding link to go to account transactions index
@model SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account.Account <h1 class="heading-xlarge" id="company-Name">@Model.Name</h1> <div class="grid-row"> <div class="column-two-thirds"> <div style="max-width: 90%"> <div class="grid-row"> <div class="column-half"> <h3 class="heading-medium" style="margin-top: 0;"> <a href="@Url.Action("View", new { accountId = Model.Id })">Team</a> </h3> <p>Invite new users and manage existing ones</p> </div> <div class="column-half "> <h3 class="heading-medium" style="margin-top: 0"> <a href="#">Funding</a> </h3> <p>Manage your funds including how much you have available to spend, your transactions and funds you could lose</p> </div> </div> </div> </div> </div>
@model SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account.Account <h1 class="heading-xlarge" id="company-Name">@Model.Name</h1> <div class="grid-row"> <div class="column-two-thirds"> <div style="max-width: 90%"> <div class="grid-row"> <div class="column-half"> <h3 class="heading-medium" style="margin-top: 0;"> <a href="@Url.Action("View", new { accountId = Model.Id })">Team</a> </h3> <p>Invite new users and manage existing ones</p> </div> <div class="column-half "> <h3 class="heading-medium" style="margin-top: 0"> <a href="@Url.Action("Index", "EmployerAccountTransactions", new { accountId = Model.Id })">Funding</a> </h3> <p>Manage your funds including how much you have available to spend, your transactions and funds you could lose</p> </div> </div> </div> </div> </div>
Make custom ingredient optional on extension method
namespace MadeWithLove.Middleware { using Owin; public static class Extensions { public static void MakeWithLove(this IAppBuilder app, string customIngredient) { app.Use<MadeWithLoveMiddleware>(customIngredient); } } }
namespace MadeWithLove.Middleware { using Owin; public static class Extensions { public static void MakeWithLove(this IAppBuilder app, string customIngredient = null) { app.Use<MadeWithLoveMiddleware>(customIngredient); } } }
Add empty inputhandlers list for headless execution.
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Input; using osu.Framework.Statistics; namespace osu.Framework.OS { /// <summary> /// A GameHost which doesn't require a graphical or sound device. /// </summary> public class HeadlessGameHost : BasicGameHost { public override GLControl GLControl => null; public override bool IsActive => true; public override TextInputSource TextInput => null; protected override void DrawFrame() { //we can't draw. } public override void Run() { while (!ExitRequested) { UpdateMonitor.NewFrame(); using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Scheduler)) { UpdateScheduler.Update(); } using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Update)) { UpdateSubTree(); using (var buffer = DrawRoots.Get(UsageType.Write)) buffer.Object = GenerateDrawNodeSubtree(buffer.Object); } using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Sleep)) { UpdateClock.ProcessFrame(); } } } } }
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Input; using osu.Framework.Input.Handlers; using osu.Framework.Statistics; namespace osu.Framework.OS { /// <summary> /// A GameHost which doesn't require a graphical or sound device. /// </summary> public class HeadlessGameHost : BasicGameHost { public override GLControl GLControl => null; public override bool IsActive => true; public override TextInputSource TextInput => null; protected override void DrawFrame() { //we can't draw. } public override void Run() { while (!ExitRequested) { UpdateMonitor.NewFrame(); using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Scheduler)) { UpdateScheduler.Update(); } using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Update)) { UpdateSubTree(); using (var buffer = DrawRoots.Get(UsageType.Write)) buffer.Object = GenerateDrawNodeSubtree(buffer.Object); } using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Sleep)) { UpdateClock.ProcessFrame(); } } } public override IEnumerable<InputHandler> GetInputHandlers() => new InputHandler[] { }; } }
Increase version number to 0.1.0.0.
using System; using System.Reflection; using System.Runtime.InteropServices; //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.225 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: AssemblyProductAttribute("Gitnub: Automated Tasks for Github")] [assembly: AssemblyCompanyAttribute("Tall Ambitions LLC")] [assembly: AssemblyCopyrightAttribute("Copyright 2011 Tall Ambitions LLC, and contributors")] [assembly: AssemblyVersionAttribute("0.0.0.0")] [assembly: AssemblyFileVersionAttribute("0.0.0.0")] [assembly: ComVisibleAttribute(false)] [assembly: CLSCompliantAttribute(true)]
using System; using System.Reflection; using System.Runtime.InteropServices; //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.225 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: AssemblyProductAttribute("Gitnub: Automated Tasks for Github")] [assembly: AssemblyCompanyAttribute("Tall Ambitions LLC")] [assembly: AssemblyCopyrightAttribute("Copyright 2011 Tall Ambitions LLC, and contributors")] [assembly: AssemblyVersionAttribute("0.1.0.0")] [assembly: AssemblyFileVersionAttribute("0.1.0.0")] [assembly: ComVisibleAttribute(false)] [assembly: CLSCompliantAttribute(true)]
Add short name for Worst Segments
using System.Collections.Generic; namespace LiveSplit.Model.Comparisons { public class StandardComparisonGeneratorsFactory : IComparisonGeneratorsFactory { static StandardComparisonGeneratorsFactory() { CompositeComparisons.AddShortComparisonName(BestSegmentsComparisonGenerator.ComparisonName, BestSegmentsComparisonGenerator.ShortComparisonName); CompositeComparisons.AddShortComparisonName(Run.PersonalBestComparisonName, "PB"); CompositeComparisons.AddShortComparisonName(AverageSegmentsComparisonGenerator.ComparisonName, AverageSegmentsComparisonGenerator.ShortComparisonName); CompositeComparisons.AddShortComparisonName(PercentileComparisonGenerator.ComparisonName, PercentileComparisonGenerator.ShortComparisonName); } public IEnumerable<IComparisonGenerator> Create(IRun run) { yield return new BestSegmentsComparisonGenerator(run); yield return new AverageSegmentsComparisonGenerator(run); } public IEnumerable<IComparisonGenerator> GetAllGenerators(IRun run) { yield return new BestSegmentsComparisonGenerator(run); yield return new BestSplitTimesComparisonGenerator(run); yield return new AverageSegmentsComparisonGenerator(run); yield return new WorstSegmentsComparisonGenerator(run); yield return new PercentileComparisonGenerator(run); yield return new NoneComparisonGenerator(run); } } }
using System.Collections.Generic; namespace LiveSplit.Model.Comparisons { public class StandardComparisonGeneratorsFactory : IComparisonGeneratorsFactory { static StandardComparisonGeneratorsFactory() { CompositeComparisons.AddShortComparisonName(BestSegmentsComparisonGenerator.ComparisonName, BestSegmentsComparisonGenerator.ShortComparisonName); CompositeComparisons.AddShortComparisonName(Run.PersonalBestComparisonName, "PB"); CompositeComparisons.AddShortComparisonName(AverageSegmentsComparisonGenerator.ComparisonName, AverageSegmentsComparisonGenerator.ShortComparisonName); CompositeComparisons.AddShortComparisonName(WorstSegmentsComparisonGenerator.ComparisonName, WorstSegmentsComparisonGenerator.ShortComparisonName); CompositeComparisons.AddShortComparisonName(PercentileComparisonGenerator.ComparisonName, PercentileComparisonGenerator.ShortComparisonName); } public IEnumerable<IComparisonGenerator> Create(IRun run) { yield return new BestSegmentsComparisonGenerator(run); yield return new AverageSegmentsComparisonGenerator(run); } public IEnumerable<IComparisonGenerator> GetAllGenerators(IRun run) { yield return new BestSegmentsComparisonGenerator(run); yield return new BestSplitTimesComparisonGenerator(run); yield return new AverageSegmentsComparisonGenerator(run); yield return new WorstSegmentsComparisonGenerator(run); yield return new PercentileComparisonGenerator(run); yield return new NoneComparisonGenerator(run); } } }
Correct compie time constant to be NET46
namespace Microsoft.ApplicationInsights.AspNetCore.Tests.ContextInitializers { using System; using System.Globalization; using System.Net; using System.Net.NetworkInformation; using Helpers; using Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.AspNetCore.Http; using Xunit; public class DomainNameRoleInstanceTelemetryInitializerTests { private const string TestListenerName = "TestListener"; [Fact] public void RoleInstanceNameIsSetToDomainAndHost() { var source = new DomainNameRoleInstanceTelemetryInitializer(); var requestTelemetry = new RequestTelemetry(); source.Initialize(requestTelemetry); string hostName = Dns.GetHostName(); #if net46 string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName; if (hostName.EndsWith(domainName, StringComparison.OrdinalIgnoreCase) == false) { hostName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", hostName, domainName); } #endif Assert.Equal(hostName, requestTelemetry.Context.Cloud.RoleInstance); } [Fact] public void ContextInitializerDoesNotOverrideMachineName() { var source = new DomainNameRoleInstanceTelemetryInitializer(); var requestTelemetry = new RequestTelemetry(); requestTelemetry.Context.Cloud.RoleInstance = "Test"; source.Initialize(requestTelemetry); Assert.Equal("Test", requestTelemetry.Context.Cloud.RoleInstance); } } }
namespace Microsoft.ApplicationInsights.AspNetCore.Tests.ContextInitializers { using System; using System.Globalization; using System.Net; using System.Net.NetworkInformation; using Helpers; using Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.AspNetCore.Http; using Xunit; public class DomainNameRoleInstanceTelemetryInitializerTests { private const string TestListenerName = "TestListener"; [Fact] public void RoleInstanceNameIsSetToDomainAndHost() { var source = new DomainNameRoleInstanceTelemetryInitializer(); var requestTelemetry = new RequestTelemetry(); source.Initialize(requestTelemetry); string hostName = Dns.GetHostName(); #if NET46 string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName; if (hostName.EndsWith(domainName, StringComparison.OrdinalIgnoreCase) == false) { hostName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", hostName, domainName); } #endif Assert.Equal(hostName, requestTelemetry.Context.Cloud.RoleInstance); } [Fact] public void ContextInitializerDoesNotOverrideMachineName() { var source = new DomainNameRoleInstanceTelemetryInitializer(); var requestTelemetry = new RequestTelemetry(); requestTelemetry.Context.Cloud.RoleInstance = "Test"; source.Initialize(requestTelemetry); Assert.Equal("Test", requestTelemetry.Context.Cloud.RoleInstance); } } }
Move more stuff to superclass
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectronicCash { public abstract class BaseActor { public string Name { get; set; } public Guid ActorGuid { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectronicCash { /// <summary> /// The base actor abstracts all common properties of our actors (mainly Bank, Merchant, Customer) /// </summary> public abstract class BaseActor { public string Name { get; set; } public Guid ActorGuid { get; set; } public Int32 Money { get; set; } public Dictionary<Guid, List<MoneyOrder>> Ledger { get; private set; } } }
Add environment check to determine architecture
using System; using System.Linq; namespace CefSharp.Example { public static class CefExample { public const string DefaultUrl = "custom://cefsharp/BindingTest.html"; // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work. private const bool debuggingSubProcess = true; public static void Init() { var settings = new CefSettings(); settings.RemoteDebuggingPort = 8088; //settings.CefCommandLineArgs.Add("renderer-process-limit", "1"); //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog"); if (debuggingSubProcess) { settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\x86\\Debug\\CefSharp.BrowserSubprocess.exe"; } settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeName, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory() }); if (!Cef.Initialize(settings)) { if (Environment.GetCommandLineArgs().Contains("--type=renderer")) { Environment.Exit(0); } else { return; } } } } }
using System; using System.Linq; namespace CefSharp.Example { public static class CefExample { public const string DefaultUrl = "custom://cefsharp/BindingTest.html"; // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work. private const bool debuggingSubProcess = true; public static void Init() { var settings = new CefSettings(); settings.RemoteDebuggingPort = 8088; //settings.CefCommandLineArgs.Add("renderer-process-limit", "1"); //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog"); if (debuggingSubProcess) { var architecture = Environment.Is64BitProcess ? "x64" : "x86"; settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe"; } settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeName, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory() }); if (!Cef.Initialize(settings)) { if (Environment.GetCommandLineArgs().Contains("--type=renderer")) { Environment.Exit(0); } else { return; } } } } }
Include version to get e.g ReSharper happy.
using System.Reflection; #if DEBUG [assembly: AssemblyProduct("Ensure.That (Debug)")] [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyProduct("Ensure.That (Release)")] [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyDescription("Yet another guard clause project.")] [assembly: AssemblyCompany("Daniel Wertheim")] [assembly: AssemblyCopyright("Copyright © Daniel Wertheim")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("0.0.0.0")] [assembly: AssemblyFileVersion("0.0.0.0")]
using System.Reflection; #if DEBUG [assembly: AssemblyProduct("Ensure.That (Debug)")] [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyProduct("Ensure.That (Release)")] [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyDescription("Yet another guard clause project.")] [assembly: AssemblyCompany("Daniel Wertheim")] [assembly: AssemblyCopyright("Copyright © Daniel Wertheim")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("0.10.1.*")] [assembly: AssemblyFileVersion("0.10.1")]
Fix poorly written test (sorry).
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace Moq.Tests { public class ExtensionsFixture { [Fact] public void IsMockeableReturnsFalseForValueType() { Assert.False(typeof(int).IsMockeable()); } // [Fact] // public void OnceDoesNotThrowOnSecondCallIfCountWasResetBefore() // { // var mock = new Mock<IFooReset>(); // mock.Setup(foo => foo.Execute("ping")) // .Returns("ack") // .AtMostOnce(); // Assert.Equal("ack", mock.Object.Execute("ping")); // mock.ResetAllCalls(); // Assert.DoesNotThrow(() => mock.Object.Execute("ping")); // } } public interface IFooReset { object Execute(string ping); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace Moq.Tests { public class ExtensionsFixture { #region Public Methods [Fact] public void IsMockeableReturnsFalseForValueType() { Assert.False(typeof(int).IsMockeable()); } [Fact] public void OnceDoesNotThrowOnSecondCallIfCountWasResetBefore() { var mock = new Mock<IFooReset>(); mock.Setup(foo => foo.Execute("ping")).Returns("ack"); mock.Object.Execute("ping"); mock.ResetAllCalls(); mock.Object.Execute("ping"); mock.Verify(o => o.Execute("ping"), Times.Once()); } #endregion } public interface IFooReset { #region Public Methods object Execute(string ping); #endregion } }
Support remote scripts with empty/null Content Type
using System; using System.IO; using System.IO.Compression; using System.Net.Http; using System.Threading.Tasks; namespace Dotnet.Script.Core { public class ScriptDownloader { public async Task<string> Download(string uri) { using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead)) { response.EnsureSuccessStatusCode(); using (HttpContent content = response.Content) { var mediaType = content.Headers.ContentType.MediaType?.ToLowerInvariant().Trim(); switch (mediaType) { case null: case "": case "text/plain": return await content.ReadAsStringAsync(); case "application/gzip": case "application/x-gzip": using (var stream = await content.ReadAsStreamAsync()) using (var gzip = new GZipStream(stream, CompressionMode.Decompress)) using (var reader = new StreamReader(gzip)) return await reader.ReadToEndAsync(); default: throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https"); } } } } } } }
using System; using System.IO; using System.IO.Compression; using System.Net.Http; using System.Threading.Tasks; namespace Dotnet.Script.Core { public class ScriptDownloader { public async Task<string> Download(string uri) { using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead)) { response.EnsureSuccessStatusCode(); using (HttpContent content = response.Content) { var mediaType = content.Headers.ContentType?.MediaType?.ToLowerInvariant().Trim(); switch (mediaType) { case null: case "": case "text/plain": return await content.ReadAsStringAsync(); case "application/gzip": case "application/x-gzip": using (var stream = await content.ReadAsStreamAsync()) using (var gzip = new GZipStream(stream, CompressionMode.Decompress)) using (var reader = new StreamReader(gzip)) return await reader.ReadToEndAsync(); default: throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https"); } } } } } } }
Add bio and Github profile
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MartijnVanDijk : IAmAMicrosoftMVP, IAmAXamarinMVP { public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://medium.com/feed/@martijn00"); } } public string FirstName => "Martijn"; public string LastName => "Van Dijk"; public string StateOrRegion => "Amsterdam, Netherlands"; public string EmailAddress => "mhvdijk@gmail.com"; public string ShortBioOrTagLine => ""; public Uri WebSite => new Uri("https://medium.com/@martijn00"); public string TwitterHandle => "mhvdijk"; public string GravatarHash => "22155f520ab611cf04f76762556ca3f5"; public string GitHubHandle => string.Empty; public GeoPosition Position => new GeoPosition(52.3702160, 4.8951680); } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MartijnVanDijk : IAmAMicrosoftMVP, IAmAXamarinMVP { public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://medium.com/feed/@martijn00"); } } public string FirstName => "Martijn"; public string LastName => "Van Dijk"; public string StateOrRegion => "Amsterdam, Netherlands"; public string EmailAddress => "mhvdijk@gmail.com"; public string ShortBioOrTagLine => "is a Xamarin and Microsoft MVP working with MvvmCross"; public Uri WebSite => new Uri("https://medium.com/@martijn00"); public string TwitterHandle => "mhvdijk"; public string GravatarHash => "22155f520ab611cf04f76762556ca3f5"; public string GitHubHandle => "martijn00"; public GeoPosition Position => new GeoPosition(52.3702160, 4.8951680); } }
Use a type converter to try and convert values
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Internals.Mapping { using System; using Reflection; public class NullableValueObjectMapper<T, TValue> : IObjectMapper<T> where TValue : struct { readonly ReadWriteProperty<T> _property; public NullableValueObjectMapper(ReadWriteProperty<T> property) { _property = property; } public void ApplyTo(T obj, IObjectValueProvider valueProvider) { object value; if (valueProvider.TryGetValue(_property.Property.Name, out value)) { TValue? nullableValue = value as TValue?; if (!nullableValue.HasValue) nullableValue = (TValue)Convert.ChangeType(value, typeof(TValue)); _property.Set(obj, nullableValue); } } } }
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Internals.Mapping { using System; using System.ComponentModel; using Reflection; public class NullableValueObjectMapper<T, TValue> : IObjectMapper<T> where TValue : struct { readonly ReadWriteProperty<T> _property; public NullableValueObjectMapper(ReadWriteProperty<T> property) { _property = property; } public void ApplyTo(T obj, IObjectValueProvider valueProvider) { object value; if (valueProvider.TryGetValue(_property.Property.Name, out value)) { TValue? nullableValue = null; if (value != null) { var converter = TypeDescriptor.GetConverter(typeof(TValue)); nullableValue = converter.CanConvertFrom(value.GetType()) ? (TValue)converter.ConvertFrom(value) : default(TValue?); } _property.Set(obj, nullableValue); } } } }
Remove no longer required SDL2 P/Invokes in Linux clipboard
// 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.Runtime.InteropServices; namespace osu.Framework.Platform.Linux.SDL2 { public class SDL2Clipboard : Clipboard { private const string lib = "libSDL2.so"; [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_free", ExactSpelling = true)] internal static extern void SDL_free(IntPtr ptr); /// <returns>Returns the clipboard text on success or <see cref="IntPtr.Zero"/> on failure. </returns> [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)] internal static extern IntPtr SDL_GetClipboardText(); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)] internal static extern int SDL_SetClipboardText(string text); public override string GetText() { IntPtr ptrToText = SDL_GetClipboardText(); string text = Marshal.PtrToStringAnsi(ptrToText); SDL_free(ptrToText); return text; } public override void SetText(string selectedText) { SDL_SetClipboardText(selectedText); } } }
// 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 SDL2; namespace osu.Framework.Platform.Linux.SDL2 { public class SDL2Clipboard : Clipboard { public override string GetText() => SDL.SDL_GetClipboardText(); public override void SetText(string selectedText) => SDL.SDL_SetClipboardText(selectedText); } }
Store OOP server persistence database in a different file.
// 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.Collections.Generic; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Remote.Storage { [ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared] [Export(typeof(RemotePersistentStorageLocationService))] internal class RemotePersistentStorageLocationService : IPersistentStorageLocationService { private static readonly object _gate = new object(); private static readonly Dictionary<SolutionId, string> _idToStorageLocation = new Dictionary<SolutionId, string>(); public string GetStorageLocation(Solution solution) { string result; _idToStorageLocation.TryGetValue(solution.Id, out result); return result; } public bool IsSupported(Workspace workspace) { lock (_gate) { return _idToStorageLocation.ContainsKey(workspace.CurrentSolution.Id); } } public static void UpdateStorageLocation(SolutionId id, string storageLocation) { lock (_gate) { _idToStorageLocation[id] = storageLocation; } } } }
// 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.Collections.Generic; using System.Composition; using System.IO; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Remote.Storage { [ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared] [Export(typeof(RemotePersistentStorageLocationService))] internal class RemotePersistentStorageLocationService : IPersistentStorageLocationService { private static readonly object _gate = new object(); private static readonly Dictionary<SolutionId, string> _idToStorageLocation = new Dictionary<SolutionId, string>(); public string GetStorageLocation(Solution solution) { string result; _idToStorageLocation.TryGetValue(solution.Id, out result); return result; } public bool IsSupported(Workspace workspace) { lock (_gate) { return _idToStorageLocation.ContainsKey(workspace.CurrentSolution.Id); } } public static void UpdateStorageLocation(SolutionId id, string storageLocation) { lock (_gate) { // Store the esent database in a different location for the out of proc server. _idToStorageLocation[id] = Path.Combine(storageLocation, "Server"); } } } }
Update Disqus partial to use node name for the page title configuration variable
@inherits UmbracoViewPage<IMaster> <div id="disqus_thread"></div> <script> var disqus_config = function () { this.page.url = '@Umbraco.NiceUrlWithDomain(Model.Id)'; this.page.identifier = '@Model.Id'; this.page.title = '@Model.SeoMetadata.Title'; }; (function () { var d = document, s = d.createElement('script'); s.src = '//stevenhar-land.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); }()); </script>
@inherits UmbracoViewPage<IPublishedContent> <div id="disqus_thread"></div> <script> var disqus_config = function () { this.page.url = '@Umbraco.NiceUrlWithDomain(Model.Id)'; this.page.identifier = '@Model.Id'; this.page.title = '@Model.Name'; }; (function () { var d = document, s = d.createElement('script'); s.src = '//stevenhar-land.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); }()); </script>
Fix assembly metadata to fix package verifier warnings
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Net.WebSockets")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [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("9a9e41ae-1494-4d87-a66f-a4019ff68ce5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")] [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyProduct("Microsoft ASP.NET Core")]
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft.Net.WebSockets")] [assembly: ComVisible(false)] [assembly: Guid("9a9e41ae-1494-4d87-a66f-a4019ff68ce5")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")] [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyProduct("Microsoft ASP.NET Core")]
Change char to byte in gaf frame header
namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public char Unknown1; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(Stream f, ref GafFrameData e) { BinaryReader b = new BinaryReader(f); e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.Unknown1 = b.ReadChar(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public byte Unknown1; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(Stream f, ref GafFrameData e) { BinaryReader b = new BinaryReader(f); e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.Unknown1 = b.ReadByte(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
Update 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> /// <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 questions = _dbContext.SingleMultipleAnswerQuestion.ToList(); return questions; } /// <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(); } } }