commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13 values | lang stringclasses 23 values |
|---|---|---|---|---|---|---|---|---|
8382881127d2384848d24bbf8a12925ddd365e65 | Remove requirement for [schema_owner] = 'dbo' | Seddryck/NBi,Seddryck/NBi | NBi.Core/Structure/Relational/Builders/SchemaDiscoveryCommandBuilder.cs | NBi.Core/Structure/Relational/Builders/SchemaDiscoveryCommandBuilder.cs | using NBi.Core.Structure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Structure.Relational.Builders
{
class SchemaDiscoveryCommandBuilder : RelationalDiscoveryCommandBuilder
{
protected override string BasicCommandText
{
get { return base.BasicCommandText; }
}
public SchemaDiscoveryCommandBuilder()
{
CaptionName = "schema";
TableName = "schemata";
}
protected override IEnumerable<ICommandFilter> BuildCaptionFilters(IEnumerable<CaptionFilter> filters)
{
var filter = filters.SingleOrDefault(f => f.Target == Target.Perspectives);
if (filter != null)
yield return new CommandFilter(string.Format("[schema_name]='{0}'"
, filter.Caption
));
}
}
}
| using NBi.Core.Structure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Structure.Relational.Builders
{
class SchemaDiscoveryCommandBuilder : RelationalDiscoveryCommandBuilder
{
protected override string BasicCommandText
{
get { return base.BasicCommandText + " and [schema_owner]='dbo'"; }
}
public SchemaDiscoveryCommandBuilder()
{
CaptionName = "schema";
TableName = "schemata";
}
protected override IEnumerable<ICommandFilter> BuildCaptionFilters(IEnumerable<CaptionFilter> filters)
{
var filter = filters.SingleOrDefault(f => f.Target == Target.Perspectives);
if (filter != null)
yield return new CommandFilter(string.Format("[schema_name]='{0}'"
, filter.Caption
));
}
}
}
| apache-2.0 | C# |
521105a378324a9a0bd0751615ec52aa4155ec21 | Update DisabledFacetTest.cs | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | NakedFramework/NakedFramework.Metamodel.Test/Facet/DisabledFacetTest.cs | NakedFramework/NakedFramework.Metamodel.Test/Facet/DisabledFacetTest.cs | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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.VisualStudio.TestTools.UnitTesting;
using Moq;
using NakedFramework;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.interactions;
using NakedFramework.Core.Exception;
using NakedObjects.Meta.Facet;
namespace NakedObjects.Metamodel.Test.Facet {
[TestClass]
public class DisabledFacetTest {
[TestMethod]
public void TestDisabledFacetAlways() {
IDisabledFacet facet = new DisabledFacetAlways(null);
Assert.AreEqual(Resources.NakedObjects.AlwaysDisabled, facet.DisabledReason(null));
}
[TestMethod]
public void TestDisabledFacetAnnotationAlways() {
IDisabledFacet facet = new DisabledFacetAnnotation(WhenTo.Always, null);
Assert.AreEqual(Resources.NakedObjects.AlwaysDisabled, facet.DisabledReason(null));
}
[TestMethod]
public void TestDisabledFacetAnnotationNever() {
IDisabledFacet facet = new DisabledFacetAnnotation(WhenTo.Never, null);
Assert.IsNull(facet.DisabledReason(null));
}
private static INakedObjectAdapter Mock(object obj) {
var mockParm = new Mock<INakedObjectAdapter>();
mockParm.Setup(p => p.Object).Returns(obj);
return mockParm.Object;
}
[TestMethod]
public void TestDisabledFacetAnnotationAsInteraction() {
IDisablingInteractionAdvisor facet = new DisabledFacetAnnotation(WhenTo.Never, null);
var target = Mock(new object());
var mockIc = new Mock<IInteractionContext>();
mockIc.Setup(ic => ic.Target).Returns(target);
var e = facet.CreateExceptionFor(mockIc.Object);
Assert.IsInstanceOfType(e, typeof(DisabledException));
Assert.AreEqual("Exception of type 'NakedFramework.Core.Exception.DisabledException' was thrown.", e.Message);
}
}
} | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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.VisualStudio.TestTools.UnitTesting;
using Moq;
using NakedFramework;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.interactions;
using NakedFramework.Core.Exception;
using NakedObjects.Meta.Facet;
namespace NakedObjects.Metamodel.Test.Facet {
[TestClass]
public class DisabledFacetTest {
[TestMethod]
public void TestDisabledFacetAlways() {
IDisabledFacet facet = new DisabledFacetAlways(null);
Assert.AreEqual(Resources.NakedObjects.AlwaysDisabled, facet.DisabledReason(null));
}
[TestMethod]
public void TestDisabledFacetAnnotationAlways() {
IDisabledFacet facet = new DisabledFacetAnnotation(WhenTo.Always, null);
Assert.AreEqual(Resources.NakedObjects.AlwaysDisabled, facet.DisabledReason(null));
}
[TestMethod]
public void TestDisabledFacetAnnotationNever() {
IDisabledFacet facet = new DisabledFacetAnnotation(WhenTo.Never, null);
Assert.IsNull(facet.DisabledReason(null));
}
private static INakedObjectAdapter Mock(object obj) {
var mockParm = new Mock<INakedObjectAdapter>();
mockParm.Setup(p => p.Object).Returns(obj);
return mockParm.Object;
}
[TestMethod]
public void TestDisabledFacetAnnotationAsInteraction() {
IDisablingInteractionAdvisor facet = new DisabledFacetAnnotation(WhenTo.Never, null);
var target = Mock(new object());
var mockIc = new Mock<IInteractionContext>();
mockIc.Setup(ic => ic.Target).Returns(target);
var e = facet.CreateExceptionFor(mockIc.Object);
Assert.IsInstanceOfType(e, typeof(DisabledException));
Assert.AreEqual("Exception of type 'NakedFramework.Core.DisabledException' was thrown.", e.Message);
}
}
} | apache-2.0 | C# |
e53896d604476baa9af2d0befe104dcd1df967a9 | Add space before hint. (#7966) | stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2 | src/OrchardCore.Modules/OrchardCore.Users/Views/UserFields.cshtml | src/OrchardCore.Modules/OrchardCore.Users/Views/UserFields.cshtml | @model SummaryAdminUserViewModel
<h5 class="float-left">@Model.User.UserName <span class="hint dashed">@Model.User.Email</span></h5>
@if (!Model.User.IsEnabled)
{
<span class="badge badge-danger ml-2" title="@T["Disabled"]">
<i class="fas fa-user-alt-slash"></i> @T["Disabled"]
</span>
}
| @model SummaryAdminUserViewModel
<h5 class="float-left">@Model.User.UserName<span class="hint dashed">@Model.User.Email</span></h5>
@if (!Model.User.IsEnabled)
{
<span class="badge badge-danger ml-2" title="@T["Disabled"]">
<i class="fas fa-user-alt-slash"></i> @T["Disabled"]
</span>
}
| bsd-3-clause | C# |
8ca9c442fd2c05a8fa6bf9c34a28762c333b6af2 | allow domaineventbus without eventsubscriberprovider | IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework | Src/iFramework.Plugins/iFramework.MessageQueue.ZeroMQ/DomainEventBus.cs | Src/iFramework.Plugins/iFramework.MessageQueue.ZeroMQ/DomainEventBus.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IFramework.Infrastructure;
using IFramework.Message;
using IFramework.Message.Impl;
using System.Collections;
using IFramework.Event;
using System.Collections.Concurrent;
using IFramework.MessageQueue.MessageFormat;
namespace IFramework.MessageQueue.ZeroMQ
{
public class DomainEventBus : IDomainEventBus
{
protected ConcurrentQueue<IMessageContext> DomainEventContextQueue;
protected IEventSubscriberProvider EventSubscriberProvider { get; set; }
protected IEventPublisher EventPublisher { get; set; }
public DomainEventBus(IEventSubscriberProvider provider, IEventPublisher eventPublisher)
{
EventPublisher = eventPublisher;
EventSubscriberProvider = provider;
DomainEventContextQueue = new ConcurrentQueue<IMessageContext>();
}
public virtual void Commit()
{
EventPublisher.Publish(DomainEventContextQueue.ToArray());
}
public void Publish<TEvent>(TEvent @event) where TEvent : IDomainEvent
{
DomainEventContextQueue.Enqueue(new MessageContext(@event));
if (EventSubscriberProvider != null)
{
var eventSubscriberTypes = EventSubscriberProvider.GetHandlerTypes(@event.GetType());
eventSubscriberTypes.ForEach(eventSubscriberType =>
{
var eventSubscriber = IoCFactory.Resolve(eventSubscriberType);
((dynamic)eventSubscriber).Handle((dynamic)@event);
});
}
}
public void Publish<TEvent>(IEnumerable<TEvent> eventContexts) where TEvent : IDomainEvent
{
eventContexts.ForEach(@event => Publish(@event));
}
public virtual void Dispose()
{
}
public IEnumerable<IMessageContext> GetMessageContexts()
{
return DomainEventContextQueue;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IFramework.Infrastructure;
using IFramework.Message;
using IFramework.Message.Impl;
using System.Collections;
using IFramework.Event;
using System.Collections.Concurrent;
using IFramework.MessageQueue.MessageFormat;
namespace IFramework.MessageQueue.ZeroMQ
{
public class DomainEventBus : IDomainEventBus
{
protected ConcurrentQueue<IMessageContext> DomainEventContextQueue;
protected IEventSubscriberProvider EventSubscriberProvider { get; set; }
protected IEventPublisher EventPublisher { get; set; }
public DomainEventBus(IEventSubscriberProvider provider, IEventPublisher eventPublisher)
{
EventPublisher = eventPublisher;
EventSubscriberProvider = provider;
DomainEventContextQueue = new ConcurrentQueue<IMessageContext>();
}
public virtual void Commit()
{
EventPublisher.Publish(DomainEventContextQueue.ToArray());
}
public void Publish<TEvent>(TEvent @event) where TEvent : IDomainEvent
{
DomainEventContextQueue.Enqueue(new MessageContext(@event));
var eventSubscriberTypes = EventSubscriberProvider.GetHandlerTypes(@event.GetType());
eventSubscriberTypes.ForEach(eventSubscriberType =>
{
var eventSubscriber = IoCFactory.Resolve(eventSubscriberType);
((dynamic)eventSubscriber).Handle((dynamic)@event);
});
}
public void Publish<TEvent>(IEnumerable<TEvent> eventContexts) where TEvent : IDomainEvent
{
eventContexts.ForEach(@event => Publish(@event));
}
public virtual void Dispose()
{
}
public IEnumerable<IMessageContext> GetMessageContexts()
{
return DomainEventContextQueue;
}
}
}
| mit | C# |
10cc3798463ad445407962a5dd3d9804818131ad | Move FilterOperator outside of ApiFilter | CalebChalmers/KAGTools | KAGTools/Data/ApiFilter.cs | KAGTools/Data/ApiFilter.cs | using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KAGTools.Data
{
public struct ApiFilter
{
public ApiFilter(string field, object value, FilterOperator op = FilterOperator.eq)
{
Field = field;
Operator = op;
Value = value;
}
[JsonProperty("field")]
public string Field { get; }
[JsonProperty("op")]
public FilterOperator Operator { get; }
[JsonProperty("value")]
public object Value { get; }
}
[JsonConverter(typeof(StringEnumConverter))]
public enum FilterOperator
{
eq, // =
ne, // !=
le, // <=
lt, // <
ge, // >=
gt, // >
}
}
| using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KAGTools.Data
{
public struct ApiFilter
{
public ApiFilter(string field, object value, FilterOperator op = FilterOperator.eq)
{
Field = field;
Operator = op;
Value = value;
}
[JsonProperty("field")]
public string Field { get; }
[JsonProperty("op")]
public FilterOperator Operator { get; }
[JsonProperty("value")]
public object Value { get; }
}
[JsonConverter(typeof(StringEnumConverter))]
public enum FilterOperator
{
eq, // =
ne, // !=
le, // <=
lt, // <
ge, // >=
gt, // >
}
}
}
| mit | C# |
afa288582500903422eb57e227b838b82c4b0276 | Bump version to 0.5.0 | ar3cka/Journalist | src/SolutionInfo.cs | src/SolutionInfo.cs | // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.5.0")]
[assembly: AssemblyInformationalVersionAttribute("0.5.0")]
[assembly: AssemblyFileVersionAttribute("0.5.0")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.5.0";
}
}
| // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.4.0")]
[assembly: AssemblyInformationalVersionAttribute("0.4.0")]
[assembly: AssemblyFileVersionAttribute("0.4.0")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.4.0";
}
}
| apache-2.0 | C# |
d812262f32851691813a0566eaa5a8d43bcbc66c | Add store external tokens to OpenID Client recipe step (#10373) | xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2 | src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdClientSettingsStep.cs | src/OrchardCore.Modules/OrchardCore.OpenId/Recipes/OpenIdClientSettingsStep.cs | using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using OrchardCore.OpenId.Services;
using OrchardCore.OpenId.Settings;
using OrchardCore.Recipes.Models;
using OrchardCore.Recipes.Services;
namespace OrchardCore.OpenId.Recipes
{
/// <summary>
/// This recipe step sets general OpenID Connect Client settings.
/// </summary>
public class OpenIdClientSettingsStep : IRecipeStepHandler
{
private readonly IOpenIdClientService _clientService;
public OpenIdClientSettingsStep(IOpenIdClientService clientService)
{
_clientService = clientService;
}
public async Task ExecuteAsync(RecipeExecutionContext context)
{
if (!string.Equals(context.Name, "OpenIdClientSettings", StringComparison.OrdinalIgnoreCase))
{
return;
}
var model = context.Step.ToObject<OpenIdClientSettingsStepModel>();
var settings = await _clientService.LoadSettingsAsync();
settings.Scopes = model.Scopes.Split(' ', ',');
settings.Authority = !string.IsNullOrEmpty(model.Authority) ? new Uri(model.Authority, UriKind.Absolute) : null;
settings.CallbackPath = model.CallbackPath;
settings.ClientId = model.ClientId;
settings.ClientSecret = model.ClientSecret;
settings.DisplayName = model.DisplayName;
settings.ResponseMode = model.ResponseMode;
settings.ResponseType = model.ResponseType;
settings.SignedOutCallbackPath = model.SignedOutCallbackPath;
settings.SignedOutRedirectUri = model.SignedOutRedirectUri;
settings.StoreExternalTokens = model.StoreExternalTokens;
settings.Parameters = model.Parameters;
await _clientService.UpdateSettingsAsync(settings);
}
}
public class OpenIdClientSettingsStepModel
{
public string DisplayName { get; set; }
[Url]
public string Authority { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string CallbackPath { get; set; }
public string SignedOutRedirectUri { get; set; }
public string SignedOutCallbackPath { get; set; }
public string Scopes { get; set; }
public string ResponseType { get; set; }
public string ResponseMode { get; set; }
public bool StoreExternalTokens { get; set; }
public ParameterSetting[] Parameters { get; set; }
}
}
| using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using OrchardCore.OpenId.Services;
using OrchardCore.OpenId.Settings;
using OrchardCore.Recipes.Models;
using OrchardCore.Recipes.Services;
namespace OrchardCore.OpenId.Recipes
{
/// <summary>
/// This recipe step sets general OpenID Connect Client settings.
/// </summary>
public class OpenIdClientSettingsStep : IRecipeStepHandler
{
private readonly IOpenIdClientService _clientService;
public OpenIdClientSettingsStep(IOpenIdClientService clientService)
{
_clientService = clientService;
}
public async Task ExecuteAsync(RecipeExecutionContext context)
{
if (!string.Equals(context.Name, "OpenIdClientSettings", StringComparison.OrdinalIgnoreCase))
{
return;
}
var model = context.Step.ToObject<OpenIdClientSettingsStepModel>();
var settings = await _clientService.LoadSettingsAsync();
settings.Scopes = model.Scopes.Split(' ', ',');
settings.Authority = !string.IsNullOrEmpty(model.Authority) ? new Uri(model.Authority, UriKind.Absolute) : null;
settings.CallbackPath = model.CallbackPath;
settings.ClientId = model.ClientId;
settings.ClientSecret = model.ClientSecret;
settings.DisplayName = model.DisplayName;
settings.ResponseMode = model.ResponseMode;
settings.ResponseType = model.ResponseType;
settings.SignedOutCallbackPath = model.SignedOutCallbackPath;
settings.SignedOutRedirectUri = model.SignedOutRedirectUri;
settings.Parameters = model.Parameters;
await _clientService.UpdateSettingsAsync(settings);
}
}
public class OpenIdClientSettingsStepModel
{
public string DisplayName { get; set; }
[Url]
public string Authority { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string CallbackPath { get; set; }
public string SignedOutRedirectUri { get; set; }
public string SignedOutCallbackPath { get; set; }
public string Scopes { get; set; }
public string ResponseType { get; set; }
public string ResponseMode { get; set; }
public ParameterSetting[] Parameters { get; set; }
}
}
| bsd-3-clause | C# |
92ff40930b7d4dd7be93f502a17cbfa1150bf42c | Update NinjectWebCommon.cs | TheDarkCode/SwiftDotNet,TheDarkCode/SwiftDotNet,TheDarkCode/SwiftDotNet | src/Server/WebAPI/net461/SwiftDotNet.WebAPI/SwiftDotNet.WebAPI/App_Start/NinjectWebCommon.cs | src/Server/WebAPI/net461/SwiftDotNet.WebAPI/SwiftDotNet.WebAPI/App_Start/NinjectWebCommon.cs | [assembly: WebActivatorEx.PreApplicationStartMethod(typeof(DryverlessAds.AffiliateApi.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(DryverlessAds.AffiliateApi.App_Start.NinjectWebCommon), "Stop")]
namespace DryverlessAds.AffiliateApi.App_Start
{
using System;
using System.Web;
using SwiftDotNet.WebAPI.Repositories;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using SwiftDotNet.WebAPI.Controllers.api;
using SwiftDotNet.WebAPI.Repositories;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
//kernel.Bind<DocumentDbClient>().ToSelf().InRequestScope();
kernel.Bind<IAnalyticRepository>().To<AnalyticRepository>().InRequestScope();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SwiftDotNet.WebAPI.App_Start
{
class NinjectWebCommon
{
}
}
| mit | C# |
ba00adc29348272e4f55a98efbf53cc7d292b32c | Enable middleware to extract trace from incoming request headers. | criteo/zipkin4net,criteo/zipkin4net | zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingMiddleware.cs | zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingMiddleware.cs | using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new ZipkinHttpTraceExtractor();
app.Use(async (context, next) => {
Trace trace;
if (!extractor.TryExtract(context.Request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
trace.Record(Annotations.ServerRecv());
trace.Record(Annotations.ServiceName(serviceName));
trace.Record(Annotations.Rpc(context.Request.Method));
await next.Invoke();
trace.Record(Annotations.ServerSend());
});
}
}
} | using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
app.Use(async (context, next) => {
var trace = Trace.Create();
Trace.Current = trace;
trace.Record(Annotations.ServerRecv());
trace.Record(Annotations.ServiceName(serviceName));
trace.Record(Annotations.Rpc(context.Request.Method));
await next.Invoke();
trace.Record(Annotations.ServerSend());
});
}
}
} | apache-2.0 | C# |
cdd70d134ca74df3c0a6e1a1c7234607a3f5a2e5 | Correct href in <see/> tag | mikebarker/Plethora.NET | src/Plethora.Common/MathEx.cs | src/Plethora.Common/MathEx.cs | using System;
namespace Plethora
{
public static class MathEx
{
/// <summary>
/// Returns the greatest common divisor of two numbers.
/// </summary>
/// <param name="a">The first number.</param>
/// <param name="b">The second number.</param>
/// <returns>The greatest common divisor of <paramref name="a"/> and <paramref name="b"/>.</returns>
/// <remarks>
/// This implementation uses the Euclidean algorithm.
/// <seealso href="https://en.wikipedia.org/wiki/Euclidean_algorithm"/>
/// </remarks>
public static int GreatestCommonDivisor(int a, int b)
{
a = Math.Abs(a);
b = Math.Abs(b);
while (b != 0)
{
int rem = a % b;
a = b;
b = rem;
}
return a;
}
}
}
| using System;
namespace Plethora
{
public static class MathEx
{
/// <summary>
/// Returns the greatest common divisor of two numbers.
/// </summary>
/// <param name="a">The first number.</param>
/// <param name="b">The second number.</param>
/// <returns>The greatest common divisor of <paramref name="a"/> and <paramref name="b"/>.</returns>
/// <remarks>
/// This implementation uses the Euclidean algorithm.
/// <seealso cref="https://en.wikipedia.org/wiki/Euclidean_algorithm"/>
/// </remarks>
public static int GreatestCommonDivisor(int a, int b)
{
a = Math.Abs(a);
b = Math.Abs(b);
while (b != 0)
{
int rem = a % b;
a = b;
b = rem;
}
return a;
}
}
}
| mit | C# |
af56e5c9f724aad319d86dd452644b0e891df2c3 | Throw an exception of [CallerMemberName] misbehaves. | orospakr/sharpify,orospakr/sharpify,orospakr/sharpify | ShopifyAPIAdapterLibrary/ShopifyAPIAdapterLibrary.Models/ShopifyResourceModel.cs | ShopifyAPIAdapterLibrary/ShopifyAPIAdapterLibrary.Models/ShopifyResourceModel.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace ShopifyAPIAdapterLibrary.Models
{
public class ShopifyResourceModel : IResourceModel
{
public event PropertyChangedEventHandler PropertyChanged;
private HashSet<string> Dirty;
public void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = null)
{
if (name == null)
{
throw new ShopifyConfigurationException("Field name is coming up null in SetProperty. Something's wrong.");
}
Console.WriteLine("SETTING PROPERTY {0} to {1}", name, value);
// thanks to http://danrigby.com/2012/03/01/inotifypropertychanged-the-net-4-5-way/
if (!EqualityComparer<T>.Default.Equals(field, value))
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
field = value;
Dirty.Add(name);
}
}
public void Reset()
{
Dirty.Clear();
}
public bool IsFieldDirty(string field)
{
return Dirty.Contains(field);
}
public bool IsClean()
{
return Dirty.Count == 0;
}
private int? id;
public int? Id
{
get { return id; }
set
{
SetProperty(ref id, value);
}
}
public ShopifyResourceModel()
{
Dirty = new HashSet<string>();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace ShopifyAPIAdapterLibrary.Models
{
public class ShopifyResourceModel : IResourceModel
{
public event PropertyChangedEventHandler PropertyChanged;
private HashSet<string> Dirty;
public void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = "")
{
// thanks to http://danrigby.com/2012/03/01/inotifypropertychanged-the-net-4-5-way/
if (!EqualityComparer<T>.Default.Equals(field, value))
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
field = value;
Dirty.Add(name);
}
}
public void Reset()
{
Dirty.Clear();
}
public bool IsFieldDirty(string field)
{
return Dirty.Contains(field);
}
public bool IsClean()
{
return Dirty.Count == 0;
}
private int? id;
public int? Id
{
get { return id; }
set
{
SetProperty(ref id, value);
}
}
public ShopifyResourceModel()
{
Dirty = new HashSet<string>();
}
}
}
| mit | C# |
dcf3ae5765dc5ce9eb39ae4cbdf7d5c47ee74f9c | Reduce exposure of public API | oliver-feng/libgit2sharp,AArnott/libgit2sharp,nulltoken/libgit2sharp,AArnott/libgit2sharp,carlosmn/libgit2sharp,rcorre/libgit2sharp,dlsteuer/libgit2sharp,github/libgit2sharp,xoofx/libgit2sharp,mono/libgit2sharp,jeffhostetler/public_libgit2sharp,mono/libgit2sharp,psawey/libgit2sharp,Skybladev2/libgit2sharp,libgit2/libgit2sharp,vivekpradhanC/libgit2sharp,nulltoken/libgit2sharp,jamill/libgit2sharp,rcorre/libgit2sharp,whoisj/libgit2sharp,AMSadek/libgit2sharp,shana/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,red-gate/libgit2sharp,jamill/libgit2sharp,shana/libgit2sharp,github/libgit2sharp,paulcbetts/libgit2sharp,vorou/libgit2sharp,vorou/libgit2sharp,red-gate/libgit2sharp,dlsteuer/libgit2sharp,Zoxive/libgit2sharp,jorgeamado/libgit2sharp,OidaTiftla/libgit2sharp,oliver-feng/libgit2sharp,Skybladev2/libgit2sharp,carlosmn/libgit2sharp,whoisj/libgit2sharp,jorgeamado/libgit2sharp,AMSadek/libgit2sharp,sushihangover/libgit2sharp,psawey/libgit2sharp,GeertvanHorrik/libgit2sharp,jeffhostetler/public_libgit2sharp,sushihangover/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,vivekpradhanC/libgit2sharp,GeertvanHorrik/libgit2sharp,Zoxive/libgit2sharp,ethomson/libgit2sharp,PKRoma/libgit2sharp,ethomson/libgit2sharp,paulcbetts/libgit2sharp,OidaTiftla/libgit2sharp,xoofx/libgit2sharp | LibGit2Sharp/IndexEntry.cs | LibGit2Sharp/IndexEntry.cs | using System;
using System.Runtime.InteropServices;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
public class IndexEntry
{
public IndexEntryState State { get; private set; }
public string Path { get; private set; }
public ObjectId Id { get; private set; }
internal static IndexEntry CreateFromPtr(IntPtr ptr)
{
var entry = (GitIndexEntry) Marshal.PtrToStructure(ptr, typeof (GitIndexEntry));
return new IndexEntry
{
Path = entry.Path,
Id = new ObjectId(entry.oid),
};
}
}
} | using System;
using System.Runtime.InteropServices;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
public class IndexEntry
{
public IndexEntryState State { get; set; }
public string Path { get; private set; }
public ObjectId Id { get; private set; }
internal static IndexEntry CreateFromPtr(IntPtr ptr)
{
var entry = (GitIndexEntry) Marshal.PtrToStructure(ptr, typeof (GitIndexEntry));
return new IndexEntry
{
Path = entry.Path,
Id = new ObjectId(entry.oid),
};
}
}
} | mit | C# |
1bed1f68d3258b761370b02cf427557a8396edbe | Add settings for EmailServiceProducer. | LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform | src/CompetitionPlatform/Data/AzureRepositories/Settings/BaseSettings.cs | src/CompetitionPlatform/Data/AzureRepositories/Settings/BaseSettings.cs | using Lykke.EmailSenderProducer.Interfaces;
namespace CompetitionPlatform.Data.AzureRepositories.Settings
{
public class BaseSettings
{
public AzureSettings Azure { get; set; }
public AuthenticationSettings Authentication { get; set; }
public NotificationsSettings Notifications { get; set; }
public string EmailServiceBusSettingsUrl { get; set; }
}
public class AuthenticationSettings
{
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string PostLogoutRedirectUri { get; set; }
public string Authority { get; set; }
}
public class AzureSettings
{
public string StorageConnString { get; set; }
}
public class NotificationsSettings
{
public string EmailsQueueConnString { get; set; }
public string SlackQueueConnString { get; set; }
}
public class EmailServiceBusSettings
{
public EmailServiceBus EmailServiceBus;
}
public class EmailServiceBus : IServiceBusEmailSettings
{
public string Key { get; set; }
public string QueueName { get; set; }
public string NamespaceUrl { get; set; }
public string PolicyName { get; set; }
}
}
| namespace CompetitionPlatform.Data.AzureRepositories.Settings
{
public class BaseSettings
{
public AzureSettings Azure { get; set; }
public AuthenticationSettings Authentication { get; set; }
public NotificationsSettings Notifications { get; set; }
}
public class AuthenticationSettings
{
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string PostLogoutRedirectUri { get; set; }
public string Authority { get; set; }
}
public class AzureSettings
{
public string StorageConnString { get; set; }
}
public class NotificationsSettings
{
public string EmailsQueueConnString { get; set; }
public string SlackQueueConnString { get; set; }
}
}
| mit | C# |
2627b502f03415d25186c034a17038695dd7a84e | Update ValuesOut.cs | EricZimmerman/RegistryPlugins | RegistryPlugin.RunMRU/ValuesOut.cs | RegistryPlugin.RunMRU/ValuesOut.cs | using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.RunMRU
{
public class ValuesOut:IValueOut
{
public ValuesOut(string valueName, string executable, int mruPosition, DateTimeOffset? openedOn)
{
Executable = executable;
ValueName = valueName;
MruPosition = mruPosition;
OpenedOn = openedOn?.UtcDateTime;
}
public string ValueName { get; }
public int MruPosition { get; }
public string Executable { get; }
public DateTime? OpenedOn { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Executable: {Executable}";
public string BatchValueData2 => $"Opened on: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}";
public string BatchValueData3 => $"MRU: {MruPosition}";
}
} | using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.RunMRU
{
public class ValuesOut:IValueOut
{
public ValuesOut(string valueName, string executable, int mruPosition, DateTimeOffset? openedOn)
{
Executable = executable;
ValueName = valueName;
MruPosition = mruPosition;
OpenedOn = openedOn?.UtcDateTime;
}
public string ValueName { get; }
public int MruPosition { get; }
public string Executable { get; }
public DateTime? OpenedOn { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Executable: {Executable}";
public string BatchValueData2 => $"Opened on: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff} ";
public string BatchValueData3 => $"Mru: {MruPosition}";
}
} | mit | C# |
99cadd73d6e1de4d4661d9d167d2c79aabfd3351 | Fix workspace references in liveshare unit tests. | tannergooding/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,tmat/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,wvdd007/roslyn,gafter/roslyn,tmat/roslyn,mgoertz-msft/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,genlu/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,genlu/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,aelij/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,physhi/roslyn,AlekseyTs/roslyn,weltkante/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,brettfo/roslyn,agocke/roslyn,dotnet/roslyn,weltkante/roslyn,AlekseyTs/roslyn,sharwell/roslyn,reaction1989/roslyn,abock/roslyn,physhi/roslyn,physhi/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,diryboy/roslyn,KevinRansom/roslyn,aelij/roslyn,mgoertz-msft/roslyn,genlu/roslyn,abock/roslyn,tannergooding/roslyn,AmadeusW/roslyn,diryboy/roslyn,aelij/roslyn,reaction1989/roslyn,davkean/roslyn,CyrusNajmabadi/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,dotnet/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,davkean/roslyn,jmarolf/roslyn,diryboy/roslyn,mavasani/roslyn,abock/roslyn,gafter/roslyn,ErikSchierboom/roslyn,eriawan/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,heejaechang/roslyn,tannergooding/roslyn,reaction1989/roslyn,stephentoub/roslyn,mavasani/roslyn,AmadeusW/roslyn,davkean/roslyn,agocke/roslyn,gafter/roslyn,panopticoncentral/roslyn,AmadeusW/roslyn,panopticoncentral/roslyn,sharwell/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,agocke/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,dotnet/roslyn,KevinRansom/roslyn,tmat/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn | src/VisualStudio/LiveShare/Test/MockDocumentNavigationServiceFactory.cs | src/VisualStudio/LiveShare/Test/MockDocumentNavigationServiceFactory.cs | // 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.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests
{
using Workspace = CodeAnalysis.Workspace;
[Shared]
[ExportWorkspaceServiceFactory(typeof(IDocumentNavigationService), WorkspaceKind.Test)]
[PartNotDiscoverable]
internal class MockDocumentNavigationServiceFactory : IWorkspaceServiceFactory
{
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
return new MockDocumentNavigationService();
}
private class MockDocumentNavigationService : IDocumentNavigationService
{
public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset) => true;
public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0) => true;
public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan) => true;
public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options = null) => true;
public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0, OptionSet options = null) => true;
public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options = null) => true;
}
}
}
| // 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.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests
{
[Shared]
[ExportWorkspaceServiceFactory(typeof(IDocumentNavigationService), WorkspaceKind.Test)]
[PartNotDiscoverable]
internal class MockDocumentNavigationServiceFactory : IWorkspaceServiceFactory
{
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
return new MockDocumentNavigationService();
}
private class MockDocumentNavigationService : IDocumentNavigationService
{
public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset) => true;
public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0) => true;
public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan) => true;
public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options = null) => true;
public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0, OptionSet options = null) => true;
public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options = null) => true;
}
}
}
| mit | C# |
968ae02176be9c25a3678cbd46b6ff2785bcafed | Update Console Program with the Repository call - Update GetRoleMessage | penblade/Training.CSharpWorkshop | Training.CSharpWorkshop/Program.cs | Training.CSharpWorkshop/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Training.CSharpWorkshop
{
public class Program
{
public static void Main(string[] args)
{
Process();
}
public static void Process()
{
Console.WriteLine("Welcome to the C# Workshop.");
Console.WriteLine("Please enter your user name: ");
var userName = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("Hello " + userName + ".");
Console.WriteLine(GetRoleMessage(userName));
Console.WriteLine();
Console.WriteLine("Press enter to continue.");
Console.ReadLine();
}
public static string GetRoleMessage(string userName)
{
string role;
var repository = new Repository();
var user = repository.GetUserByName(userName);
if (user == null)
{
role = "None";
}
else if (user.Role == RoleEnum.Admin)
{
role = "Admin";
}
else
{
role = "Guest";
}
return String.Format("Role: {0}.", role);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Training.CSharpWorkshop
{
public class Program
{
public static void Main(string[] args)
{
Process();
}
public static void Process()
{
Console.WriteLine("Welcome to the C# Workshop.");
Console.WriteLine("Please enter your user name: ");
var userName = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("Hello " + userName + ".");
Console.WriteLine(GetRoleMessage(userName));
Console.WriteLine();
Console.WriteLine("Press enter to continue.");
Console.ReadLine();
}
public static string GetRoleMessage(string userName)
{
string role;
if (userName == "Andrew")
{
role = "Admin";
}
else
{
role = "Guest";
}
return String.Format("Role: {0}.", role);
}
}
}
| mit | C# |
a9e88207cb461f015554947a86e009f15fe0f8e7 | Update StaticCache_Tests.cs | hikalkan/samples,hikalkan/samples,hikalkan/samples,hikalkan/samples | SingletonVsStatic/SingletonVsStatic.StaticLib.Tests/StaticCache_Tests.cs | SingletonVsStatic/SingletonVsStatic.StaticLib.Tests/StaticCache_Tests.cs | using Xunit;
namespace SingletonVsStatic.StaticLib.Tests
{
public class StaticCache_Tests
{
static StaticCache_Tests()
{
StaticCache.Add("TestKey1", "TestValue1");
StaticCache.Add("TestKey2", "TestValue2");
}
[Fact]
public void Should_Contain_Initial_Values()
{
Assert.Equal(2, StaticCache.GetCount());
Assert.Equal("TestValue1", StaticCache.GetOrNull("TestKey1"));
Assert.Equal("TestValue2", StaticCache.GetOrNull("TestKey2"));
}
[Fact]
public void Should_Add_And_Get_Values()
{
StaticCache.Add("MyNumber", 42);
Assert.Equal(42, StaticCache.GetOrNull("MyNumber"));
}
[Fact]
public void Should_Increase_Count_When_A_New_Item_Added()
{
Assert.Equal(2, StaticCache.GetCount());
StaticCache.Add("TestKeyX", "X");
Assert.Equal(3, StaticCache.GetCount());
}
[Fact]
public void Clear_Should_Delete_All_Values()
{
StaticCache.Clear();
Assert.Equal(0, StaticCache.GetCount());
Assert.Null(StaticCache.GetOrNull("TestKey1"));
}
[Fact]
public void Should_Remove_Values()
{
StaticCache.Remove("TestKey1");
Assert.Null(StaticCache.GetOrNull("TestKey1"));
}
[Fact]
public void Should_Use_Factory_Only_If_The_Value_Was_Not_Present()
{
//The key is already present, so it doesn't use the factory to create a new one
Assert.Equal("TestValue1", StaticCache.GetOrAdd("TestKey1", () => "TestValue1_Changed"));
StaticCache.Remove("TestKey1");
//The key is not present, so it uses the factory to create a new one
Assert.Equal("TestValue1_Changed", StaticCache.GetOrAdd("TestKey1", () => "TestValue1_Changed"));
}
}
} | using Xunit;
namespace SingletonVsStatic.StaticLib.Tests
{
public class StaticCache_Tests
{
public StaticCache_Tests()
{
StaticCache.Add("TestKey1", "TestValue1");
StaticCache.Add("TestKey2", "TestValue2");
}
[Fact]
public void Should_Contain_Initial_Values()
{
Assert.Equal(2, StaticCache.GetCount());
Assert.Equal("TestValue1", StaticCache.GetOrNull("TestKey1"));
Assert.Equal("TestValue2", StaticCache.GetOrNull("TestKey2"));
}
[Fact]
public void Should_Add_And_Get_Values()
{
StaticCache.Add("MyNumber", 42);
Assert.Equal(42, StaticCache.GetOrNull("MyNumber"));
}
[Fact]
public void Should_Increase_Count_When_A_New_Item_Added()
{
Assert.Equal(2, StaticCache.GetCount());
StaticCache.Add("TestKeyX", "X");
Assert.Equal(3, StaticCache.GetCount());
}
[Fact]
public void Clear_Should_Delete_All_Values()
{
StaticCache.Clear();
Assert.Equal(0, StaticCache.GetCount());
Assert.Null(StaticCache.GetOrNull("TestKey1"));
}
[Fact]
public void Should_Remove_Values()
{
StaticCache.Remove("TestKey1");
Assert.Null(StaticCache.GetOrNull("TestKey1"));
}
[Fact]
public void Should_Use_Factory_Only_If_The_Value_Was_Not_Present()
{
//The key is already present, so it doesn't use the factory to create a new one
Assert.Equal("TestValue1", StaticCache.GetOrAdd("TestKey1", () => "TestValue1_Changed"));
StaticCache.Remove("TestKey1");
//The key is not present, so it uses the factory to create a new one
Assert.Equal("TestValue1_Changed", StaticCache.GetOrAdd("TestKey1", () => "TestValue1_Changed"));
}
}
} | mit | C# |
8f496095a9a42d5ada559ad3cb565511284ade70 | Change version to 0.9.0.0 for the premature build | chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TweetDick")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TweetDick")]
[assembly: AssemblyCopyright("")]
[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("7f09373d-8beb-416f-a48d-45d8aaeb8caf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TweetDick")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TweetDick")]
[assembly: AssemblyCopyright("")]
[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("7f09373d-8beb-416f-a48d-45d8aaeb8caf")]
// 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")]
| mit | C# |
da7464670c132ecb93d03580b15bdaad060a89c9 | Add ResolveByName attribute to StyledElement property | wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors | src/Avalonia.Xaml.Interactions/Custom/AddClassAction.cs | src/Avalonia.Xaml.Interactions/Custom/AddClassAction.cs | using Avalonia.Controls;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// Adds a specified <see cref="AddClassAction.ClassName"/> to the <see cref="IStyledElement.Classes"/> collection when invoked.
/// </summary>
public class AddClassAction : AvaloniaObject, IAction
{
/// <summary>
/// Identifies the <seealso cref="ClassName"/> avalonia property.
/// </summary>
public static readonly StyledProperty<string> ClassNameProperty =
AvaloniaProperty.Register<AddClassAction, string>(nameof(ClassName));
/// <summary>
/// Identifies the <seealso cref="StyledElement"/> avalonia property.
/// </summary>
public static readonly StyledProperty<IStyledElement?> StyledElementProperty =
AvaloniaProperty.Register<AddClassAction, IStyledElement?>(nameof(StyledElement));
/// <summary>
/// Identifies the <seealso cref="RemoveIfExists"/> avalonia property.
/// </summary>
public static readonly StyledProperty<bool> RemoveIfExistsProperty =
AvaloniaProperty.Register<AddClassAction, bool>(nameof(RemoveIfExists));
/// <summary>
/// Gets or sets the class name that should be added. This is a avalonia property.
/// </summary>
public string ClassName
{
get => GetValue(ClassNameProperty);
set => SetValue(ClassNameProperty, value);
}
/// <summary>
/// Gets or sets the target styled element that class name that should be added to. This is a avalonia property.
/// </summary>
[ResolveByName]
public IStyledElement? StyledElement
{
get => GetValue(StyledElementProperty);
set => SetValue(StyledElementProperty, value);
}
/// <summary>
/// Gets or sets the flag indicated whether to remove the class if already exists before adding. This is a avalonia property.
/// </summary>
public bool RemoveIfExists
{
get => GetValue(RemoveIfExistsProperty);
set => SetValue(RemoveIfExistsProperty, value);
}
/// <summary>
/// Executes the action.
/// </summary>
/// <param name="sender">The <see cref="object"/> that is passed to the action by the behavior. Generally this is <seealso cref="IBehavior.AssociatedObject"/> or a target object.</param>
/// <param name="parameter">The value of this parameter is determined by the caller.</param>
/// <returns>True if the class is successfully added; else false.</returns>
public object Execute(object? sender, object? parameter)
{
var target = GetValue(StyledElementProperty) is { } ? StyledElement : sender as IStyledElement;
if (target is null || string.IsNullOrEmpty(ClassName))
{
return false;
}
if (RemoveIfExists && target.Classes.Contains(ClassName))
{
target.Classes.Remove(ClassName);
}
target.Classes.Add(ClassName);
return true;
}
}
| using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// Adds a specified <see cref="AddClassAction.ClassName"/> to the <see cref="IStyledElement.Classes"/> collection when invoked.
/// </summary>
public class AddClassAction : AvaloniaObject, IAction
{
/// <summary>
/// Identifies the <seealso cref="ClassName"/> avalonia property.
/// </summary>
public static readonly StyledProperty<string> ClassNameProperty =
AvaloniaProperty.Register<AddClassAction, string>(nameof(ClassName));
/// <summary>
/// Identifies the <seealso cref="StyledElement"/> avalonia property.
/// </summary>
public static readonly StyledProperty<IStyledElement?> StyledElementProperty =
AvaloniaProperty.Register<AddClassAction, IStyledElement?>(nameof(StyledElement));
/// <summary>
/// Identifies the <seealso cref="RemoveIfExists"/> avalonia property.
/// </summary>
public static readonly StyledProperty<bool> RemoveIfExistsProperty =
AvaloniaProperty.Register<AddClassAction, bool>(nameof(RemoveIfExists));
/// <summary>
/// Gets or sets the class name that should be added. This is a avalonia property.
/// </summary>
public string ClassName
{
get => GetValue(ClassNameProperty);
set => SetValue(ClassNameProperty, value);
}
/// <summary>
/// Gets or sets the target styled element that class name that should be added to. This is a avalonia property.
/// </summary>
public IStyledElement? StyledElement
{
get => GetValue(StyledElementProperty);
set => SetValue(StyledElementProperty, value);
}
/// <summary>
/// Gets or sets the flag indicated whether to remove the class if already exists before adding. This is a avalonia property.
/// </summary>
public bool RemoveIfExists
{
get => GetValue(RemoveIfExistsProperty);
set => SetValue(RemoveIfExistsProperty, value);
}
/// <summary>
/// Executes the action.
/// </summary>
/// <param name="sender">The <see cref="object"/> that is passed to the action by the behavior. Generally this is <seealso cref="IBehavior.AssociatedObject"/> or a target object.</param>
/// <param name="parameter">The value of this parameter is determined by the caller.</param>
/// <returns>True if the class is successfully added; else false.</returns>
public object Execute(object? sender, object? parameter)
{
var target = GetValue(StyledElementProperty) is { } ? StyledElement : sender as IStyledElement;
if (target is null || string.IsNullOrEmpty(ClassName))
{
return false;
}
if (RemoveIfExists && target.Classes.Contains(ClassName))
{
target.Classes.Remove(ClassName);
}
target.Classes.Add(ClassName);
return true;
}
} | mit | C# |
874ceeca8a9fa6152a0b2d0f4faa91771613d5a8 | Update StartupSettings.cs | quartz-software/kephas,quartz-software/kephas | src/Kephas.Application/Configuration/StartupSettings.cs | src/Kephas.Application/Configuration/StartupSettings.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="StartupSettings.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Application.Configuration
{
using System.Collections.Generic;
/// <summary>
/// Settings for the application startup.
/// </summary>
public class StartupSettings
{
/// <summary>
/// Gets or sets the settings for the application instances.
/// </summary>
public IDictionary<string, AppInstanceSettings> Instances { get; set; } = new Dictionary<string, AppInstanceSettings>();
}
/// <summary>
/// Settings for the application instances.
/// </summary>
public class AppInstanceSettings
{
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="StartupSettings.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Application.Configuration
{
using System.Collections.Generic;
/// <summary>
/// Settings for the application startup.
/// </summary>
public class StartupSettings
{
/// <summary>
/// Gets or sets the settings for the application instances.
/// </summary>
IDictionary<string, AppInstanceSettings> Instances { get; set; } = new Dictionary<string, AppInstanceSettings>();
}
/// <summary>
/// Settings for the application instances.
/// </summary>
public class AppInstanceSettings
{
}
}
| mit | C# |
8f5c9f6b30d5b7d7ff1ecbcb0cae887c6092f34a | fix bug where bool props would always be set to true even if provided value of false | galaktor/autofac-extensions | CommandLine/Args/Prop.cs | CommandLine/Args/Prop.cs | // Copyright (c) 2013 Raphael Estrada
// License: The MIT License - see "LICENSE" file for details
// Author URL: http://www.galaktor.net
// Author E-Mail: galaktor@gmx.de
using System;
using System.Linq;
using System.Reflection;
using Autofac.Core;
namespace Autofac.CommandLine.Args
{
public class Prop
{
private readonly PropertyInfo p;
private readonly IModule target;
public Prop(IModule target, PropertyInfo p)
{
this.target = target;
this.p = p;
FullName = p.Name;
Type = p.PropertyType;
var aliasAtt = p.GetCustomAttributes(true).FirstOrDefault(a => a.GetType() == typeof (AliasAttribute)) as AliasAttribute;
if (aliasAtt != null)
{
Alias = aliasAtt;
}
}
public string FullName { get; set; }
public Type Type { get; set; }
public AliasAttribute Alias { get; set; }
public void Set(string value)
{
if (String.IsNullOrWhiteSpace(value) && Type == typeof (bool))
{
// treat presence of boolean flag as implicit "True"
value = "true";
}
object val = value.ConvertTo(Type);
p.SetValue(target, val, new object[0]);
}
}
} | // Copyright (c) 2013 Raphael Estrada
// License: The MIT License - see "LICENSE" file for details
// Author URL: http://www.galaktor.net
// Author E-Mail: galaktor@gmx.de
using System;
using System.Linq;
using System.Reflection;
using Autofac.Core;
namespace Autofac.CommandLine.Args
{
public class Prop
{
private readonly PropertyInfo p;
private readonly IModule target;
public Prop(IModule target, PropertyInfo p)
{
this.target = target;
this.p = p;
FullName = p.Name;
Type = p.PropertyType;
var aliasAtt = p.GetCustomAttributes(true).FirstOrDefault(a => a.GetType() == typeof (AliasAttribute)) as AliasAttribute;
if (aliasAtt != null)
{
Alias = aliasAtt;
}
}
public string FullName { get; set; }
public Type Type { get; set; }
public AliasAttribute Alias { get; set; }
public void Set(string value)
{
if (String.IsNullOrWhiteSpace(value) || Type == typeof (bool))
{
// treat presence of boolean flag as implicit "True"
value = "true";
}
object val = value.ConvertTo(Type);
p.SetValue(target, val, new object[0]);
}
}
} | mit | C# |
233bfce42198493fe7c854bb91cbfea18ff557c8 | allow complex default values through inheritance | workabyte/PowerArgs,BlackFrog1/PowerArgs,workabyte/PowerArgs,adamabdelhamed/PowerArgs,BlackFrog1/PowerArgs,adamabdelhamed/PowerArgs | PowerArgs/Hooks/DefaultValueAttribute.cs | PowerArgs/Hooks/DefaultValueAttribute.cs | using System;
namespace PowerArgs
{
/// <summary>
/// Use this attribute to set the default value for a parameter. Note that this only
/// works for simple types since only compile time constants can be passed to an attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
public class DefaultValueAttribute : ArgHook, ICommandLineArgumentMetadata
{
/// <summary>
/// The default value that was specified on the attribute. Note that the value will get
/// converted to a string and then fed into the parser to be revived.
/// </summary>
public object Value { get; protected set; }
/// <summary>
/// Creates a new DefaultValueAttribute with the given value. Note that the value will get
/// converted to a string and then fed into the parser to be revived.
/// </summary>
/// <param name="value">The default value for the property</param>
public DefaultValueAttribute(object value)
{
Value = value;
}
/// <summary>
/// Creates a new DefaultValueAttribute without value. Value can be specified in derived class.
/// Note that the value will get converted to a string and then fed into the parser to be revived.
/// </summary>
protected DefaultValueAttribute()
{
}
/// <summary>
/// Before the property is revived and validated, if the user didn't specify a value,
/// then substitue the default value.
///
/// </summary>
/// <param name="Context"></param>
public override void BeforePopulateProperty(HookContext Context)
{
if (Context.ArgumentValue == null) Context.ArgumentValue = Value.ToString();
}
}
/// <summary>
/// Use this attribute to set the default value for a parameter. Note that this only
/// works for simple types since only compile time constants can be passed to an attribute.
/// </summary>
public class ArgDefaultValueAttribute : DefaultValueAttribute
{
/// <summary>
/// Creates a new ArgDefaultValueAttribute with the given value. Note that the value will get
/// converted to a string and then fed into the parser to be revived.
/// </summary>
/// <param name="value">The default value for the property</param>
public ArgDefaultValueAttribute(object value) : base(value) { }
}
}
| using System;
namespace PowerArgs
{
/// <summary>
/// Use this attribute to set the default value for a parameter. Note that this only
/// works for simple types since only compile time constants can be passed to an attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
public class DefaultValueAttribute : ArgHook, ICommandLineArgumentMetadata
{
/// <summary>
/// The default value that was specified on the attribute. Note that the value will get
/// converted to a string and then fed into the parser to be revived.
/// </summary>
public object Value { get; private set; }
/// <summary>
/// Creates a new DefaultValueAttribute with the given value. Note that the value will get
/// converted to a string and then fed into the parser to be revived.
/// </summary>
/// <param name="value">The default value for the property</param>
public DefaultValueAttribute(object value)
{
Value = value;
}
/// <summary>
/// Before the property is revived and validated, if the user didn't specify a value,
/// then substitue the default value.
///
/// </summary>
/// <param name="Context"></param>
public override void BeforePopulateProperty(HookContext Context)
{
if (Context.ArgumentValue == null) Context.ArgumentValue = Value.ToString();
}
}
/// <summary>
/// Use this attribute to set the default value for a parameter. Note that this only
/// works for simple types since only compile time constants can be passed to an attribute.
/// </summary>
public class ArgDefaultValueAttribute : DefaultValueAttribute
{
/// <summary>
/// Creates a new ArgDefaultValueAttribute with the given value. Note that the value will get
/// converted to a string and then fed into the parser to be revived.
/// </summary>
/// <param name="value">The default value for the property</param>
public ArgDefaultValueAttribute(object value) : base(value) { }
}
}
| mit | C# |
a9f6ad312a757475426e8fd6ec25a7d717d86808 | Remove list element when switching scene | DragonEyes7/ConcoursUBI17,DragonEyes7/ConcoursUBI17 | Proto/Assets/Scripts/UI/LeaderboardUI.cs | Proto/Assets/Scripts/UI/LeaderboardUI.cs | using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LeaderboardUI : MonoBehaviour
{
[SerializeField] private RectTransform _scoresList;
[SerializeField] private Text _sceneTitle;
[SerializeField] private string _defaultScene = "Tuto";
private const string _path = "./";
private string _filePath;
private Leaderboard _leaderboard;
private const string _leaderboardTitle = "Leaderboard - ";
private void Start ()
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
LoadScene(_defaultScene);
}
public void LoadScene(string scene)
{
ResetList();
_filePath = _path + scene + ".json";
_leaderboard = new Leaderboard(_filePath);
_leaderboard.Show(_scoresList);
UpdateLeaderboardTitle(scene);
}
private void ResetList()
{
for (var i = 0; i < _scoresList.childCount; ++i)
{
Destroy(_scoresList.GetChild(i).gameObject);
}
}
public void BackToMainMenu()
{
SceneManager.LoadScene("MainMenu");
}
private void UpdateLeaderboardTitle(string sceneTitle)
{
_sceneTitle.text = _leaderboardTitle + sceneTitle;
}
}
| using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LeaderboardUI : MonoBehaviour
{
[SerializeField] private RectTransform _scoresList;
[SerializeField] private Text _sceneTitle;
[SerializeField] private string _defaultScene = "Tuto";
private const string _path = "./";
private string _filePath;
private Leaderboard _leaderboard;
private const string _leaderboardTitle = "Leaderboard - ";
private void Start ()
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
LoadScene(_defaultScene);
}
public void LoadScene(string scene)
{
_filePath = _path + scene + ".json";
_leaderboard = new Leaderboard(_filePath);
_leaderboard.Show(_scoresList);
UpdateLeaderboardTitle(scene);
}
public void BackToMainMenu()
{
SceneManager.LoadScene("MainMenu");
}
private void UpdateLeaderboardTitle(string sceneTitle)
{
_sceneTitle.text = _leaderboardTitle + sceneTitle;
}
}
| mit | C# |
40111b09bba17653e6bc4e887b21e68d169c1c34 | Increment version to v1.0.0.8 | TDaphneB/XeroAPI.Net,MatthewSteeples/XeroAPI.Net,jcvandan/XeroAPI.Net,XeroAPI/XeroAPI.Net | source/XeroApi/Properties/AssemblyInfo.cs | source/XeroApi/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.8")]
[assembly: AssemblyFileVersion("1.1.0.8")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.7")]
[assembly: AssemblyFileVersion("1.1.0.7")]
| mit | C# |
fb435ccfc5fc2a032bd0b77813539696b4f41e8f | Allow an IScheduler to be specified in settings | jskeet/gax-dotnet,googleapis/gax-dotnet,jskeet/gax-dotnet,googleapis/gax-dotnet | src/Google.Api.Gax/ServiceSettingsBase.cs | src/Google.Api.Gax/ServiceSettingsBase.cs | /*
* Copyright 2016 Google Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
using Grpc.Core;
using System;
namespace Google.Api.Gax
{
/// <summary>
/// Common settings for all services.
/// </summary>
public abstract class ServiceSettingsBase
{
/// <summary>
/// Constructs a new service settings base object with a default user agent, unset call settings and
/// unset clock.
/// </summary>
protected ServiceSettingsBase()
{
UserAgent = new UserAgentBuilder()
.AppendDotNetEnvironment()
.AppendAssemblyVersion("gax", typeof(CallSettings))
.AppendAssemblyVersion("grpc", typeof(Channel))
// TODO: Use the assembly name instead of the namespace? Allow it to be specified?
.AppendAssemblyVersion(GetType().Namespace, GetType())
.ToString();
}
/// <summary>
/// Constructs a new service settings base object by cloning the settings from an existing one.
/// </summary>
/// <param name="existing">The existing settings object to clone settings from. Must not be null.</param>
protected ServiceSettingsBase(ServiceSettingsBase existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
CallSettings = existing.CallSettings?.Clone();
Clock = existing.Clock;
Scheduler = existing.Scheduler;
UserAgent = existing.UserAgent;
}
internal string UserAgent { get; }
/// <summary>
/// If not null, <see cref="CallSettings"/> that are applied to every RPC performed by the client.
/// If null or unset, RPC default settings will be used for all settings.
/// </summary>
public CallSettings CallSettings { get; set; }
/// <summary>
/// If not null, the clock used to calculate RPC deadlines. If null or unset, the <see cref="SystemClock"/> is used.
/// </summary>
/// <remarks>
/// This is primarily only to be set for testing.
/// In production code generally leave this unset to use the <see cref="SystemClock"/>.
/// </remarks>
public IClock Clock { get; set; }
/// <summary>
/// If not null, the scheduler used for delays between operations (e.g. for retry).
/// If null or unset, the <see cref="SystemScheduler"/> is used.
/// </summary>
/// <remarks>
/// This is primarily only to be set for testing.
/// In production code generally leave this unset to use the <see cref="SystemScheduler"/>.
/// </remarks>
public IScheduler Scheduler { get; set; }
}
}
| /*
* Copyright 2016 Google Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
using Grpc.Core;
using System;
namespace Google.Api.Gax
{
/// <summary>
/// Common settings for all services.
/// </summary>
public abstract class ServiceSettingsBase
{
/// <summary>
/// Constructs a new service settings base object with a default user agent, unset call settings and
/// unset clock.
/// </summary>
protected ServiceSettingsBase()
{
UserAgent = new UserAgentBuilder()
.AppendDotNetEnvironment()
.AppendAssemblyVersion("gax", typeof(CallSettings))
.AppendAssemblyVersion("grpc", typeof(Channel))
// TODO: Use the assembly name instead of the namespace? Allow it to be specified?
.AppendAssemblyVersion(GetType().Namespace, GetType())
.ToString();
}
/// <summary>
/// Constructs a new service settings base object by cloning the settings from an existing one.
/// </summary>
/// <param name="existing">The existing settings object to clone settings from. Must not be null.</param>
protected ServiceSettingsBase(ServiceSettingsBase existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
CallSettings = existing.CallSettings?.Clone();
Clock = existing.Clock;
UserAgent = existing.UserAgent;
}
internal string UserAgent { get; }
/// <summary>
/// If not null, <see cref="CallSettings"/> that are applied to every RPC performed by the client.
/// If null or unset, RPC default settings will be used for all settings.
/// </summary>
public CallSettings CallSettings { get; set; }
/// <summary>
/// If not null, the clock used to calculate RPC deadlines. If null or unset, the <see cref="SystemClock"/> is used.
/// </summary>
/// <remarks>
/// This is primarily only to be set for testing.
/// In production code generally leave this unset to use the <see cref="SystemClock"/>.
/// </remarks>
public IClock Clock { get; set; }
}
}
| bsd-3-clause | C# |
4b489b52efdf1635a17fefcf740765967837ea2f | Bump version again | mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,rasmuseeg/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,madsoulswe/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,madsoulswe/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,rasmuseeg/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,abjerner/Umbraco-CMS,rasmuseeg/Umbraco-CMS,NikRimington/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,NikRimington/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,bjarnef/Umbraco-CMS | src/SolutionInfo.cs | src/SolutionInfo.cs | using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany("Umbraco")]
[assembly: AssemblyCopyright("Copyright © Umbraco 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
// versions
// read https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin
// note: do NOT change anything here manually, use the build scripts
// this is the ONLY ONE the CLR cares about for compatibility
// should change ONLY when "hard" breaking compatibility (manual change)
[assembly: AssemblyVersion("8.0.0")]
// these are FYI and changed automatically
[assembly: AssemblyFileVersion("8.1.0")]
[assembly: AssemblyInformationalVersion("8.1.0")]
| using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany("Umbraco")]
[assembly: AssemblyCopyright("Copyright © Umbraco 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
// versions
// read https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin
// note: do NOT change anything here manually, use the build scripts
// this is the ONLY ONE the CLR cares about for compatibility
// should change ONLY when "hard" breaking compatibility (manual change)
[assembly: AssemblyVersion("8.0.0")]
// these are FYI and changed automatically
[assembly: AssemblyFileVersion("8.0.0")]
[assembly: AssemblyInformationalVersion("8.0.0")]
| mit | C# |
e01a5b15b1f0bf66148dc9d844638938bb07d6cb | Save layout works | JakobChristensen/Sitecore.ContentDelivery | src/Sitecore.ContentDelivery/Constants.cs | src/Sitecore.ContentDelivery/Constants.cs | // © 2015-2017 by Jakob Christensen. All rights reserved.
namespace Sitecore.ContentDelivery
{
public static class Constants
{
public const string AppDataDatabasesDirectory = "/App_Data/Sitecore.ContentDelivery/Databases";
public const string BasePath = "ContentDelivery.BasePath";
public const string Version = "1.0.2";
}
}
| // © 2015-2017 by Jakob Christensen. All rights reserved.
namespace Sitecore.ContentDelivery
{
public static class Constants
{
public const string AppDataDatabasesDirectory = "/App_Data/Sitecore.ContentDelivery/Databases";
public const string BasePath = "ContentDelivery.BasePath";
public const string Version = "1.0.1";
}
}
| mit | C# |
d3a445a35347202e340dcf8bf5c6c7016a31fc0d | Fix compile error. | jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr | test/HelloCoreClrApp.Test/TestserverStartup.cs | test/HelloCoreClrApp.Test/TestserverStartup.cs | using System;
using HelloCoreClrApp.Data;
using HelloCoreClrApp.Data.Entities;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace HelloCoreClrApp.Test
{
public class TestserverStartup : Startup
{
public TestserverStartup(IHostingEnvironment env, ILoggerFactory loggerFactory)
: base(env, loggerFactory)
{
}
public override DbContextOptionsBuilder<GreetingDbContext> CreateDatabaseOptions()
{
var builder = new DbContextOptionsBuilder<GreetingDbContext>()
.UseInMemoryDatabase("TestserverStartup");
SeedDatabase(builder.Options);
return builder;
}
private static void SeedDatabase(DbContextOptions options)
{
using (var db = new GreetingDbContext(options))
{
db.Greetings.Add(new Greeting{Name = "First Greeting", TimestampUtc = DateTime.Now.ToUniversalTime()});
db.Greetings.Add(new Greeting{Name = "Second Greeting", TimestampUtc = DateTime.Now.ToUniversalTime()});
db.SaveChanges();
}
}
}
} | using System;
using HelloCoreClrApp.Data;
using HelloCoreClrApp.Data.Entities;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
namespace HelloCoreClrApp.Test
{
public class TestserverStartup : Startup
{
public TestserverStartup(IHostingEnvironment env)
: base(env)
{
}
public override DbContextOptionsBuilder<GreetingDbContext> CreateDatabaseOptions()
{
var builder = new DbContextOptionsBuilder<GreetingDbContext>()
.UseInMemoryDatabase("TestserverStartup");
SeedDatabase(builder.Options);
return builder;
}
private static void SeedDatabase(DbContextOptions options)
{
using (var db = new GreetingDbContext(options))
{
db.Greetings.Add(new Greeting{Name = "First Greeting", TimestampUtc = DateTime.Now.ToUniversalTime()});
db.Greetings.Add(new Greeting{Name = "Second Greeting", TimestampUtc = DateTime.Now.ToUniversalTime()});
db.SaveChanges();
}
}
}
} | mit | C# |
4c162561160a6dcb83500d8c80e6e2f36b33f655 | Fix for content type NULL in rare cercumstances | danielwertheim/mycouch,danielwertheim/mycouch | source/projects/MyCouch.Net45/Responses/Materializers/BasicResponseMaterializer.cs | source/projects/MyCouch.Net45/Responses/Materializers/BasicResponseMaterializer.cs | using System.Net.Http;
using MyCouch.Extensions;
namespace MyCouch.Responses.Materializers
{
public class BasicResponseMaterializer
{
public virtual void Materialize(Response response, HttpResponseMessage httpResponse)
{
response.RequestUri = httpResponse.RequestMessage.RequestUri;
response.StatusCode = httpResponse.StatusCode;
response.RequestMethod = httpResponse.RequestMessage.Method;
response.ContentLength = httpResponse.Content.Headers.ContentLength;
response.ContentType = httpResponse.Content.Headers.ContentType != null ? httpResponse.Content.Headers.ContentType.ToString() : null;
response.ETag = httpResponse.Headers.GetETag();
}
}
} | using System.Net.Http;
using MyCouch.Extensions;
namespace MyCouch.Responses.Materializers
{
public class BasicResponseMaterializer
{
public virtual void Materialize(Response response, HttpResponseMessage httpResponse)
{
response.RequestUri = httpResponse.RequestMessage.RequestUri;
response.StatusCode = httpResponse.StatusCode;
response.RequestMethod = httpResponse.RequestMessage.Method;
response.ContentLength = httpResponse.Content.Headers.ContentLength;
response.ContentType = httpResponse.Content.Headers.ContentType.ToString();
response.ETag = httpResponse.Headers.GetETag();
}
}
} | mit | C# |
06ae6b2bcc81bc3bdda6f9d61c75c04f1144c97f | move to class level variables | jefking/King.B-Trak | King.B-Trak/Synchronizer.cs | King.B-Trak/Synchronizer.cs | namespace King.BTrak
{
using King.Azure.Data;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading.Tasks;
/// <summary>
///
/// </summary>
public class Synchronizer : ISynchronizer
{
#region Members
/// <summary>
/// Configuration Values
/// </summary>
protected readonly IConfigValues config = null;
/// <summary>
/// SQL Connection
/// </summary>
protected SqlConnection database = null;
/// <summary>
/// Table Storage
/// </summary>
protected ITableStorage table = null;
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="config">Configuration Values</param>
public Synchronizer(IConfigValues config)
{
if (null == config)
{
throw new ArgumentNullException("config");
}
this.config = config;
}
#endregion
#region Methods
/// <summary>
/// Innitialize Members
/// </summary>
/// <returns></returns>
public virtual ISynchronizer Initialize()
{
Trace.TraceInformation("Initializing...");
this.database = new SqlConnection(config.SQLConenction);
this.table = new TableStorage(config.StorageTableName, config.StorageAccountConnection);
Task.WaitAll(this.database.OpenAsync(), this.table.CreateIfNotExists());
Trace.TraceInformation("Initialized.");
return this;
}
/// <summary>
/// Run Synchronization
/// </summary>
/// <returns></returns>
public virtual ISynchronizer Run()
{
Trace.TraceInformation("Running...");
Trace.TraceInformation("Loading Database Schema.");
Trace.TraceInformation("Loaded Database Schema.");
Trace.TraceInformation("Loading SQL Server Data.");
Trace.TraceInformation("Loaded SQL Server Data.");
Trace.TraceInformation("Storing SQL Server Data.");
Trace.TraceInformation("Stored SQL Server Data.");
Trace.TraceInformation("Ran.");
return this;
}
#endregion
}
} | namespace King.BTrak
{
using King.Azure.Data;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading.Tasks;
/// <summary>
///
/// </summary>
public class Synchronizer : ISynchronizer
{
#region Members
/// <summary>
/// Configuration Values
/// </summary>
protected readonly IConfigValues config;
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="config">Configuration Values</param>
public Synchronizer(IConfigValues config)
{
if (null == config)
{
throw new ArgumentNullException("config");
}
this.config = config;
}
#endregion
#region Methods
/// <summary>
/// Innitialize Members
/// </summary>
/// <returns></returns>
public virtual ISynchronizer Initialize()
{
Trace.TraceInformation("Initializing...");
var database = new SqlConnection(config.SQLConenction);
var table = new TableStorage(config.StorageTableName, config.StorageAccountConnection);
Task.WaitAll(database.OpenAsync(), table.CreateIfNotExists());
Trace.TraceInformation("Initialized.");
return this;
}
/// <summary>
/// Run Synchronization
/// </summary>
/// <returns></returns>
public virtual ISynchronizer Run()
{
Trace.TraceInformation("Running...");
Trace.TraceInformation("Loading Database Schema.");
Trace.TraceInformation("Loaded Database Schema.");
Trace.TraceInformation("Loading SQL Server Data.");
Trace.TraceInformation("Loaded SQL Server Data.");
Trace.TraceInformation("Storing SQL Server Data.");
Trace.TraceInformation("Stored SQL Server Data.");
Trace.TraceInformation("Ran.");
return this;
}
#endregion
}
} | mit | C# |
faaf270e51135d1a8e34665d2051de5007518a63 | Bump version to 0.6.0 | whampson/bft-spec,whampson/cascara | Src/WHampson.Bft/Properties/AssemblyInfo.cs | Src/WHampson.Bft/Properties/AssemblyInfo.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("WHampson.BFT")]
[assembly: AssemblyDescription("Binary File Template parser.")]
[assembly: AssemblyProduct("WHampson.BFT")]
[assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")]
[assembly: AssemblyFileVersion("0.6.0")]
[assembly: AssemblyVersion("0.6.0")]
[assembly: AssemblyInformationalVersion("0.6.0")]
| #region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("WHampson.BFT")]
[assembly: AssemblyDescription("Binary File Template parser.")]
[assembly: AssemblyProduct("WHampson.BFT")]
[assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")]
[assembly: AssemblyFileVersion("0.5.3")]
[assembly: AssemblyVersion("0.5.3")]
[assembly: AssemblyInformationalVersion("0.5.3")]
| mit | C# |
50963adcbf82d2cb797cf435764a42dc1f25a44a | Set fixed height and add debug messages for OnAppearing/OnDisappearing | esskar/TelerikListViewPoc | TelerikListViewPoc/Controls/BookListCell.cs | TelerikListViewPoc/Controls/BookListCell.cs | using System.Diagnostics;
using Telerik.XamarinForms.DataControls.ListView;
using TelerikListViewPoc.Components;
using Xamarin.Forms;
namespace TelerikListViewPoc.Controls
{
public class BookListCell : ListViewTemplateCell
{
public BookListCell()
{
var titleLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Default, typeof(Label))
};
titleLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Title), BindingMode.OneWay);
var authorLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label))
};
authorLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Author), BindingMode.OneWay);
var yearLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label))
};
yearLabel.SetBinding(Label.TextProperty, nameof(this.DataContext.Year), BindingMode.OneWay);
var viewLayout = new StackLayout
{
Orientation = StackOrientation.Vertical,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { titleLabel, authorLabel, yearLabel },
HeightRequest = 100
};
this.View = viewLayout;
}
public Book DataContext
{
get { return this.BindingContext as Book; }
}
protected override void OnAppearing()
{
Debug.WriteLine("OnAppearing");
base.OnAppearing();
}
protected override void OnDisappearing()
{
Debug.WriteLine("OnDisappearing");
base.OnDisappearing();
}
}
}
| using Telerik.XamarinForms.DataControls.ListView;
using TelerikListViewPoc.Components;
using Xamarin.Forms;
namespace TelerikListViewPoc.Controls
{
public class BookListCell : ListViewTemplateCell
{
public BookListCell()
{
var titleLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Default, typeof(Label))
};
titleLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Title), BindingMode.OneWay);
var authorLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label))
};
authorLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Author), BindingMode.OneWay);
var yearLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label))
};
yearLabel.SetBinding(Label.TextProperty, nameof(this.DataContext.Year), BindingMode.OneWay);
var viewLayout = new StackLayout
{
Orientation = StackOrientation.Vertical,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { titleLabel, authorLabel, yearLabel }
};
this.View = viewLayout;
}
public Book DataContext
{
get { return this.BindingContext as Book; }
}
}
}
| mit | C# |
b6eb090ed0f8ac213806d010ef8ac35327ca4888 | Fix PKCS7Padding padding | miniter/SSH.NET,sshnet/SSH.NET,Bloomcredit/SSH.NET,GenericHero/SSH.NET | Renci.SshClient/Renci.SshNet/Security/Cryptography/Ciphers/Paddings/PKCS7Padding.cs | Renci.SshClient/Renci.SshNet/Security/Cryptography/Ciphers/Paddings/PKCS7Padding.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Renci.SshNet.Security.Cryptography.Ciphers.Paddings
{
/// <summary>
/// Implements PKCS7 cipher padding
/// </summary>
public class PKCS7Padding : CipherPadding
{
/// <summary>
/// Transforms the specified input.
/// </summary>
/// <param name="blockSize">Size of the block.</param>
/// <param name="input">The input.</param>
/// <returns>
/// Padded data array.
/// </returns>
public override byte[] Pad(int blockSize, byte[] input)
{
var numOfPaddedBytes = blockSize - (input.Length % blockSize);
var output = new byte[input.Length + numOfPaddedBytes];
Buffer.BlockCopy(input, 0, output, 0, input.Length);
for (int i = 0; i < numOfPaddedBytes; i++)
{
output[input.Length + i] = (byte)numOfPaddedBytes;
}
return output;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Renci.SshNet.Security.Cryptography.Ciphers.Paddings
{
/// <summary>
/// Implements PKCS7 cipher padding
/// </summary>
public class PKCS7Padding : CipherPadding
{
/// <summary>
/// Transforms the specified input.
/// </summary>
/// <param name="blockSize">Size of the block.</param>
/// <param name="input">The input.</param>
/// <returns>
/// Padded data array.
/// </returns>
public override byte[] Pad(int blockSize, byte[] input)
{
var numOfPaddedBytes = blockSize - (input.Length % blockSize);
var output = new byte[input.Length + numOfPaddedBytes];
Buffer.BlockCopy(input, 0, output, 0, input.Length);
for (int i = 0; i < numOfPaddedBytes; i++)
{
output[input.Length + i] = output[input.Length - 1];
}
return output;
}
}
}
| mit | C# |
be87440a2362b31e53b97542f802245b8cb16754 | Fix collider on audiotrigger | pierre-galaup/globalgamejam2016 | Assets/AudioTriggerHandler.cs | Assets/AudioTriggerHandler.cs | using UnityEngine;
using System.Collections;
public class AudioTriggerHandler : MonoBehaviour
{
[SerializeField]
private MonoBehaviour ScriptToRun;
[SerializeField]
private AudioClip Clip;
[SerializeField] private AudioSource audioSource;
public void OnTriggerEnter(Collider other)
{
if (other.tag != "Player")
return;
if (this.Clip != null)
this.audioSource.PlayOneShot(this.Clip);
if (this.ScriptToRun != null)
this.ScriptToRun.enabled = true;
}
}
| using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class AudioTriggerHandler : MonoBehaviour
{
[SerializeField]
private MonoBehaviour ScriptToRun;
[SerializeField]
private AudioClip Clip;
private AudioSource audioSource;
public void Awake()
{
this.audioSource = this.GetComponent<AudioSource>();
}
public void OnTriggerEnter(Collider other)
{
if (this.Clip != null)
this.audioSource.PlayOneShot(this.Clip);
if (this.ScriptToRun != null)
this.ScriptToRun.enabled = true;
}
}
| cc0-1.0 | C# |
c6bab56464daec94558959649be8eaf448d10720 | Bump version number | AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet | adal/src/Microsoft.IdentityModel.Clients.ActiveDirectory/Properties/AssemblyInfo.cs | adal/src/Microsoft.IdentityModel.Clients.ActiveDirectory/Properties/AssemblyInfo.cs | //------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// Version and Metadata are set at build time from msbuild properties defined in the csproj
[assembly: AssemblyMetadata("Serviceable", "True")]
// 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)]
[assembly: CLSCompliant(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff47962a-d498-4c63-b7e9-4db3653ad7db")]
| //------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// Version and Metadata are set at build time from msbuild properties defined in the csproj
[assembly: AssemblyMetadata("Serviceable", "True")]
// 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)]
[assembly: CLSCompliant(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff47962a-d498-4c63-b7e9-4db3653ad7db")] | mit | C# |
a82f6ef4c6618c2a6ab09ab53933ab04a885b7fd | create MappingTester.Source on request instead of in the constructor in case the user already has a TSource they want to use | mvbalaw/Mapper | MvbaMapper/MappingTester.cs | MvbaMapper/MappingTester.cs | using System.Collections.Generic;
using System.Linq;
using CodeQuery;
using MvbaCore;
namespace MvbaMapper
{
public class MappingTester<TSource, TDestination>
where TSource : class, new()
{
private readonly Dictionary<string, object> _propertyValues = new Dictionary<string, object>();
private TSource _source;
public TSource Source
{
get
{
if (_source == null)
{
_source = new TSource();
Populate(_source);
}
return _source;
}
}
private void Populate(TSource source)
{
foreach (var propertyInfo in source.GetType()
.GetProperties()
.ThatHaveAGetter()
.ThatHaveASetter())
{
var value = RandomValueType.GetFor(propertyInfo.PropertyType.FullName).CreateRandomValue();
_propertyValues.Add(propertyInfo.Name, value);
propertyInfo.SetValue(source, value, null);
}
}
public Notification Verify(TDestination actual, TDestination expected)
{
Notification notification = new Notification();
var destinationProperties = expected.GetType()
.GetProperties()
.ThatHaveASetter()
.ThatHaveAGetter()
.ToDictionary(x => x.Name, x => x);
foreach (var propertyInfo in destinationProperties.Values)
{
var expectedValue = propertyInfo.GetValue(expected, null);
var actualValue = propertyInfo.GetValue(actual, null);
if (expectedValue == null && actualValue == null)
{
continue;
}
if (expectedValue == null || actualValue == null)
{
notification.Add(Notification.WarningFor(propertyInfo.Name));
continue;
}
if (!expectedValue.Equals(actualValue))
{
notification.Add(Notification.WarningFor(propertyInfo.Name));
}
}
return notification;
}
}
} | using System.Collections.Generic;
using System.Linq;
using CodeQuery;
using MvbaCore;
namespace MvbaMapper
{
public class MappingTester<TSource, TDestination>
where TSource : new()
{
private readonly Dictionary<string, object> _propertyValues = new Dictionary<string, object>();
private readonly TSource _source;
public MappingTester()
{
_source = new TSource();
Populate(_source);
}
public TSource Source
{
get { return _source; }
}
private void Populate(TSource source)
{
foreach (var propertyInfo in source.GetType()
.GetProperties()
.ThatHaveAGetter()
.ThatHaveASetter())
{
var value = RandomValueType.GetFor(propertyInfo.PropertyType.FullName).CreateRandomValue();
_propertyValues.Add(propertyInfo.Name, value);
propertyInfo.SetValue(source, value, null);
}
}
public Notification Verify(TDestination actual, TDestination expected)
{
Notification notification = new Notification();
var destinationProperties = expected.GetType()
.GetProperties()
.ThatHaveASetter()
.ThatHaveAGetter()
.ToDictionary(x => x.Name, x => x);
foreach (var propertyInfo in destinationProperties.Values)
{
var expectedValue = propertyInfo.GetValue(expected, null);
var actualValue = propertyInfo.GetValue(actual, null);
if (expectedValue == null && actualValue == null)
{
continue;
}
if (expectedValue == null || actualValue == null)
{
notification.Add(Notification.WarningFor(propertyInfo.Name));
continue;
}
if (!expectedValue.Equals(actualValue))
{
notification.Add(Notification.WarningFor(propertyInfo.Name));
}
}
return notification;
}
}
} | mit | C# |
5c9cd4f3ebcfb738fb8fb66a6bbdc19500b90a14 | change screenshot counter | accu-rate/SumoVizUnity,accu-rate/SumoVizUnity | Assets/Scripts/Screenshots/NormalScreenshots.cs | Assets/Scripts/Screenshots/NormalScreenshots.cs | using UnityEngine;
using System.Collections;
using System.IO;
public class NormalScreenshots : MonoBehaviour {
public int superSizeFactor = 1;
public int fps = 25;
private PlaybackControl pc;
private int count = 0;
void Start () {
pc = GameObject.Find("PlaybackControl").GetComponent<PlaybackControl>();
Time.captureFramerate = fps;
Application.runInBackground = true;
Screenrecorder.init ();
}
void OnPostRender () {
//void Update() {
if (pc.inFirstRound ()) {
//Application.CaptureScreenshot ("Screenshots/screenshot" + (count ++) + ".png", superSizeFactor);
Texture2D screenshot = new Texture2D (Screen.width, Screen.height, TextureFormat.RGB24, false); // via http://answers.unity3d.com/answers/1190178/view.html
screenshot.ReadPixels (new Rect (0, 0, Screen.width, Screen.height), 0, 0);
screenshot.Apply ();
byte[] bytes = screenshot.EncodeToJPG ();
//File.WriteAllBytes("Screenshots/screenshot" + (count ++) + ".jpg", bytes);
Screenrecorder.writeImg (bytes);
Object.Destroy (screenshot);
count ++;
Debug.Log ("frame #" + count + " captured");
} else {
if (!Screenrecorder.isClosed) {
Debug.Log ("video exported with " + count + " frames");
Screenrecorder.close ();
}
}
}
}
| using UnityEngine;
using System.Collections;
using System.IO;
public class NormalScreenshots : MonoBehaviour {
public int superSizeFactor = 1;
public int fps = 25;
private PlaybackControl pc;
private int count = 0;
void Start () {
pc = GameObject.Find("PlaybackControl").GetComponent<PlaybackControl>();
Time.captureFramerate = fps;
Application.runInBackground = true;
Screenrecorder.init ();
}
void OnPostRender () {
//void Update() {
if (pc.inFirstRound ()) {
//Application.CaptureScreenshot ("Screenshots/screenshot" + (count ++) + ".png", superSizeFactor);
Texture2D screenshot = new Texture2D (Screen.width, Screen.height, TextureFormat.RGB24, false); // via http://answers.unity3d.com/answers/1190178/view.html
screenshot.ReadPixels (new Rect (0, 0, Screen.width, Screen.height), 0, 0);
screenshot.Apply ();
byte[] bytes = screenshot.EncodeToJPG ();
//File.WriteAllBytes("Screenshots/screenshot" + (count ++) + ".jpg", bytes);
Screenrecorder.writeImg (bytes);
Object.Destroy (screenshot);
Debug.Log ("frame #" + (count ++) + " captured");
} else {
if (!Screenrecorder.isClosed) {
Debug.Log ("video exported with " + (count - 1) + " frames");
Screenrecorder.close ();
}
}
}
}
| mit | C# |
2fc47c6b2fb0ecd98c0a89cce430a22c7f195f54 | Use struct instead of class for event/notification data. | modulexcite/DartVS,modulexcite/DartVS,modulexcite/DartVS,DartVS/DartVS,DartVS/DartVS,DartVS/DartVS | DanTup.DartAnalysis/Events/ServerStatusEvent.cs | DanTup.DartAnalysis/Events/ServerStatusEvent.cs | using System;
namespace DanTup.DartAnalysis
{
#region JSON deserialisation objects
class ServerStatusEvent
{
public ServerAnalysisStatus analysis = null;
}
class ServerAnalysisStatus
{
public bool analyzing = false;
}
#endregion
public struct ServerStatusNotification
{
public bool IsAnalysing { get; internal set; }
}
internal static class ServerStatusEventImplementation
{
public static void RaiseServerStatusEvent(this DartAnalysisService service, ServerStatusEvent notification, EventHandler<ServerStatusNotification> handler)
{
if (handler != null)
handler.Invoke(service, new ServerStatusNotification { IsAnalysing = notification.analysis.analyzing });
}
}
}
| using System;
namespace DanTup.DartAnalysis
{
#region JSON deserialisation objects
class ServerStatusEvent
{
public ServerAnalysisStatus analysis = null;
}
class ServerAnalysisStatus
{
public bool analyzing = false;
}
#endregion
public class ServerStatusNotification
{
public bool IsAnalysing { get; internal set; }
}
internal static class ServerStatusEventImplementation
{
public static void RaiseServerStatusEvent(this DartAnalysisService service, ServerStatusEvent notification, EventHandler<ServerStatusNotification> handler)
{
if (handler != null)
handler.Invoke(service, new ServerStatusNotification { IsAnalysing = notification.analysis.analyzing });
}
}
}
| mit | C# |
0fec10413ae7c85849587609efeea4beefa9bcd5 | Update SDK version to 4.0.2 | NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity | ncmb_unity/Assets/NCMB/Script/CommonConstant.cs | ncmb_unity/Assets/NCMB/Script/CommonConstant.cs | /*******
Copyright 2017-2018 FUJITSU CLOUD TECHNOLOGIES LIMITED 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 System.Collections;
namespace NCMB.Internal
{
//通信種別
internal enum ConnectType
{
//GET通信
GET,
//POST通信
POST,
//PUT通信
PUT,
//DELETE通信
DELETE
}
/// <summary>
/// 定数を定義する共通用のクラスです
/// </summary>
internal static class CommonConstant
{
//service
public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン
public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL
public static readonly string API_VERSION = "2013-09-01";//APIバージョン
public static readonly string SDK_VERSION = "4.0.2"; //SDKバージョン
//DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください
}
}
| /*******
Copyright 2017-2018 FUJITSU CLOUD TECHNOLOGIES LIMITED 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 System.Collections;
namespace NCMB.Internal
{
//通信種別
internal enum ConnectType
{
//GET通信
GET,
//POST通信
POST,
//PUT通信
PUT,
//DELETE通信
DELETE
}
/// <summary>
/// 定数を定義する共通用のクラスです
/// </summary>
internal static class CommonConstant
{
//service
public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン
public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL
public static readonly string API_VERSION = "2013-09-01";//APIバージョン
public static readonly string SDK_VERSION = "4.0.1"; //SDKバージョン
//DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください
}
}
| apache-2.0 | C# |
b70fb1e2c19586c9a88dbd929167439cb05f041b | Update BindingSyntaxExtensions.cs | justinyoo/EntityFramework.Testing,scott-xu/EntityFramework.Testing,justinyoo/EntityFramework.Testing | src/EntityFramework.Testing.Moq.Ninject/BindingSyntaxExtensions.cs | src/EntityFramework.Testing.Moq.Ninject/BindingSyntaxExtensions.cs | //-----------------------------------------------------------------------------------------------------
// <copyright file="BindingSyntaxExtensions.cs" company="Scott Xu">
// Copyright (c) 2014 Scott Xu.
// </copyright>
//-----------------------------------------------------------------------------------------------------
namespace Ninject.MockingKernel
{
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using global::Moq;
using global::Ninject;
using global::Ninject.MockingKernel.Moq;
using global::Ninject.Syntax;
/// <summary>
/// Extension methods for <see cref="IBindingToSyntax{T}"/>.
/// </summary>
public static class BindingSyntaxExtensions
{
/// <summary>
/// SetReturnsDefault method.
/// </summary>
private static readonly MethodInfo SetReturnsDefaultMethod
= typeof(Mock<>).GetMethod("SetReturnsDefault");
/// <summary>
/// Bind the derived <see cref="DbContext"/> to mock and auto setup its <see cref="DbSet{T}"/> properties.
/// </summary>
/// <typeparam name="T">The derived <see cref="DbContext"/> type.</typeparam>
/// <param name="builder">The binding builder.</param>
/// <returns>The binding syntax.</returns>
public static IBindingNamedWithOrOnSyntax<T> ToMockDbContext<T>(this IBindingToSyntax<T> builder) where T : DbContext
{
var kernel = builder.Kernel as MoqMockingKernel;
var result = builder.ToMock().InSingletonScope();
foreach (var dbsetType in typeof(T).GetProperties()
.Where(p => p.PropertyType.IsGenericType &&
p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>) &&
p.CanWrite)
.Select(pi => pi.PropertyType))
{
kernel.Bind(dbsetType)
.ToMethod(ctx =>
{
dynamic mockDbSet = kernel.Get(typeof(Mock<>).MakeGenericType(new[] { dbsetType }));
return mockDbSet.Object;
})
.InSingletonScope();
SetReturnsDefaultMethod.MakeGenericMethod(dbsetType).Invoke(kernel.GetMock<T>(), new[] { kernel.Get(dbsetType) });
}
return result;
}
}
}
| //-----------------------------------------------------------------------------------------------------
// <copyright file="BindingSyntaxExtensions.cs" company="Scott Xu">
// Copyright (c) 2014 Scott Xu.
// </copyright>
//-----------------------------------------------------------------------------------------------------
namespace Ninject.MockingKernel
{
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using global::Moq;
using global::Ninject;
using global::Ninject.MockingKernel.Moq;
using global::Ninject.Syntax;
/// <summary>
/// Extension methods for <see cref="IBindingToSyntax{T}"/>.
/// </summary>
public static class BindingSyntaxExtensions
{
/// <summary>
/// SetReturnsDefault method.
/// </summary>
private static readonly MethodInfo SetReturnsDefaultMethod
= typeof(Mock<>).GetMethod("SetReturnsDefault");
/// <summary>
/// Bind the derived <see cref="DbContext"/> to mock and auto setup its <see cref="DbSet{T}"/> properties.
/// </summary>
/// <typeparam name="T">The derived <see cref="DbContext"/> type.</typeparam>
/// <param name="builder">The binding builder.</param>
/// <returns>The binding syntax.</returns>
public static IBindingNamedWithOrOnSyntax<T> ToMockDbContext<T>(this IBindingToSyntax<T> builder) where T : DbContext
{
var kernel = builder.Kernel as MoqMockingKernel;
var result = builder.ToMock().InSingletonScope();
foreach (var dbsetType in typeof(T).GetProperties()
.Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>) && p.CanWrite)
.Select(pi => pi.PropertyType))
{
kernel.Bind(dbsetType)
.ToMethod(ctx =>
{
dynamic mDbSet = kernel.Get(typeof(Mock<>).MakeGenericType(new[] { dbsetType }));
return mDbSet.Object;
})
.InSingletonScope();
SetReturnsDefaultMethod.MakeGenericMethod(dbsetType).Invoke(kernel.GetMock<T>(), new[] { kernel.Get(dbsetType) });
}
return result;
}
}
}
| apache-2.0 | C# |
655a63bd61dca22f94055156c5ca10519f65d197 | Update StringExtension to validate email | SSWConsulting/SSWTV.DevSuperPower.DI,SSWConsulting/SSWTV.DevSuperPower.DI,SSWConsulting/SSWTV.DevSuperPower.DI | src/Step-0-No-DI/AdamS.StoreTemp/Models/Common/StringExtensions.cs | src/Step-0-No-DI/AdamS.StoreTemp/Models/Common/StringExtensions.cs | using System.Text.RegularExpressions;
namespace AdamS.StoreTemp.Models.Common
{
public static class StringExtensions
{
public static bool IsValidEmailAddress(this string emailAddress)
{
Regex regex = new Regex(@"^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$");
Match match = regex.Match(emailAddress);
return match.Success;
}
}
} | namespace AdamS.StoreTemp.Models.Common
{
public static class StringExtensions
{
public static bool IsValidEmailAddress(this string emailAddress)
{
return !string.IsNullOrWhiteSpace(emailAddress);
}
}
} | apache-2.0 | C# |
fe507d8dafd37b9ab3ac5f2d5b919b6b9d723bf5 | Comment typo fix | madelson/DistributedLock | DistributedLock.Tests/Infrastructure/Shared/MariaDbCredentials.cs | DistributedLock.Tests/Infrastructure/Shared/MariaDbCredentials.cs | using MySqlConnector;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Medallion.Threading.Tests
{
internal static class MariaDbCredentials
{
// MARIADB SETUP NOTE
//
// In order to enable application name tracking, we must enable the performance schema. Add the following to
// C:\Program Files\MariaDB 10.6\data\my.ini in the [mysqld] section
//
// ;from https://mariadb.com/kb/en/performance-schema-overview/#activating-the-performance-schema
// performance_schema=ON
private static (string username, string password) GetCredentials(string baseDirectory)
{
var file = Path.GetFullPath(Path.Combine(baseDirectory, "..", "..", "..", "credentials", "mariadb.txt"));
if (!File.Exists(file)) { throw new InvalidOperationException($"Unable to find MariaDB credentials file {file}"); }
var lines = File.ReadAllLines(file);
if (lines.Length != 2) { throw new FormatException($"{file} must contain exactly 2 lines of text"); }
return (lines[0], lines[1]);
}
public static string GetConnectionString(string baseDirectory)
{
var (username, password) = GetCredentials(baseDirectory);
return new MySqlConnectionStringBuilder
{
Port = 3307,
Server = "localhost",
Database = "mysql",
UserID = username,
Password = password,
PersistSecurityInfo = true,
// set a high pool size so that we don't empty the pool through things like lock abandonment tests
MaximumPoolSize = 500,
}.ConnectionString;
}
}
}
| using MySqlConnector;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Medallion.Threading.Tests
{
internal static class MariaDbCredentials
{
// MARIADB SETUP NOTE
//
// In order to enable application name tracking, we mus enable the performance schema. Add the following to
// C:\Program Files\MariaDB 10.6\data\my.ini in the [mysqld] section
//
// ;from https://mariadb.com/kb/en/performance-schema-overview/#activating-the-performance-schema
// performance_schema=ON
private static (string username, string password) GetCredentials(string baseDirectory)
{
var file = Path.GetFullPath(Path.Combine(baseDirectory, "..", "..", "..", "credentials", "mariadb.txt"));
if (!File.Exists(file)) { throw new InvalidOperationException($"Unable to find MariaDB credentials file {file}"); }
var lines = File.ReadAllLines(file);
if (lines.Length != 2) { throw new FormatException($"{file} must contain exactly 2 lines of text"); }
return (lines[0], lines[1]);
}
public static string GetConnectionString(string baseDirectory)
{
var (username, password) = GetCredentials(baseDirectory);
return new MySqlConnectionStringBuilder
{
Port = 3307,
Server = "localhost",
Database = "mysql",
UserID = username,
Password = password,
PersistSecurityInfo = true,
// set a high pool size so that we don't empty the pool through things like lock abandonment tests
MaximumPoolSize = 500,
}.ConnectionString;
}
}
}
| mit | C# |
6cd0df2dbc2361421aacb69b770ecbd17b107852 | Add more | martijn00/XamarinMediaManager,mike-rowley/XamarinMediaManager,martijn00/XamarinMediaManager,mike-rowley/XamarinMediaManager | MediaManager/Platforms/Ios/Video/PlayerViewController.cs | MediaManager/Platforms/Ios/Video/PlayerViewController.cs | using AVKit;
namespace MediaManager.Platforms.Ios.Video
{
public class PlayerViewController : AVPlayerViewController
{
protected static MediaManagerImplementation MediaManager => CrossMediaManager.Apple;
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
if (MediaManager.MediaPlayer.AutoAttachVideoView)
MediaManager.MediaPlayer.VideoView = View.Superview as VideoView;
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
if (MediaManager.MediaPlayer.AutoAttachVideoView && MediaManager.MediaPlayer.VideoView == View.Superview)
{
MediaManager.MediaPlayer.VideoView = null;
}
Player = null;
}
}
}
| using AVKit;
namespace MediaManager.Platforms.Ios.Video
{
public class PlayerViewController : AVPlayerViewController
{
protected static MediaManagerImplementation MediaManager => CrossMediaManager.Apple;
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
if (MediaManager.MediaPlayer.AutoAttachVideoView)
MediaManager.MediaPlayer.VideoView = View.Superview as VideoView;
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
if (MediaManager.MediaPlayer.AutoAttachVideoView && MediaManager.MediaPlayer.VideoView == View.Superview)
{
MediaManager.MediaPlayer.VideoView = null;
}
Player = null;
}
}
}
| mit | C# |
c5de1afefaaf087a2ddbfbc3cfd3498ee7611564 | Save and retrive excluded file types setting | BigEggTools/PowerMode | PowerMode/Settings/SettingsRepository.GeneralSettings.cs | PowerMode/Settings/SettingsRepository.GeneralSettings.cs | namespace BigEgg.Tools.PowerMode.Settings
{
using System;
public static partial class SettingsRepository
{
private static readonly string GENERAL_SETTINGS_CATELOG = "General";
public static GeneralSettings GetGeneralSettings(IServiceProvider serviceProvider)
{
if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); }
GeneralSettings generalSettingsCache = null;
var store = GetSettingsStore(serviceProvider);
generalSettingsCache = new GeneralSettings();
generalSettingsCache.IsEnablePowerMode = GetBoolOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnablePowerMode)).GetValueOrDefault(generalSettingsCache.IsEnablePowerMode);
generalSettingsCache.IsEnableParticles = GetBoolOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableParticles)).GetValueOrDefault(generalSettingsCache.IsEnableParticles);
generalSettingsCache.IsEnableScreenShake = GetBoolOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableScreenShake)).GetValueOrDefault(generalSettingsCache.IsEnableScreenShake);
generalSettingsCache.IsEnableComboMode = GetBoolOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableComboMode)).GetValueOrDefault(generalSettingsCache.IsEnableComboMode);
generalSettingsCache.IsEnableAudio = GetBoolOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableAudio)).GetValueOrDefault(generalSettingsCache.IsEnableAudio);
var types = GetStringOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.ExcludedFileTypesString));
if (types != null)
generalSettingsCache.ExcludedFileTypesString = GetStringOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.ExcludedFileTypesString));
return generalSettingsCache;
}
public static void SaveToStorage(GeneralSettings settings, IServiceProvider serviceProvider)
{
if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); }
if (settings == null) { throw new ArgumentNullException("settings"); }
var store = GetSettingsStore(serviceProvider);
SetOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnablePowerMode), settings.IsEnablePowerMode);
SetOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableParticles), settings.IsEnableParticles);
SetOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableScreenShake), settings.IsEnableScreenShake);
SetOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableComboMode), settings.IsEnableComboMode);
SetOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableAudio), settings.IsEnableAudio);
SetOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.ExcludedFileTypesString), settings.ExcludedFileTypesString);
}
}
}
| namespace BigEgg.Tools.PowerMode.Settings
{
using System;
public static partial class SettingsRepository
{
private static readonly string GENERAL_SETTINGS_CATELOG = "General";
public static GeneralSettings GetGeneralSettings(IServiceProvider serviceProvider)
{
if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); }
GeneralSettings generalSettingsCache = null;
var store = GetSettingsStore(serviceProvider);
generalSettingsCache = new GeneralSettings();
generalSettingsCache.IsEnablePowerMode = GetBoolOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnablePowerMode)).GetValueOrDefault(generalSettingsCache.IsEnablePowerMode);
generalSettingsCache.IsEnableParticles = GetBoolOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableParticles)).GetValueOrDefault(generalSettingsCache.IsEnableParticles);
generalSettingsCache.IsEnableScreenShake = GetBoolOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableScreenShake)).GetValueOrDefault(generalSettingsCache.IsEnableScreenShake);
generalSettingsCache.IsEnableComboMode = GetBoolOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableComboMode)).GetValueOrDefault(generalSettingsCache.IsEnableComboMode);
generalSettingsCache.IsEnableAudio = GetBoolOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableAudio)).GetValueOrDefault(generalSettingsCache.IsEnableAudio);
return generalSettingsCache;
}
public static void SaveToStorage(GeneralSettings settings, IServiceProvider serviceProvider)
{
if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); }
if (settings == null) { throw new ArgumentNullException("settings"); }
var store = GetSettingsStore(serviceProvider);
SetOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnablePowerMode), settings.IsEnablePowerMode);
SetOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableParticles), settings.IsEnableParticles);
SetOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableScreenShake), settings.IsEnableScreenShake);
SetOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableComboMode), settings.IsEnableComboMode);
SetOption(store, GENERAL_SETTINGS_CATELOG, nameof(GeneralSettings.IsEnableAudio), settings.IsEnableAudio);
}
}
}
| mit | C# |
951b5c7e4d1ef1917402110e6329935b119d6b8d | Replace ASN array with IList | mstrother/BmpListener | BmpListener/Bgp/BgpMessage.cs | BmpListener/Bgp/BgpMessage.cs | using System;
namespace BmpListener.Bgp
{
public abstract class BgpMessage
{
protected const int BgpHeaderLength = 19;
protected BgpMessage(ArraySegment<byte> data)
{
Header = new BgpHeader(data);
var offset = data.Offset + BgpHeaderLength;
var count = Header.Length - BgpHeaderLength;
MessageData = new ArraySegment<byte>(data.Array, offset, count);
}
public enum Type
{
Open = 1,
Update,
Notification,
Keepalive,
RouteRefresh
}
protected ArraySegment<byte> MessageData { get; }
public BgpHeader Header { get; }
public abstract void DecodeFromBytes(ArraySegment<byte> data);
public static BgpMessage GetBgpMessage(ArraySegment<byte> data)
{
var msgType = (Type)data.Array[data.Offset + 18];
switch (msgType)
{
case Type.Open:
return new BgpOpenMessage(data);
case Type.Update:
return new BgpUpdateMessage(data);
case Type.Notification:
return new BgpNotification(data);
case Type.Keepalive:
throw new NotImplementedException();
case Type.RouteRefresh:
throw new NotImplementedException();
default:
throw new NotImplementedException();
}
}
}
} | using System;
using System.Linq;
namespace BmpListener.Bgp
{
public abstract class BgpMessage
{
protected const int BgpHeaderLength = 19;
protected BgpMessage(ref ArraySegment<byte> data)
{
Header = new BgpHeader(data);
var offset = data.Offset + BgpHeaderLength;
var count = Header.Length - BgpHeaderLength;
data = new ArraySegment<byte>(data.Array, offset, count);
}
public enum Type
{
Open = 1,
Update,
Notification,
Keepalive,
RouteRefresh
}
public BgpHeader Header { get; }
public abstract void DecodeFromBytes(ArraySegment<byte> data);
public static BgpMessage GetBgpMessage(ArraySegment<byte> data)
{
var msgType = (Type) data.ElementAt(18);
switch (msgType)
{
case Type.Open:
return new BgpOpenMessage(data);
case Type.Update:
return new BgpUpdateMessage(data);
case Type.Notification:
return new BgpNotification(data);
case Type.Keepalive:
throw new NotImplementedException();
case Type.RouteRefresh:
throw new NotImplementedException();
default:
throw new NotImplementedException();
}
}
}
} | mit | C# |
ea2111f0f4d7848c1d86b66e90dca23ded9fc04a | refactor viewModel | Borayvor/ASP.NET-MVC-CourseProject,Borayvor/ASP.NET-MVC-CourseProject,Borayvor/ASP.NET-MVC-CourseProject | EntertainmentSystem/Web/EntertainmentSystem.Web/Areas/Administration/ViewModels/AdminUserViewModel.cs | EntertainmentSystem/Web/EntertainmentSystem.Web/Areas/Administration/ViewModels/AdminUserViewModel.cs | namespace EntertainmentSystem.Web.Areas.Administration.ViewModels
{
using System.ComponentModel.DataAnnotations;
using Common.Constants;
using Data.Models;
using Infrastructure.Mapping;
using Web.ViewModels;
public class AdminUserViewModel : BaseViewModel<string>, IMapFrom<ApplicationUser>
{
[Display(Name = "First name")]
[Required]
[MaxLength(GlobalConstants.UserFirstNameMaxLength)]
[MinLength(GlobalConstants.UserFirstNameMinLength)]
public string FirstName { get; set; }
[Display(Name = "Last name")]
[Required]
[MaxLength(GlobalConstants.UserLastNameMaxLength)]
[MinLength(GlobalConstants.UserLastNameMinLength)]
public string LastName { get; set; }
[Required]
[MaxLength(GlobalConstants.UserUserNameMaxLength)]
[MinLength(GlobalConstants.UserUserNameMinLength)]
public string UserName { get; set; }
[Display(Name = "Avatar")]
[MaxLength(GlobalConstants.UserAvatarImageUrlMaxLength)]
public string AvatarImageUrl { get; set; }
[Required]
[EmailAddress]
[MaxLength(GlobalConstants.UserEmailMaxLength)]
public string Email { get; set; }
public int VotePoints { get; set; }
}
}
| namespace EntertainmentSystem.Web.Areas.Administration.ViewModels
{
using System.ComponentModel.DataAnnotations;
using Common.Constants;
using Data.Models;
using Infrastructure.Mapping;
using Web.ViewModels;
public class AdminUserViewModel : BaseViewModel<string>, IMapFrom<ApplicationUser>
{
[Display(Name = "First name")]
[Required]
[MaxLength(GlobalConstants.UserFirstNameMaxLength)]
[MinLength(GlobalConstants.UserFirstNameMinLength)]
public string FirstName { get; set; }
[Display(Name = "Last name")]
[Required]
[MaxLength(GlobalConstants.UserLastNameMaxLength)]
[MinLength(GlobalConstants.UserLastNameMinLength)]
public string LastName { get; set; }
[Required]
[MaxLength(GlobalConstants.UserUserNameMaxLength)]
[MinLength(GlobalConstants.UserUserNameMinLength)]
[Display(Name = "User name")]
public string UserNameTrue { get; set; }
[Display(Name = "Avatar")]
[MaxLength(GlobalConstants.UserAvatarImageUrlMaxLength)]
public string AvatarImageUrl { get; set; }
[Required]
[EmailAddress]
[MaxLength(GlobalConstants.UserEmailMaxLength)]
public string Email { get; set; }
public int VotePoints { get; set; }
}
}
| mit | C# |
ce9101b26ed50eaeb2a245cbf5cdbd9bafd700dd | handle infinite timeout on winstore/wp8.1 | tim-hoff/Xamarin.Plugins,JC-Chris/Xamarin.Plugins,labdogg1003/Xamarin.Plugins,LostBalloon1/Xamarin.Plugins,monostefan/Xamarin.Plugins,predictive-technology-laboratory/Xamarin.Plugins,jamesmontemagno/Xamarin.Plugins | Geolocator/Geolocator/Geolocator.Plugin.WindowsPhone81/Timeout.cs | Geolocator/Geolocator/Geolocator.Plugin.WindowsPhone81/Timeout.cs | //
// Copyright 2011-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Threading.Tasks;
namespace Geolocator.Plugin
{
internal class Timeout
{
public Timeout(int timeout, Action timesup)
{
if (timeout == Infite)
return; // nothing to do
if (timeout < 0)
throw new ArgumentOutOfRangeException("timeout");
if (timesup == null)
throw new ArgumentNullException("timesup");
this.timeout = TimeSpan.FromMilliseconds(timeout);
this.timesup = timesup;
Task.Factory.StartNew(Runner, TaskCreationOptions.LongRunning);
}
public void Cancel()
{
this.canceled = true;
}
private readonly TimeSpan timeout;
private readonly Action timesup;
private volatile bool canceled;
private void Runner()
{
DateTime start = DateTime.Now;
while (!this.canceled)
{
if (DateTime.Now - start < this.timeout)
{
Task.Delay(1).Wait();
continue;
}
this.timesup();
return;
}
}
public const int Infite = -1;
}
}
| //
// Copyright 2011-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Threading.Tasks;
namespace Geolocator.Plugin
{
internal class Timeout
{
public Timeout(int timeout, Action timesup)
{
if (timeout < 0)
throw new ArgumentOutOfRangeException("timeout");
if (timesup == null)
throw new ArgumentNullException("timesup");
this.timeout = TimeSpan.FromMilliseconds(timeout);
this.timesup = timesup;
Task.Factory.StartNew(Runner, TaskCreationOptions.LongRunning);
}
public void Cancel()
{
this.canceled = true;
}
private readonly TimeSpan timeout;
private readonly Action timesup;
private volatile bool canceled;
private void Runner()
{
DateTime start = DateTime.Now;
while (!this.canceled)
{
if (DateTime.Now - start < this.timeout)
{
Task.Delay(1).Wait();
continue;
}
this.timesup();
return;
}
}
public const int Infite = -1;
}
}
| mit | C# |
e387ddcb3681e8df0d4d39ad329c358fb236c2b3 | fix typo (#446) | twilio/twilio-csharp | src/Twilio/Types/OutboundCallPriceWithOrigin.cs | src/Twilio/Types/OutboundCallPriceWithOrigin.cs | using System.Collections.Generic;
using Newtonsoft.Json;
namespace Twilio.Types
{
/// <summary>
/// POCO for outbound call price with origin
/// </summary>
public class OutboundCallPriceWithOrigin {
/// <summary>
/// Base price of outbound call
/// </summary>
[JsonProperty("base_price")]
public double? BasePrice { get; }
/// <summary>
/// Current price of outbound call
/// </summary>
/// <returns></returns>
[JsonProperty("current_price")]
public double? CurrentPrice { get; }
/// <summary>
/// List of origination prefixes of outbound call
/// </summary>
/// <returns></returns>
[JsonProperty("origination_prefixes")]
public List<string> OriginationPrefixes { get; }
/// <summary>
/// Create a new OutboundCallPriceWithOrigin
/// </summary>
/// <param name="basePrice">Base price of call</param>
/// <param name="currentPrice">Current price of call</param>
/// <param name="originationPrefixes">List of origination prefixes of call</param>
public OutboundCallPriceWithOrigin (double basePrice, double currentPrice, List<string> originationPrefixes) {
BasePrice = basePrice;
CurrentPrice = currentPrice;
OriginationPrefixes = originationPrefixes;
}
}
} | using System.Collections.Generic;
using Newtonsoft.Json;
namespace Twilio.Types
{
/// <summary>
/// POCO for outbound call price with origin
/// </summary>
public class OutboundCallPriceWithOrigin {
/// <summary>
/// Base price of outbound call
/// </summary>
[JsonProperty("base_price")]
public double? BasePrice { get; }
/// <summary>
/// Current price of outbound call
/// </summary>
/// <returns></returns>
[JsonProperty("base_price")]
public double? CurrentPrice { get; }
/// <summary>
/// List of origination prefixes of outbound call
/// </summary>
/// <returns></returns>
[JsonProperty("origination_prefixes")]
public List<string> OriginationPrefixes { get; }
/// <summary>
/// Create a new OutboundCallPriceWithOrigin
/// </summary>
/// <param name="basePrice">Base price of call</param>
/// <param name="currentPrice">Current price of call</param>
/// <param name="originationPrefixes">List of origination prefixes of call</param>
public OutboundCallPriceWithOrigin (double basePrice, double currentPrice, List<string> originationPrefixes) {
BasePrice = basePrice;
CurrentPrice = currentPrice;
OriginationPrefixes = originationPrefixes;
}
}
} | mit | C# |
e316ceb44dc410931099c2124e35b04e87d00004 | make class abstract | NebulousConcept/b2-csharp-client | b2-csharp-client/B2.Client/Rest/Request/MultipartPostRestRequest.cs | b2-csharp-client/B2.Client/Rest/Request/MultipartPostRestRequest.cs | using System.Net.Http;
using B2.Client.Rest.Request.Param;
namespace B2.Client.Rest.Request
{
/// <summary>
/// A multipart REST request using HTTP POST.
/// </summary>
public abstract class MultipartPostRestRequest : MultipartRestRequest
{
/// <summary>
/// Create a new multipart POST request.
/// </summary>
/// <param name="urlParams">The parameters in the URL.</param>
/// <param name="headerParams">The parameters in the HTTP headerParams.</param>
/// <param name="bodyParams">The parameters in the HTTP body.</param>
/// <param name="dataParams">The data parameters.</param>
protected MultipartPostRestRequest(UrlParams urlParams, HeaderParams headerParams, BodyParams bodyParams, DataParams dataParams)
: base(HttpMethod.Post, urlParams, headerParams, bodyParams, dataParams) { }
}
} | using System.Net.Http;
using B2.Client.Rest.Request.Param;
namespace B2.Client.Rest.Request
{
/// <summary>
/// A multipart REST request using HTTP POST.
/// </summary>
public class MultipartPostRestRequest : MultipartRestRequest
{
/// <summary>
/// Create a new multipart POST request.
/// </summary>
/// <param name="urlParams">The parameters in the URL.</param>
/// <param name="headerParams">The parameters in the HTTP headerParams.</param>
/// <param name="bodyParams">The parameters in the HTTP body.</param>
/// <param name="dataParams">The data parameters.</param>
public MultipartPostRestRequest(UrlParams urlParams, HeaderParams headerParams, BodyParams bodyParams, DataParams dataParams)
: base(HttpMethod.Post, urlParams, headerParams, bodyParams, dataParams) { }
}
} | mit | C# |
1d3cd2d05a062f41de07c397a187537bcad81370 | Fix XWT assembly and type names when locating XWT backends | mono/guiunit | src/framework/GuiUnit/XwtMainLoopIntegration.cs | src/framework/GuiUnit/XwtMainLoopIntegration.cs | using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace GuiUnit
{
public class XwtMainLoopIntegration : IMainLoopIntegration
{
// List of Xwt backends we will try to use in order of priority
Tuple<string,string>[] backends = new[] {
Tuple.Create ("Xwt.Gtk.dll", "Xwt.GtkBackend.GtkEngine, Xwt.Gtk"),
Tuple.Create ("Xwt.WPF.dll", "Xwt.WPFBackend.WPFEngine, Xwt.WPF"),
Tuple.Create ("Xwt.XamMac.dll", "Xwt.Mac.MacEngine, Xwt.XamMac")
};
Type Application {
get; set;
}
public XwtMainLoopIntegration ()
{
Application = Type.GetType ("Xwt.Application, Xwt");
if (Application == null)
throw new NotSupportedException ();
}
public void InitializeToolkit ()
{
Type assemblyType = typeof (Assembly);
PropertyInfo locationProperty = assemblyType.GetProperty ("Location");
if (locationProperty == null)
throw new NotSupportedException();
if (TestRunner.LoadFileMethod == null)
throw new NotSupportedException();
string assemblyDirectory = Path.GetDirectoryName ((string)locationProperty.GetValue (Application.Assembly, null));
// Firstly init Xwt
var initialized = false;
var initMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var initMethod = initMethods.First (m => m.Name == "Initialize" && m.GetParameters ().Length == 1 && m.GetParameters ()[0].ParameterType == typeof (string));
foreach (var impl in backends) {
var xwtImpl = Path.Combine (assemblyDirectory, impl.Item1);
if (File.Exists (xwtImpl)) {
TestRunner.LoadFileMethod.Invoke (null, new[] { xwtImpl });
initMethod.Invoke (null, new object[] { impl.Item2 });
initialized = true;
break;
}
}
if (!initialized)
initMethod.Invoke (null, new object[] { null });
}
public void InvokeOnMainLoop (InvokerHelper helper)
{
var application = Type.GetType ("Xwt.Application, Xwt");
var invokeOnMainThreadMethod = application.GetMethod ("Invoke", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke");
invokeOnMainThreadMethod.Invoke (null, new [] { invoker });
}
public void RunMainLoop ()
{
Application.GetMethod ("Run").Invoke (null, null);
}
public void Shutdown ()
{
Application.GetMethod ("Exit").Invoke (null, null);
}
}
}
| using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace GuiUnit
{
public class XwtMainLoopIntegration : IMainLoopIntegration
{
// List of Xwt backends we will try to use in order of priority
Tuple<string,string>[] backends = new[] {
Tuple.Create ("Xwt.Gtk.dll", "Xwt.GtkBackend.GtkEngine, Xwt.Gtk"),
Tuple.Create ("Xwt.WPF.dll", "Xwt.WPFBackend.WPFEngine, Xwt.WPF"),
Tuple.Create ("Xwt.Mac.dll", "Xwt.Mac.MacEngine, Xwt.Mac")
};
Type Application {
get; set;
}
public XwtMainLoopIntegration ()
{
Application = Type.GetType ("Xwt.Application, Xwt");
if (Application == null)
throw new NotSupportedException ();
}
public void InitializeToolkit ()
{
Type assemblyType = typeof (Assembly);
PropertyInfo locationProperty = assemblyType.GetProperty ("Location");
if (locationProperty == null)
throw new NotSupportedException();
if (TestRunner.LoadFileMethod == null)
throw new NotSupportedException();
string assemblyDirectory = Path.GetDirectoryName ((string)locationProperty.GetValue (Application.Assembly, null));
// Firstly init Xwt
var initialized = false;
var initMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var initMethod = initMethods.First (m => m.Name == "Initialize" && m.GetParameters ().Length == 1 && m.GetParameters ()[0].ParameterType == typeof (string));
foreach (var impl in backends) {
var xwtImpl = Path.Combine (assemblyDirectory, impl.Item1);
if (File.Exists (xwtImpl)) {
TestRunner.LoadFileMethod.Invoke (null, new[] { xwtImpl });
initMethod.Invoke (null, new object[] { impl.Item2 });
initialized = true;
break;
}
}
if (!initialized)
initMethod.Invoke (null, new object[] { null });
}
public void InvokeOnMainLoop (InvokerHelper helper)
{
var application = Type.GetType ("Xwt.Application, Xwt");
var invokeOnMainThreadMethod = application.GetMethod ("Invoke", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke");
invokeOnMainThreadMethod.Invoke (null, new [] { invoker });
}
public void RunMainLoop ()
{
Application.GetMethod ("Run").Invoke (null, null);
}
public void Shutdown ()
{
Application.GetMethod ("Exit").Invoke (null, null);
}
}
}
| mit | C# |
4c2f697858f4838549a8e6d1bfe15557311b3342 | Fix import tracer to property trace all imports | jefflinse/MSBuildTracer | MSBuildTracer/ImportTracer.cs | MSBuildTracer/ImportTracer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using MBEV = Microsoft.Build.Evaluation;
using MBEX = Microsoft.Build.Execution;
namespace MSBuildTracer
{
class ImportTracer
{
private MBEV.Project project;
public ImportTracer(MBEV.Project project)
{
this.project = project;
}
public void Trace(MBEV.ResolvedImport import, int traceLevel = 0)
{
PrintImportInfo(import, traceLevel);
foreach (var childImport in project.Imports.Where(
i => string.Equals(i.ImportingElement.ContainingProject.FullPath,
project.ResolveAllProperties(import.ImportedProject.Location.File),
StringComparison.OrdinalIgnoreCase)))
{
Trace(childImport, traceLevel + 1);
}
}
private void PrintImportInfo(MBEV.ResolvedImport import, int indentCount)
{
var indent = indentCount > 0 ? new StringBuilder().Insert(0, " ", indentCount).ToString() : "";
Utils.WriteColor(indent, ConsoleColor.White);
Utils.WriteColor($"{import.ImportingElement.Location.Line}: ", ConsoleColor.Cyan);
Utils.WriteLineColor(project.ResolveAllProperties(import.ImportedProject.Location.File), ConsoleColor.Green);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using MBEV = Microsoft.Build.Evaluation;
using MBEX = Microsoft.Build.Execution;
namespace MSBuildTracer
{
class ImportTracer
{
private MBEV.Project project;
public ImportTracer(MBEV.Project project)
{
this.project = project;
}
public void Trace(MBEV.ResolvedImport import, int traceLevel = 0)
{
PrintImportInfo(import, traceLevel);
foreach (var childImport in project.Imports.Where(
i => string.Equals(i.ImportingElement.ContainingProject.FullPath,
project.ResolveAllProperties(import.ImportingElement.Project),
StringComparison.OrdinalIgnoreCase)))
{
Trace(childImport, traceLevel + 1);
}
}
private void PrintImportInfo(MBEV.ResolvedImport import, int indentCount)
{
var indent = indentCount > 0 ? new StringBuilder().Insert(0, " ", indentCount).ToString() : "";
Utils.WriteColor(indent, ConsoleColor.White);
Utils.WriteColor($"{import.ImportingElement.Location.Line}: ", ConsoleColor.Cyan);
Utils.WriteLineColor(project.ResolveAllProperties(import.ImportedProject.Location.File), ConsoleColor.Green);
}
}
}
| mit | C# |
7a1525b7f4c631130fa21f4c766287a98bbc337b | Fix MediatR examples exception handlers overrides | jbogard/MediatR | samples/MediatR.Examples/ExceptionHandler/ExceptionsHandlersOverrides.cs | samples/MediatR.Examples/ExceptionHandler/ExceptionsHandlersOverrides.cs | using MediatR.Pipeline;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace MediatR.Examples.ExceptionHandler.Overrides;
public class CommonExceptionHandler : AsyncRequestExceptionHandler<PingResourceTimeout, Pong>
{
private readonly TextWriter _writer;
public CommonExceptionHandler(TextWriter writer) => _writer = writer;
protected override async Task Handle(PingResourceTimeout request,
Exception exception,
RequestExceptionHandlerState<Pong> state,
CancellationToken cancellationToken)
{
// Exception type name required because it is checked later in messages
await _writer.WriteLineAsync($"Handling {exception.GetType().FullName}");
// Exception handler type name required because it is checked later in messages
await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(CommonExceptionHandler).FullName}'").ConfigureAwait(false);
state.SetHandled(new Pong());
}
}
public class ServerExceptionHandler : ExceptionHandler.ServerExceptionHandler
{
private readonly TextWriter _writer;
public ServerExceptionHandler(TextWriter writer) : base(writer) => _writer = writer;
public override async Task Handle(PingNewResource request,
ServerException exception,
RequestExceptionHandlerState<Pong> state,
CancellationToken cancellationToken)
{
// Exception type name required because it is checked later in messages
await _writer.WriteLineAsync($"Handling {exception.GetType().FullName}");
// Exception handler type name required because it is checked later in messages
await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(ServerExceptionHandler).FullName}'").ConfigureAwait(false);
state.SetHandled(new Pong());
}
}
| using MediatR.Pipeline;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace MediatR.Examples.ExceptionHandler.Overrides;
public class CommonExceptionHandler : AsyncRequestExceptionHandler<PingResourceTimeout, Pong>
{
private readonly TextWriter _writer;
public CommonExceptionHandler(TextWriter writer) => _writer = writer;
protected override async Task Handle(PingResourceTimeout request,
Exception exception,
RequestExceptionHandlerState<Pong> state,
CancellationToken cancellationToken)
{
await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(CommonExceptionHandler).FullName}'").ConfigureAwait(false);
state.SetHandled(new Pong());
}
}
public class ServerExceptionHandler : ExceptionHandler.ServerExceptionHandler
{
private readonly TextWriter _writer;
public ServerExceptionHandler(TextWriter writer) : base(writer) => _writer = writer;
public override async Task Handle(PingNewResource request,
ServerException exception,
RequestExceptionHandlerState<Pong> state,
CancellationToken cancellationToken)
{
await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(ServerExceptionHandler).FullName}'").ConfigureAwait(false);
state.SetHandled(new Pong());
}
} | apache-2.0 | C# |
2cd41b96564a6229efee1110175327f50f03df49 | Add Price test | Spreads/Spreads | tests/Spreads.Extensions.Tests/DataTypesTest.cs | tests/Spreads.Extensions.Tests/DataTypesTest.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using System.Runtime.InteropServices;
using System.Threading;
using Spreads.DataTypes;
using Spreads.Serialization;
using Spreads.Storage;
namespace Spreads.Core.Tests {
[TestFixture]
public class DataTypesTest {
[Test]
public void SymbolWorks()
{
var text = "test symbol 16 b";
var symbol = new Symbol(text);
var symbol2 = new Symbol(text);
var symbol3 = new Symbol("different symbol");
Assert.AreEqual(text, symbol.ToString());
Assert.AreEqual(symbol, symbol2);
Assert.AreNotEqual(symbol3, symbol);
Assert.IsTrue(symbol == symbol2);
Assert.IsTrue(symbol3 != symbol2);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
var symbol4 = new Symbol("this symbol is very long");
});
}
[Test]
public void PriceWorks()
{
var price = new Price(42.31400M, 4);
var price2 = new Price(42.31400M, 5);
var price3 = new Price(-42.31400M, 5);
var asString = price.ToString();
Assert.AreEqual("42.3140", asString);
var sum = price + price;
Assert.AreEqual("84.6280", sum.ToString());
var sum2 = price + price2;
Assert.AreEqual("84.62800", sum2.ToString());
Assert.AreEqual(sum2.Exponent, 5);
var sum3 = price + price3;
Assert.AreEqual("0.0000", sum3.ToString());
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using System.Runtime.InteropServices;
using System.Threading;
using Spreads.DataTypes;
using Spreads.Serialization;
using Spreads.Storage;
namespace Spreads.Core.Tests {
[TestFixture]
public class DataTypesTest {
[Test]
public void SymbolWorks()
{
var text = "test symbol 16 b";
var symbol = new Symbol(text);
var symbol2 = new Symbol(text);
var symbol3 = new Symbol("different symbol");
Assert.AreEqual(text, symbol.ToString());
Assert.AreEqual(symbol, symbol2);
Assert.AreNotEqual(symbol3, symbol);
Assert.IsTrue(symbol == symbol2);
Assert.IsTrue(symbol3 != symbol2);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
var symbol4 = new Symbol("this symbol is very long");
});
}
}
}
| mpl-2.0 | C# |
5597306ee8295737e2022ed77c9e3bcceaa9564a | Remove Playing property from SongModel | GeorgeHahn/SOVND | SOVND.Lib/Models/SongModel.cs | SOVND.Lib/Models/SongModel.cs | namespace SOVND.Lib.Models
{
public class SongModel
{
public string SongID { get; set; }
public string Voters { get; set; }
public int Votes { get; set; }
public long Votetime { get; set; }
public bool Removed { get; set; }
}
} | namespace SOVND.Lib.Models
{
public class SongModel
{
public string SongID { get; set; }
public string Voters { get; set; }
public int Votes { get; set; }
public long Votetime { get; set; }
public bool Removed { get; set; }
public bool Playing { get; set; }
}
} | epl-1.0 | C# |
6035869f05545d8f18b7c07b291c71ddd25c348d | Move from MSTest to NUnit | aloisdg/SharpResume | SharpResume.Tests/UnitTest.cs | SharpResume.Tests/UnitTest.cs | using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using SharpResume.Model;
using Assert = NUnit.Framework.Assert;
namespace SharpResume.Tests
{
[TestFixture]
public class UnitTest
{
const string JsonName = "resume.json";
static readonly string _json = File.ReadAllText(Path.Combine(
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName,
JsonName));
readonly Resume _resume = Resume.Create(_json);
readonly dynamic _expected = JObject.Parse(_json);
[Test]
public void TestName()
{
string name = _expected.basics.name;
Assert.AreEqual(name, _resume.Basics.Name);
}
[Test]
public void TestCoursesCount()
{
var educations = _expected.education.ToObject<List<Education>>();
Assert.AreEqual(educations.Count, _resume.Education.Length);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using SharpResume.Model;
using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
namespace SharpResume.Tests
{
[TestClass]
public class UnitTest
{
const string JsonName = "resume.json";
static readonly string _json = File.ReadAllText(Path.Combine(
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName,
JsonName));
readonly Resume _resume = Resume.Create(_json);
readonly dynamic _expected = JObject.Parse(_json);
[TestMethod]
public void TestName()
{
string name = _expected.basics.name;
Assert.AreEqual(name, _resume.Basics.Name);
}
[TestMethod]
public void TestCoursesCount()
{
var educations = _expected.education.ToObject<List<Education>>();
Assert.AreEqual(educations.Count, _resume.Education.Length);
}
}
}
| mit | C# |
fc54ffc96e428c8ec609ccc8267183ba72c842f9 | fix build | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/Microsoft.AspNetCore.WebSockets.Internal.ConformanceTest/Helpers.cs | test/Microsoft.AspNetCore.WebSockets.Internal.ConformanceTest/Helpers.cs | // 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;
using System.IO;
namespace Microsoft.AspNetCore.WebSockets.Internal.ConformanceTest
{
public class Helpers
{
public static string GetApplicationPath(string projectName)
{
var applicationBasePath = AppContext.BaseDirectory;
var directoryInfo = new DirectoryInfo(applicationBasePath);
do
{
var solutionFileInfo = new FileInfo(Path.Combine(directoryInfo.FullName, "SignalR.sln"));
if (solutionFileInfo.Exists)
{
return Path.GetFullPath(Path.Combine(directoryInfo.FullName, "test", projectName));
}
directoryInfo = directoryInfo.Parent;
}
while (directoryInfo.Parent != null);
throw new Exception($"Solution root could not be found using {applicationBasePath}");
}
}
}
| // 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;
using System.IO;
using Microsoft.Extensions.PlatformAbstractions;
namespace Microsoft.AspNetCore.WebSockets.Internal.ConformanceTest
{
public class Helpers
{
public static string GetApplicationPath(string projectName)
{
var applicationBasePath = PlatformServices.Default.Application.ApplicationBasePath;
var directoryInfo = new DirectoryInfo(applicationBasePath);
do
{
var solutionFileInfo = new FileInfo(Path.Combine(directoryInfo.FullName, "SignalR.sln"));
if (solutionFileInfo.Exists)
{
return Path.GetFullPath(Path.Combine(directoryInfo.FullName, "test", projectName));
}
directoryInfo = directoryInfo.Parent;
}
while (directoryInfo.Parent != null);
throw new Exception($"Solution root could not be found using {applicationBasePath}");
}
}
}
| apache-2.0 | C# |
ccb64a98c40b656cf12f70153698464555ef7e8e | Fix comment (which was in an unsaved file, unfortunately) | googleapis/google-cloudevents-dotnet,googleapis/google-cloudevents-dotnet | src/Google.Events.Protobuf/Cloud/PubSub/V1/ConverterAttributes.cs | src/Google.Events.Protobuf/Cloud/PubSub/V1/ConverterAttributes.cs | // Copyright 2020, Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// TODO: Generate this file!
// This file contains partial classes for all event data messages, to apply
// the converter attributes to them.
namespace Google.Events.Protobuf.Cloud.PubSub.V1
{
[CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<PubsubMessage>))]
public partial class PubsubMessage { }
}
| // Copyright 2020, Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// TODO: Generate this file!
// This file contains partial classes for all event and event data messages, to apply
// the converter attributes to them.
namespace Google.Events.Protobuf.Cloud.PubSub.V1
{
[CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<PubsubMessage>))]
public partial class PubsubMessage { }
}
| apache-2.0 | C# |
d3e5beb5e1e410758803646f4fa4b681b822e994 | Disable F# test. | sdanyliv/linq2db,fraillt/linq2db,barsgroup/bars2db,lvaleriu/linq2db,MaceWindu/linq2db,LinqToDB4iSeries/linq2db,AK107/linq2db,fraillt/linq2db,ronnyek/linq2db,rechkalov/linq2db,scratch-net/linq2db,LinqToDB4iSeries/linq2db,giuliohome/linq2db,genusP/linq2db,linq2db/linq2db,AK107/linq2db,yonglehou/linq2db,inickvel/linq2db,MaceWindu/linq2db,scratch-net/linq2db,linq2db/linq2db,jogibear9988/linq2db,lvaleriu/linq2db,yonglehou/linq2db,jogibear9988/linq2db,sdanyliv/linq2db,genusP/linq2db,enginekit/linq2db,stdray/linq2db,barsgroup/linq2db | Tests/Linq/Linq/FSharpTest.cs | Tests/Linq/Linq/FSharpTest.cs | using System;
using NUnit.Framework;
namespace Tests.Linq
{
[TestFixture]
public class FSharpTest : TestBase
{
[Test, DataContextSource]
public void LoadSingle(string context)
{
using (var db = GetDataContext(context))
FSharp.WhereTest.LoadSingle(db);
}
[Test, DataContextSource]
public void LoadSingleComplexPerson(string context)
{
using (var db = GetDataContext(context))
FSharp.WhereTest.LoadSingleComplexPerson(db);
}
[Test, DataContextSource]
public void LoadSingleDeeplyComplexPerson(string context)
{
using (var db = GetDataContext(context))
FSharp.WhereTest.LoadSingleDeeplyComplexPerson(db);
}
[Test, DataContextSource]
public void LoadColumnOfDeeplyComplexPerson(string context)
{
using (var db = GetDataContext(context))
FSharp.WhereTest.LoadColumnOfDeeplyComplexPerson(db);
}
[Test, DataContextSource]
public void SelectField(string context)
{
using (var db = GetDataContext(context))
FSharp.SelectTest.SelectField(db);
}
[Test, DataContextSource, Ignore("Not currently supported")]
public void SelectFieldDeeplyComplexPerson(string context)
{
using (var db = GetDataContext(context))
FSharp.SelectTest.SelectFieldDeeplyComplexPerson(db);
}
[Test, DataContextSource]
public void Insert1(string context)
{
using (var db = GetDataContext(context))
FSharp.InsertTest.Insert1(db);
}
[Test, DataContextSource, Ignore("It breaks following tests.")]
public void Insert2(string context)
{
using (var db = GetDataContext(context))
FSharp.InsertTest.Insert2(db);
}
}
}
| using System;
using NUnit.Framework;
namespace Tests.Linq
{
[TestFixture]
public class FSharpTest : TestBase
{
[Test, DataContextSource]
public void LoadSingle(string context)
{
using (var db = GetDataContext(context))
FSharp.WhereTest.LoadSingle(db);
}
[Test, DataContextSource]
public void LoadSingleComplexPerson(string context)
{
using (var db = GetDataContext(context))
FSharp.WhereTest.LoadSingleComplexPerson(db);
}
[Test, DataContextSource]
public void LoadSingleDeeplyComplexPerson(string context)
{
using (var db = GetDataContext(context))
FSharp.WhereTest.LoadSingleDeeplyComplexPerson(db);
}
[Test, DataContextSource]
public void LoadColumnOfDeeplyComplexPerson(string context)
{
using (var db = GetDataContext(context))
FSharp.WhereTest.LoadColumnOfDeeplyComplexPerson(db);
}
[Test, DataContextSource]
public void SelectField(string context)
{
using (var db = GetDataContext(context))
FSharp.SelectTest.SelectField(db);
}
[Test, DataContextSource, Ignore("Not currently supported")]
public void SelectFieldDeeplyComplexPerson(string context)
{
using (var db = GetDataContext(context))
FSharp.SelectTest.SelectFieldDeeplyComplexPerson(db);
}
[Test, DataContextSource]
public void Insert1(string context)
{
using (var db = GetDataContext(context))
FSharp.InsertTest.Insert1(db);
}
[Test, DataContextSource]
public void Insert2(string context)
{
using (var db = GetDataContext(context))
FSharp.InsertTest.Insert2(db);
}
}
}
| mit | C# |
e2c93e748418feb07699de9066d39afe1555641b | Add timings | kamsar/Leprechaun | src/Leprechaun.Console/Program.cs | src/Leprechaun.Console/Program.cs | using System;
using System.Diagnostics;
using System.Xml;
using Leprechaun.CodeGen;
using Leprechaun.Console.Variables;
namespace Leprechaun.Console
{
class Program
{
static void Main(string[] args)
{
// args:
// -watch
// -config=c:\foo.config
// ??
var timer = new Stopwatch();
timer.Start();
var configuration = BuildConfiguration();
var orchestrator = configuration.Shared.Resolve<Orchestrator>();
var metadata = orchestrator.GenerateMetadata(configuration.Configurations);
foreach (var meta in metadata)
{
var codeGen = meta.Configuration.Resolve<ICodeGenerator>();
codeGen.GenerateCode(meta);
}
timer.Stop();
System.Console.ForegroundColor = ConsoleColor.Green;
System.Console.WriteLine($"Leprechaun has completed in {timer.ElapsedMilliseconds}ms.");
System.Console.ResetColor();
System.Console.ReadKey();
}
private static LeprechaunConfigurationBuilder BuildConfiguration()
{
var config = new XmlDocument();
config.Load("Leprechaun.config");
var replacer = new ChainedVariablesReplacer(new ConfigurationNameVariablesReplacer(), new HelixConventionVariablesReplacer());
return new LeprechaunConfigurationBuilder(replacer, config.DocumentElement["configurations"], config.DocumentElement["defaults"], config.DocumentElement["shared"]);
}
}
}
| using System.Xml;
using Leprechaun.CodeGen;
using Leprechaun.Console.Variables;
namespace Leprechaun.Console
{
class Program
{
static void Main(string[] args)
{
// args:
// -watch
// -config=c:\foo.config
// ??
var configuration = BuildConfiguration();
var orchestrator = configuration.Shared.Resolve<Orchestrator>();
var metadata = orchestrator.GenerateMetadata(configuration.Configurations);
foreach (var meta in metadata)
{
var codeGen = meta.Configuration.Resolve<ICodeGenerator>();
codeGen.GenerateCode(meta);
}
System.Console.ReadKey();
}
private static LeprechaunConfigurationBuilder BuildConfiguration()
{
var config = new XmlDocument();
config.Load("Leprechaun.config");
var replacer = new ChainedVariablesReplacer(new ConfigurationNameVariablesReplacer(), new HelixConventionVariablesReplacer());
return new LeprechaunConfigurationBuilder(replacer, config.DocumentElement["configurations"], config.DocumentElement["defaults"], config.DocumentElement["shared"]);
}
}
}
| mit | C# |
0a6c2444ec570fc08bb5db0a9fcc75fd008f7546 | Fix nested if statement | stevedesmond-ca/dotnet-libyear | src/LibYear.Lib/PackageVersion.cs | src/LibYear.Lib/PackageVersion.cs | using System;
using NuGet.Versioning;
namespace LibYear.Lib
{
public class PackageVersion : NuGetVersion
{
public bool IsWildcard { get; }
public PackageVersion(string version)
: this(Parse(version))
{
}
public PackageVersion(bool isWildcard)
: this(0, 0, 0)
{
IsWildcard = isWildcard;
}
public PackageVersion(NuGetVersion version)
: base(version)
{
}
public PackageVersion(int major, int minor, int patch)
: base(major, minor, patch)
{
}
public PackageVersion(int major, int minor, int patch, int revision)
: base(major, minor, patch, revision)
{
}
public new static PackageVersion Parse(string version)
{
if (version.Equals("*"))
{
return new PackageVersion(true);
}
return new PackageVersion(NuGetVersion.Parse(version));
}
public override string ToString()
{
if (string.IsNullOrEmpty(OriginalVersion) || IsSemVer2)
{
return ToString("N", VersionFormatter.Instance);
}
return OriginalVersion;
}
public new virtual string ToString(string format, IFormatProvider formatProvider)
{
if (formatProvider == null
|| !TryFormatter(format, formatProvider, out string formattedString))
{
formattedString = ToString();
}
return formattedString;
}
protected new bool TryFormatter(string format, IFormatProvider formatProvider, out string formattedString)
{
if (formatProvider is ICustomFormatter formatter)
{
formattedString = formatter.Format(format, this, formatProvider);
return true;
}
formattedString = null;
return false;
}
}
} | using System;
using NuGet.Versioning;
namespace LibYear.Lib
{
public class PackageVersion : NuGetVersion
{
public bool IsWildcard { get; private set; }
public PackageVersion(string version)
: this(Parse(version))
{
}
public PackageVersion(bool isWildcard)
: this(0,0,0)
{
IsWildcard = isWildcard;
}
public PackageVersion(NuGetVersion version)
: base(version)
{
}
public PackageVersion(int major, int minor, int patch)
: base(major, minor, patch)
{
}
public PackageVersion(int major, int minor, int patch, int revision)
: base(major, minor, patch, revision)
{
}
public new static PackageVersion Parse(string version)
{
if (version.Equals("*"))
{
return new PackageVersion(true);
}
return new PackageVersion(NuGetVersion.Parse(version));
}
public override string ToString()
{
if (string.IsNullOrEmpty(OriginalVersion) || IsSemVer2)
{
return ToString("N", VersionFormatter.Instance);
}
return OriginalVersion;
}
public new virtual string ToString(string format, IFormatProvider formatProvider)
{
if (formatProvider == null
|| !TryFormatter(format, formatProvider, out string formattedString))
{
formattedString = ToString();
}
return formattedString;
}
protected new bool TryFormatter(string format, IFormatProvider formatProvider, out string formattedString)
{
var formatted = false;
formattedString = null;
if (formatProvider != null)
{
if (formatProvider is ICustomFormatter formatter)
{
formatted = true;
formattedString = formatter.Format(format, this, formatProvider);
}
}
return formatted;
}
}
} | mit | C# |
add533cdc6fb091222ceb14ac47c4a94eb72d01d | Allow manual changing of Value | jcmoyer/Yeena | Yeena/Data/PersistentCache.cs | Yeena/Data/PersistentCache.cs | // Copyright 2013 J.C. Moyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Threading.Tasks;
namespace Yeena.Data {
abstract class PersistentCache<T> where T : class {
protected string Name { get; private set; }
public T Value { get; set; }
protected PersistentCache(string name) {
Name = name;
}
public T Load(Func<T> factory) {
OnLoad();
return Value ?? (Value = factory());
}
public async Task<T> LoadAsync(Func<Task<T>> factory) {
OnLoad();
return Value ?? (Value = await factory());
}
public void Save() {
OnSave();
}
protected abstract void OnLoad();
protected abstract void OnSave();
}
}
| // Copyright 2013 J.C. Moyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Threading.Tasks;
namespace Yeena.Data {
abstract class PersistentCache<T> where T : class {
protected string Name { get; private set; }
public T Value { get; protected set; }
protected PersistentCache(string name) {
Name = name;
}
public T Load(Func<T> factory) {
OnLoad();
return Value ?? (Value = factory());
}
public async Task<T> LoadAsync(Func<Task<T>> factory) {
OnLoad();
return Value ?? (Value = await factory());
}
public void Save() {
OnSave();
}
protected abstract void OnLoad();
protected abstract void OnSave();
}
}
| apache-2.0 | C# |
c4ba83bdf316d1d5b65d87d264cfa03f1605d7e3 | Remove mispredict testing code. | space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Shared/GameObjects/EntitySystems/SharedCombatModeSystem.cs | Content.Shared/GameObjects/EntitySystems/SharedCombatModeSystem.cs | using Content.Shared.GameObjects.Components.Mobs;
using Content.Shared.GameObjects.EntitySystemMessages;
using Content.Shared.Interfaces;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.Random;
using Robust.Shared.IoC;
using Robust.Shared.Random;
using Logger = Robust.Shared.Log.Logger;
namespace Content.Shared.GameObjects.EntitySystems
{
public abstract class SharedCombatModeSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeNetworkEvent<CombatModeSystemMessages.SetCombatModeActiveMessage>(CombatModeActiveHandler);
SubscribeLocalEvent<CombatModeSystemMessages.SetCombatModeActiveMessage>(CombatModeActiveHandler);
}
private void CombatModeActiveHandler(CombatModeSystemMessages.SetCombatModeActiveMessage ev, EntitySessionEventArgs eventArgs)
{
var entity = eventArgs.SenderSession.AttachedEntity;
if (!entity.TryGetComponent(out SharedCombatModeComponent combatModeComponent))
{
return;
}
combatModeComponent.IsInCombatMode = ev.Active;
}
}
}
| using Content.Shared.GameObjects.Components.Mobs;
using Content.Shared.GameObjects.EntitySystemMessages;
using Content.Shared.Interfaces;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.Random;
using Robust.Shared.IoC;
using Robust.Shared.Random;
using Logger = Robust.Shared.Log.Logger;
namespace Content.Shared.GameObjects.EntitySystems
{
public abstract class SharedCombatModeSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeNetworkEvent<CombatModeSystemMessages.SetCombatModeActiveMessage>(CombatModeActiveHandler);
SubscribeLocalEvent<CombatModeSystemMessages.SetCombatModeActiveMessage>(CombatModeActiveHandler);
}
private void CombatModeActiveHandler(CombatModeSystemMessages.SetCombatModeActiveMessage ev, EntitySessionEventArgs eventArgs)
{
var entity = eventArgs.SenderSession.AttachedEntity;
if (!entity.TryGetComponent(out SharedCombatModeComponent combatModeComponent))
{
return;
}
if (IoCManager.Resolve<IModuleManager>().IsServerModule && IoCManager.Resolve<IRobustRandom>().Prob(0.5f))
{
Logger.Info("Mispredict!");
return;
}
combatModeComponent.IsInCombatMode = ev.Active;
}
}
}
| mit | C# |
0a7c47dd673f7347932ffaf685f695cdaaff2e9f | update about | tolu/tobiaslundin.se | src/Views/Home/About.cshtml | src/Views/Home/About.cshtml | @{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>LinkedIn motto</h3>
<p>My dream is to find, or create, the job that makes a perfect blend of social life, hobbies and work.</p>
<p>Meanwhile I´ll keep learning about new technologies and best practices, meeting exciting people and getting to know different organizations and I'll keep traveling to places I´ve not yet placed my foot to broaden my view and to aquire new perspectives of life.</p>
<p>I´ll read interesting books about psychology and philosophy, hopefully getting a grip on the nature of reality, the value of time or the ethics of gods.</p>
<p>
I´ve been engaged in many student societies and love what it taught me about what a few people could do with just a burning desire to help others with a zeroed account as baseline.
I´ve recruited students to work at the student pub, I´ve been a councillor in the student delegate body.
I've arranged the reception for the new students, from Sweden and abroad and learned valuable lessons about cultural differences.
I´m very sociable and through my commitments I´ve aquired a large network of friends and acquaintances.
</p>
<p>I specialize in front end development</p>
<p>Since 2011 I've been working with NRK (The Norwegian public broadcaster) building https://tv.nrk.no, http://radio.nrk.no, Chromecast and AppleTV-apps</p> | @{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>LinkedIn motto</h3>
<p>My dream is to find, or create, the job that makes a perfect blend of social life, hobbies and work. And I´ll tell you, Netlight is a pretty damn good place to be for that recipe!</p>
<p>Meanwhile I´ll keep learning about new technologies and best practices, meeting exciting people and getting to know different organizations and I'll keep traveling to places I´ve not yet placed my foot to broaden my view and to aquire new perspectives of life.</p>
<p>I´ll read interesting books about psychology and philosophy, hopefully getting a grip on the nature of reality, the value of time or the ethics of gods.</p>
<p>
I´ve been engaged in many student societies and love what it taught me about what a few people could do with just a burning desire to help others with a zeroed account as baseline.
I´ve recruited students to work at the student pub, I´ve been a councillor in the student delegate body.
I've arranged the reception for the new students, from Sweden and abroad and learned valuable lessons about cultural differences.
I´m very sociable and through my commitments I´ve aquired a large network of friends and acquaintances.
</p>
<p>I specialize in front end development, C#, Asp.Net mvc and have spent my days building http://tv.nrk.no for the last 3 years.</p> | mit | C# |
323728833fb87df9d9eeea746f9b4f24295e1797 | Prepare for a release - this will go out with v2 R255 | xibosignage/xibo-windows-client-watchdog | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XiboClientWatchdog")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XiboClientWatchdog")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("ec4eaabc-ad30-4ac5-8e0a-0ddb06dad4b1")]
// 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.3.0")]
[assembly: AssemblyFileVersion("1.0.3.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XiboClientWatchdog")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XiboClientWatchdog")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("ec4eaabc-ad30-4ac5-8e0a-0ddb06dad4b1")]
// 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.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
| agpl-3.0 | C# |
a38d72edf383e7f4c26e18d7ab698fad86b75a47 | Update CombineMultipleWorkbooksSingleWorkbook.cs | aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Articles/CombineMultipleWorkbooksSingleWorkbook.cs | Examples/CSharp/Articles/CombineMultipleWorkbooksSingleWorkbook.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class CombineMultipleWorkbooksSingleWorkbook
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Define the first source
//Open the first excel file.
Workbook SourceBook1 = new Workbook(dataDir+ "SampleChart.xlsx");
//Define the second source book.
//Open the second excel file.
Workbook SourceBook2 = new Workbook(dataDir+ "SampleImage.xlsx");
//Combining the two workbooks
SourceBook1.Combine(SourceBook2);
//Save the target book file.
SourceBook1.Save(dataDir+ "Combined.out.xlsx");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class CombineMultipleWorkbooksSingleWorkbook
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Define the first source
//Open the first excel file.
Workbook SourceBook1 = new Workbook(dataDir+ "SampleChart.xlsx");
//Define the second source book.
//Open the second excel file.
Workbook SourceBook2 = new Workbook(dataDir+ "SampleImage.xlsx");
//Combining the two workbooks
SourceBook1.Combine(SourceBook2);
//Save the target book file.
SourceBook1.Save(dataDir+ "Combined.out.xlsx");
}
}
} | mit | C# |
f50cdf5ac7ae56c41f022edab867ca7062b1d0de | Add logging to missing underlying enum type | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | csharp/extractor/Semmle.Extraction.CIL/Entities/CustomAttributeDecoder.cs | csharp/extractor/Semmle.Extraction.CIL/Entities/CustomAttributeDecoder.cs | using System;
using System.Reflection.Metadata;
namespace Semmle.Extraction.CIL.Entities
{
/// <summary>
/// Helper class to decode the attribute structure.
/// Note that there are some unhandled cases that should be fixed in due course.
/// </summary>
internal class CustomAttributeDecoder : ICustomAttributeTypeProvider<Type>
{
private readonly Context cx;
public CustomAttributeDecoder(Context cx) { this.cx = cx; }
public Type GetPrimitiveType(PrimitiveTypeCode typeCode) => cx.Create(typeCode);
public Type GetSystemType() => new NoMetadataHandleType(cx, "System.Type");
public Type GetSZArrayType(Type elementType) =>
cx.Populate(new ArrayType(cx, elementType));
public Type GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) =>
(Type)cx.Create(handle);
public Type GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) =>
(Type)cx.Create(handle);
public Type GetTypeFromSerializedName(string name) => new NoMetadataHandleType(cx, name);
public PrimitiveTypeCode GetUnderlyingEnumType(Type type)
{
if (type is TypeDefinitionType tdt &&
tdt.GetUnderlyingEnumType() is var underlying &&
underlying.HasValue)
{
return underlying.Value;
}
var name = type.GetQualifiedName();
cx.Cx.Extractor.Logger.Log(Util.Logging.Severity.Info, $"Couldn't get underlying enum type for {name}");
// We can't fall back to Int32, because the type returned here defines how many bytes are read from the
// stream and how those bytes are interpreted.
throw new NotImplementedException();
}
public bool IsSystemType(Type type) => type.GetQualifiedName() == "System.Type";
}
}
| using System;
using System.Reflection.Metadata;
namespace Semmle.Extraction.CIL.Entities
{
/// <summary>
/// Helper class to decode the attribute structure.
/// Note that there are some unhandled cases that should be fixed in due course.
/// </summary>
internal class CustomAttributeDecoder : ICustomAttributeTypeProvider<Type>
{
private readonly Context cx;
public CustomAttributeDecoder(Context cx) { this.cx = cx; }
public Type GetPrimitiveType(PrimitiveTypeCode typeCode) => cx.Create(typeCode);
public Type GetSystemType() => new NoMetadataHandleType(cx, "System.Type");
public Type GetSZArrayType(Type elementType) =>
cx.Populate(new ArrayType(cx, elementType));
public Type GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) =>
(Type)cx.Create(handle);
public Type GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) =>
(Type)cx.Create(handle);
public Type GetTypeFromSerializedName(string name) => new NoMetadataHandleType(cx, name);
public PrimitiveTypeCode GetUnderlyingEnumType(Type type)
{
if (type is TypeDefinitionType tdt &&
tdt.GetUnderlyingEnumType() is var underlying &&
underlying.HasValue)
{
return underlying.Value;
}
// We can't fall back to Int32, because the type returned here defines how many bytes are read from the
// stream and how those bytes are interpreted.
throw new NotImplementedException();
}
public bool IsSystemType(Type type) => type.GetQualifiedName() == "System.Type";
}
}
| mit | C# |
d8374b76cc712153a10ed6d36f1ad3dfc68d0d6e | Return IEnumerable<FulfillmentOrder> instead of ListResult<FulfillmentOrder> | nozzlegear/ShopifySharp,clement911/ShopifySharp | ShopifySharp/Services/FulfillmentOrders/FulfillmentOrderService.cs | ShopifySharp/Services/FulfillmentOrders/FulfillmentOrderService.cs | using System.Net.Http;
using ShopifySharp.Filters;
using System.Collections.Generic;
using System.Threading.Tasks;
using ShopifySharp.Infrastructure;
using System;
using System.Threading;
using ShopifySharp.Lists;
namespace ShopifySharp
{
/// <summary>
/// A service for manipulating Shopify fulfillment orders.
/// </summary>
public class FulfillmentOrderService : ShopifyService
{
/// <summary>
/// Creates a new instance of <see cref="FulfillmentOrderService" />.
/// </summary>
/// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param>
/// <param name="shopAccessToken">An API access token for the shop.</param>
public FulfillmentOrderService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { }
/// <summary>
/// Gets a list of up to 250 of the order's fulfillments.
/// </summary>
/// <param name="orderId">The order id to which the fulfillments belong.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<IEnumerable<FulfillmentOrder>> ListAsync(long orderId, CancellationToken cancellationToken = default)
{
var req = PrepareRequest($"orders/{orderId}/fulfillment_orders.json");
var response = await ExecuteRequestAsync<IEnumerable<FulfillmentOrder>>(req, HttpMethod.Get, cancellationToken, rootElement: "fulfillment_orders");
return response.Result;
}
}
}
| using System.Net.Http;
using ShopifySharp.Filters;
using System.Collections.Generic;
using System.Threading.Tasks;
using ShopifySharp.Infrastructure;
using System;
using System.Threading;
using ShopifySharp.Lists;
namespace ShopifySharp
{
/// <summary>
/// A service for manipulating Shopify fulfillment orders.
/// </summary>
public class FulfillmentOrderService : ShopifyService
{
/// <summary>
/// Creates a new instance of <see cref="FulfillmentOrderService" />.
/// </summary>
/// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param>
/// <param name="shopAccessToken">An API access token for the shop.</param>
public FulfillmentOrderService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { }
/// <summary>
/// Gets a list of up to 250 of the order's fulfillments.
/// </summary>
/// <param name="orderId">The order id to which the fulfillments belong.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<ListResult<FulfillmentOrder>> ListAsync(long orderId, CancellationToken cancellationToken = default)
{
return await ExecuteGetListAsync<FulfillmentOrder>($"orders/{orderId}/fulfillment_orders.json", "fulfillment_orders",null, cancellationToken);
}
}
}
| mit | C# |
111f494ab8cb2b1c25335db6b20b52af18ff1d39 | Fix TestResult mapping | cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium | Src/MaintainableSelenium/MaintainableSelenium.VisualAssertions/Infrastructure/Persistence/Mappings/TestResultMap.cs | Src/MaintainableSelenium/MaintainableSelenium.VisualAssertions/Infrastructure/Persistence/Mappings/TestResultMap.cs | using FluentNHibernate.Mapping;
using MaintainableSelenium.VisualAssertions.Screenshots.Domain;
namespace MaintainableSelenium.VisualAssertions.Infrastructure.Persistence.Mappings
{
public class TestResultMap : ClassMap<TestResult>
{
public TestResultMap()
{
Id(x => x.Id);
Map(x => x.ScreenshotName);
Map(x => x.BrowserName);
Map(x => x.TestPassed);
Map(x => x.Category);
Map(x => x.ErrorScreenshot).Length(int.MaxValue).LazyLoad();
References(x => x.Pattern);
References(x => x.TestSession);
HasManyToMany(x => x.BlindRegionsSnapshot).Cascade.Persist().Table("TestResultBlindRegionsSnapshot");
}
}
} | using FluentNHibernate.Mapping;
using MaintainableSelenium.VisualAssertions.Screenshots.Domain;
namespace MaintainableSelenium.VisualAssertions.Infrastructure.Persistence.Mappings
{
public class TestResultMap : ClassMap<TestResult>
{
public TestResultMap()
{
Id(x => x.Id);
Map(x => x.ScreenshotName);
Map(x => x.BrowserName);
Map(x => x.TestPassed);
Map(x => x.Category);
Map(x => x.ErrorScreenshot).Length(int.MaxValue).LazyLoad();
References(x => x.Pattern);
References(x => x.TestSession);
HasMany(x => x.BlindRegionsSnapshot).Cascade.Persist();
}
}
} | mit | C# |
c95647ff91ab64f93bb1f2ab583cf5d064b41a55 | fix feedback | AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell | src/ResourceManager/AnalysisServices/Commands.AnalysisServices/Commands/NewAzureRmAnalysisServicesFirewallConfig.cs | src/ResourceManager/AnalysisServices/Commands.AnalysisServices/Commands/NewAzureRmAnalysisServicesFirewallConfig.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.AnalysisServices.Models;
using Microsoft.Azure.Commands.AnalysisServices.Properties;
using Microsoft.Rest.Azure;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using System.Collections.Generic;
namespace Microsoft.Azure.Commands.AnalysisServices
{
[Cmdlet(VerbsCommon.New, "AzureRmAnalysisServicesFirewallConfig"), OutputType(typeof(PsAzureAnalysisServicesFirewallConfig))]
public class NewAzureRmAnalysisServicesFirewallConfig : AnalysisServicesCmdletBase
{
[Parameter(ValueFromPipelineByPropertyName = true, Position = 0, Mandatory = true,
HelpMessage = "Option to enable PowerBI service")]
[ValidateNotNullOrEmpty]
public SwitchParameter EnablePowerBIService { get; set; }
[Parameter(ValueFromPipelineByPropertyName = true, Position = 1, Mandatory = false,
HelpMessage = "Firewall rules")]
public List<PsAzureAnalysisServicesFirewallRule> FirewallRule { get; set; }
public override void ExecuteCmdlet()
{
PsAzureAnalysisServicesFirewallConfig config = new PsAzureAnalysisServicesFirewallConfig((EnablePowerBIService) ? true : false, FirewallRule);
WriteObject(config);
}
public NewAzureRmAnalysisServicesFirewallConfig()
{
}
}
} | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.AnalysisServices.Models;
using Microsoft.Azure.Commands.AnalysisServices.Properties;
using Microsoft.Rest.Azure;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using System.Collections.Generic;
namespace Microsoft.Azure.Commands.AnalysisServices
{
[Cmdlet(VerbsCommon.New, "AzureRmAnalysisServicesFirewallConfig"), OutputType(typeof(PsAzureAnalysisServicesFirewallConfig))]
public class NewAzureRmAnalysisServicesFirewallConfig : AnalysisServicesCmdletBase
{
[Parameter(ValueFromPipelineByPropertyName = true, Position = 0, Mandatory = true,
HelpMessage = "Option to enable PowerBI service")]
[ValidateNotNullOrEmpty]
public bool EnablePowerBIService { get; set; }
[Parameter(ValueFromPipelineByPropertyName = true, Position = 1, Mandatory = false,
HelpMessage = "Firewall rules")]
public List<PsAzureAnalysisServicesFirewallRule> FirewallRule { get; set; }
public override void ExecuteCmdlet()
{
PsAzureAnalysisServicesFirewallConfig config = new PsAzureAnalysisServicesFirewallConfig(EnablePowerBIService, FirewallRule);
WriteObject(config);
}
public NewAzureRmAnalysisServicesFirewallConfig()
{
}
}
} | apache-2.0 | C# |
6915db67f2c071742814afde0ec9e877402e6812 | Update tests to properly return tasks. | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectAuthenticationHandlerForTestingAuthenticate.cs | test/Microsoft.AspNet.Authentication.Test/OpenIdConnect/OpenIdConnectAuthenticationHandlerForTestingAuthenticate.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.OpenIdConnect;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Newtonsoft.Json.Linq;
namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
{
/// <summary>
/// Allows for custom processing of ApplyResponseChallenge, ApplyResponseGrant and AuthenticateCore
/// </summary>
public class OpenIdConnectAuthenticationHandlerForTestingAuthenticate : OpenIdConnectAuthenticationHandler
{
public OpenIdConnectAuthenticationHandlerForTestingAuthenticate()
: base(null)
{
}
protected override async Task<bool> HandleUnauthorizedAsync(ChallengeContext context)
{
return await base.HandleUnauthorizedAsync(context);
}
protected override Task<OpenIdConnectTokenEndpointResponse> RedeemAuthorizationCodeAsync(string authorizationCode, string redirectUri)
{
var jsonResponse = new JObject();
jsonResponse.Add(OpenIdConnectParameterNames.IdToken, "test token");
return Task.FromResult(new OpenIdConnectTokenEndpointResponse(jsonResponse));
}
protected override Task<AuthenticationTicket> GetUserInformationAsync(AuthenticationProperties properties, OpenIdConnectMessage message, AuthenticationTicket ticket)
{
var claimsIdentity = (ClaimsIdentity)ticket.Principal.Identity;
if (claimsIdentity == null)
{
claimsIdentity = new ClaimsIdentity();
}
claimsIdentity.AddClaim(new Claim("test claim", "test value"));
return Task.FromResult(new AuthenticationTicket(new ClaimsPrincipal(claimsIdentity), ticket.Properties, ticket.AuthenticationScheme));
}
}
}
| // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.OpenIdConnect;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Newtonsoft.Json.Linq;
namespace Microsoft.AspNet.Authentication.Tests.OpenIdConnect
{
/// <summary>
/// Allows for custom processing of ApplyResponseChallenge, ApplyResponseGrant and AuthenticateCore
/// </summary>
public class OpenIdConnectAuthenticationHandlerForTestingAuthenticate : OpenIdConnectAuthenticationHandler
{
public OpenIdConnectAuthenticationHandlerForTestingAuthenticate()
: base(null)
{
}
protected override async Task<bool> HandleUnauthorizedAsync(ChallengeContext context)
{
return await base.HandleUnauthorizedAsync(context);
}
protected override async Task<OpenIdConnectTokenEndpointResponse> RedeemAuthorizationCodeAsync(string authorizationCode, string redirectUri)
{
var jsonResponse = new JObject();
jsonResponse.Add(OpenIdConnectParameterNames.IdToken, "test token");
return new OpenIdConnectTokenEndpointResponse(jsonResponse);
}
protected override async Task<AuthenticationTicket> GetUserInformationAsync(AuthenticationProperties properties, OpenIdConnectMessage message, AuthenticationTicket ticket)
{
var claimsIdentity = (ClaimsIdentity)ticket.Principal.Identity;
if (claimsIdentity == null)
{
claimsIdentity = new ClaimsIdentity();
}
claimsIdentity.AddClaim(new Claim("test claim", "test value"));
return new AuthenticationTicket(new ClaimsPrincipal(claimsIdentity), ticket.Properties, ticket.AuthenticationScheme);
}
}
}
| apache-2.0 | C# |
cb7f4d6462be63e97cbb3a99c7f713e969cbaf6a | Correct UniformRandomSelection constructor. | geoem/MSolve,geoem/MSolve | ISAAR.MSolve.Analyzers/Optimization/Algorithms/Metaheuristics/GeneticAlgorithms/Selections/UniformRandomSelection.cs | ISAAR.MSolve.Analyzers/Optimization/Algorithms/Metaheuristics/GeneticAlgorithms/Selections/UniformRandomSelection.cs | using ISAAR.MSolve.Analyzers.Optimization.Commons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Troschuetz.Random;
namespace ISAAR.MSolve.Analyzers.Optimization.Algorithms.Metaheuristics.GeneticAlgorithms.Selections
{
class UniformRandomSelection : SelectionStrategy
{
private readonly bool allowIdenticalParents;
private readonly IGenerator rng;
public UniformRandomSelection(): this(RandomNumberGenerationUtilities.troschuetzRandom)
{
}
public UniformRandomSelection(IGenerator randomNumberGenerator, bool allowIdenticalParents = false)
{
if (randomNumberGenerator == null) throw new ArgumentException("The random number generator must not be null");
this.rng = randomNumberGenerator;
this.allowIdenticalParents = allowIdenticalParents;
}
Tuple<Individual, Individual>[] SelectionStrategy.Apply(Individual[] population, int offspringsCount)
{
int pairsCount = (offspringsCount - 1) / 2 + 1;
var pairs = new Tuple<Individual, Individual>[pairsCount];
for (int i = 0; i < pairsCount; ++i)
{
int parent1 = rng.Next(population.Length);
int parent2 = rng.Next(population.Length);
if (!allowIdenticalParents)
{
while (parent1 == parent2) parent2 = rng.Next(population.Length);
}
pairs[i] = new Tuple<Individual, Individual>(population[parent1], population[parent2]);
}
return pairs;
}
}
}
| using ISAAR.MSolve.Analyzers.Optimization.Commons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Troschuetz.Random;
namespace ISAAR.MSolve.Analyzers.Optimization.Algorithms.Metaheuristics.GeneticAlgorithms.Selections
{
class UniformRandomSelection : SelectionStrategy
{
private readonly bool allowIdenticalParents;
private readonly IGenerator rng;
public UniformRandomSelection(): this(RandomNumberGenerationUtilities.troschuetzRandom)
{
}
public UniformRandomSelection(IGenerator randomNumberGenerator, bool allowIdenticalParents = false)
{
if (randomNumberGenerator == null) throw new ArgumentException("The random number generator must not be null");
this.allowIdenticalParents = allowIdenticalParents;
}
Tuple<Individual, Individual>[] SelectionStrategy.Apply(Individual[] population, int offspringsCount)
{
int pairsCount = (offspringsCount - 1) / 2 + 1;
var pairs = new Tuple<Individual, Individual>[pairsCount];
for (int i = 0; i < pairsCount; ++i)
{
int parent1 = rng.Next(population.Length);
int parent2 = rng.Next(population.Length);
if (!allowIdenticalParents)
{
while (parent1 == parent2) parent2 = rng.Next(population.Length);
}
pairs[i] = new Tuple<Individual, Individual>(population[parent1], population[parent2]);
}
return pairs;
}
}
}
| apache-2.0 | C# |
98d3ebcc1192b6bac82229719fe059738bc932d3 | Fix crash when acrobat is not correctly installed | xcomponent/xcomponent.ui,Invivoo-software/xcomponent.ui | UI/Pdf/WinFormPdfHost.cs | UI/Pdf/WinFormPdfHost.cs | using System;
using System.Windows.Forms;
namespace XComponent.Common.UI.Pdf
{
public partial class WinFormPdfHost : UserControl
{
public WinFormPdfHost()
{
InitializeComponent();
if(!DesignMode)
axAcroPDF1.setShowToolbar(true);
}
public void LoadFile(string path)
{
if (path != null)
{
try
{
axAcroPDF1.LoadFile(path);
axAcroPDF1.src = path;
axAcroPDF1.setViewScroll("FitH", 0);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString());
}
}
}
public void SetShowToolBar(bool on)
{
axAcroPDF1.setShowToolbar(on);
}
}
}
| using System.Windows.Forms;
namespace XComponent.Common.UI.Pdf
{
public partial class WinFormPdfHost : UserControl
{
public WinFormPdfHost()
{
InitializeComponent();
if(!DesignMode)
axAcroPDF1.setShowToolbar(true);
}
public void LoadFile(string path)
{
if (path != null)
{
axAcroPDF1.LoadFile(path);
axAcroPDF1.src = path;
axAcroPDF1.setViewScroll("FitH", 0);
}
}
public void SetShowToolBar(bool on)
{
axAcroPDF1.setShowToolbar(on);
}
}
}
| apache-2.0 | C# |
58899eb48a7d28e12b70ed9aa74035786c215093 | Teste 789 | Thiago-Caramelo/patchsearch | Program.cs | Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace PatchSearch
{
// teste teste
class Program
{
static void Main(string[] args)
{
if (args == null || args.Length == 0)
{
return;
}
// obter todos os arquivos da pasta
string[] files = Directory.GetFiles(Directory.GetCurrentDirectory());
foreach (var item in files) //teste
{
using (StreamReader reader = new StreamReader(item)) // teste f
{
string fileContent = reader.ReadToEnd(); // teste 456
int qt = 0;//teste 7
foreach (var term in args) // teste 745
{
if (fileContent.Contains(term))
{
qt++;
}
}
if (qt == args.Length)
{
Console.WriteLine(Path.GetFileName(item));
}
}
}
}
}
}
//teste c
//teste d | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace PatchSearch
{
// teste teste
class Program
{
static void Main(string[] args)
{
if (args == null || args.Length == 0)
{
return;
}
// obter todos os arquivos da pasta
string[] files = Directory.GetFiles(Directory.GetCurrentDirectory());
foreach (var item in files) //teste
{
using (StreamReader reader = new StreamReader(item)) // teste f
{
string fileContent = reader.ReadToEnd(); // teste 456
int qt = 0;//teste 7
foreach (var term in args)
{
if (fileContent.Contains(term))
{
qt++;
}
}
if (qt == args.Length)
{
Console.WriteLine(Path.GetFileName(item));
}
}
}
}
}
}
//teste c
//teste d | mit | C# |
2c5a0bb463cccceef741f871f99a149eacec796f | Use the right name for cmdlet | ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell | src/ResourceManager/Network/Commands.Network/AzureFirewall/NatRuleCollection/NewAzureFirewallNatRuleCollectionCommand.cs | src/ResourceManager/Network/Commands.Network/AzureFirewall/NatRuleCollection/NewAzureFirewallNatRuleCollectionCommand.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.Azure.Commands.Network.Models;
using MNM = Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Commands.Network
{
[Cmdlet(VerbsCommon.New, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "FirewallNatRuleCollection", SupportsShouldProcess = true), OutputType(typeof(PSAzureFirewallNatRuleCollection))]
public class NewAzureFirewallNatRuleCollectionCommand : NetworkBaseCmdlet
{
[Parameter(
Mandatory = true,
HelpMessage = "The name of the NAT Rule Collection")]
[ValidateNotNullOrEmpty]
public virtual string Name { get; set; }
[Parameter(
Mandatory = true,
HelpMessage = "The priority of the rule collection")]
[ValidateRange(100, 65000)]
public uint Priority { get; set; }
[Parameter(
Mandatory = true,
HelpMessage = "The list of NAT rules")]
[ValidateNotNullOrEmpty]
public List<PSAzureFirewallNatRule> Rule { get; set; }
public override void Execute()
{
base.Execute();
var networkRuleCollection = new PSAzureFirewallNatRuleCollection
{
Name = this.Name,
Priority = this.Priority,
Rules = this.Rule,
Action = new PSAzureFirewallNatRCAction { Type = MNM.AzureFirewallNatRCActionType.Dnat }
};
WriteObject(networkRuleCollection);
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.Azure.Commands.Network.Models;
using MNM = Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Commands.Network
{
[Cmdlet(VerbsCommon.New, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "NatRuleCollection", SupportsShouldProcess = true), OutputType(typeof(PSAzureFirewallNatRuleCollection))]
public class NewAzureFirewallNatRuleCollectionCommand : NetworkBaseCmdlet
{
[Parameter(
Mandatory = true,
HelpMessage = "The name of the NAT Rule Collection")]
[ValidateNotNullOrEmpty]
public virtual string Name { get; set; }
[Parameter(
Mandatory = true,
HelpMessage = "The priority of the rule collection")]
[ValidateRange(100, 65000)]
public uint Priority { get; set; }
[Parameter(
Mandatory = true,
HelpMessage = "The list of NAT rules")]
[ValidateNotNullOrEmpty]
public List<PSAzureFirewallNatRule> Rule { get; set; }
public override void Execute()
{
base.Execute();
var networkRuleCollection = new PSAzureFirewallNatRuleCollection
{
Name = this.Name,
Priority = this.Priority,
Rules = this.Rule,
Action = new PSAzureFirewallNatRCAction { Type = MNM.AzureFirewallNatRCActionType.Dnat }
};
WriteObject(networkRuleCollection);
}
}
}
| apache-2.0 | C# |
fefcc46159775d5e8a70405b469bed0b1bcd32aa | add DefaultSlug there | tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web | src/Tugberk.Domain/Post.cs | src/Tugberk.Domain/Post.cs | using System.Collections.Generic;
using System.Linq;
namespace Tugberk.Domain
{
public class Post
{
public string Id { get; set; }
public string Language { get; set; }
public string Title { get; set; }
public string Abstract { get; set; }
public string Content { get; set; }
public PostFormat Format { get; set; }
public ChangeRecord CreationRecord { get; set; }
public IReadOnlyCollection<ChangeRecord> UpdateRecords { get; set; }
public IReadOnlyCollection<User> Authors { get; set; }
public IReadOnlyCollection<Slug> Slugs { get; set; }
public IReadOnlyCollection<Tag> Tags { get; set; }
public IReadOnlyCollection<CommentStatusActionRecord> CommentStatusActions { get; set; }
public IReadOnlyCollection<ApprovalStatusActionRecord> ApprovaleStatusActions { get; set; }
public Slug DefaultSlug => Slugs.Where(x => x.IsDefault)
.OrderByDescending(x => x.CreatedOn)
.First();
public bool IsApproved => ApprovaleStatusActions
.OrderByDescending(x => x.RecordedOn)
.First().Status == ApprovalStatus.Approved;
}
}
| using System.Collections.Generic;
using System.Linq;
namespace Tugberk.Domain
{
public class Post
{
public string Id { get; set; }
public string Language { get; set; }
public string Title { get; set; }
public string Abstract { get; set; }
public string Content { get; set; }
public PostFormat Format { get; set; }
public ChangeRecord CreationRecord { get; set; }
public IReadOnlyCollection<ChangeRecord> UpdateRecords { get; set; }
public IReadOnlyCollection<User> Authors { get; set; }
public IReadOnlyCollection<Slug> Slugs { get; set; }
public IReadOnlyCollection<Tag> Tags { get; set; }
public IReadOnlyCollection<CommentStatusActionRecord> CommentStatusActions { get; set; }
public IReadOnlyCollection<ApprovalStatusActionRecord> ApprovaleStatusActions { get; set; }
public bool IsApproved => ApprovaleStatusActions
.OrderByDescending(x => x.RecordedOn)
.First().Status == ApprovalStatus.Approved;
}
}
| agpl-3.0 | C# |
463d4080854d79984df0214a21cddde73de69ece | test fixed | IMCubator/Sandbox | bdinsight/BdInsight.Core.Tests/Class1.cs | bdinsight/BdInsight.Core.Tests/Class1.cs | using Xunit;
namespace BdInsight.Core.Tests
{
public class Class1
{
[Fact]
public void PassingTest()
{
Assert.Equal(4, Add(2, 2));
}
[Fact]
public void FailingTest()
{
Assert.NotEqual(5, Add(2, 2));
}
int Add(int x, int y)
{
return x + y;
}
[Theory]
[InlineData(3)]
[InlineData(41)]
[InlineData(5)]
[InlineData(61)]
public void MyFirstTheory(int value)
{
Assert.True(IsOdd(value));
}
bool IsOdd(int value)
{
return value % 2 == 1;
}
}
} | using Xunit;
namespace BdInsight.Core.Tests
{
public class Class1
{
[Fact]
public void PassingTest()
{
Assert.Equal(4, Add(2, 2));
}
[Fact]
public void FailingTest()
{
Assert.NotEqual(5, Add(2, 2));
}
int Add(int x, int y)
{
return x + y;
}
[Theory]
[InlineData(3)]
[InlineData(4)]
[InlineData(5)]
[InlineData(6)]
public void MyFirstTheory(int value)
{
Assert.True(IsOdd(value));
}
bool IsOdd(int value)
{
return value % 2 == 1;
}
}
} | mit | C# |
54462fa1f676cbb997878bba0ebd52d1311727d9 | check os | CoinVault/Nako,CoinVault/Nako,CoinVault/Nako,CoinVault/Nako | core/Program.cs | core/Program.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="SoftChains">
// Copyright 2016 Dan Gershony
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
// // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Nako
{
#region Using Directives
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Autofac;
using Nako.Api;
using Nako.Config;
using Nako.Sync;
#endregion
/// <summary>
/// The application program.
/// </summary>
internal class Program
{
#region Methods
/// <summary>
/// The main entry point.
/// </summary>
internal static void Main(string[] args)
{
if (!IsRunningOnLinux())
{
Console.BufferHeight = 1000;
Console.WindowHeight = 25;
Console.WindowWidth = 150;
}
var builder = new ContainerBuilder();
builder.RegisterInstance(ConfigStartup.LoadConfiguration(args)).As<NakoConfiguration>();
builder.RegisterAssemblyModules(Assembly.GetEntryAssembly());
var container = builder.Build();
container.Resolve<ApiServer>().StartApi(container);
container.Resolve<SyncServer>().StartSync(container);
container.Resolve<Terminator>().Start();
container.Resolve<NakoApplication>().SyncToken.WaitHandle.WaitOne();
container.Resolve<NakoApplication>().ApiTokenSource.Cancel();
container.Resolve<NakoApplication>().ApiToken.WaitHandle.WaitOne();
//Console.Read();
}
public static bool IsRunningOnLinux()
{
return System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux);
}
#endregion
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="SoftChains">
// Copyright 2016 Dan Gershony
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
// // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Nako
{
#region Using Directives
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Autofac;
using Nako.Api;
using Nako.Config;
using Nako.Sync;
#endregion
/// <summary>
/// The application program.
/// </summary>
internal class Program
{
#region Methods
/// <summary>
/// The main entry point.
/// </summary>
internal static void Main(string[] args)
{
if (!IsRunningOnMono())
{
Console.BufferHeight = 1000;
Console.WindowHeight = 25;
Console.WindowWidth = 150;
}
var builder = new ContainerBuilder();
builder.RegisterInstance(ConfigStartup.LoadConfiguration(args)).As<NakoConfiguration>();
builder.RegisterAssemblyModules(Assembly.GetEntryAssembly());
var container = builder.Build();
container.Resolve<ApiServer>().StartApi(container);
container.Resolve<SyncServer>().StartSync(container);
container.Resolve<Terminator>().Start();
container.Resolve<NakoApplication>().SyncToken.WaitHandle.WaitOne();
container.Resolve<NakoApplication>().ApiTokenSource.Cancel();
container.Resolve<NakoApplication>().ApiToken.WaitHandle.WaitOne();
//Console.Read();
}
public static bool IsRunningOnMono()
{
return Type.GetType("Mono.Runtime") != null;
}
#endregion
}
} | mit | C# |
24cb4663d91db1933b37253c8c1df2c16525818e | fix ios http stack bug (#2192) | AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet | src/client/Microsoft.Identity.Client/Platforms/iOS/IosHttpClientFactory.cs | src/client/Microsoft.Identity.Client/Platforms/iOS/IosHttpClientFactory.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Net.Http;
using Microsoft.Identity.Client.Http;
using UIKit;
namespace Microsoft.Identity.Client.Platforms.iOS
{
internal class IosHttpClientFactory : IMsalHttpClientFactory
{
public HttpClient GetHttpClient()
{
HttpClient httpClient;
if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0))
{
var handler = new NSUrlSessionHandler()
{
BypassBackgroundSessionCheck = false,
};
httpClient = new HttpClient(handler);
}
else
{
httpClient = new HttpClient();
}
HttpClientConfig.ConfigureRequestHeadersAndSize(httpClient);
return httpClient;
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Net.Http;
using Microsoft.Identity.Client.Http;
using UIKit;
namespace Microsoft.Identity.Client.Platforms.iOS
{
internal class IosHttpClientFactory : IMsalHttpClientFactory
{
public HttpClient GetHttpClient()
{
HttpClient httpClient;
if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0))
{
httpClient = new HttpClient(new NSUrlSessionHandler());
}
else
{
httpClient = new HttpClient();
}
HttpClientConfig.ConfigureRequestHeadersAndSize(httpClient);
return httpClient;
}
}
}
| mit | C# |
4d26ca9028d9a93522ea9272a72e1cba06eb6e71 | Move call to UseFluentActions before UseMvc in api test project | ExplicitlyImplicit/AspNetCore.Mvc.FluentActions,ExplicitlyImplicit/AspNetCore.Mvc.FluentActions | test/WebApps/SimpleApi/Startup.cs | test/WebApps/SimpleApi/Startup.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
namespace SimpleApi
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddFluentActions();
services.AddTransient<IUserService, UserService>();
services.AddTransient<INoteService, NoteService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
actions.Add(UserActions.All);
actions.Add(NoteActions.All);
});
app.UseMvc();
}
}
}
| using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
namespace SimpleApi
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddFluentActions();
services.AddTransient<IUserService, UserService>();
services.AddTransient<INoteService, NoteService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
actions.Add(UserActions.All);
actions.Add(NoteActions.All);
});
}
}
}
| mit | C# |
36ebc115ec70f1ef1440dbd68516600bc83b9fc5 | fix breaking change after upgrade | Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode | MakingDotNETApplicationsFaster/MakingDotNETApplicationsFaster/CoreConfig.cs | MakingDotNETApplicationsFaster/MakingDotNETApplicationsFaster/CoreConfig.cs | using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Order;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
namespace MakingDotNETApplicationsFaster
{
public class CoreConfig : ManualConfig
{
public CoreConfig()
{
Orderer = new FastestToSlowestOrderer();
}
private class FastestToSlowestOrderer : IOrderer
{
public IEnumerable<BenchmarkCase> GetExecutionOrder(ImmutableArray<BenchmarkCase> benchmarksCase, IEnumerable<BenchmarkLogicalGroupRule> order = null) =>
from benchmark in benchmarksCase
orderby benchmark.Parameters["X"] descending,
benchmark.Descriptor.WorkloadMethodDisplayInfo
select benchmark;
IEnumerable<BenchmarkCase> IOrderer.GetSummaryOrder(ImmutableArray<BenchmarkCase> benchmarksCases, Summary summary)
{
return GetSummaryOrder(benchmarksCases, summary);
}
public IEnumerable<BenchmarkCase> GetSummaryOrder(ImmutableArray<BenchmarkCase> benchmarksCase, Summary summary) =>
from benchmark in benchmarksCase
orderby summary[benchmark].ResultStatistics.Mean
select benchmark;
public string GetHighlightGroupKey(BenchmarkCase benchmarkCase) => null;
string IOrderer.GetLogicalGroupKey(ImmutableArray<BenchmarkCase> allBenchmarksCases, BenchmarkCase benchmarkCase)
{
return GetLogicalGroupKey(allBenchmarksCases, benchmarkCase);
}
public IEnumerable<IGrouping<string, BenchmarkCase>> GetLogicalGroupOrder(IEnumerable<IGrouping<string, BenchmarkCase>> logicalGroups, IEnumerable<BenchmarkLogicalGroupRule> order = null) =>
logicalGroups.OrderBy(it => it.Key);
public string GetLogicalGroupKey(ImmutableArray<BenchmarkCase> allBenchmarksCases, BenchmarkCase benchmarkCase) =>
benchmarkCase.Job.DisplayInfo + "_" + benchmarkCase.Parameters.DisplayInfo;
public bool SeparateLogicalGroups => true;
}
}
} | using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Order;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
namespace MakingDotNETApplicationsFaster
{
public class CoreConfig : ManualConfig
{
public CoreConfig()
{
Orderer = new FastestToSlowestOrderer();
}
private class FastestToSlowestOrderer : IOrderer
{
public IEnumerable<BenchmarkCase> GetExecutionOrder(ImmutableArray<BenchmarkCase> benchmarksCase) =>
from benchmark in benchmarksCase
orderby benchmark.Parameters["X"] descending,
benchmark.Descriptor.WorkloadMethodDisplayInfo
select benchmark;
IEnumerable<BenchmarkCase> IOrderer.GetSummaryOrder(ImmutableArray<BenchmarkCase> benchmarksCases, Summary summary)
{
return GetSummaryOrder(benchmarksCases, summary);
}
public IEnumerable<BenchmarkCase> GetSummaryOrder(ImmutableArray<BenchmarkCase> benchmarksCase, Summary summary) =>
from benchmark in benchmarksCase
orderby summary[benchmark].ResultStatistics.Mean
select benchmark;
public string GetHighlightGroupKey(BenchmarkCase benchmarkCase) => null;
string IOrderer.GetLogicalGroupKey(ImmutableArray<BenchmarkCase> allBenchmarksCases, BenchmarkCase benchmarkCase)
{
return GetLogicalGroupKey(allBenchmarksCases, benchmarkCase);
}
public string GetLogicalGroupKey(ImmutableArray<BenchmarkCase> allBenchmarksCases, BenchmarkCase benchmarkCase) =>
benchmarkCase.Job.DisplayInfo + "_" + benchmarkCase.Parameters.DisplayInfo;
public IEnumerable<IGrouping<string, BenchmarkCase>> GetLogicalGroupOrder(IEnumerable<IGrouping<string, BenchmarkCase>> logicalGroups) =>
logicalGroups.OrderBy(it => it.Key);
public bool SeparateLogicalGroups => true;
}
}
} | mit | C# |
f99e353eadf11d9b5e8f7772a75d9bc7cdc2bdc4 | Update WorkspaceClientCapabilities type | PowerShell/PowerShellEditorServices | src/PowerShellEditorServices.Protocol/LanguageServer/WorkspaceClientCapabilities.cs | src/PowerShellEditorServices.Protocol/LanguageServer/WorkspaceClientCapabilities.cs | namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class WorkspaceClientCapabilities
{
/// <summary>
/// The client supports applying batch edits to the workspace by
/// by supporting the request `workspace/applyEdit'
/// /// </summary>
bool ApplyEdit { get; set; }
/// <summary>
/// Capabilities specific to `WorkspaceEdit`.
/// </summary>
public WorkspaceEditCapabilities WorkspaceEdit { get; set; }
/// <summary>
/// Capabilities specific to the `workspace/didChangeConfiguration` notification.
/// </summary>
public DynamicRegistrationCapability DidChangeConfiguration { get; set; }
/// <summary>
/// Capabilities specific to the `workspace/didChangeWatchedFiles` notification.
/// </summary>
public DynamicRegistrationCapability DidChangeWatchedFiles { get; set; }
/// <summary>
/// Capabilities specific to the `workspace/symbol` request.
/// </summary>
public DynamicRegistrationCapability Symbol { get; set; }
/// <summary>
/// Capabilities specific to the `workspace/executeCommand` request.
/// </summary>
public DynamicRegistrationCapability ExecuteCommand { get; set; }
}
/// <summary>
/// Class to represent capabilities specific to `WorkspaceEdit`.
/// </summary>
public class WorkspaceEditCapabilities
{
/// <summary>
/// The client supports versioned document changes in `WorkspaceEdit`
/// </summary>
bool DocumentChanges { get; set; }
}
}
| namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class WorkspaceClientCapabilities
{
/// <summary>
/// The client supports applying batch edits to the workspace by
/// by supporting the request `workspace/applyEdit'
/// /// </summary>
bool ApplyEdit { get; set; }
/// <summary>
/// Capabilities specific to `WorkspaceEdit`.
/// </summary>
public WorkspaceEditCapabilities WorkspaceEdit { get; set; }
/// <summary>
/// Capabilities specific to the `workspace/didChangeConfiguration` notification.
/// </summary>
public DidChangeConfigurationCapabilities DidChangeConfiguration { get; set; }
/// <summary>
/// Capabilities specific to the `workspace/didChangeWatchedFiles` notification.
/// </summary>
public DidChangeWatchedFilesCapabilities DidChangeWatchedFiles { get; set; }
/// <summary>
/// Capabilities specific to the `workspace/symbol` request.
/// </summary>
public SymbolCapabilities Symbol { get; set; }
/// <summary>
/// Capabilities specific to the `workspace/executeCommand` request.
/// </summary>
public ExecuteCommandCapabilities ExecuteCommand { get; set; }
}
/// <summary>
/// Class to represent capabilities specific to `WorkspaceEdit`.
/// </summary>
public class WorkspaceEditCapabilities
{
/// <summary>
/// The client supports versioned document changes in `WorkspaceEdit`
/// </summary>
bool DocumentChanges { get; set; }
}
/// <summary>
/// Class to represent capabilities specific to the `workspace/didChangeConfiguration` notification.
/// </summary>
public class DidChangeConfigurationCapabilities
{
/// <summary>
/// Did change configuration supports dynamic registration.
/// </summary>
bool DynamicRegistration { get; set; }
}
/// <summary>
/// Class to represent capabilities specific to the `workspace/didChangeWatchedFiles` notification.
/// </summary>
public class DidChangeWatchedFilesCapabilities
{
/// <summary>
/// Did change watched files notification supports dynamic registration.
/// </summary>
bool DynamicRegistration { get; set; }
}
/// <summary>
/// Class to represent capabilities specific to the `workspace/symbol` request.
/// </summary>
public class SymbolCapabilities
{
/// <summary>
/// Symbol request supports dynamic registration.
/// </summary>
bool DynamicRegistration { get; set; }
}
/// <summary>
/// Class to represent capabilities specific to the `workspace/executeCommand` request.
/// </summary>
public class ExecuteCommandCapabilities
{
/// <summary>
/// Execute command supports dynamic registration.
/// </summary>
bool DynamicRegistration { get; set; }
}
}
| mit | C# |
748054c05919078980474ed86cad86f5dfebe664 | Change access modifier for constants. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Core/TraktConstants.cs | Source/Lib/TraktApiSharp/Core/TraktConstants.cs | namespace TraktApiSharp.Core
{
internal static class TraktConstants
{
internal static string OAuthBaseAuthorizeUrl => "https://trakt.tv";
internal static string OAuthAuthorizeUri => "oauth/authorize";
internal static string OAuthTokenUri => "oauth/token";
internal static string OAuthRevokeUri => "oauth/revoke";
internal static string OAuthDeviceCodeUri => "oauth/device/code";
internal static string OAuthDeviceTokenUri => "oauth/device/token";
}
}
| namespace TraktApiSharp.Core
{
public static class TraktConstants
{
public static string OAuthBaseAuthorizeUrl => "https://trakt.tv";
public static string OAuthAuthorizeUri => "oauth/authorize";
public static string OAuthTokenUri => "oauth/token";
public static string OAuthRevokeUri => "oauth/revoke";
public static string OAuthDeviceCodeUri => "oauth/device/code";
public static string OAuthDeviceTokenUri => "oauth/device/token";
}
}
| mit | C# |
000653c887f65b438b65bce212831f075e6a8ef3 | remove of ref | Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal | Master/Appleseed/WebSites/Appleseed/DesktopModules/CoreModules/MVC/MVCModule.ascx.cs | Master/Appleseed/WebSites/Appleseed/DesktopModules/CoreModules/MVC/MVCModule.ascx.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Appleseed.Framework.Web.UI.WebControls;
//using System.Web.Mvc;
//using Microsoft.Web.Mvc;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Appleseed.Framework;
public partial class DesktopModules_CoreModules_MVC_MVCModule : MVCModuleControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public DesktopModules_CoreModules_MVC_MVCModule()
{
}
public override Guid GuidID
{
get
{
return new Guid("{9073EC6C-9E21-44ba-A33E-22F0E301B867}");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Appleseed.Framework.Web.UI.WebControls;
using System.Web.Mvc;
//using Microsoft.Web.Mvc;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Appleseed.Framework;
public partial class DesktopModules_CoreModules_MVC_MVCModule : MVCModuleControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public DesktopModules_CoreModules_MVC_MVCModule()
{
}
public override Guid GuidID
{
get
{
return new Guid("{9073EC6C-9E21-44ba-A33E-22F0E301B867}");
}
}
}
| apache-2.0 | C# |
97ee7413492336a718d8f4a8b188073b2df436b1 | Update NetworkFileSystemTest to test new specs | HatfieldConsultants/Hatfield.EnviroData.FileSystems | Test/Hatfield.EnviroData.FileSystems.NetworkFileSystem.Test/NetworkFileSystemTest.cs | Test/Hatfield.EnviroData.FileSystems.NetworkFileSystem.Test/NetworkFileSystemTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using NUnit.Framework;
namespace Hatfield.EnviroData.FileSystems.NetworkFileSystem.Test
{
[TestFixture]
public class NetworkFileSystemTest
{
[Test]
[ExpectedException(typeof(IOException))]
[TestCase(@"\\machine-name\invalid\path\to\file.ext")]
[TestCase(@"\\machine-name\invalid\path\to\directory")]
public void NetworkFileSystemThisUserInvalidPath(string path)
{
var networkFileSystem = new NetworkFileSystem(path);
networkFileSystem.FetchData();
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void AnonymousFetchDataNullUriTest()
{
var networkFileSystem = new NetworkFileSystem(null);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void SecureFetchDataNullUriTest()
{
var networkFileSystem = new NetworkFileSystem(null, "username", "password", "domain");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using NUnit.Framework;
namespace Hatfield.EnviroData.FileSystems.NetworkFileSystem.Test
{
[TestFixture]
public class NetworkFileSystemTest
{
[Test]
[ExpectedException(typeof(IOException))]
public void InvalidNetworkDownloadTest()
{
var filePath = @"\\machine-name\invalid\path\file.txt";
var networkFileSystem = new NetworkFileSystem(filePath);
var dataFromFileSystem = networkFileSystem.FetchData();
}
}
}
| mpl-2.0 | C# |
41ce004a6b8c3339a349bfbefed67e375eb762dd | Fix warning | Lombiq/Helpful-Extensions,Lombiq/Helpful-Extensions | Extensions/ShapeTracing/Startup.cs | Extensions/ShapeTracing/Startup.cs | using Microsoft.Extensions.DependencyInjection;
using OrchardCore.DisplayManagement.Implementation;
using OrchardCore.Modules;
namespace Lombiq.HelpfulExtensions.Extensions.ShapeTracing
{
[Feature(FeatureIds.ShapeTracing)]
public class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services) =>
services.AddScoped<IShapeDisplayEvents, ShapeTracingShapeEvents>();
}
}
| using Microsoft.Extensions.DependencyInjection;
using OrchardCore.DisplayManagement.Implementation;
using OrchardCore.Modules;
namespace Lombiq.HelpfulExtensions.Extensions.ShapeTracing
{
[Feature(FeatureIds.ShapeTracing)]
public class Startup
{
public void ConfigureServices(IServiceCollection services) =>
services.AddScoped<IShapeDisplayEvents, ShapeTracingShapeEvents>();
}
}
| bsd-3-clause | C# |
6dc07c84cf5e1cc2199a1b74b97e48fdde3a6bc8 | Revert "Update _TermsAndConditionBody.cshtml" | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Web/Views/TermsAndConditions/_TermsAndConditionBody.cshtml | src/SFA.DAS.EmployerUsers.Web/Views/TermsAndConditions/_TermsAndConditionBody.cshtml | <p>To use this service you agree to:</p>
<ul class="list list-bullet">
<li>Sign out at the end of each session</li>
<li>Input truthful and accurate information</li>
<li>Adhere to the <a href="http://www.legislation.gov.uk/ukpga/1990/18/contents" target="_blank">Computer Misuse Act 1990</a></li>
<li>Use only a legitimate email address that you or people in your organisation has access to</li>
<li>Keep your sign in details secure and do not share them with third parties</li>
<li>Not use discriminatory wording as set out in the <a href="https://www.gov.uk/guidance/equality-act-2010-guidance#equalities-act-2010-legislation" target="_blank">Equality Act 2010</a></li>
<li>Make sure the published rates of pay comply with the <a href="https://www.gov.uk/national-minimum-wage-rates" target="_blank">National Minimum Wage</a> guidelines and are not misleading to candidates</li>
<li>Adhere to all relevant <a href="https://www.gov.uk/browse/employing-people" target="_blank">UK employment law</a></li>
<li>If you are a commercial organisation as defined in <a href="https://www.legislation.gov.uk/ukpga/2015/30/section/54/enacted" target="_blank">section 54 of the Modern Slavery Act 2015</a>, adhere to the annual reporting requirements</li>
<li>Your apprenticeship adverts being publicly accessible, including the possibility of partner websites displaying them</li>
<li>Comply with the government safeguarding policies for <a href="https://www.gov.uk/government/publications/ofsted-safeguarding-policy" target="_blank">children</a> and <a href="https://www.gov.uk/government/publications/safeguarding-policy-protecting-vulnerable-adults" target="_blank">vulnerable adults</a></li>
<li>Not provide feedback on a training provider when you are an employer provider</li>
<li>Be an active and trading business at the point of creating an apprenticeship service account</li>
<li>Only add apprentices that are linked to the PAYE scheme registered in your employer account</li>
<li>Comply at all times with the Apprenticeship Agreement for Employers and Apprenticeship Funding Rules</li>
</ul>
<p>When you sign up for an apprenticeship service account we may need to verify and validate your company. You may not be granted an account if you fail the checks conducted by ESFA.</p>
<p>Your contact details and information associated with your account will be collected and used for the support and administration of your account.</p>
<p>We will not:</p>
<ul class="list list-bullet">
<li>Use or disclose this information for other purposes (except where we’re legally required to do so)</li>
<li>Use your details for any marketing purposes or for any reason unrelated to the use of your account</li>
</ul>
<p>We may update these terms and conditions at any time without notice. You’ll agree to any changes if you continue to use this service after the terms and conditions have been updated.</p>
| <p>To use this service you agree to:</p>
<ul class="list list-bullet">
<li>sign out at the end of each session</li>
<li>input truthful and accurate information</li>
<li>adhere to the <a href="http://www.legislation.gov.uk/ukpga/1990/18/contents" target="_blank">Computer Misuse Act 1990</a></li>
<li>use only a legitimate email address that you or people in your organisation has access to</li>
<li>keep your sign in details secure and do not share them with third parties</li>
<li>not use discriminatory wording as set out in the <a href="https://www.gov.uk/guidance/equality-act-2010-guidance#equalities-act-2010-legislation" target="_blank">Equality Act 2010</a></li>
<li>make sure the published rates of pay comply with the <a href="https://www.gov.uk/national-minimum-wage-rates" target="_blank">National Minimum Wage</a> guidelines and are not misleading to candidates</li>
<li>adhere to all relevant <a href="https://www.gov.uk/browse/employing-people" target="_blank">UK employment law</a></li>
<li>if you are a commercial organisation as defined in <a href="https://www.legislation.gov.uk/ukpga/2015/30/section/54/enacted" target="_blank">section 54 of the Modern Slavery Act 2015</a>, adhere to the annual reporting requirements</li>
<li>your apprenticeship adverts being publicly accessible, including the possibility of partner websites displaying them</li>
<li>comply with the government safeguarding policies for <a href="https://www.gov.uk/government/publications/ofsted-safeguarding-policy" target="_blank">children</a> and <a href="https://www.gov.uk/government/publications/safeguarding-policy-protecting-vulnerable-adults" target="_blank">vulnerable adults</a></li>
<li>not provide feedback on a training provider when you are an employer provider</li>
<li>be an active and trading business at the point of creating an apprenticeship service account</li>
<li>only add apprentices that are linked to the PAYE scheme registered in your employer account</li>
<li>comply at all times with the Apprenticeship Agreement for Employers and Apprenticeship Funding Rules</li>
</ul>
<p>When you sign up for an apprenticeship service account we may need to verify and validate your company. You may not be granted an account if you fail the checks conducted by ESFA.</p>
<p>Your contact details and information associated with your account will be collected and used for the support and administration of your account.</p>
<p>We will not:</p>
<ul class="list list-bullet">
<li>use or disclose this information for other purposes (except where we’re legally required to do so)</li>
<li>use your details for any marketing purposes or for any reason unrelated to the use of your account</li>
</ul>
<p>We may update these terms and conditions at any time without notice. You’ll agree to any changes if you continue to use this service after the terms and conditions have been updated.</p>
| mit | C# |
b2134657df2b5685c76d93e690870abf215d336f | Fix #1419077 - Update the copyright year. | PintaProject/Pinta,PintaProject/Pinta,jakeclawson/Pinta,PintaProject/Pinta,jakeclawson/Pinta,Mailaender/Pinta,Mailaender/Pinta,Fenex/Pinta,Fenex/Pinta | Pinta/Dialogs/AboutPintaTabPage.cs | Pinta/Dialogs/AboutPintaTabPage.cs | // AboutPintaTabPage.cs
//
// Author:
// Viktoria Dudka (viktoriad@remobjects.com)
//
// Copyright (c) 2009 RemObjects Software
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using Gtk;
using Mono.Unix;
using Pinta.Core;
namespace Pinta
{
internal class AboutPintaTabPage : VBox
{
public AboutPintaTabPage ()
{
Label label = new Label ();
label.Markup = String.Format (
"<b>{0}</b>\n {1}",
Catalog.GetString ("Version"),
PintaCore.ApplicationVersion);
HBox hBoxVersion = new HBox ();
hBoxVersion.PackStart (label, false, false, 5);
this.PackStart (hBoxVersion, false, true, 0);
label = null;
label = new Label ();
label.Markup = string.Format ("<b>{0}</b>\n {1}", Catalog.GetString ("License"), Catalog.GetString ("Released under the MIT X11 License."));
HBox hBoxLicense = new HBox ();
hBoxLicense.PackStart (label, false, false, 5);
this.PackStart (hBoxLicense, false, true, 5);
label = null;
label = new Label ();
label.Markup = string.Format ("<b>{0}</b>\n (c) 2010-2015 {1}", Catalog.GetString ("Copyright"), Catalog.GetString ("by Pinta contributors"));
HBox hBoxCopyright = new HBox ();
hBoxCopyright.PackStart (label, false, false, 5);
this.PackStart (hBoxCopyright, false, true, 5);
this.ShowAll ();
}
}
}
| // AboutPintaTabPage.cs
//
// Author:
// Viktoria Dudka (viktoriad@remobjects.com)
//
// Copyright (c) 2009 RemObjects Software
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using Gtk;
using Mono.Unix;
using Pinta.Core;
namespace Pinta
{
internal class AboutPintaTabPage : VBox
{
public AboutPintaTabPage ()
{
Label label = new Label ();
label.Markup = String.Format (
"<b>{0}</b>\n {1}",
Catalog.GetString ("Version"),
PintaCore.ApplicationVersion);
HBox hBoxVersion = new HBox ();
hBoxVersion.PackStart (label, false, false, 5);
this.PackStart (hBoxVersion, false, true, 0);
label = null;
label = new Label ();
label.Markup = string.Format ("<b>{0}</b>\n {1}", Catalog.GetString ("License"), Catalog.GetString ("Released under the MIT X11 License."));
HBox hBoxLicense = new HBox ();
hBoxLicense.PackStart (label, false, false, 5);
this.PackStart (hBoxLicense, false, true, 5);
label = null;
label = new Label ();
label.Markup = string.Format ("<b>{0}</b>\n (c) 2010-2014 {1}", Catalog.GetString ("Copyright"), Catalog.GetString ("by Pinta contributors"));
HBox hBoxCopyright = new HBox ();
hBoxCopyright.PackStart (label, false, false, 5);
this.PackStart (hBoxCopyright, false, true, 5);
this.ShowAll ();
}
}
}
| mit | C# |
c5183b6f69106d15e5863c9bad4e9cd1aa4367eb | make text file report overwrite the file at each pass | MetaG8/Metrics.NET,huoxudong125/Metrics.NET,alhardy/Metrics.NET,etishor/Metrics.NET,DeonHeyns/Metrics.NET,mnadel/Metrics.NET,MetaG8/Metrics.NET,cvent/Metrics.NET,Recognos/Metrics.NET,mnadel/Metrics.NET,huoxudong125/Metrics.NET,Liwoj/Metrics.NET,Liwoj/Metrics.NET,alhardy/Metrics.NET,ntent-ad/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,Recognos/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,etishor/Metrics.NET | Src/Metrics/Reporters/TextFileReport.cs | Src/Metrics/Reporters/TextFileReport.cs | using System;
using System.IO;
using System.Text;
namespace Metrics.Reporters
{
public class TextFileReport : HumanReadableReport
{
private readonly string fileName;
private StringBuilder buffer = new StringBuilder();
public TextFileReport(string fileName)
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
this.fileName = fileName;
}
protected override void WriteLine(string line, params string[] args)
{
buffer.AppendFormat(line, args);
buffer.AppendLine();
}
protected override void EndReport(string contextName, DateTime timestamp)
{
try
{
File.WriteAllText(this.fileName, this.buffer.ToString());
}
catch (Exception x)
{
MetricsErrorHandler.Handle(x, "Error writing text file " + this.fileName);
}
buffer = new StringBuilder();
base.EndReport(contextName, timestamp);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
namespace Metrics.Reporters
{
public class TextFileReport : HumanReadableReport
{
private readonly string fileName;
private readonly List<string> buffer = new List<string>();
public TextFileReport(string fileName)
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
this.fileName = fileName;
}
protected override void WriteLine(string line, params string[] args)
{
this.buffer.Add(string.Format(line, args));
}
protected override void EndReport(string contextName, DateTime timestamp)
{
File.WriteAllLines(this.fileName, this.buffer);
buffer.Clear();
base.EndReport(contextName, timestamp);
}
}
}
| apache-2.0 | C# |
2ed04f05b456e68d794fd196b2296d5872586f62 | Update CoinCounter.cs | mikkokok/DinosaurGame | Assets/CoinCounter.cs | Assets/CoinCounter.cs | using UnityEngine;
using System.Collections;
public class CoinCounter : MonoBehaviour
{
public static int coincount;
public static void Addcoin () {
coincount++;
//Debug.Log("coincount: "+coincount ); // For debugging
if (coincount == 10)
{
Destroy(GameObject.FindWithTag ("Car"));
}
}
public static void AddSilvercoin () {
for(int i =0; i<5;i++){
this.Addcoin();
}
}
public static void Losecoin (){
if(coincount == 0) return;
coincount = coincount -1;
}
public static void Losecoin (int m){
if(coincount - m < 0){
coincount = 0;
}
else coincount = coincount -m;
}
public static string GetCoin () {
return coincount.ToString();
}
} // CoinCounter
| using UnityEngine;
using System.Collections;
public class CoinCounter : MonoBehaviour
{
public static int coincount;
public static void Addcoin () {
coincount++;
//Debug.Log("coincount: "+coincount ); // For debugging
if (coincount == 10)
{
Destroy(GameObject.FindWithTag ("Car"));
}
}
public static void AddSilvercoin () {
coincount = coincount + 5;
}
public static void Losecoin (){
if(coincount == 0) return;
coincount = coincount -1;
}
public static void Losecoin (int m){
if(coincount - m < 0){
coincount = 0;
}
else coincount = coincount -m;
}
public static string GetCoin () {
return coincount.ToString();
}
} // CoinCounter
| apache-2.0 | C# |
83570fcc3c92263b3f6ed7f834f01d61217325bb | Make AddStyleSheet create the <head> element if it doesn't exist yet | tombogle/libpalaso,glasseyes/libpalaso,mccarthyrb/libpalaso,mccarthyrb/libpalaso,andrew-polk/libpalaso,marksvc/libpalaso,marksvc/libpalaso,marksvc/libpalaso,chrisvire/libpalaso,hatton/libpalaso,andrew-polk/libpalaso,chrisvire/libpalaso,gtryus/libpalaso,hatton/libpalaso,JohnThomson/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,darcywong00/libpalaso,darcywong00/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,gmartin7/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,hatton/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,chrisvire/libpalaso,andrew-polk/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,JohnThomson/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,ermshiperete/libpalaso,hatton/libpalaso,chrisvire/libpalaso,JohnThomson/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso | Palaso/Xml/XmlDomExtensions.cs | Palaso/Xml/XmlDomExtensions.cs | using System;
using System.IO;
using System.Xml;
namespace Palaso.Xml
{
public static class XmlDomExtensions
{
public static XmlDocument StripXHtmlNameSpace(this XmlDocument node)
{
XmlDocument x = new XmlDocument();
x.LoadXml(node.OuterXml.Replace("xmlns", "xmlnsNeutered"));
return x;
}
public static void AddStyleSheet(this XmlDocument dom, string cssFilePath)
{
dom.AddStyleSheet(cssFilePath, null);
}
public static void AddStyleSheet(this XmlDocument dom, string cssFilePath, string nameSpaceIfDesired)
{
RemoveStyleSheetIfFound(dom, cssFilePath);//prevent duplicates
var head = XmlUtils.GetOrCreateElement(dom, "//html", "head"); //dom.SelectSingleNodeHonoringDefaultNS("//head");
AddSheet(dom, head, cssFilePath, nameSpaceIfDesired);
}
public static void RemoveStyleSheetIfFound(XmlDocument dom, string cssFilePath)
{
foreach (XmlElement linkNode in dom.SafeSelectNodes("/html/head/link"))
{
var href = linkNode.GetAttribute("href");
if (href == null)
{
continue;
}
//strip it down to just the name+extension, so other forms (e.g., via slightly different urls) will be removed.
var path = href.ToLower().Replace("file://", "");
if(Path.GetFileName(path)==Path.GetFileName(cssFilePath.ToLower()))
{
linkNode.ParentNode.RemoveChild(linkNode);
}
}
}
private static void AddSheet(this XmlDocument dom, XmlNode head, string cssFilePath, string namespaceIfDesired)
{
var link = string.IsNullOrEmpty(namespaceIfDesired) ? dom.CreateElement("link") : dom.CreateElement("link", namespaceIfDesired);
link.SetAttribute("rel", "stylesheet");
if(cssFilePath.Contains(Path.DirectorySeparatorChar.ToString())) // review: not sure about relative vs. complete paths
{
link.SetAttribute("href", "file://" + cssFilePath);
}
else //at least with gecko/firefox, something like "file://foo.css" is never found, so just give it raw
{
link.SetAttribute("href",cssFilePath);
}
link.SetAttribute("type", "text/css");
head.AppendChild(link);
}
}
} | using System;
using System.IO;
using System.Xml;
namespace Palaso.Xml
{
public static class XmlDomExtensions
{
public static XmlDocument StripXHtmlNameSpace(this XmlDocument node)
{
XmlDocument x = new XmlDocument();
x.LoadXml(node.OuterXml.Replace("xmlns", "xmlnsNeutered"));
return x;
}
public static void AddStyleSheet(this XmlDocument dom, string cssFilePath)
{
dom.AddStyleSheet(cssFilePath, null);
}
public static void AddStyleSheet(this XmlDocument dom, string cssFilePath, string nameSpaceIfDesired)
{
RemoveStyleSheetIfFound(dom, cssFilePath);//prevent duplicates
var head = dom.SelectSingleNodeHonoringDefaultNS("//head");
AddSheet(dom, head, cssFilePath, nameSpaceIfDesired);
}
public static void RemoveStyleSheetIfFound(XmlDocument dom, string cssFilePath)
{
foreach (XmlElement linkNode in dom.SafeSelectNodes("/html/head/link"))
{
var href = linkNode.GetAttribute("href");
if (href == null)
{
continue;
}
//strip it down to just the name+extension, so other forms (e.g., via slightly different urls) will be removed.
var path = href.ToLower().Replace("file://", "");
if(Path.GetFileName(path)==Path.GetFileName(cssFilePath.ToLower()))
{
linkNode.ParentNode.RemoveChild(linkNode);
}
}
}
private static void AddSheet(this XmlDocument dom, XmlNode head, string cssFilePath, string namespaceIfDesired)
{
var link = string.IsNullOrEmpty(namespaceIfDesired) ? dom.CreateElement("link") : dom.CreateElement("link", namespaceIfDesired);
link.SetAttribute("rel", "stylesheet");
if(cssFilePath.Contains(Path.DirectorySeparatorChar.ToString())) // review: not sure about relative vs. complete paths
{
link.SetAttribute("href", "file://" + cssFilePath);
}
else //at least with gecko/firefox, something like "file://foo.css" is never found, so just give it raw
{
link.SetAttribute("href",cssFilePath);
}
link.SetAttribute("type", "text/css");
head.AppendChild(link);
}
}
} | mit | C# |
02d17d180f98ae00bdbeb9f7334b93b2dffbc461 | Update Program.cs | box/box-windows-sdk-v2 | Box.V2.Samples.Core.File.Upload/Program.cs | Box.V2.Samples.Core.File.Upload/Program.cs | using System;
using System.IO;
using System.Threading.Tasks;
using Box.V2.Config;
using Box.V2.Models;
using Box.V2.Auth;
using System.Diagnostics;
using Box.V2.Utility;
namespace Box.V2.Core.Sample
{
public class Program
{
private static void Main(string[] args)
{
try
{
new Program().ExecuteMainAsync().Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private async Task ExecuteMainAsync()
{
Console.WriteLine("Access token: ");
var accessToken = Console.ReadLine();
Console.WriteLine("Remote file name: ");
var fileName = Console.ReadLine();
Console.WriteLine("Local file path: ");
var localFilePath = Console.ReadLine();
Console.WriteLine("Parent folder Id: ");
var parentFolderId = Console.ReadLine();
var timer = Stopwatch.StartNew();
var auth = new OAuthSession(accessToken, "YOUR_REFRESH_TOKEN", 3600, "bearer");
var config = new BoxConfig("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", new Uri("http://boxsdk"));
var client = new BoxClient(config, auth);
var file = File.OpenRead(localFilePath);
var fileRequest = new BoxFileRequest
{
Name = fileName,
Parent = new BoxFolderRequest { Id = parentFolderId }
};
// Normal file upload
// var bFile = await client.FilesManager.UploadAsync(fileRequest, file);
// Supercharged filed upload with progress report, only works with file >= 50m.
var progress = new Progress<BoxProgress>(val => { Console.WriteLine("{0}%", val.progress); });
var bFile = await client.FilesManager.UploadUsingSessionAsync(file, fileName, parentFolderId, null, progress);
Console.WriteLine("{0} uploaded to folder: {1} as file: {2}",localFilePath, parentFolderId, bFile.Id);
Console.WriteLine("Time spend : {0} ms", timer.ElapsedMilliseconds);
}
}
}
| using System;
using System.IO;
using System.Threading.Tasks;
using Box.V2.Config;
using Box.V2.Models;
using Box.V2.Auth;
using System.Diagnostics;
using Box.V2.Utility;
namespace Box.V2.Core.Sample
{
public class Program
{
private static void Main(string[] args)
{
try
{
new Program().ExecuteMainAsync().Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private async Task ExecuteMainAsync()
{
Console.WriteLine("Access token: ");
var accessToken = Console.ReadLine();
Console.WriteLine("Remote file name: ");
var fileName = Console.ReadLine();
Console.WriteLine("Local file path: ");
var localFilePath = Console.ReadLine();
Console.WriteLine("Parent folder Id: ");
var parentFolderId = Console.ReadLine();
var timer = Stopwatch.StartNew();
var auth = new OAuthSession(accessToken, "YOUR_REFRESH_TOKEN", 3600, "bearer");
var config = new BoxConfig("YOUR_CLIENT_ID", "YOUR_CLIENT_ID", new Uri("http://boxsdk"));
var client = new BoxClient(config, auth);
var file = File.OpenRead(localFilePath);
var fileRequest = new BoxFileRequest
{
Name = fileName,
Parent = new BoxFolderRequest { Id = parentFolderId }
};
// Normal file upload
// var bFile = await client.FilesManager.UploadAsync(fileRequest, file);
// Supercharged filed upload with progress report, only works with file >= 50m.
var progress = new Progress<BoxProgress>(val => { Console.WriteLine("{0}%", val.progress); });
var bFile = await client.FilesManager.UploadUsingSessionAsync(file, fileName, parentFolderId, null, progress);
Console.WriteLine("{0} uploaded to folder: {1} as file: {2}",localFilePath, parentFolderId, bFile.Id);
Console.WriteLine("Time spend : {0} ms", timer.ElapsedMilliseconds);
}
}
} | apache-2.0 | C# |
81f0971db93b156b58b9c0b6fa8d82c94a44bd5c | Bump version from 1.3 to 1.4 | AlexxEG/FalloutLauncher | FalloutLauncher/Properties/AssemblyInfo.cs | FalloutLauncher/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FalloutLauncher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Alexander Ellingsen")]
[assembly: AssemblyProduct("FalloutLauncher")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1e94daec-eaa2-4706-bdd0-913537af234e")]
// 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.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FalloutLauncher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Alexander Ellingsen")]
[assembly: AssemblyProduct("FalloutLauncher")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1e94daec-eaa2-4706-bdd0-913537af234e")]
// 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.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
| mit | C# |
0d8ad7b1ff7239c974641b8c44bd82fe1d4e148b | Fix Log4Net path for loading config file | vebin/MassTransit,abombss/MassTransit,ccellar/MassTransit,lahma/MassTransit,abombss/MassTransit,petedavis/MassTransit,ccellar/MassTransit,lahma/MassTransit,D3-LucaPiombino/MassTransit,abombss/MassTransit,ccellar/MassTransit,lahma/MassTransit,jsmale/MassTransit,lahma/MassTransit,ccellar/MassTransit,petedavis/MassTransit,vebin/MassTransit,lahma/MassTransit | src/Loggers/MassTransit.Log4NetIntegration/Logging/Log4NetLogger.cs | src/Loggers/MassTransit.Log4NetIntegration/Logging/Log4NetLogger.cs | // Copyright 2007-2011 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.Log4NetIntegration.Logging
{
using System;
using System.IO;
using MassTransit.Logging;
using log4net;
using log4net.Config;
public class Log4NetLogger :
ILogger
{
public MassTransit.Logging.ILog Get(string name)
{
return new Log4NetLog(LogManager.GetLogger(name));
}
public static void Use()
{
Logger.UseLogger(new Log4NetLogger());
}
public static void Use(string file)
{
Logger.UseLogger(new Log4NetLogger());
file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file);
var configFile = new FileInfo(file);
XmlConfigurator.Configure(configFile);
}
}
} | // Copyright 2007-2011 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.Log4NetIntegration.Logging
{
using System.IO;
using MassTransit.Logging;
using log4net;
using log4net.Config;
public class Log4NetLogger :
ILogger
{
public MassTransit.Logging.ILog Get(string name)
{
return new Log4NetLog(LogManager.GetLogger(name));
}
public static void Use()
{
Logger.UseLogger(new Log4NetLogger());
}
public static void Use(string file)
{
Logger.UseLogger(new Log4NetLogger());
var configFile = new FileInfo(file);
XmlConfigurator.Configure(configFile);
}
}
} | apache-2.0 | C# |
7fe05d872d173f3eb5499b33af61ab7bc966c943 | Add implementation for SlothEvent | CindyB/sloth | Sloth/Sloth/Core/SlothEvent.cs | Sloth/Sloth/Core/SlothEvent.cs | using Sloth.Interfaces.Core;
using System;
namespace Sloth.Core
{
public class SlothEvent : ISlothEvent
{
private string controlName;
private uint message;
private string windowsName;
public SlothEvent()
{
controlName = string.Empty;
message = uint.MinValue;
windowsName = string.Empty;
}
public string ControlName
{
get
{
return controlName;
}
set
{
controlName = value;
}
}
public uint Message
{
get
{
return message;
}
set
{
message = value;
}
}
public string WindowsName
{
get
{
return windowsName;
}
set
{
windowsName = value;
}
}
}
}
| using Sloth.Interfaces.Core;
using System;
namespace Sloth.Core
{
public class SlothEvent : ISlothEvent
{
public string ControlName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public uint Message
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string WindowsName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
}
| mit | C# |
5f45edf4b6d54ecbe403bb1c02f9b89653b674cf | Update SolrNet/Impl/ISolrQueryBody.cs | SolrNet/SolrNet,SolrNet/SolrNet | SolrNet/Impl/ISolrQueryBody.cs | SolrNet/Impl/ISolrQueryBody.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace SolrNet.Impl
{
/// <summary>
/// Represents the body of a query to be sent to Solr.
/// </summary>
public interface ISolrQueryBody
{
/// <summary>
/// Convert the body into a string to send to Solr.
/// </summary>
/// <returns></returns>
string Serialize();
/// <summary>
/// The MimeType to use when sending the request.
/// </summary>
string MimeType { get; }
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace SolrNet.Impl
{
/// <summary>
/// Represents the body of a query to be sent to Solr.
/// </summary>
public interface ISolrQueryBody
{
/// <summary>
/// Convert the body into a string to send to Solr.
/// </summary>
/// <returns></returns>
string Serialize();
/// <summary>
/// The MimeType to use when sending the request.
/// </summary>
string mimeType { get; }
}
}
| apache-2.0 | C# |
ae4dc19b1643a7764aa697a64c813dc1a1e74331 | Update Flip method of Player. | DerTraveler/into-the-thick-of-it | Assets/Script/Player.cs | Assets/Script/Player.cs | /* Copyright (c) 2016 Kevin Fischer
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 1.0f;
private Animator animator;
public enum State {
Idle,
Walking,
Attacking
}
[SerializeField]
private State state = State.Idle;
[SerializeField]
private string currentAnimation = "IdleDown";
[SerializeField]
private Vector2 moveDirection = new Vector2(0, 0);
[SerializeField]
private Vector2 faceDirection = new Vector2(0, -1);
[SerializeField]
private bool directionPressed = false;
void Start () {
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
ReadInput();
UpdateState();
PlayAnimation();
UpdateTransform();
}
private void ReadInput() {
moveDirection.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
directionPressed = moveDirection.sqrMagnitude > float.Epsilon;
if (Mathf.Approximately(moveDirection.sqrMagnitude, 1.0f)) {
faceDirection.Set(moveDirection.x, moveDirection.y);
}
}
private void UpdateState() {
switch(state) {
case State.Idle:
if (directionPressed) {
state = State.Walking;
}
break;
case State.Walking:
if (!directionPressed) {
state = State.Idle;
}
break;
}
}
private void PlayAnimation() {
FlipIfNecessary();
string nextAnimation = currentAnimation;
switch (state) {
case State.Idle:
nextAnimation = "Idle" + getDirectionName();
break;
case State.Walking:
nextAnimation = "Walk" + getDirectionName();
break;
}
if (nextAnimation != currentAnimation) {
currentAnimation = nextAnimation;
animator.Play(currentAnimation);
}
}
private void FlipIfNecessary() {
Vector3 scale = transform.localScale;
float scaleX = Mathf.Abs(scale.x);
scale.Set(Mathf.Approximately(faceDirection.x, -1.0f) ? -scaleX: scaleX, scale.y, scale.z);
transform.localScale = scale;
}
private string getDirectionName() {
if (faceDirection.y > 0) {
return "Up";
} else if (faceDirection.y < 0) {
return "Down";
} else {
return "Side";
}
}
private void UpdateTransform() {
if (state == State.Walking) {
Vector3 newPos = transform.position + (Vector3)(moveDirection * speed * Time.deltaTime);
transform.position = newPos;
}
}
}
| /* Copyright (c) 2016 Kevin Fischer
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 1.0f;
private Animator animator;
private SpriteRenderer spriteRenderer;
public enum State {
Idle,
Walking,
Attacking
}
[SerializeField]
private State state = State.Idle;
[SerializeField]
private string currentAnimation = "IdleDown";
[SerializeField]
private Vector2 moveDirection = new Vector2(0, 0);
[SerializeField]
private Vector2 faceDirection = new Vector2(0, -1);
[SerializeField]
private bool directionPressed = false;
void Start () {
animator = GetComponent<Animator>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update () {
ReadInput();
UpdateState();
PlayAnimation();
UpdateTransform();
}
private void ReadInput() {
moveDirection.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
directionPressed = moveDirection.sqrMagnitude > float.Epsilon;
if (Mathf.Approximately(moveDirection.sqrMagnitude, 1.0f)) {
faceDirection.Set(moveDirection.x, moveDirection.y);
}
}
private void UpdateState() {
switch(state) {
case State.Idle:
if (directionPressed) {
state = State.Walking;
}
break;
case State.Walking:
if (!directionPressed) {
state = State.Idle;
}
break;
}
}
private void PlayAnimation() {
// Flipping on X axis
spriteRenderer.flipX = Mathf.Approximately(faceDirection.x, -1.0f);
string nextAnimation = currentAnimation;
switch (state) {
case State.Idle:
nextAnimation = "Idle" + getDirectionName();
break;
case State.Walking:
nextAnimation = "Walk" + getDirectionName();
break;
}
if (nextAnimation != currentAnimation) {
currentAnimation = nextAnimation;
animator.Play(currentAnimation);
}
}
private string getDirectionName() {
if (faceDirection.y > 0) {
return "Up";
} else if (faceDirection.y < 0) {
return "Down";
} else {
return "Side";
}
}
private void UpdateTransform() {
if (state == State.Walking) {
Vector3 newPos = transform.position + (Vector3)(moveDirection * speed * Time.deltaTime);
transform.position = newPos;
}
}
}
| mpl-2.0 | C# |
4c80fbd0eedbae3bb030655bc3b2df28b33c8e39 | Add helper functions for Semester. | tsinghua-io/learn | Base/Models/Semester.cs | Base/Models/Semester.cs | using System;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using LearnTsinghua.Services;
namespace LearnTsinghua.Models
{
public class BasicSemester : IResource
{
public string Id { get; set; }
public DateTime BeginAt { get; set; }
public string DocId()
{
return API.SemesterURL();
}
public const string RESOURCE_TYPE = "semester";
public string ResourceType()
{
return RESOURCE_TYPE;
}
public async Task Update()
{
Console.WriteLine("Updating semester.");
var semester = await API.Semester();
semester.Save();
Console.WriteLine(string.Format("Semester updated to {0}, began at {1}.", semester.Id, semester.BeginAt));
}
}
public class Semester : BasicSemester
{
public static Semester Get()
{
return Database.Get<Semester>(new Semester().DocId());
}
public override string ToString()
{
return JObject.FromObject(this).ToString();
}
public static string IdToString(string id)
{
if (id.Length == 11)
{
var year = id.Substring(0, 9);
var season = id.Substring(10);
switch (season)
{
case "1":
return year + "秋季学期";
case "2":
return year + "春季学期";
case "3":
return year + "夏季学期";
}
}
return id; // We don't know how to handle it.
}
public int WeekNow()
{
var diff = DateTime.Now - BeginAt;
return diff.Days / 7 + 1;
}
}
}
| using System;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using LearnTsinghua.Services;
namespace LearnTsinghua.Models
{
public class BasicSemester : IResource
{
public string Id { get; set; }
public DateTime BeginAt { get; set; }
public string DocId()
{
return API.SemesterURL();
}
public const string RESOURCE_TYPE = "semester";
public string ResourceType()
{
return RESOURCE_TYPE;
}
public async Task Update()
{
Console.WriteLine("Updating semester.");
var semester = await API.Semester();
semester.Save();
Console.WriteLine(string.Format("Semester updated to {0}, began at {1}.", semester.Id, semester.BeginAt));
}
}
public class Semester : BasicSemester
{
public static Semester Get()
{
return Database.Get<Semester>(new Semester().DocId());
}
public override string ToString()
{
return JObject.FromObject(this).ToString();
}
}
}
| mit | C# |
35410597bd2fa249eb555b7a07b2dc6bbfffee89 | Format Timestamp | carbon/Amazon | src/Amazon.Ssm/Models/Timestamp.cs | src/Amazon.Ssm/Models/Timestamp.cs | using System;
using System.Text.Json.Serialization;
using Amazon.Ssm.Converters;
namespace Amazon.Ssm;
[JsonConverter(typeof(TimestampConverter))]
public readonly struct Timestamp
{
private readonly double _value;
public Timestamp(double value)
{
_value = value;
}
public double Value => _value;
public static implicit operator DateTime(Timestamp timestamp)
{
long unixTimeMillseconds = (long)(timestamp.Value * 1000d);
return DateTimeOffset.FromUnixTimeMilliseconds(unixTimeMillseconds).UtcDateTime;
}
public static implicit operator DateTimeOffset(Timestamp timestamp)
{
long unixTimeMillseconds = (long)(timestamp.Value * 1000d);
return DateTimeOffset.FromUnixTimeMilliseconds(unixTimeMillseconds);
}
}
// scientific notation: 1.494825472676E9
| using System;
using System.Text.Json.Serialization;
using Amazon.Ssm.Converters;
namespace Amazon.Ssm
{
[JsonConverter(typeof(TimestampConverter))]
public readonly struct Timestamp
{
private readonly double value;
public Timestamp(double value)
{
this.value = value;
}
public double Value => value;
public static implicit operator DateTime(Timestamp timestamp)
{
long unixTimeMillseconds = (long)(timestamp.Value * 1000d);
return DateTimeOffset.FromUnixTimeMilliseconds(unixTimeMillseconds).UtcDateTime;
}
public static implicit operator DateTimeOffset(Timestamp timestamp)
{
long unixTimeMillseconds = (long)(timestamp.Value * 1000d);
return DateTimeOffset.FromUnixTimeMilliseconds(unixTimeMillseconds);
}
}
}
// scientific notation: 1.494825472676E9
| mit | C# |
fad891b549be9ca7ae4ac3d02db649cc0dd255df | Make DelegateNamer public | droyad/Assent | src/Assent/Namers/DelegateNamer.cs | src/Assent/Namers/DelegateNamer.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Assent.Namers
{
public class DelegateNamer : INamer
{
readonly Func<TestMetadata, string> _f;
public DelegateNamer(Func<TestMetadata, string> f)
{
_f = f;
}
public string GetName(TestMetadata metadata)
{
return _f(metadata);
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Assent.Namers
{
class DelegateNamer : INamer
{
readonly Func<TestMetadata, string> _f;
public DelegateNamer(Func<TestMetadata, string> f)
{
_f = f;
}
public string GetName(TestMetadata metadata)
{
return _f(metadata);
}
}
}
| mit | C# |
2aed1f7a085fcac5646a61a3a18bfbb94a4b7772 | add sounds | svmnotn/cuddly-octo-adventure | Game/UI/MainWindow.cs | Game/UI/MainWindow.cs | namespace COA.Game.UI {
using System;
using System.Media;
using System.Windows.Forms;
using Controls;
using Data;
internal partial class MainWindow : Form {
UserControl current;
internal UserControl Current {
get { return current; }
set {
if(current != null) {
current.Visible = false;
}
if(!Controls.Contains(value)) {
Controls.Add(value);
}
current = value;
current.Dock = DockStyle.Fill;
current.Visible = true;
}
}
internal readonly Archive archive;
internal GameMode gm;
internal int currTeam;
internal Action timerFire;
internal int timerCount;
internal SoundPlayer main;
internal SoundPlayer yes;
internal SoundPlayer no;
internal MainWindow() : this(Archive.Default) { }
internal MainWindow(Archive a) {
InitializeComponent();
archive = a;
if(!string.IsNullOrWhiteSpace(archive.settings.sound.backgroundSoundLoc)) {
main = new SoundPlayer();
main.SoundLocation = archive.settings.sound.backgroundSoundLoc.RelativeTo(Program.ArchivePath(archive));
main.PlayLooping();
}
if(!string.IsNullOrWhiteSpace(archive.settings.sound.correctSoundLoc)) {
yes = new SoundPlayer();
yes.SoundLocation = archive.settings.sound.correctSoundLoc.RelativeTo(Program.ArchivePath(archive));
yes.LoadAsync();
}
if(!string.IsNullOrWhiteSpace(archive.settings.sound.wrongSoundLoc)) {
no = new SoundPlayer();
no.SoundLocation = archive.settings.sound.wrongSoundLoc.RelativeTo(Program.ArchivePath(archive));
no.LoadAsync();
}
Text = a.name;
BackColor = archive.settings.backgroundColor;
if(!string.IsNullOrWhiteSpace(archive.settings.backgroundLoc)) {
BackgroundImage = archive.settings.background ?? Extensions.LoadImage(Program.ArchivePath(archive), archive.settings.backgroundLoc);
}
Current = new ModeSelect();
}
private void OnTick(object sender, EventArgs e) {
if(timerFire != null) {
timerFire();
}
}
private void OnClose(object sender, FormClosedEventArgs e) {
Application.Exit();
}
}
} | namespace COA.Game.UI {
using System;
using System.Windows.Forms;
using Controls;
using Data;
internal partial class MainWindow : Form {
UserControl current;
internal UserControl Current {
get { return current; }
set {
if(current != null) {
current.Visible = false;
}
if(!Controls.Contains(value)) {
Controls.Add(value);
}
current = value;
current.Dock = DockStyle.Fill;
current.Visible = true;
}
}
internal readonly Archive archive;
internal GameMode gm;
internal int currTeam;
internal Action timerFire;
internal int timerCount;
internal MainWindow() : this(Archive.Default) { }
internal MainWindow(Archive a) {
InitializeComponent();
archive = a;
Text = a.name;
BackColor = archive.settings.backgroundColor;
if(!string.IsNullOrWhiteSpace(archive.settings.backgroundLoc)) {
BackgroundImage = archive.settings.background ?? Extensions.LoadImage(Program.ArchivePath(archive), archive.settings.backgroundLoc);
}
Current = new ModeSelect();
}
private void OnTick(object sender, EventArgs e) {
if(timerFire != null) {
timerFire();
}
}
private void OnClose(object sender, FormClosedEventArgs e) {
Application.Exit();
}
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.