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 |
---|---|---|---|---|---|---|---|---|
fb419b85135a346fcd0d54d5cd58b6a062762a82 | add data member | Paymentsense/Dapper.SimpleSave | PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Application/ApplicationDetailsMetadataDto.cs | PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Application/ApplicationDetailsMetadataDto.cs | using System.Collections.Generic;
using System.Runtime.Serialization;
using PS.Mothership.Core.Common.Template.App;
using PS.Mothership.Core.Common.Template.Gen;
using PS.Mothership.Core.Common.Dto.Merchant;
namespace PS.Mothership.Core.Common.Dto.Application
{
[DataContract]
public class ApplicationDetailsMetadataDto
{
[DataMember]
public IEnumerable<OfferSalesChannelDto> SalesChannels { get; set; }
[DataMember]
public IList<GenBusinessLegalType> BusinessLegalTypes { get; set; }
[DataMember]
public IList<AppAdvertisingFlags> AdvertisingTypes { get; set; }
[DataMember]
public IList<AppPremisesType> PremisesTypes { get; set; }
[DataMember]
public IList<GenSalutation> SalutationTypes { get; set; }
[DataMember]
public IList<GenContactRole> ContactRoles { get; set; }
[DataMember]
public IList<ApplicationDetailPrincipalDto> AvailableContactDetails { get; set; }
}
}
| using System.Collections.Generic;
using System.Runtime.Serialization;
using PS.Mothership.Core.Common.Template.App;
using PS.Mothership.Core.Common.Template.Gen;
using PS.Mothership.Core.Common.Dto.Merchant;
namespace PS.Mothership.Core.Common.Dto.Application
{
[DataContract]
public class ApplicationDetailsMetadataDto
{
[DataMember]
public IEnumerable<OfferSalesChannelDto> SalesChannels { get; set; }
[DataMember]
public IList<GenBusinessLegalType> BusinessLegalTypes { get; set; }
[DataMember]
public IList<AppAdvertisingFlags> AdvertisingTypes { get; set; }
[DataMember]
public IList<AppPremisesType> PremisesTypes { get; set; }
[DataMember]
public IList<GenSalutation> SalutationTypes { get; set; }
[DataMember]
public IList<GenContactRole> ContactRoles { get; set; }
}
}
| mit | C# |
8c180a11b5fe3876230c173385699a8b2df0f22f | Add FindCustomAttributes method. | Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver | src/AsmResolver.DotNet/IHasCustomAttribute.cs | src/AsmResolver.DotNet/IHasCustomAttribute.cs | using System.Collections.Generic;
using System.Linq;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a member that can be referenced by a HasCustomAttribute coded index,
/// </summary>
public interface IHasCustomAttribute : IMetadataMember
{
/// <summary>
/// Gets a collection of custom attributes assigned to this member.
/// </summary>
IList<CustomAttribute> CustomAttributes { get; }
}
/// <summary>
/// Provides extensions for various metadata members.
/// </summary>
public static partial class Extensions
{
/// <summary>
/// Finds all custom attributes that were assigned to a metadata member that match a particular namespace and name.
/// </summary>
/// <param name="self">The metadata member.</param>
/// <param name="ns">The namespace of the attribute type.</param>
/// <param name="name">The name of the attribute type.</param>
/// <returns>The matching attributes.</returns>
public static IEnumerable<CustomAttribute> FindCustomAttributes(this IHasCustomAttribute self, string ns, string name)
{
foreach (var attribute in self.CustomAttributes)
{
var declaringType = attribute.Constructor?.DeclaringType;
if (declaringType is null)
continue;
if (declaringType.IsTypeOf(ns, name))
yield return attribute;
}
}
/// <summary>
/// Indicates whether the specified member is compiler generated.
/// </summary>
/// <param name="self">The referenced member to check</param>
/// <returns><c>true</c> if the member was generated by the compiler, otherwise <c>false</c></returns>
public static bool IsCompilerGenerated(this IHasCustomAttribute self) => self
.FindCustomAttributes("System.Runtime.CompilerServices", "CompilerGeneratedAttribute")
.Any();
}
} | using System.Collections.Generic;
using System.Linq;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a member that can be referenced by a HasCustomAttribute coded index,
/// </summary>
public interface IHasCustomAttribute : IMetadataMember
{
/// <summary>
/// Gets a collection of custom attributes assigned to this member.
/// </summary>
IList<CustomAttribute> CustomAttributes { get; }
}
/// <summary>
/// Provides extensions for various metadata members.
/// </summary>
public static partial class Extensions
{
/// <summary>
/// Indicates whether the specified member is compiler generated.
/// </summary>
/// <param name="attribute">The referenced member to check</param>
/// <returns><c>true</c> if the member was generated by the compiler, otherwise <c>false</c></returns>
public static bool IsCompilerGenerated(this IHasCustomAttribute attribute)
{
return attribute.CustomAttributes.Any(c =>
c.Constructor.DeclaringType.IsTypeOf("System.Runtime.CompilerServices", "CompilerGeneratedAttribute"));
}
}
} | mit | C# |
bb478c62be8dbba59a420fc87dc4248bf58ce06a | Remove todo | Krusen/ErgastApi.Net | src/ErgastiApi/Ids/FinishingStatusIdParser.cs | src/ErgastiApi/Ids/FinishingStatusIdParser.cs | using System;
using System.Text.RegularExpressions;
namespace ErgastApi.Ids
{
public static class FinishingStatusIdParser
{
public static FinishingStatusId Parse(string value)
{
FinishingStatusId statusId;
var lapsMatch = Regex.Match(value, @"\+(\d+) Laps?", RegexOptions.IgnoreCase);
if (lapsMatch.Success)
{
value = "Laps" + lapsMatch.Groups[1].Value;
if (Enum.TryParse(value, out statusId))
return statusId;
}
value = Regex.Replace(value, @"\s", "");
Enum.TryParse(value, true, out statusId);
return statusId;
}
}
}
| using System;
using System.Text.RegularExpressions;
namespace ErgastApi.Ids
{
// TODO: Maybe move
public static class FinishingStatusIdParser
{
public static FinishingStatusId Parse(string value)
{
FinishingStatusId statusId;
var lapsMatch = Regex.Match(value, @"\+(\d+) Laps?", RegexOptions.IgnoreCase);
if (lapsMatch.Success)
{
value = "Laps" + lapsMatch.Groups[1].Value;
if (Enum.TryParse(value, out statusId))
return statusId;
}
value = Regex.Replace(value, @"\s", "");
Enum.TryParse(value, true, out statusId);
return statusId;
}
}
}
| unlicense | C# |
34833ad6b6ca1bf108aef4009b01da058c4edab4 | Update TransformExtensions.cs | SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia | src/Avalonia.Visuals/Media/TransformExtensions.cs | src/Avalonia.Visuals/Media/TransformExtensions.cs | using System;
using Avalonia.Media.Immutable;
namespace Avalonia.Media
{
/// <summary>
/// Extension methods for transform classes.
/// </summary>
public static class TransformExtensions
{
/// <summary>
/// Converts a transform to an immutable transform.
/// </summary>
/// <param name="transform">The transform.</param>
/// <returns>
/// The result of calling <see cref="Transform.ToImmutable"/> if the transform is mutable,
/// otherwise <paramref name="transform"/>.
/// </returns>
public static ImmutableTransform ToImmutable(this ITransform transform)
{
_ = transform ?? throw new ArgumentNullException(nameof(transform));
return (transform as Transform)?.ToImmutable() ?? new ImmutableTransform(transform.Value);
}
}
}
| using System;
using Avalonia.Media.Immutable;
namespace Avalonia.Media
{
/// <summary>
/// Extension methods for transform classes.
/// </summary>
public static class TransformExtensions
{
/// <summary>
/// Converts a transform to an immutable transform.
/// </summary>
/// <param name="transform">The transform.</param>
/// <returns>
/// The result of calling <see cref="Transform.ToImmutable"/> if the transform is mutable,
/// otherwise <paramref name="transform"/>.
/// </returns>
public static ImmutableTransform ToImmutable(this ITransform? transform)
{
Contract.Requires<ArgumentNullException>(transform != null);
return (transform as Transform)?.ToImmutable() ?? new ImmutableTransform(transform.Value);
}
}
}
| mit | C# |
5f0787f3e05edd19bf51b850b3b77a7135050452 | Bump version number | Netuitive/netuitive-windows-agent | src/CollectdWinService/Properties/AssemblyInfo.cs | src/CollectdWinService/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("CollectdWinService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Netuitive, Inc.")]
[assembly: AssemblyProduct("CollectdWinService")]
[assembly: AssemblyCopyright("Copyright © Netuitive, Inc. 2017")]
[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
// AP - This assembly is not accessible from COM so guid is not needed
//[assembly: Guid("dc0404f4-acd7-40b3-ab7a-6e63f023ac40")]
// 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.10.6.*")]
| 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("CollectdWinService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Netuitive, Inc.")]
[assembly: AssemblyProduct("CollectdWinService")]
[assembly: AssemblyCopyright("Copyright © Netuitive, Inc. 2017")]
[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
// AP - This assembly is not accessible from COM so guid is not needed
//[assembly: Guid("dc0404f4-acd7-40b3-ab7a-6e63f023ac40")]
// 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.10.5.*")]
| apache-2.0 | C# |
366a019e11253f45a9ed4186d83782fd6ac1d44e | Tidy up logger configuration | datalust/piggy,datalust/piggy,datalust/piggy | src/Datalust.Piggy/Cli/Features/LoggingFeature.cs | src/Datalust.Piggy/Cli/Features/LoggingFeature.cs | using System;
using Serilog;
using Serilog.Events;
namespace Datalust.Piggy.Cli.Features
{
class LoggingFeature : CommandFeature
{
string _serverUrl, _apiKey;
LogEventLevel _level = LogEventLevel.Information;
public override void Enable(OptionSet options)
{
options.Add("log-seq=", "Log output to a Seq server at the specified URL", v => _serverUrl = v);
options.Add("log-seq-apikey=", "If logging to Seq, an optional API key", v => _apiKey = v);
options.Add("log-debug", "Write additional diagnostic log output", v => _level = LogEventLevel.Debug);
}
public void Configure()
{
var loggerConfiguration = new LoggerConfiguration()
.MinimumLevel.Is(_level)
.Enrich.WithProperty("Application", "Piggy")
.Enrich.WithProperty("Invocation", Guid.NewGuid())
.WriteTo.Console();
if (!string.IsNullOrWhiteSpace(_serverUrl))
loggerConfiguration
.WriteTo.Seq(_serverUrl, apiKey: _apiKey);
Log.Logger = loggerConfiguration.CreateLogger();
}
}
}
| using System;
using Serilog;
using Serilog.Events;
namespace Datalust.Piggy.Cli.Features
{
class LoggingFeature : CommandFeature
{
string _serverUrl, _apiKey;
LogEventLevel _level = LogEventLevel.Information;
public override void Enable(OptionSet options)
{
options.Add("log-seq=", "Log output to a Seq server at the specified URL", v => _serverUrl = v);
options.Add("log-seq-apikey=", "If logging to Seq, an optional API key", v => _apiKey = v);
options.Add("log-debug", "Write additional diagnostic log output", v => _level = LogEventLevel.Debug);
}
public void Configure()
{
var loggerConfiguration = new LoggerConfiguration()
.MinimumLevel.Is(_level)
.Enrich.WithProperty("Invocation", Guid.NewGuid())
.WriteTo.Console();
if (!string.IsNullOrWhiteSpace(_serverUrl))
loggerConfiguration
.Enrich.WithProperty("Application", "Piggy")
.WriteTo.Seq(_serverUrl, apiKey: _apiKey);
Log.Logger = loggerConfiguration.CreateLogger();
}
}
}
| apache-2.0 | C# |
38bb4bf6bf176cc84bfb36fadc50b15ecb34d7f9 | Change test to map with allign with initial design and documentation | Seddryck/NBi,Seddryck/NBi | NBi.Testing/Unit/Core/Query/CommandBuilderTest.cs | NBi.Testing/Unit/Core/Query/CommandBuilderTest.cs | using NBi.Core.Query;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Testing.Unit.Core.Query
{
[TestFixture]
public class CommandBuilderTest
{
[Test]
public void Build_TimeoutSpecified_TimeoutSet()
{
var builder = new CommandBuilder();
var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 5000);
Assert.That(cmd.CommandTimeout, Is.EqualTo(5));
}
[Test]
public void Build_TimeoutSetToZero_TimeoutSet0Seconds()
{
var builder = new CommandBuilder();
var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 0);
Assert.That(cmd.CommandTimeout, Is.EqualTo(0));
}
[Test]
public void Build_TimeoutSetTo30_TimeoutSet30Seconds()
{
var builder = new CommandBuilder();
var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 30000);
Assert.That(cmd.CommandTimeout, Is.EqualTo(30));
}
}
}
| using NBi.Core.Query;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Testing.Unit.Core.Query
{
[TestFixture]
public class CommandBuilderTest
{
[Test]
public void Build_TimeoutSpecified_TimeoutSet()
{
var builder = new CommandBuilder();
var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 5000);
Assert.That(cmd.CommandTimeout, Is.EqualTo(5));
}
[Test]
public void Build_TimeoutSetToZero_TimeoutSet30Seconds()
{
var builder = new CommandBuilder();
var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 0);
Assert.That(cmd.CommandTimeout, Is.EqualTo(30));
}
[Test]
public void Build_TimeoutSetTo30_TimeoutSet30Seconds()
{
var builder = new CommandBuilder();
var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 30000);
Assert.That(cmd.CommandTimeout, Is.EqualTo(30));
}
}
}
| apache-2.0 | C# |
6c3ba87cab3ffa9aedfffe6fedbbd8dc790443d2 | Revert "sandbox demo of shutdown cancel." | jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Perspex | samples/Sandbox/App.axaml.cs | samples/Sandbox/App.axaml.cs | using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
namespace Sandbox
{
public class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktopLifetime)
{
desktopLifetime.MainWindow = new MainWindow();
}
}
}
}
| using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
namespace Sandbox
{
public class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktopLifetime)
{
desktopLifetime.MainWindow = new MainWindow();
desktopLifetime.ShutdownRequested += DesktopLifetime_ShutdownRequested;
}
}
private void DesktopLifetime_ShutdownRequested(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
}
}
| mit | C# |
71a60bdaa3e3e686d196b4f81b1def6c3de2d4e3 | Fix compilation | monoman/PackageManagerAddin | NuPackAddin.Extensions/DotNetProjectExtensions.cs | NuPackAddin.Extensions/DotNetProjectExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MonoDevelop.Projects;
using NuPack;
namespace NuPackAddin.Extensions
{
public static class DotNetProjectExtensions
{
public static void AddPackage(this DotNetProject project, IPackage package)
{
// TODO: implement it
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MonoDevelop.Projects;
using NuPack;
namespace NuPackAddin.Extensions
{
public class DotNetProjectExtensions
{
public static void AddPackage(this DotNetProject project, IPackage package)
{
// TODO: implement it
}
}
}
| apache-2.0 | C# |
ded764546bf1ea0cf1a816aee3ad99eec5b4e93d | fix typo | danielgerlag/workflow-core | src/WorkflowCore/Interface/IPersistenceProvider.cs | src/WorkflowCore/Interface/IPersistenceProvider.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WorkflowCore.Models;
namespace WorkflowCore.Interface
{
/// <remarks>
/// The implemention of this interface will be responsible for
/// persisting running workflow instances to a durable store
/// </remarks>
public interface IPersistenceProvider
{
Task<string> CreateNewWorkflow(WorkflowInstance workflow);
Task PersistWorkflow(WorkflowInstance workflow);
Task<IEnumerable<string>> GetRunnableInstances(DateTime asAt);
[Obsolete]
Task<IEnumerable<WorkflowInstance>> GetWorkflowInstances(WorkflowStatus? status, string type, DateTime? createdFrom, DateTime? createdTo, int skip, int take);
Task<WorkflowInstance> GetWorkflowInstance(string Id);
Task<IEnumerable<WorkflowInstance>> GetWorkflowInstances(IEnumerable<string> ids);
Task<string> CreateEventSubscription(EventSubscription subscription);
Task<IEnumerable<EventSubscription>> GetSubcriptions(string eventName, string eventKey, DateTime asOf);
Task TerminateSubscription(string eventSubscriptionId);
Task<string> CreateEvent(Event newEvent);
Task<Event> GetEvent(string id);
Task<IEnumerable<string>> GetRunnableEvents(DateTime asAt);
Task<IEnumerable<string>> GetEvents(string eventName, string eventKey, DateTime asOf);
Task MarkEventProcessed(string id);
Task MarkEventUnprocessed(string id);
Task PersistErrors(IEnumerable<ExecutionError> errors);
void EnsureStoreExists();
}
}
| using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WorkflowCore.Models;
namespace WorkflowCore.Interface
{
/// <remarks>
/// The implemention of this interface will be responsible for
/// persisiting running workflow instances to a durable store
/// </remarks>
public interface IPersistenceProvider
{
Task<string> CreateNewWorkflow(WorkflowInstance workflow);
Task PersistWorkflow(WorkflowInstance workflow);
Task<IEnumerable<string>> GetRunnableInstances(DateTime asAt);
[Obsolete]
Task<IEnumerable<WorkflowInstance>> GetWorkflowInstances(WorkflowStatus? status, string type, DateTime? createdFrom, DateTime? createdTo, int skip, int take);
Task<WorkflowInstance> GetWorkflowInstance(string Id);
Task<IEnumerable<WorkflowInstance>> GetWorkflowInstances(IEnumerable<string> ids);
Task<string> CreateEventSubscription(EventSubscription subscription);
Task<IEnumerable<EventSubscription>> GetSubcriptions(string eventName, string eventKey, DateTime asOf);
Task TerminateSubscription(string eventSubscriptionId);
Task<string> CreateEvent(Event newEvent);
Task<Event> GetEvent(string id);
Task<IEnumerable<string>> GetRunnableEvents(DateTime asAt);
Task<IEnumerable<string>> GetEvents(string eventName, string eventKey, DateTime asOf);
Task MarkEventProcessed(string id);
Task MarkEventUnprocessed(string id);
Task PersistErrors(IEnumerable<ExecutionError> errors);
void EnsureStoreExists();
}
}
| mit | C# |
eb9cf47f82fbebb276377a974cd10074b4d82534 | Bump version to beta2 | kevinkuszyk/test-framework | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("Kevin Kuszyk")]
[assembly: AssemblyCopyright("Copyright Kevin Kuszyk 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta2")]
[assembly: AssemblyProduct("Test Framework")] | using System.Reflection;
[assembly: AssemblyCompany("Kevin Kuszyk")]
[assembly: AssemblyCopyright("Copyright Kevin Kuszyk 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta1")]
[assembly: AssemblyProduct("Test Framework")] | mit | C# |
7e55e1684e30c5cec047eca319c2e0c1cf214c36 | bump ver | AntonyCorbett/OnlyT,AntonyCorbett/OnlyT | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.39")] | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.38")] | mit | C# |
730eef70defedfd514d5f54373b82c048982d7a1 | exit after job complete | ucdavis/Namster,ucdavis/Namster,ucdavis/Namster | src/Namster.Jobs.ElasticSync/NamSearchUploader.cs | src/Namster.Jobs.ElasticSync/NamSearchUploader.cs | using System;
using Dapper;
using Microsoft.Extensions.Configuration;
using Namster.Jobs.ElasticSync.Helpers;
using Namster.Jobs.ElasticSync.Models;
using Namster.Jobs.ElasticSync.Services;
using Nest;
namespace Namster.Jobs.ElasticSync
{
public class NamSearchUploader
{
private readonly DbService _dbService;
private readonly string _indexName;
private readonly Uri _connectionString;
private readonly string _dbConnectionString;
public NamSearchUploader(IConfiguration configuration)
{
_dbService = new DbService();
_dbConnectionString = configuration["Data:DefaultConnection:ConnectionString"];
_connectionString = new Uri(configuration["Search:Url"]);
_indexName = configuration["Search:IndexName"];
}
public void Run()
{
using (var conn = _dbService.GetDbConnection(_dbConnectionString))
{
var nams = conn.Query<DataNam>("select * from DataNamsFlattened inner join VLanContactsFlattened on DataNamsFlattened.Vlan = VLanContactsFlattened.Vlan");
Console.WriteLine("Nams retrieved from DB");
var settings = new ConnectionSettings(_connectionString);
settings.DefaultIndex(_indexName);
var client = new ElasticClient(settings);
if (client.Indices.Exists(_indexName).Exists)
{
client.Indices.Delete(_indexName);
}
client.Indices.Create(_indexName, c => c.Map<DataNam>(m => m.AutoMap()));
Console.WriteLine("Index recreated, starting indexing");
var namsBuckets = nams.Partition(5000);
foreach (var bucket in namsBuckets)
{
Console.WriteLine("indexing bucket");
client.Bulk(b => b.IndexMany(bucket));
}
Console.WriteLine("Indexing complete, exiting");
}
}
}
}
| using System;
using Dapper;
using Microsoft.Extensions.Configuration;
using Namster.Jobs.ElasticSync.Helpers;
using Namster.Jobs.ElasticSync.Models;
using Namster.Jobs.ElasticSync.Services;
using Nest;
namespace Namster.Jobs.ElasticSync
{
public class NamSearchUploader
{
private readonly DbService _dbService;
private readonly string _indexName;
private readonly Uri _connectionString;
private readonly string _dbConnectionString;
public NamSearchUploader(IConfiguration configuration)
{
_dbService = new DbService();
_dbConnectionString = configuration["Data:DefaultConnection:ConnectionString"];
_connectionString = new Uri(configuration["Search:Url"]);
_indexName = configuration["Search:IndexName"];
}
public void Run()
{
using (var conn = _dbService.GetDbConnection(_dbConnectionString))
{
var nams = conn.Query<DataNam>("select * from DataNamsFlattened inner join VLanContactsFlattened on DataNamsFlattened.Vlan = VLanContactsFlattened.Vlan");
Console.WriteLine("Nams retrieved from DB");
var settings = new ConnectionSettings(_connectionString);
settings.DefaultIndex(_indexName);
var client = new ElasticClient(settings);
if (client.Indices.Exists(_indexName).Exists)
{
client.Indices.Delete(_indexName);
}
client.Indices.Create(_indexName, c => c.Map<DataNam>(m => m.AutoMap()));
Console.WriteLine("Index recreated, starting indexing");
var namsBuckets = nams.Partition(5000);
foreach (var bucket in namsBuckets)
{
Console.WriteLine("indexing bucket");
client.Bulk(b => b.IndexMany(bucket));
}
Console.WriteLine("Indexing complete, press any key to end");
Console.ReadKey();
}
}
}
}
| mit | C# |
f9df32afa75f67830dc93d4183fe8a80c2c5812e | fix ws | nataren/NServiceKit.Redis,NServiceKit/NServiceKit.Redis,MindTouch/NServiceKit.Redis | src/ServiceStack.Redis/Properties/AssemblyInfo.cs | src/ServiceStack.Redis/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("ServiceStack.Redis")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServiceStack.Redis")]
[assembly: AssemblyCopyright("Copyright © ServiceStack 2012")]
[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("70a33fa7-9f81-418d-bb25-6a4be6648ae4")]
// 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("3.9.24.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("ServiceStack.Redis.Tests")]
| 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("ServiceStack.Redis")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServiceStack.Redis")]
[assembly: AssemblyCopyright("Copyright © ServiceStack 2012")]
[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("70a33fa7-9f81-418d-bb25-6a4be6648ae4")]
// 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("3.9.24.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("ServiceStack.Redis.Tests")]
| bsd-3-clause | C# |
e8d08a5856d0a61050378e40472b358e838102cf | Add ProtocolNotSupported to OracleResponseCode (#2164) | AntShares/AntShares | src/neo/Network/P2P/Payloads/OracleResponseCode.cs | src/neo/Network/P2P/Payloads/OracleResponseCode.cs | namespace Neo.Network.P2P.Payloads
{
public enum OracleResponseCode : byte
{
Success = 0x00,
ProtocolNotSupported = 0x10,
ConsensusUnreachable = 0x12,
NotFound = 0x14,
Timeout = 0x16,
Forbidden = 0x18,
ResponseTooLarge = 0x1a,
InsufficientFunds = 0x1c,
Error = 0xff
}
}
| namespace Neo.Network.P2P.Payloads
{
public enum OracleResponseCode : byte
{
Success = 0x00,
ConsensusUnreachable = 0x10,
NotFound = 0x12,
Timeout = 0x14,
Forbidden = 0x16,
ResponseTooLarge = 0x18,
InsufficientFunds = 0x1a,
Error = 0xff
}
}
| mit | C# |
283475c3c6dc6194207489c5e9950b17c0fd06e0 | Fix code formatting | Microsoft/ApplicationInsights-dotnet-logging | src/Adapters.Tests/Etw.Net451.Tests/TestProvider.cs | src/Adapters.Tests/Etw.Net451.Tests/TestProvider.cs | //-----------------------------------------------------------------------
// <copyright file="TestProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.ApplicationInsights.EtwTelemetryCollector.Tests
{
using System;
using System.Diagnostics.Tracing;
[EventSource(Name = TestProvider.ProviderName)]
internal class TestProvider : EventSource
{
public const string ProviderName = "Microsoft-ApplicationInsights-Extensibility-Etw-Provider-Tests";
public const int InfoEventId = 1;
public const int WarningEventId = 2;
public const int ComplexEventId = 4;
public const int RequestStartEventId = 5;
public const int RequestStopEventId = 6;
public const int TrickyEventId = 7;
public static readonly TestProvider Log = new TestProvider();
[Event(InfoEventId, Level = EventLevel.Informational, Message = "{0}", Keywords = Keywords.Routine)]
public void Info(string information)
{
WriteEvent(InfoEventId, information);
}
[Event(WarningEventId, Level = EventLevel.Warning, Message = "Warning!", Keywords = Keywords.NonRoutine)]
public void Warning(int i1, int i2)
{
WriteEvent(WarningEventId, i1, i2);
}
[Event(ComplexEventId, Level = EventLevel.Verbose, Message = "Blah blah", Keywords = Keywords.Routine,
Channel = EventChannel.Debug, Opcode = EventOpcode.Extension, Tags = (EventTags)17, Task = (EventTask)32)]
public void Complex(Guid uniqueId)
{
WriteEvent(ComplexEventId, uniqueId);
}
[Event(TrickyEventId, Level = EventLevel.Informational, Message = "Manifest message")]
public void Tricky(int EventId, string EventName, string Message)
{
WriteEvent(TrickyEventId, EventId, EventName, Message);
}
[Event(RequestStartEventId, Level = EventLevel.Informational, ActivityOptions = EventActivityOptions.Recursive)]
public void RequestStart(int requestId)
{
WriteEvent(RequestStartEventId, requestId);
}
[Event(RequestStopEventId, Level = EventLevel.Informational, ActivityOptions = EventActivityOptions.Recursive)]
public void RequestStop(int requestId)
{
WriteEvent(RequestStopEventId, requestId);
}
public class Keywords
{
public const EventKeywords Routine = (EventKeywords)0x01;
public const EventKeywords NonRoutine = (EventKeywords)0x2;
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="TestProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.ApplicationInsights.EtwTelemetryCollector.Tests
{
using System;
using System.Diagnostics.Tracing;
[EventSource(Name = TestProvider.ProviderName)]
internal class TestProvider : EventSource
{
public const string ProviderName = "Microsoft-ApplicationInsights-Extensibility-Etw-Provider-Tests";
public const int InfoEventId = 1;
public const int WarningEventId = 2;
public const int ComplexEventId = 4;
public const int RequestStartEventId = 5;
public const int RequestStopEventId = 6;
public const int TrickyEventId = 7;
public static readonly TestProvider Log = new TestProvider();
[Event(InfoEventId, Level = EventLevel.Informational, Message = "{0}", Keywords = Keywords.Routine)]
public void Info(string information)
{
WriteEvent(InfoEventId, information);
}
[Event(WarningEventId, Level = EventLevel.Warning, Message = "Warning!", Keywords = Keywords.NonRoutine)]
public void Warning(int i1, int i2)
{
WriteEvent(WarningEventId, i1, i2);
}
[Event(ComplexEventId, Level = EventLevel.Verbose, Message = "Blah blah", Keywords = Keywords.Routine,
Channel = EventChannel.Debug, Opcode = EventOpcode.Extension, Tags = (EventTags)17, Task = (EventTask)32)]
public void Complex(Guid uniqueId)
{
WriteEvent(ComplexEventId, uniqueId);
}
[Event(TrickyEventId, Level = EventLevel.Informational, Message = "Manifest message")]
public void Tricky(int EventId, string EventName, string Message)
{
WriteEvent(TrickyEventId, EventId, EventName, Message);
}
[Event(RequestStartEventId, Level = EventLevel.Informational, ActivityOptions = EventActivityOptions.Recursive)]
public void RequestStart(int requestId)
{
WriteEvent(RequestStartEventId, requestId);
}
[Event(RequestStopEventId, Level = EventLevel.Informational, ActivityOptions = EventActivityOptions.Recursive)]
public void RequestStop(int requestId)
{
WriteEvent(RequestStopEventId, requestId);
}
public class Keywords
{
public const EventKeywords Routine = (EventKeywords)0x01;
public const EventKeywords NonRoutine = (EventKeywords)0x2;
}
}
}
| mit | C# |
f0a73bbf8c373ea792974c7f1e3b18520ed50f47 | Set Obsolete ZPLBarCode128 | BinaryKits/ZPLUtility | src/BinaryKits.ZPLUtility/Elements/ZPLBarcode128.cs | src/BinaryKits.ZPLUtility/Elements/ZPLBarcode128.cs | using System;
using System.Collections.Generic;
namespace BinaryKits.Utility.ZPLUtility.Elements
{
/// <summary>
/// Code 128
/// </summary>
public class ZPLBarcode128 : ZPLBarcode
{
public ZPLBarcode128(string content, int positionX, int positionY, int height = 100, string orientation = "N", bool printInterpretationLine = true, bool printInterpretationLineAboveCode = false)
: base(content, positionX, positionY, height, orientation, printInterpretationLine, printInterpretationLineAboveCode)
{
}
public override IEnumerable<string> Render(ZPLRenderOptions context)
{
//^FO100,100 ^ BY3
//^BCN,100,Y,N,N
//^FD123456 ^ FS
var result = new List<string>();
result.AddRange(Origin.Render(context));
result.Add($"^B{Orientation},{context.Scale(Height)},{(PrintInterpretationLine ? "Y" : "N")},{(PrintInterpretationLineAboveCode ? "Y" : "N")}");
result.Add($"^FD{Content}^FS");
return result;
}
}
[Obsolete("ZPLBarCode128 is deprecated, please use ZPLBarcode128 instead.")]
public class ZPLBarCode128 : ZPLBarcode128
{
public ZPLBarCode128(string content, int positionX, int positionY, int height = 100, string orientation = "N", bool printInterpretationLine = true, bool printInterpretationLineAboveCode = false)
: base(content, positionX, positionY, height, orientation, printInterpretationLine, printInterpretationLineAboveCode)
{
}
}
}
| using System.Collections.Generic;
namespace BinaryKits.Utility.ZPLUtility.Elements
{
/// <summary>
/// Code 128
/// </summary>
public class ZPLBarcode128 : ZPLBarcode
{
public ZPLBarcode128(string content, int positionX, int positionY, int height = 100, string orientation = "N", bool printInterpretationLine = true, bool printInterpretationLineAboveCode = false)
: base(content, positionX, positionY, height, orientation, printInterpretationLine, printInterpretationLineAboveCode)
{
}
public override IEnumerable<string> Render(ZPLRenderOptions context)
{
//^FO100,100 ^ BY3
//^BCN,100,Y,N,N
//^FD123456 ^ FS
var result = new List<string>();
result.AddRange(Origin.Render(context));
result.Add($"^B{Orientation},{context.Scale(Height)},{(PrintInterpretationLine ? "Y" : "N")},{(PrintInterpretationLineAboveCode ? "Y" : "N")}");
result.Add($"^FD{Content}^FS");
return result;
}
}
}
| mit | C# |
3cbcf36a5a5c8836c415e411e8004729a5664391 | fix HistoricDeposit type | Domysee/BittrexSharp | BittrexSharp/Domain/HistoricDeposit.cs | BittrexSharp/Domain/HistoricDeposit.cs | using System;
namespace BittrexSharp.Domain
{
public class HistoricDeposit
{
public long Id { get; set; }
public decimal Amount { get; set; }
public string Currency { get; set; }
public int Confirmations { get; set; }
public DateTime LastUpdated { get; set; }
public string TxId { get; set; }
public string CryptoAddress { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace BittrexSharp.Domain
{
public class HistoricDeposit
{
public string PaymentUuid { get; set; }
public string Currency { get; set; }
public decimal Amount { get; set; }
public string Address { get; set; }
public DateTime Opened { get; set; }
public bool Authorized { get; set; }
public bool PendingPayment { get; set; }
public decimal TxCost { get; set; }
public string TxId { get; set; }
public bool Canceled { get; set; }
public bool InvalidAddress { get; set; }
}
}
| mit | C# |
c351e35abedca3e71a2f918eff23ac65666660c1 | bump ver | AntonyCorbett/OnlyT,AntonyCorbett/OnlyT | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.37")] | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.36")] | mit | C# |
d5f617606f37a05b1b7b8ce4e40c0442c1ae2034 | initialise collections to empty | Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen | Dashen/Models/GraphControlViewModel.cs | Dashen/Models/GraphControlViewModel.cs | using System.Collections.Generic;
using System.Linq;
namespace Dashen.Models
{
public class GraphControlViewModel : ControlViewModel
{
public IEnumerable<KeyValuePair<int, int>> Points { get; set; }
public IEnumerable<KeyValuePair<int, string>> XTicks { get; set; }
public IEnumerable<KeyValuePair<int, string>> YTicks { get; set; }
public GraphControlViewModel()
{
Points = Enumerable.Empty<KeyValuePair<int, int>>();
XTicks = Enumerable.Empty<KeyValuePair<int, string>>();
YTicks = Enumerable.Empty<KeyValuePair<int, string>>();
}
}
}
| using System.Collections.Generic;
namespace Dashen.Models
{
public class GraphControlViewModel : ControlViewModel
{
public IEnumerable<KeyValuePair<int, int>> Points { get; set; }
public IEnumerable<KeyValuePair<int, string>> XTicks { get; set; }
}
}
| lgpl-2.1 | C# |
dd160fdf585c737458d6c1d3fcc521ac3f02337f | Add Max Token Length to Whitespace Tokenizer (#3172) | elastic/elasticsearch-net,elastic/elasticsearch-net | src/Nest/Analysis/Tokenizers/WhitespaceTokenizer.cs | src/Nest/Analysis/Tokenizers/WhitespaceTokenizer.cs | using Newtonsoft.Json;
namespace Nest
{
/// <summary>
/// A tokenizer of type whitespace that divides text at whitespace.
/// </summary>
public interface IWhitespaceTokenizer : ITokenizer
{
/// <summary>
/// The maximum token length. If a token is seen that exceeds this length then it is split at
/// <see cref="MaxTokenLength"/> intervals. Defaults to 255.
/// </summary>
/// <remarks>
/// Valid for Elasticsearch 6.1.0+
/// </remarks>
[JsonProperty("max_token_length")]
int? MaxTokenLength { get; set; }
}
/// <inheritdoc cref="IWhitespaceTokenizer"/>
public class WhitespaceTokenizer : TokenizerBase, IWhitespaceTokenizer
{
public WhitespaceTokenizer() { Type = "whitespace"; }
/// <inheritdoc />
public int? MaxTokenLength { get; set; }
}
/// <inheritdoc cref="IWhitespaceTokenizer"/>
public class WhitespaceTokenizerDescriptor
: TokenizerDescriptorBase<WhitespaceTokenizerDescriptor, IWhitespaceTokenizer>, IWhitespaceTokenizer
{
protected override string Type => "whitespace";
int? IWhitespaceTokenizer.MaxTokenLength { get; set; }
/// <inheritdoc cref="IWhitespaceTokenizer.MaxTokenLength"/>
public WhitespaceTokenizerDescriptor MaxTokenLength(int? maxTokenLength) =>
Assign(a => a.MaxTokenLength = maxTokenLength);
}
}
| namespace Nest
{
/// <summary>
/// A tokenizer of type whitespace that divides text at whitespace.
/// </summary>
public interface IWhitespaceTokenizer : ITokenizer { }
/// <inheritdoc/>
public class WhitespaceTokenizer : TokenizerBase, IWhitespaceTokenizer
{
public WhitespaceTokenizer() { Type = "whitespace"; }
}
/// <inheritdoc/>
public class WhitespaceTokenizerDescriptor
: TokenizerDescriptorBase<WhitespaceTokenizerDescriptor, IWhitespaceTokenizer>, IWhitespaceTokenizer
{
protected override string Type => "whitespace";
}
} | apache-2.0 | C# |
e7e39df05463dfb19bd79cf96b15778736ab84ae | Update version to 1.0.0-prerelease03 | affecto/dotnet-Middleware.Monitoring.Owin | Source/Monitoring.Owin/Properties/AssemblyInfo.cs | Source/Monitoring.Owin/Properties/AssemblyInfo.cs | using System.Reflection;
// 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("Affecto.Middleware.Monitoring.Owin")]
[assembly: AssemblyDescription("Monitoring middleware implementation based on OWIN interface defined in Microsoft.Owin NuGet.")]
[assembly: AssemblyProduct("Affecto.Middleware.Monitoring")]
[assembly: AssemblyCompany("Affecto")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// This version is used by NuGet:
[assembly: AssemblyInformationalVersion("1.0.0-prerelease03")]
| using System.Reflection;
// 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("Affecto.Middleware.Monitoring.Owin")]
[assembly: AssemblyDescription("Monitoring middleware implementation based on OWIN interface defined in Microsoft.Owin NuGet.")]
[assembly: AssemblyProduct("Affecto.Middleware.Monitoring")]
[assembly: AssemblyCompany("Affecto")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// This version is used by NuGet:
[assembly: AssemblyInformationalVersion("1.0.0-prerelease02")]
| mit | C# |
e27164d293e26f035c24e819c067f23ef3bb41da | Add Vector4/Matrix.FormatForMathematica | virtuallynaked/virtually-naked,virtuallynaked/virtually-naked | Viewer/src/math/FormatForMathematicaExtensions.cs | Viewer/src/math/FormatForMathematicaExtensions.cs | using SharpDX;
public static class FormatForMathematicaExtensions {
public static string FormatForMathematica(this Vector3 v) {
return "{" + v.X + ", " + v.Y + ", " + v.Z + "}";
}
public static string FormatForMathematica(this Matrix3x3 m) {
return "{" + FormatForMathematica(m.Row1) + ", " + FormatForMathematica(m.Row2) + ", " + FormatForMathematica(m.Row3) + "}";
}
public static string FormatForMathematica(this Matrix m) {
return "{" + FormatForMathematica(m.Row1) + ", " + FormatForMathematica(m.Row2) + ", " + FormatForMathematica(m.Row3) + ", " + FormatForMathematica(m.Row4) + "}";
}
public static string FormatForMathematica(this Vector4 v) {
return "{" + v.X + ", " + v.Y + ", " + v.Z + ", " + v.W + "}";
}
public static string FormatForMathematica(this Quaternion q) {
return $"{{{q.W}, {q.X}, {q.Y}, {q.Z}}}";
}
}
| using SharpDX;
public static class FormatForMathematicaExtensions {
public static string FormatForMathematica(this Vector3 v) {
return "{" + v.X + ", " + v.Y + ", " + v.Z + "}";
}
public static string FormatForMathematica(this Matrix3x3 m) {
return "{" + FormatForMathematica(m.Row1) + ", " + FormatForMathematica(m.Row2) + ", " + FormatForMathematica(m.Row3) + "}";
}
public static string FormatForMathematica(this Quaternion q) {
return $"{{{q.W}, {q.X}, {q.Y}, {q.Z}}}";
}
}
| mit | C# |
ada90aa4e048dc77ee990d6508aba9570b68a0f5 | refactor FindMemberExpression | RadicalFx/radical | src/Radical/Extensions/Linq/ExpressionExtensions.cs | src/Radical/Extensions/Linq/ExpressionExtensions.cs | using System;
using System.Linq.Expressions;
namespace Radical.Linq
{
/// <summary>
/// Extends the expression class.
/// </summary>
public static class ExpressionExtensions
{
/// <summary>
/// Gets the name of the member.
/// </summary>
/// <typeparam name="T">The member type.</typeparam>
/// <param name="source">The source expression that represents the member.</param>
/// <returns>The name of the member.</returns>
public static string GetMemberName<T>(this Expression<Func<T>> source)
{
var expression = source.Body as MemberExpression;
if (expression != null)
{
var member = expression.Member;
return member.Name;
}
var unary = source.Body as UnaryExpression;
if (unary != null && unary.Operand is MemberExpression)
{
var name = ((MemberExpression)unary.Operand).Member.Name;
return name;
}
throw new NotSupportedException("Only MemberExpression(s) & Convert UnaryExpressions are supported.");
}
/// <summary>
/// Gets the name of the member.
/// </summary>
/// <typeparam name="T">The type of object that expose the member.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="source">The source.</param>
/// <returns>The name of the member.</returns>
public static string GetMemberName<T, TProperty>(this Expression<Func<T, TProperty>> source)
{
var expression = FindMemberExpression(source.Body);
var member = expression.Member;
return member.Name;
}
static MemberExpression FindMemberExpression(Expression exp)
{
switch (exp)
{
case MemberExpression _:
return (MemberExpression)exp;
case UnaryExpression _:
return FindMemberExpression(((UnaryExpression)exp).Operand);
}
throw new NotSupportedException("The supplied expression type is not supported.");
}
}
}
| using System;
using System.Linq.Expressions;
namespace Radical.Linq
{
/// <summary>
/// Extends the expression class.
/// </summary>
public static class ExpressionExtensions
{
/// <summary>
/// Gets the name of the member.
/// </summary>
/// <typeparam name="T">The member type.</typeparam>
/// <param name="source">The source expression that represents the member.</param>
/// <returns>The name of the member.</returns>
public static string GetMemberName<T>(this Expression<Func<T>> source)
{
var expression = source.Body as MemberExpression;
if (expression != null)
{
var member = expression.Member;
return member.Name;
}
var unary = source.Body as UnaryExpression;
if (unary != null && unary.Operand is MemberExpression)
{
var name = ((MemberExpression)unary.Operand).Member.Name;
return name;
}
throw new NotSupportedException("Only MemberExpression(s) & Convert UnaryExpressions are supported.");
}
/// <summary>
/// Gets the name of the member.
/// </summary>
/// <typeparam name="T">The type of object that expose the member.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="source">The source.</param>
/// <returns>The name of the member.</returns>
public static string GetMemberName<T, TProperty>(this Expression<Func<T, TProperty>> source)
{
var expression = FindMemberExpression(source.Body);
var member = expression.Member;
return member.Name;
}
static MemberExpression FindMemberExpression(Expression exp)
{
if (exp is MemberExpression)
{
return (MemberExpression)exp;
}
if (exp is UnaryExpression)
{
return FindMemberExpression(((UnaryExpression)exp).Operand);
}
throw new NotSupportedException("The supplied expression type is not supported.");
}
}
}
| mit | C# |
d31efbe4cf9de97e9893e467fd47564755b64e7f | Use weak reference in for Gesture last press. | wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,MrDaedra/Avalonia,MrDaedra/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,susloparovdenis/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,grokys/Perspex,Perspex/Perspex,akrisiun/Perspex,OronDF343/Avalonia,grokys/Perspex,OronDF343/Avalonia,susloparovdenis/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,susloparovdenis/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,punker76/Perspex,wieslawsoltes/Perspex,susloparovdenis/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jazzay/Perspex | src/Perspex.Input/Gestures.cs | src/Perspex.Input/Gestures.cs | // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Perspex.Interactivity;
namespace Perspex.Input
{
public static class Gestures
{
public static readonly RoutedEvent<RoutedEventArgs> TappedEvent = RoutedEvent.Register<RoutedEventArgs>(
"Tapped",
RoutingStrategies.Bubble,
typeof(Gestures));
public static readonly RoutedEvent<RoutedEventArgs> DoubleTappedEvent = RoutedEvent.Register<RoutedEventArgs>(
"DoubleTapped",
RoutingStrategies.Bubble,
typeof(Gestures));
private static WeakReference s_lastPress;
static Gestures()
{
InputElement.PointerPressedEvent.RouteFinished.Subscribe(PointerPressed);
InputElement.PointerReleasedEvent.RouteFinished.Subscribe(PointerReleased);
}
private static void PointerPressed(RoutedEventArgs ev)
{
if (ev.Route == RoutingStrategies.Bubble)
{
var e = (PointerPressedEventArgs)ev;
if (e.ClickCount <= 1)
{
s_lastPress = new WeakReference(e.Source);
}
else if (s_lastPress?.IsAlive == true && e.ClickCount == 2 && s_lastPress.Target == e.Source)
{
e.Source.RaiseEvent(new RoutedEventArgs(DoubleTappedEvent));
}
}
}
private static void PointerReleased(RoutedEventArgs ev)
{
if (ev.Route == RoutingStrategies.Bubble)
{
var e = (PointerReleasedEventArgs)ev;
if (s_lastPress?.IsAlive == true && s_lastPress.Target == e.Source)
{
((IInteractive)s_lastPress.Target).RaiseEvent(new RoutedEventArgs(TappedEvent));
}
}
}
}
}
| // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Perspex.Interactivity;
namespace Perspex.Input
{
public static class Gestures
{
public static readonly RoutedEvent<RoutedEventArgs> TappedEvent = RoutedEvent.Register<RoutedEventArgs>(
"Tapped",
RoutingStrategies.Bubble,
typeof(Gestures));
public static readonly RoutedEvent<RoutedEventArgs> DoubleTappedEvent = RoutedEvent.Register<RoutedEventArgs>(
"DoubleTapped",
RoutingStrategies.Bubble,
typeof(Gestures));
private static IInteractive s_lastPress;
static Gestures()
{
InputElement.PointerPressedEvent.RouteFinished.Subscribe(PointerPressed);
InputElement.PointerReleasedEvent.RouteFinished.Subscribe(PointerReleased);
}
private static void PointerPressed(RoutedEventArgs ev)
{
if (ev.Route == RoutingStrategies.Bubble)
{
var e = (PointerPressedEventArgs)ev;
if (e.ClickCount <= 1)
{
s_lastPress = e.Source;
}
else if (e.ClickCount == 2 && s_lastPress == e.Source)
{
e.Source.RaiseEvent(new RoutedEventArgs(DoubleTappedEvent));
}
}
}
private static void PointerReleased(RoutedEventArgs ev)
{
if (ev.Route == RoutingStrategies.Bubble)
{
var e = (PointerReleasedEventArgs)ev;
if (s_lastPress == e.Source)
{
s_lastPress.RaiseEvent(new RoutedEventArgs(TappedEvent));
}
}
}
}
}
| mit | C# |
553ae4781f0eb3dc6ca26c3def0ce1c43dd87d01 | Remove unnecessary local implementation in `TestScenePlaybackControl` | peppy/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu | osu.Game.Tests/Visual/Editing/TestScenePlaybackControl.cs | osu.Game.Tests/Visual/Editing/TestScenePlaybackControl.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens.Edit.Components;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestScenePlaybackControl : EditorClockTestScene
{
[BackgroundDependencyLoader]
private void load()
{
Child = new PlaybackControl
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(200, 100)
};
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Components;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestScenePlaybackControl : EditorClockTestScene
{
[BackgroundDependencyLoader]
private void load()
{
var clock = new EditorClock { IsCoupled = false };
Dependencies.CacheAs(clock);
var playback = new PlaybackControl
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(200, 100)
};
Beatmap.Value = CreateWorkingBeatmap(new Beatmap());
Child = playback;
}
}
}
| mit | C# |
cc6041d0642bcbdc4e1ea3b76e5eacb4735a0120 | Remove unused | BenPhegan/NuGet.Extensions | NuGet.Extensions.Tests/ReferenceAnalysers/ReferenceNugetifierTester.cs | NuGet.Extensions.Tests/ReferenceAnalysers/ReferenceNugetifierTester.cs | using System.Collections.Generic;
using System.IO;
using Moq;
using NuGet.Common;
using NuGet.Extensions.MSBuild;
using NuGet.Extensions.ReferenceAnalysers;
using NuGet.Extensions.Tests.Mocks;
namespace NuGet.Extensions.Tests.ReferenceAnalysers
{
public class ReferenceNugetifierTester {
public static List<ManifestDependency> GetManifestDependencies(ReferenceNugetifier nugetifier, ISharedPackageRepository sharedPackageRepository = null, List<string> projectReferences = null, PackageReferenceFile packageReferenceFile = null)
{
sharedPackageRepository = sharedPackageRepository ?? new Mock<ISharedPackageRepository>().Object;
projectReferences = projectReferences ?? new List<string>();
packageReferenceFile = packageReferenceFile ?? GetPackageReferenceFile(GetMockFileSystem(GetMockDirectory()));
return nugetifier.AddNugetMetadataForReferences(sharedPackageRepository, projectReferences, packageReferenceFile, true);
}
public static ReferenceNugetifier BuildNugetifier(IFileSystem projectFileSystem = null, Mock<IVsProject> vsProject = null, IPackageRepository packageRepository = null)
{
var console = new Mock<IConsole>();
var solutionRoot = GetMockDirectory();
projectFileSystem = projectFileSystem ?? GetMockFileSystem(solutionRoot);
vsProject = vsProject ?? new Mock<IVsProject>();
vsProject.SetupGet(p => p.ProjectDirectory).Returns(GetMockDirectory());
packageRepository = packageRepository ?? new MockPackageRepository();
return new ReferenceNugetifier(vsProject.Object, packageRepository, projectFileSystem, console.Object);
}
private static PackageReferenceFile GetPackageReferenceFile(IFileSystem projectFileSystem)
{
return new PackageReferenceFile(projectFileSystem, projectFileSystem.Root);
}
private static MockFileSystem GetMockFileSystem(DirectoryInfo solutionRoot)
{
return new MockFileSystem(solutionRoot.FullName);
}
private static DirectoryInfo GetMockDirectory()
{
return new DirectoryInfo("c:\\isAnyFolder");
}
public static void NugetifyReferencesInProject(ReferenceNugetifier nugetifier)
{
nugetifier.NugetifyReferencesInProject(GetMockDirectory());
}
}
} | using System.Collections.Generic;
using System.IO;
using Moq;
using NuGet.Common;
using NuGet.Extensions.MSBuild;
using NuGet.Extensions.ReferenceAnalysers;
using NuGet.Extensions.Tests.Mocks;
namespace NuGet.Extensions.Tests.ReferenceAnalysers
{
public class ReferenceNugetifierTester {
private const string DefaultProjectPath = "c:\\isany.csproj";
public static List<ManifestDependency> GetManifestDependencies(ReferenceNugetifier nugetifier, ISharedPackageRepository sharedPackageRepository = null, List<string> projectReferences = null, PackageReferenceFile packageReferenceFile = null)
{
sharedPackageRepository = sharedPackageRepository ?? new Mock<ISharedPackageRepository>().Object;
projectReferences = projectReferences ?? new List<string>();
packageReferenceFile = packageReferenceFile ?? GetPackageReferenceFile(GetMockFileSystem(GetMockDirectory()));
return nugetifier.AddNugetMetadataForReferences(sharedPackageRepository, projectReferences, packageReferenceFile, true);
}
public static ReferenceNugetifier BuildNugetifier(IFileSystem projectFileSystem = null, Mock<IVsProject> vsProject = null, IPackageRepository packageRepository = null)
{
var console = new Mock<IConsole>();
var solutionRoot = GetMockDirectory();
projectFileSystem = projectFileSystem ?? GetMockFileSystem(solutionRoot);
vsProject = vsProject ?? new Mock<IVsProject>();
vsProject.SetupGet(p => p.ProjectDirectory).Returns(GetMockDirectory());
packageRepository = packageRepository ?? new MockPackageRepository();
return new ReferenceNugetifier(vsProject.Object, packageRepository, projectFileSystem, console.Object);
}
private static PackageReferenceFile GetPackageReferenceFile(IFileSystem projectFileSystem)
{
return new PackageReferenceFile(projectFileSystem, projectFileSystem.Root);
}
private static MockFileSystem GetMockFileSystem(DirectoryInfo solutionRoot)
{
return new MockFileSystem(solutionRoot.FullName);
}
private static DirectoryInfo GetMockDirectory()
{
return new DirectoryInfo("c:\\isAnyFolder");
}
public static void NugetifyReferencesInProject(ReferenceNugetifier nugetifier)
{
nugetifier.NugetifyReferencesInProject(GetMockDirectory());
}
}
} | mit | C# |
f49a26acc351d91b27f6715195b983e0268be10c | Remove unused code | mysticfall/Alensia | Assets/Alensia/Demo/MainMenuHandler.cs | Assets/Alensia/Demo/MainMenuHandler.cs | using System;
using Alensia.Core.Control;
using Alensia.Core.UI;
using UniRx;
using UnityEngine;
using Zenject;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Alensia.Demo
{
public class MainMenuHandler : UIHandler
{
[Inject, NonSerialized] public IPlayerController Controller;
public Button ButtonResume;
public Button ButtonQuit;
public override void Initialize(IUIContext context)
{
base.Initialize(context);
ButtonResume.OnClick.Subscribe(_ => Close()).AddTo(this);
ButtonQuit.OnClick.Subscribe(_ => Quit()).AddTo(this);
OnClose.Subscribe(_ => EnableControls());
DisableControls();
}
protected virtual void DisableControls()
{
Controller.DisablePlayerControl();
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
protected virtual void EnableControls()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
Controller.EnablePlayerControl();
}
protected virtual void Quit()
{
Close();
#if UNITY_EDITOR
EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
} | using System;
using Alensia.Core.Control;
using Alensia.Core.UI;
using UniRx;
using UnityEngine;
using Zenject;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Alensia.Demo
{
public class MainMenuHandler : UIHandler
{
[Inject, NonSerialized] public IPlayerController Controller;
public Button ButtonResume;
public Button ButtonQuit;
public override void Initialize(IUIContext context)
{
base.Initialize(context);
ButtonResume.OnClick.Subscribe(_ => Close()).AddTo(this);
ButtonQuit.OnClick.Subscribe(_ => Quit()).AddTo(this);
OnClose.Subscribe(_ => EnableControls());
DisableControls();
}
protected virtual void DisableControls()
{
Controller.DisablePlayerControl();
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
protected virtual void EnableControls()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
Controller.EnablePlayerControl();
}
protected virtual void Quit()
{
Close();
#if UNITY_EDITOR
EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
public class Factory : Factory<MainMenuHandler>
{
}
}
} | apache-2.0 | C# |
d397eb74b3a12483e137e86448fb85ab6031210e | Fix external fonts loading example (use folders to seek fonts) | asposeslides/Aspose_Slides_NET,aspose-slides/Aspose.Slides-for-.NET | Examples/CSharp/Text/UseCustomFonts.cs | Examples/CSharp/Text/UseCustomFonts.cs | using System;
using Aspose.Slides.Export;
using Aspose.Slides.Charts;
using Aspose.Slides;
/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Slides for .NET API reference
when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Slides for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/
namespace Aspose.Slides.Examples.CSharp.Text
{
class UseCustomFonts
{
public static void Run()
{
//ExStart:UseCustomFonts
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Text();
// folders to seek fonts
String[] folders = new String[] { dataDir };
// Load the custom font directory fonts
FontsLoader.LoadExternalFonts(folders);
// Do Some work and perform presentation/slides rendering
using (Presentation presentation = new Presentation(dataDir + "DefaultFonts.pptx"))
presentation.Save(dataDir + "NewFonts_out.pptx", SaveFormat.Pptx);
// Clear Font Cachce
FontsLoader.ClearCache();
//ExEnd:UseCustomFonts
}
}
}
| using System;
using Aspose.Slides.Export;
using Aspose.Slides.Charts;
using Aspose.Slides;
/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Slides for .NET API reference
when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Slides for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/
namespace Aspose.Slides.Examples.CSharp.Text
{
class UseCustomFonts
{
public static void Run()
{
//ExStart:UseCustomFonts
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Text();
String[] loadFonts = new String[] { dataDir + "CustomFonts.ttf" };
// Load the custom font directory fonts
FontsLoader.LoadExternalFonts(loadFonts);
// Do Some work and perform presentation/slides rendering
using (Presentation presentation = new Presentation(dataDir + "DefaultFonts.pptx"))
presentation.Save(dataDir + "NewFonts_out.pptx", SaveFormat.Pptx);
// Clear Font Cachce
FontsLoader.ClearCache();
//ExEnd:UseCustomFonts
}
}
}
| mit | C# |
718a3b1201630c6aabdc1fcea529c26c30521e87 | Make all doubles explicit in all parameters. | ZLima12/osu-framework,naoey/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,paparony03/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,RedNesto/osu-framework,ppy/osu-framework,ZLima12/osu-framework,naoey/osu-framework,Tom94/osu-framework,ppy/osu-framework,Nabile-Rahmani/osu-framework,peppy/osu-framework,default0/osu-framework,paparony03/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,Tom94/osu-framework,Nabile-Rahmani/osu-framework,DrabWeb/osu-framework,default0/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,RedNesto/osu-framework | osu.Framework/Configuration/FrameworkConfigManager.cs | osu.Framework/Configuration/FrameworkConfigManager.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Platform;
namespace osu.Framework.Configuration
{
public class FrameworkConfigManager : ConfigManager<FrameworkConfig>
{
protected override string Filename => @"framework.ini";
protected override void InitialiseDefaults()
{
#pragma warning disable CS0612 // Type or member is obsolete
Set(FrameworkConfig.ShowLogOverlay, true);
Set(FrameworkConfig.Width, 1366, 640);
Set(FrameworkConfig.Height, 768, 480);
Set(FrameworkConfig.WindowedPositionX, 0.5, -0.1, 1.1);
Set(FrameworkConfig.WindowedPositionY, 0.5, -0.1, 1.1);
Set(FrameworkConfig.AudioDevice, string.Empty);
Set(FrameworkConfig.VolumeUniversal, 1.0, 0.0, 1.0);
Set(FrameworkConfig.VolumeMusic, 1.0, 0.0, 1.0);
Set(FrameworkConfig.VolumeEffect, 1.0, 0.0, 1.0);
Set(FrameworkConfig.WidthFullscreen, 9999, 320, 9999);
Set(FrameworkConfig.HeightFullscreen, 9999, 240, 9999);
Set(FrameworkConfig.Letterboxing, true);
Set(FrameworkConfig.LetterboxPositionX, 0.0, -1.0, 1.0);
Set(FrameworkConfig.LetterboxPositionY, 0.0, -1.0, 1.0);
Set(FrameworkConfig.FrameSync, FrameSync.Limit120);
Set(FrameworkConfig.WindowMode, WindowMode.Windowed);
#pragma warning restore CS0612 // Type or member is obsolete
}
public FrameworkConfigManager(Storage storage)
: base(storage)
{
}
}
public enum FrameworkConfig
{
ShowLogOverlay,
AudioDevice,
VolumeUniversal,
VolumeEffect,
VolumeMusic,
Width,
Height,
WindowedPositionX,
WindowedPositionY,
HeightFullscreen,
WidthFullscreen,
WindowMode,
Letterboxing,
LetterboxPositionX,
LetterboxPositionY,
FrameSync,
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Platform;
namespace osu.Framework.Configuration
{
public class FrameworkConfigManager : ConfigManager<FrameworkConfig>
{
protected override string Filename => @"framework.ini";
protected override void InitialiseDefaults()
{
#pragma warning disable CS0612 // Type or member is obsolete
Set(FrameworkConfig.ShowLogOverlay, true);
Set(FrameworkConfig.Width, 1366, 640);
Set(FrameworkConfig.Height, 768, 480);
Set(FrameworkConfig.WindowedPositionX, 0.5, -0.1, 1.1);
Set(FrameworkConfig.WindowedPositionY, 0.5, -0.1, 1.1);
Set(FrameworkConfig.AudioDevice, string.Empty);
Set(FrameworkConfig.VolumeUniversal, 1.0, 0, 1);
Set(FrameworkConfig.VolumeMusic, 1.0, 0, 1);
Set(FrameworkConfig.VolumeEffect, 1.0, 0, 1);
Set(FrameworkConfig.WidthFullscreen, 9999, 320, 9999);
Set(FrameworkConfig.HeightFullscreen, 9999, 240, 9999);
Set(FrameworkConfig.Letterboxing, true);
Set(FrameworkConfig.LetterboxPositionX, 0.0, -1, 1);
Set(FrameworkConfig.LetterboxPositionY, 0.0, -1, 1);
Set(FrameworkConfig.FrameSync, FrameSync.Limit120);
Set(FrameworkConfig.WindowMode, WindowMode.Windowed);
#pragma warning restore CS0612 // Type or member is obsolete
}
public FrameworkConfigManager(Storage storage)
: base(storage)
{
}
}
public enum FrameworkConfig
{
ShowLogOverlay,
AudioDevice,
VolumeUniversal,
VolumeEffect,
VolumeMusic,
Width,
Height,
WindowedPositionX,
WindowedPositionY,
HeightFullscreen,
WidthFullscreen,
WindowMode,
Letterboxing,
LetterboxPositionX,
LetterboxPositionY,
FrameSync,
}
}
| mit | C# |
9d43afacba2c02e9e6e7372c5b24216b6c291eef | Add timestamp method | fredatgithub/UsefulFunctions | ConsoleAppPrimesByHundred/Program.cs | ConsoleAppPrimesByHundred/Program.cs | using FonctionsUtiles.Fred.Csharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
namespace ConsoleAppPrimesByHundred
{
internal class Program
{
private static void Main()
{
Action<string> display = Console.WriteLine;
display("Prime numbers by hundred:");
foreach (var kvp in FunctionsPrimes.NumberOfPrimesByHundred(1000))
{
display($"{kvp.Key} - {kvp.Value}");
}
display(string.Empty);
display("Prime numbers by thousand:");
display(string.Empty);
foreach (var kvp in FunctionsPrimes.NumberOfPrimesByNthHundred(9000, 1000))
{
display($"{kvp.Key} - {kvp.Value}");
}
//int count = 0;
//for (int i = 3; i <= int.MaxValue - 4; i += 2)
//{
// if (FunctionsPrimes.IsPrimeTriplet(i))
// {
// count++;
// }
// display($"Number of prime found: {count} and i: {i}");
//}
display("no triplet prime from 3 to 2147483643");
//int count = 0;
//List<string> result = new List<string>();
//for (BigInteger i = BigInteger.Parse("2147483643"); i <= BigInteger.Parse("9147483643"); i += 2)
//{
// if (FunctionsPrimes.IsPrimeTriplet(i))
// {
// count++;
// result.Add(i.ToString());
// }
// display($"Number of prime found: {count} and i: {i}");
//}
//if (result.Count > 0)
//{
// foreach (string number in result)
// {
// display($"Prime triplet found : {number}");
// }
//}
var timestamp = DateTime.Now.ToFileTime();
display($"time stamp using ToFileTime : {timestamp.ToString()}");
string timeStamp = GetTimestamp(DateTime.Now);
display($"time stamp yyyymmddhh : {timestamp.ToString()}");
display("Press any key to exit");
Console.ReadKey();
}
public static String GetTimestamp(DateTime value)
{
return value.ToString("yyyyMMddHHmmssffff");
}
}
}
| using System;
using System.Collections.Generic;
using System.Numerics;
using FonctionsUtiles.Fred.Csharp;
namespace ConsoleAppPrimesByHundred
{
internal class Program
{
private static void Main()
{
Action<string> display = Console.WriteLine;
display("Prime numbers by hundred:");
foreach (var kvp in FunctionsPrimes.NumberOfPrimesByHundred(1000))
{
display($"{kvp.Key} - {kvp.Value}");
}
display(string.Empty);
display("Prime numbers by thousand:");
display(string.Empty);
foreach (var kvp in FunctionsPrimes.NumberOfPrimesByNthHundred(9000, 1000))
{
display($"{kvp.Key} - {kvp.Value}");
}
//int count = 0;
//for (int i = 3; i <= int.MaxValue - 4; i += 2)
//{
// if (FunctionsPrimes.IsPrimeTriplet(i))
// {
// count++;
// }
// display($"Number of prime found: {count} and i: {i}");
//}
display("no triplet prime from 3 to 2147483643");
int count = 0;
List<string> result = new List<string>();
for (BigInteger i = BigInteger.Parse("2147483643"); i <= BigInteger.Parse("9147483643"); i += 2)
{
if (FunctionsPrimes.IsPrimeTriplet(i))
{
count++;
result.Add(i.ToString());
}
display($"Number of prime found: {count} and i: {i}");
}
if (result.Count > 0)
{
foreach (string number in result)
{
display($"Prime triplet found : {number}");
}
}
display("Press any key to exit");
Console.ReadKey();
}
}
}
| mit | C# |
8b3b87bf4b137ef1317f0f3f1f04b2f3f151ffb9 | simplify some code, remove asynchrony | Pvlerick/roslyn,mgoertz-msft/roslyn,panopticoncentral/roslyn,abock/roslyn,kelltrick/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,OmarTawfik/roslyn,swaroop-sridhar/roslyn,weltkante/roslyn,mattscheffer/roslyn,AArnott/roslyn,a-ctor/roslyn,KirillOsenkov/roslyn,jeffanders/roslyn,akrisiun/roslyn,khyperia/roslyn,srivatsn/roslyn,jhendrixMSFT/roslyn,bkoelman/roslyn,gafter/roslyn,panopticoncentral/roslyn,brettfo/roslyn,ljw1004/roslyn,jhendrixMSFT/roslyn,MichalStrehovsky/roslyn,weltkante/roslyn,nguerrera/roslyn,Giftednewt/roslyn,genlu/roslyn,bbarry/roslyn,AmadeusW/roslyn,mavasani/roslyn,aelij/roslyn,mavasani/roslyn,lorcanmooney/roslyn,agocke/roslyn,wvdd007/roslyn,orthoxerox/roslyn,tannergooding/roslyn,MattWindsor91/roslyn,davkean/roslyn,Pvlerick/roslyn,mgoertz-msft/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,nguerrera/roslyn,jasonmalinowski/roslyn,natidea/roslyn,panopticoncentral/roslyn,diryboy/roslyn,reaction1989/roslyn,stephentoub/roslyn,tvand7093/roslyn,OmarTawfik/roslyn,ErikSchierboom/roslyn,physhi/roslyn,aelij/roslyn,pdelvo/roslyn,xasx/roslyn,AnthonyDGreen/roslyn,gafter/roslyn,ErikSchierboom/roslyn,swaroop-sridhar/roslyn,AmadeusW/roslyn,dpoeschl/roslyn,gafter/roslyn,mattscheffer/roslyn,swaroop-sridhar/roslyn,tannergooding/roslyn,MichalStrehovsky/roslyn,TyOverby/roslyn,khyperia/roslyn,ErikSchierboom/roslyn,jcouv/roslyn,mmitche/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,KirillOsenkov/roslyn,xoofx/roslyn,mattscheffer/roslyn,AnthonyDGreen/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,AArnott/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,Hosch250/roslyn,AArnott/roslyn,bartdesmet/roslyn,sharwell/roslyn,dpoeschl/roslyn,bkoelman/roslyn,zooba/roslyn,mgoertz-msft/roslyn,zooba/roslyn,jeffanders/roslyn,jmarolf/roslyn,agocke/roslyn,jasonmalinowski/roslyn,drognanar/roslyn,mmitche/roslyn,robinsedlaczek/roslyn,ljw1004/roslyn,genlu/roslyn,paulvanbrenk/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,xoofx/roslyn,heejaechang/roslyn,nguerrera/roslyn,diryboy/roslyn,MattWindsor91/roslyn,ljw1004/roslyn,AnthonyDGreen/roslyn,MichalStrehovsky/roslyn,davkean/roslyn,tannergooding/roslyn,KevinRansom/roslyn,heejaechang/roslyn,robinsedlaczek/roslyn,vslsnap/roslyn,reaction1989/roslyn,MattWindsor91/roslyn,Giftednewt/roslyn,kelltrick/roslyn,xasx/roslyn,physhi/roslyn,bartdesmet/roslyn,tmat/roslyn,jcouv/roslyn,DustinCampbell/roslyn,natidea/roslyn,zooba/roslyn,eriawan/roslyn,orthoxerox/roslyn,tmat/roslyn,DustinCampbell/roslyn,Hosch250/roslyn,mmitche/roslyn,jhendrixMSFT/roslyn,AlekseyTs/roslyn,yeaicc/roslyn,KirillOsenkov/roslyn,khyperia/roslyn,bbarry/roslyn,VSadov/roslyn,jcouv/roslyn,CyrusNajmabadi/roslyn,genlu/roslyn,cston/roslyn,stephentoub/roslyn,jkotas/roslyn,KevinH-MS/roslyn,jasonmalinowski/roslyn,KevinH-MS/roslyn,KevinH-MS/roslyn,agocke/roslyn,Pvlerick/roslyn,abock/roslyn,heejaechang/roslyn,TyOverby/roslyn,abock/roslyn,yeaicc/roslyn,jkotas/roslyn,jkotas/roslyn,mattwar/roslyn,diryboy/roslyn,tmeschter/roslyn,jamesqo/roslyn,davkean/roslyn,xasx/roslyn,xoofx/roslyn,srivatsn/roslyn,pdelvo/roslyn,jamesqo/roslyn,KevinRansom/roslyn,Hosch250/roslyn,brettfo/roslyn,tmeschter/roslyn,MattWindsor91/roslyn,natidea/roslyn,pdelvo/roslyn,kelltrick/roslyn,TyOverby/roslyn,tvand7093/roslyn,amcasey/roslyn,a-ctor/roslyn,weltkante/roslyn,tvand7093/roslyn,mattwar/roslyn,bbarry/roslyn,CaptainHayashi/roslyn,paulvanbrenk/roslyn,jamesqo/roslyn,mattwar/roslyn,vslsnap/roslyn,Giftednewt/roslyn,stephentoub/roslyn,wvdd007/roslyn,CaptainHayashi/roslyn,amcasey/roslyn,drognanar/roslyn,a-ctor/roslyn,amcasey/roslyn,dpoeschl/roslyn,srivatsn/roslyn,bkoelman/roslyn,VSadov/roslyn,brettfo/roslyn,CaptainHayashi/roslyn,paulvanbrenk/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,cston/roslyn,physhi/roslyn,eriawan/roslyn,jmarolf/roslyn,dotnet/roslyn,OmarTawfik/roslyn,jeffanders/roslyn,mavasani/roslyn,reaction1989/roslyn,tmeschter/roslyn,dotnet/roslyn,akrisiun/roslyn,sharwell/roslyn,DustinCampbell/roslyn,AlekseyTs/roslyn,drognanar/roslyn,cston/roslyn,vslsnap/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,lorcanmooney/roslyn,yeaicc/roslyn,AlekseyTs/roslyn,robinsedlaczek/roslyn,lorcanmooney/roslyn,aelij/roslyn,eriawan/roslyn,akrisiun/roslyn,dotnet/roslyn,orthoxerox/roslyn,VSadov/roslyn | src/Features/Core/Portable/CodeFixes/PreferFrameworkType/PreferFrameworkTypeCodeFixProvider.cs | src/Features/Core/Portable/CodeFixes/PreferFrameworkType/PreferFrameworkTypeCodeFixProvider.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes.PreferFrameworkType
{
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeFixProviderNames.PreferFrameworkType), Shared]
internal class PreferFrameworkTypeCodeFixProvider : CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(
IDEDiagnosticIds.PreferFrameworkTypeInDeclarationsDiagnosticId,
IDEDiagnosticIds.PreferFrameworkTypeInMemberAccessDiagnosticId);
public override FixAllProvider GetFixAllProvider() => BatchFixAllProvider.Instance;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(
new PreferFrameworkTypeCodeAction(
FeaturesResources.Use_framework_type,
c => CreateChangedDocumentAsync(context.Document, context.Span, c)),
context.Diagnostics);
return SpecializedTasks.EmptyTask;
}
private async Task<Document> CreateChangedDocumentAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var node = root.FindNode(span, findInsideTrivia: true, getInnermostNodeForTie: true);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var generator = document.GetLanguageService<SyntaxGenerator>();
var typeSymbol = (ITypeSymbol)semanticModel.GetSymbolInfo(node, cancellationToken).Symbol;
var replacementNode = generator.TypeExpression(typeSymbol).WithTriviaFrom(node);
return document.WithSyntaxRoot(root.ReplaceNode(node, replacementNode));
}
private class PreferFrameworkTypeCodeAction : CodeAction.DocumentChangeAction
{
public PreferFrameworkTypeCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) :
base(title, createChangedDocument, equivalenceKey: title)
{
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes.PreferFrameworkType
{
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeFixProviderNames.PreferFrameworkType), Shared]
internal class PreferFrameworkTypeCodeFixProvider : CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(
IDEDiagnosticIds.PreferFrameworkTypeInDeclarationsDiagnosticId,
IDEDiagnosticIds.PreferFrameworkTypeInMemberAccessDiagnosticId);
public override FixAllProvider GetFixAllProvider() => BatchFixAllProvider.Instance;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(
new PreferFrameworkTypeCodeAction(
FeaturesResources.Use_framework_type,
c => CreateChangedDocumentAsync(context.Document, context.Span, c)),
context.Diagnostics);
return SpecializedTasks.EmptyTask;
}
private async Task<Document> CreateChangedDocumentAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var node = root.FindNode(span, findInsideTrivia: true, getInnermostNodeForTie: true);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var generator = document.GetLanguageService<SyntaxGenerator>();
var typeSymbol = (ITypeSymbol)semanticModel.GetSymbolInfo(node, cancellationToken).Symbol;
var replacementNode = generator.TypeExpression(typeSymbol).WithTriviaFrom(node);
return await document.ReplaceNodeAsync(node, replacementNode, cancellationToken).ConfigureAwait(false);
}
private class PreferFrameworkTypeCodeAction : CodeAction.DocumentChangeAction
{
public PreferFrameworkTypeCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) :
base(title, createChangedDocument, equivalenceKey: title)
{
}
}
}
}
| mit | C# |
333b7fbb52cbc823e3efc6195940e15b4ffd6edb | Fix for #3235 | IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense | wrappers/csharp/Intel.RealSense/Types/CameraInfo.cs | wrappers/csharp/Intel.RealSense/Types/CameraInfo.cs | using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Intel.RealSense
{
public enum CameraInfo
{
Name = 0,
SerialNumber = 1,
FirmwareVersion = 2,
RecommendedFirmwareVersion = 3,
PhysicalPort = 4,
DebugOpCode = 5,
AdvancedMode = 6,
ProductId = 7,
CameraLocked = 8,
UsbTypeDescriptor = 9,
}
}
| using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Intel.RealSense
{
public enum CameraInfo
{
Name = 0,
SerialNumber = 1,
RecommendedFirmwareVersion = 2,
FirmwareVersion = 3,
PhysicalPort = 4,
DebugOpCode = 5,
AdvancedMode = 6,
ProductId = 7,
CameraLocked = 8,
UsbTypeDescriptor = 9,
}
}
| apache-2.0 | C# |
984fe7b5b90ddf7626889089f844e24af9a4d0db | Fix TeamCityOutputSink to not report errors as build problems | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/OutputSinks/TeamCityOutputSink.cs | source/Nuke.Common/OutputSinks/TeamCityOutputSink.cs | // Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.BuildServers;
using Nuke.Common.Utilities;
namespace Nuke.Common.OutputSinks
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class TeamCityOutputSink : ConsoleOutputSink
{
private readonly TeamCity _teamCity;
internal TeamCityOutputSink(TeamCity teamCity)
{
_teamCity = teamCity;
}
public override IDisposable WriteBlock(string text)
{
return DelegateDisposable.CreateBracket(
() => _teamCity.OpenBlock(text),
() => _teamCity.CloseBlock(text));
}
public override void Warn(string text, string details = null)
{
_teamCity.WriteWarning(text);
if (details != null)
_teamCity.WriteWarning(details);
}
public override void Error(string text, string details = null)
{
_teamCity.WriteError(text, details);
}
}
}
| // Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.BuildServers;
using Nuke.Common.Utilities;
namespace Nuke.Common.OutputSinks
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class TeamCityOutputSink : ConsoleOutputSink
{
private readonly TeamCity _teamCity;
internal TeamCityOutputSink(TeamCity teamCity)
{
_teamCity = teamCity;
}
public override IDisposable WriteBlock(string text)
{
return DelegateDisposable.CreateBracket(
() => _teamCity.OpenBlock(text),
() => _teamCity.CloseBlock(text));
}
public override void Warn(string text, string details = null)
{
_teamCity.WriteWarning(text);
if (details != null)
_teamCity.WriteWarning(details);
}
public override void Error(string text, string details = null)
{
_teamCity.WriteError(text, details);
_teamCity.AddBuildProblem(text);
}
}
}
| mit | C# |
5dc5f6e9b9e8a38405be3b7435d721c2dc6152a7 | rebase fix | RoomFinder/Connector,RoomFinder/Connector | ExchangeConnector/ExchangeConnector.cs | ExchangeConnector/ExchangeConnector.cs | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using FindFreeRoom.ExchangeConnector.Base;
using Microsoft.Exchange.WebServices.Data;
namespace FindFreeRoom.ExchangeConnector
{
public class ExchangeConnector
{
private readonly ExchangeService _service;
private readonly string _serverUrl;
private readonly string _serviceEmail;
public ExchangeConnector(string username, string password, string serverUrl, string serviceEmail)
{
_serverUrl = serverUrl;
_serviceEmail = serviceEmail;
_service = new ExchangeService(ExchangeVersion.Exchange2010);
if (string.IsNullOrEmpty(username))
{
_service.UseDefaultCredentials = true;
}
else
{
_service.Credentials = new WebCredentials(username, password);
}
//_service.TraceEnabled = true;
//_service.TraceFlags = TraceFlags.All;
}
public void Connect()
{
if (string.IsNullOrEmpty(_serverUrl))
{
_service.AutodiscoverUrl(_serviceEmail, RedirectionUrlValidationCallback);
}
else
{
_service.Url = new Uri(_serverUrl);
}
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
public string[] LocationFilter { get; set; }
public IEnumerable<RoomInfo> GetFilteredRooms()
{
foreach (var list in _service.GetRoomLists().Where(FilterActive))
{
foreach (var room in LoadRooms(list))
{
yield return new RoomInfo
{
LocationId = list.Address,
RoomId = room.Address,
Name = room.Name
};
}
}
}
private IEnumerable<EmailAddress> LoadRooms(EmailAddress emailAddress)
{
return _service.GetRooms(emailAddress);
}
private bool FilterActive(EmailAddress emailAddress)
{
if (LocationFilter == null)
return true;
return LocationFilter.Contains(emailAddress.Address);
}
public IEnumerable<string> GetAllRoomLists()
{
return _service.GetRoomLists().Select(x => x.Address);
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using FindFreeRoom.ExchangeConnector.Base;
using Microsoft.Exchange.WebServices.Data;
namespace FindFreeRoom.ExchangeConnector
{
public class ExchangeConnector
{
private readonly ExchangeService _service;
private readonly string _serverUrl;
private readonly string _serviceEmail;
public ExchangeConnector(string username, string password, string serverUrl, string serviceEmail)
{
_serverUrl = serverUrl;
_serviceEmail = serviceEmail;
_service = new ExchangeService(ExchangeVersion.Exchange2010);
if (string.IsNullOrEmpty(username))
{
_service.UseDefaultCredentials = true;
}
else
{
_service.Credentials = new WebCredentials(username, password);
}
//_service.TraceEnabled = true;
//_service.TraceFlags = TraceFlags.All;
}
public void Connect()
{
if (string.IsNullOrEmpty(_serverUrl))
{
_service.AutodiscoverUrl(_serviceEmail, RedirectionUrlValidationCallback);
}
else
{
_service.Url = new Uri(_serverUrl);
}
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
public string[] LocationFilter { get; set; }
public IEnumerable<RoomInfo> GetFilteredRooms()
{
foreach (var list in _service.GetRoomLists().Where(FilterActive))
{
foreach (var room in LoadRooms(list))
{
yield return new RoomInfo
{
LocationId = list.Address,
RoomId = room.Address,
Name = room.Name
};
}
}
}
private IEnumerable<EmailAddress> LoadRooms(EmailAddress emailAddress)
{
return _service.GetRooms(emailAddress);
}
private bool FilterActive(EmailAddress emailAddress)
{
if (LocationFilter == null)
return true;
return LocationFilter.Contains(emailAddress.Address);
}
}
}
| mit | C# |
a2d17ab1477a1e2270b9e992fa02312d42cfee71 | Update RequestPostProcessorBehavior.cs | jbogard/MediatR | src/MediatR/Pipeline/RequestPostProcessorBehavior.cs | src/MediatR/Pipeline/RequestPostProcessorBehavior.cs | .namespace MediatR.Pipeline
{
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>
/// Behavior for executing all <see cref="IRequestPostProcessor{TRequest,TResponse}"/> instances after handling the request
/// </summary>
/// <typeparam name="TRequest">Request type</typeparam>
/// <typeparam name="TResponse">Response type</typeparam>
public class RequestPostProcessorBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly IEnumerable<IRequestPostProcessor<TRequest, TResponse>> _postProcessors;
public RequestPostProcessorBehavior(IEnumerable<IRequestPostProcessor<TRequest, TResponse>> postProcessors)
{
_postProcessors = postProcessors;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next)
{
var response = await next().ConfigureAwait(false);
await Task.WhenAll(_postProcessors.Select(p => p.Process(request, response))).ConfigureAwait(false);
return response;
}
}
}
| namespace MediatR.Pipeline
{
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>
/// Behavior for executing all <see cref="IRequestPostProcessor{TRequest,TResponse}"/> instances after handling the request
/// </summary>
/// <typeparam name="TRequest">Request type</typeparam>
/// <typeparam name="TResponse">Response type</typeparam>
public class RequestPostProcessorBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly IEnumerable<IRequestPostProcessor<TRequest, TResponse>> _postProcessors;
public RequestPostProcessorBehavior(IEnumerable<IRequestPostProcessor<TRequest, TResponse>> postProcessors)
{
_postProcessors = postProcessors;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next)
{
var response = await next();
await Task.WhenAll(_postProcessors.Select(p => p.Process(request, response)));
return response;
}
}
} | apache-2.0 | C# |
30f462cd4179b08fcc9cc2ce5be2e8f0423d79ec | Fix GUI alpha blending | feliwir/openSage,feliwir/openSage | src/OpenSage.Game/Graphics/Effects/SpriteMaterial.cs | src/OpenSage.Game/Graphics/Effects/SpriteMaterial.cs | using System.Numerics;
using System.Runtime.InteropServices;
using OpenSage.Content;
using Veldrid;
namespace OpenSage.Graphics.Effects
{
public sealed class SpriteMaterial : EffectMaterial
{
public SpriteMaterial(ContentManager contentManager, Effect effect, in OutputDescription outputDescription)
: base(contentManager, effect)
{
SetSampler(contentManager.PointClampSampler);
PipelineState = new EffectPipelineState(
RasterizerStateDescriptionUtility.CullNoneSolid,
DepthStencilStateDescription.Disabled,
new BlendStateDescription
{
AttachmentStates = new[]
{
new BlendAttachmentDescription
{
BlendEnabled = true,
SourceColorFactor = BlendFactor.SourceAlpha,
DestinationColorFactor = BlendFactor.InverseSourceAlpha,
ColorFunction = BlendFunction.Add,
SourceAlphaFactor = BlendFactor.One,
DestinationAlphaFactor = BlendFactor.InverseSourceAlpha,
AlphaFunction = BlendFunction.Add
}
}
},
outputDescription);
}
public void SetMaterialConstantsVS(DeviceBuffer value)
{
SetProperty("ProjectionBuffer", value);
}
public void SetSampler(Sampler samplerState)
{
SetProperty("Sampler", samplerState);
}
public void SetTexture(Texture texture)
{
SetProperty("Texture", texture);
}
[StructLayout(LayoutKind.Sequential)]
public struct MaterialConstantsVS
{
public Matrix4x4 Projection;
}
}
}
| using System.Numerics;
using System.Runtime.InteropServices;
using OpenSage.Content;
using Veldrid;
namespace OpenSage.Graphics.Effects
{
public sealed class SpriteMaterial : EffectMaterial
{
public SpriteMaterial(ContentManager contentManager, Effect effect, in OutputDescription outputDescription)
: base(contentManager, effect)
{
SetSampler(contentManager.PointClampSampler);
PipelineState = new EffectPipelineState(
RasterizerStateDescriptionUtility.CullNoneSolid,
DepthStencilStateDescription.Disabled,
BlendStateDescription.SingleAlphaBlend,
outputDescription);
}
public void SetMaterialConstantsVS(DeviceBuffer value)
{
SetProperty("ProjectionBuffer", value);
}
public void SetSampler(Sampler samplerState)
{
SetProperty("Sampler", samplerState);
}
public void SetTexture(Texture texture)
{
SetProperty("Texture", texture);
}
[StructLayout(LayoutKind.Sequential)]
public struct MaterialConstantsVS
{
public Matrix4x4 Projection;
}
}
}
| mit | C# |
5fd09b43f371aec3a5a78540aa3f09bb95c1e450 | Set property type group default level to 1 | KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS | src/Umbraco.Core/Persistence/Dtos/PropertyTypeGroupDto.cs | src/Umbraco.Core/Persistence/Dtos/PropertyTypeGroupDto.cs | using System;
using System.Collections.Generic;
using NPoco;
using Umbraco.Core.Persistence.DatabaseAnnotations;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
namespace Umbraco.Core.Persistence.Dtos
{
[TableName(TableName)]
[PrimaryKey("id", AutoIncrement = true)]
[ExplicitColumns]
internal class PropertyTypeGroupDto
{
public const string TableName = Constants.DatabaseSchema.Tables.PropertyTypeGroup;
[Column("id")]
[PrimaryKeyColumn(IdentitySeed = 12)]
public int Id { get; set; }
[Column("uniqueID")]
[NullSetting(NullSetting = NullSettings.NotNull)]
[Constraint(Default = SystemMethods.NewGuid)]
[Index(IndexTypes.UniqueNonClustered, Name = "IX_cmsPropertyTypeGroupUniqueID")]
public Guid UniqueId { get; set; }
[Column("parentKey")]
[NullSetting(NullSetting = NullSettings.Null)]
[ForeignKey(typeof(PropertyTypeGroupDto), Column = "uniqueID", Name = "FK_" + TableName + "_parentKey")]
public Guid? ParentKey { get; set; }
[Column("level")]
[Constraint(Default = 1)] // TODO We default to 1 (property group) for backwards compatibility, but should use zero/no default at some point.
public short Level { get; set; } = 1;
[Column("contenttypeNodeId")]
[ForeignKey(typeof(ContentTypeDto), Column = "nodeId")]
public int ContentTypeNodeId { get; set; }
[Column("icon")]
[NullSetting(NullSetting = NullSettings.Null)]
public string Icon { get; set; }
[Column("text")]
public string Text { get; set; }
[Column("sortorder")]
public int SortOrder { get; set; }
[ResultColumn]
[Reference(ReferenceType.Many, ReferenceMemberName = "PropertyTypeGroupId")]
public List<PropertyTypeDto> PropertyTypeDtos { get; set; }
}
}
| using System;
using System.Collections.Generic;
using NPoco;
using Umbraco.Core.Persistence.DatabaseAnnotations;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
namespace Umbraco.Core.Persistence.Dtos
{
[TableName(TableName)]
[PrimaryKey("id", AutoIncrement = true)]
[ExplicitColumns]
internal class PropertyTypeGroupDto
{
public const string TableName = Constants.DatabaseSchema.Tables.PropertyTypeGroup;
[Column("id")]
[PrimaryKeyColumn(IdentitySeed = 12)]
public int Id { get; set; }
[Column("uniqueID")]
[NullSetting(NullSetting = NullSettings.NotNull)]
[Constraint(Default = SystemMethods.NewGuid)]
[Index(IndexTypes.UniqueNonClustered, Name = "IX_cmsPropertyTypeGroupUniqueID")]
public Guid UniqueId { get; set; }
[Column("parentKey")]
[NullSetting(NullSetting = NullSettings.Null)]
[ForeignKey(typeof(PropertyTypeGroupDto), Column = "uniqueID", Name = "FK_" + TableName + "_parentKey")]
public Guid? ParentKey { get; set; }
[Column("level")]
[Constraint(Default = 1)] // TODO We default to 1 (property group) for backwards compatibility, but should use zero/no default at some point.
public short Level { get; set; }
[Column("contenttypeNodeId")]
[ForeignKey(typeof(ContentTypeDto), Column = "nodeId")]
public int ContentTypeNodeId { get; set; }
[Column("icon")]
[NullSetting(NullSetting = NullSettings.Null)]
public string Icon { get; set; }
[Column("text")]
public string Text { get; set; }
[Column("sortorder")]
public int SortOrder { get; set; }
[ResultColumn]
[Reference(ReferenceType.Many, ReferenceMemberName = "PropertyTypeGroupId")]
public List<PropertyTypeDto> PropertyTypeDtos { get; set; }
}
}
| mit | C# |
c9fbdb6caaf41a69a5cf5883fcd07a000cdca5af | Fix #1359 by not locking content files when reading | skbkontur/NuGetGallery,skbkontur/NuGetGallery,JetBrains/ReSharperGallery,KuduApps/NuGetGallery,projectkudu/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,mtian/SiteExtensionGallery,KuduApps/NuGetGallery,projectkudu/SiteExtensionGallery,projectkudu/SiteExtensionGallery,KuduApps/NuGetGallery,mtian/SiteExtensionGallery,ScottShingler/NuGetGallery,JetBrains/ReSharperGallery,grenade/NuGetGallery_download-count-patch,JetBrains/ReSharperGallery,KuduApps/NuGetGallery,ScottShingler/NuGetGallery,KuduApps/NuGetGallery,ScottShingler/NuGetGallery,grenade/NuGetGallery_download-count-patch,mtian/SiteExtensionGallery | Website/Services/LocalFileReference.cs | Website/Services/LocalFileReference.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
namespace NuGetGallery
{
public class LocalFileReference : IFileReference
{
private FileInfo _file;
public string ContentId
{
get { return _file.LastWriteTimeUtc.ToString("O", CultureInfo.CurrentCulture); }
}
public LocalFileReference(FileInfo file)
{
_file = file;
}
public Stream OpenRead()
{
return _file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
}
} | using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
namespace NuGetGallery
{
public class LocalFileReference : IFileReference
{
private FileInfo _file;
public string ContentId
{
get { return _file.LastWriteTimeUtc.ToString("O", CultureInfo.CurrentCulture); }
}
public LocalFileReference(FileInfo file)
{
_file = file;
}
public Stream OpenRead()
{
return _file.Open(FileMode.Open);
}
}
} | apache-2.0 | C# |
20a397f669711c2378bccc91191681211c1cbd37 | Fix compilation error | fairycode/sharp-blueprint,fairycode/sharp-blueprint | test/SharpBlueprint.Client.Tests/SimpleHttpClientTests.cs | test/SharpBlueprint.Client.Tests/SimpleHttpClientTests.cs | using System;
using SharpBlueprint.Client;
#if NET35
using NUnit.Framework;
#else
using Xunit;
#endif
namespace SharpBlueprint.Core.Tests
{
#if NET35
[TestFixture]
#endif
public class SimpleHttpClientTests
{
#if NET35
[Test]
public void GetDotNetCountTest()
{
var client = new SimpleHttpClient();
var result = client.GetDotNetCount();
Console.WriteLine(result);
Assert.IsTrue(!string.IsNullOrEmpty(result));
}
#else
[Fact]
public void GetDotNetCountAsyncTest()
{
var client = new SimpleHttpClient();
var resultTask = client.GetDotNetCountAsync();
var result = resultTask.Result;
Console.WriteLine(result);
Assert.True(!string.IsNullOrEmpty(result));
}
#endif
}
}
| using System;
#if NET35
using NUnit.Framework;
#else
using Xunit;
#endif
namespace SharpBlueprint.Core.Tests
{
#if NET35
[TestFixture]
#endif
public class SimpleHttpClientTests
{
#if NET35
[Test]
public void GetDotNetCountTest()
{
var client = new SimpleHttpClient();
var result = client.GetDotNetCount();
Console.WriteLine(result);
Assert.IsTrue(!string.IsNullOrEmpty(result));
}
#else
[Fact]
public void GetDotNetCountAsyncTest()
{
var client = new SimpleHttpClient();
var resultTask = client.GetDotNetCountAsync();
var result = resultTask.Result;
Console.WriteLine(result);
Assert.True(!string.IsNullOrEmpty(result));
}
#endif
}
}
| mit | C# |
e4ef47573b3e63a6638cc8522276ce99d91e8b9a | optimize unit test | RenePeuser/DynamicMockCreator | MockCreator/MockCreator/TestDynamicTestExecution.cs | MockCreator/MockCreator/TestDynamicTestExecution.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestExtension;
namespace MockCreator
{
[TestClass]
public class TestDynamicTestExecution
{
private static readonly DefaultData CustomData = new DefaultData(
(sbyte)1,
(byte)1,
(short)1,
(ushort)1,
1,
(uint)1,
(long)1.1,
(ulong)1.2,
'c',
(float)1.3,
1.4,
true,
new decimal(1.5),
"MyString",
new DateTime(2016, 10, 15),
new object(),
new[] { "A..Z" },
new Collection<int> { 1, 2 });
private Dictionary<Type, object> _dictionary;
[TestInitialize]
public void Init()
{
var privateObject = CustomData.ToPrivateObject();
_dictionary = privateObject.GetField<Dictionary<Type, object>>("_defaultData");
}
[TestMethod]
public void TestFor()
{
var errors = Analyze(_dictionary);
Assert.IsFalse(errors.Any(), ToErrorString(errors));
}
private static IEnumerable<string> Analyze(Dictionary<Type, object> dictionary)
{
foreach (var keyValuePair in dictionary)
{
var result = typeof(SubstituteExtensions).InvokeGenericMethod(nameof(SubstituteExtensions.For),
new[] { keyValuePair.Key }, CustomData);
if (CustomData.GetDefaultValue(keyValuePair.Key).NotEqualityEquals(result))
{
yield return $"Expected type:{keyValuePair.Key} has not expected {result}";
}
}
}
private static string ToErrorString(IEnumerable<string> errors)
{
var stringBuilder = new StringBuilder();
errors.ForEach(e => stringBuilder.AppendLine(e));
return stringBuilder.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestExtension;
namespace MockCreator
{
[TestClass]
public class TestDynamicTestExecution
{
private static readonly DefaultData CustomData = new DefaultData(
(sbyte)1,
(byte)1,
(short)1,
(ushort)1,
1,
(uint)1,
(long)1.1,
(ulong)1.2,
'c',
(float)1.3,
1.4,
true,
new decimal(1.5),
"MyString",
new DateTime(2016, 10, 15),
new object(),
new[] { "A..Z" },
new Collection<int> { 1, 2 });
private Dictionary<Type, object> _dictionary;
[TestInitialize]
public void Init()
{
var privateObject = CustomData.ToPrivateObject();
_dictionary = privateObject.GetField<Dictionary<Type, object>>("_defaultData");
}
[TestMethod]
public void TestFor()
{
var errors = Analyze(_dictionary);
var stringBuilder = new StringBuilder();
errors.ForEach(e => stringBuilder.AppendLine(e));
Assert.IsFalse(errors.Any(), stringBuilder.ToString());
}
private static IEnumerable<string> Analyze(Dictionary<Type, object> dictionary)
{
foreach (var keyValuePair in dictionary)
{
var result = typeof(SubstituteExtensions).InvokeGenericMethod(nameof(SubstituteExtensions.For),
new[] { keyValuePair.Key }, CustomData);
if (CustomData.GetDefaultValue(keyValuePair.Key).NotEqualityEquals(result))
{
yield return $"Expected type:{keyValuePair.Key} has not expected {result}";
}
}
}
}
}
| mit | C# |
7b6e53680c6035f6b7843f3ac5bd65b90e41128d | Add coverage for the unordered case | smoogipoo/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu | osu.Game.Tests/Mods/SettingsSourceAttributeTest.cs | osu.Game.Tests/Mods/SettingsSourceAttributeTest.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Game.Configuration;
namespace osu.Game.Tests.Mods
{
[TestFixture]
public class SettingsSourceAttributeTest
{
[Test]
public void TestOrdering()
{
var objectWithSettings = new ClassWithSettings();
var orderedSettings = objectWithSettings.GetOrderedSettingsSourceProperties().ToArray();
Assert.That(orderedSettings, Has.Length.EqualTo(4));
Assert.That(orderedSettings[0].Item2.Name, Is.EqualTo(nameof(ClassWithSettings.FirstSetting)));
Assert.That(orderedSettings[1].Item2.Name, Is.EqualTo(nameof(ClassWithSettings.SecondSetting)));
Assert.That(orderedSettings[2].Item2.Name, Is.EqualTo(nameof(ClassWithSettings.ThirdSetting)));
Assert.That(orderedSettings[3].Item2.Name, Is.EqualTo(nameof(ClassWithSettings.UnorderedSetting)));
}
private class ClassWithSettings
{
[SettingSource("Unordered setting", "Should be last")]
public BindableFloat UnorderedSetting { get; set; } = new BindableFloat();
[SettingSource("Second setting", "Another description", 2)]
public BindableBool SecondSetting { get; set; } = new BindableBool();
[SettingSource("First setting", "A description", 1)]
public BindableDouble FirstSetting { get; set; } = new BindableDouble();
[SettingSource("Third setting", "Yet another description", 3)]
public BindableInt ThirdSetting { get; set; } = new BindableInt();
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Game.Configuration;
namespace osu.Game.Tests.Mods
{
[TestFixture]
public class SettingsSourceAttributeTest
{
[Test]
public void TestOrdering()
{
var objectWithSettings = new ClassWithSettings();
var orderedSettings = objectWithSettings.GetOrderedSettingsSourceProperties().ToArray();
Assert.That(orderedSettings, Has.Length.EqualTo(3));
Assert.That(orderedSettings[0].Item2.Name, Is.EqualTo(nameof(ClassWithSettings.FirstSetting)));
Assert.That(orderedSettings[1].Item2.Name, Is.EqualTo(nameof(ClassWithSettings.SecondSetting)));
Assert.That(orderedSettings[2].Item2.Name, Is.EqualTo(nameof(ClassWithSettings.ThirdSetting)));
}
private class ClassWithSettings
{
[SettingSource("Second setting", "Another description", 2)]
public BindableBool SecondSetting { get; set; } = new BindableBool();
[SettingSource("First setting", "A description", 1)]
public BindableDouble FirstSetting { get; set; } = new BindableDouble();
[SettingSource("Third setting", "Yet another description", 3)]
public BindableInt ThirdSetting { get; set; } = new BindableInt();
}
}
}
| mit | C# |
e75d21507c238ff6a6f5b374a301a7ccbe1f7a9d | Fix `GetDisplayTitleRomanisable()` relying on `ToString()` implementation | ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu | osu.Game/Beatmaps/BeatmapMetadataInfoExtensions.cs | osu.Game/Beatmaps/BeatmapMetadataInfoExtensions.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Localisation;
namespace osu.Game.Beatmaps
{
public static class BeatmapMetadataInfoExtensions
{
/// <summary>
/// An array of all searchable terms provided in contained metadata.
/// </summary>
public static string[] GetSearchableTerms(this IBeatmapMetadataInfo metadataInfo) => new[]
{
metadataInfo.Author.Username,
metadataInfo.Artist,
metadataInfo.ArtistUnicode,
metadataInfo.Title,
metadataInfo.TitleUnicode,
metadataInfo.Source,
metadataInfo.Tags
}.Where(s => !string.IsNullOrEmpty(s)).ToArray();
/// <summary>
/// A user-presentable display title representing this metadata.
/// </summary>
public static string GetDisplayTitle(this IBeatmapMetadataInfo metadataInfo)
{
string author = string.IsNullOrEmpty(metadataInfo.Author.Username) ? string.Empty : $" ({metadataInfo.Author.Username})";
string artist = string.IsNullOrEmpty(metadataInfo.Artist) ? "unknown artist" : metadataInfo.Artist;
string title = string.IsNullOrEmpty(metadataInfo.Title) ? "unknown title" : metadataInfo.Title;
return $"{artist} - {title}{author}".Trim();
}
/// <summary>
/// A user-presentable display title representing this beatmap, with localisation handling for potentially romanisable fields.
/// </summary>
public static RomanisableString GetDisplayTitleRomanisable(this IBeatmapMetadataInfo metadataInfo, bool includeCreator = true)
{
string author = !includeCreator || string.IsNullOrEmpty(metadataInfo.Author.Username) ? string.Empty : $"({metadataInfo.Author.Username})";
string artistUnicode = string.IsNullOrEmpty(metadataInfo.ArtistUnicode) ? metadataInfo.Artist : metadataInfo.ArtistUnicode;
string titleUnicode = string.IsNullOrEmpty(metadataInfo.TitleUnicode) ? metadataInfo.Title : metadataInfo.TitleUnicode;
return new RomanisableString($"{artistUnicode} - {titleUnicode} {author}".Trim(), $"{metadataInfo.Artist} - {metadataInfo.Title} {author}".Trim());
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Localisation;
namespace osu.Game.Beatmaps
{
public static class BeatmapMetadataInfoExtensions
{
/// <summary>
/// An array of all searchable terms provided in contained metadata.
/// </summary>
public static string[] GetSearchableTerms(this IBeatmapMetadataInfo metadataInfo) => new[]
{
metadataInfo.Author.Username,
metadataInfo.Artist,
metadataInfo.ArtistUnicode,
metadataInfo.Title,
metadataInfo.TitleUnicode,
metadataInfo.Source,
metadataInfo.Tags
}.Where(s => !string.IsNullOrEmpty(s)).ToArray();
/// <summary>
/// A user-presentable display title representing this metadata.
/// </summary>
public static string GetDisplayTitle(this IBeatmapMetadataInfo metadataInfo)
{
string author = string.IsNullOrEmpty(metadataInfo.Author.Username) ? string.Empty : $" ({metadataInfo.Author.Username})";
string artist = string.IsNullOrEmpty(metadataInfo.Artist) ? "unknown artist" : metadataInfo.Artist;
string title = string.IsNullOrEmpty(metadataInfo.Title) ? "unknown title" : metadataInfo.Title;
return $"{artist} - {title}{author}".Trim();
}
/// <summary>
/// A user-presentable display title representing this beatmap, with localisation handling for potentially romanisable fields.
/// </summary>
public static RomanisableString GetDisplayTitleRomanisable(this IBeatmapMetadataInfo metadataInfo, bool includeCreator = true)
{
string author = !includeCreator || string.IsNullOrEmpty(metadataInfo.Author.Username) ? string.Empty : $"({metadataInfo.Author})";
string artistUnicode = string.IsNullOrEmpty(metadataInfo.ArtistUnicode) ? metadataInfo.Artist : metadataInfo.ArtistUnicode;
string titleUnicode = string.IsNullOrEmpty(metadataInfo.TitleUnicode) ? metadataInfo.Title : metadataInfo.TitleUnicode;
return new RomanisableString($"{artistUnicode} - {titleUnicode} {author}".Trim(), $"{metadataInfo.Artist} - {metadataInfo.Title} {author}".Trim());
}
}
}
| mit | C# |
448c58c35d0aec96e9a3c91323f69564ddcb8c89 | Remove unnecessary variable discard | NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu | osu.Game/Beatmaps/Legacy/LegacyControlPointInfo.cs | osu.Game/Beatmaps/Legacy/LegacyControlPointInfo.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using JetBrains.Annotations;
using Newtonsoft.Json;
using osu.Framework.Bindables;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Beatmaps.Legacy
{
public class LegacyControlPointInfo : ControlPointInfo
{
/// <summary>
/// All sound points.
/// </summary>
[JsonProperty]
public IBindableList<SampleControlPoint> SamplePoints => samplePoints;
private readonly BindableList<SampleControlPoint> samplePoints = new BindableList<SampleControlPoint>();
/// <summary>
/// Finds the sound control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the sound control point at.</param>
/// <returns>The sound control point.</returns>
[NotNull]
public SampleControlPoint SamplePointAt(double time) => BinarySearchWithFallback(SamplePoints, time, SamplePoints.Count > 0 ? SamplePoints[0] : SampleControlPoint.DEFAULT);
public override void Clear()
{
base.Clear();
samplePoints.Clear();
}
protected override bool CheckAlreadyExisting(double time, ControlPoint newPoint)
{
if (newPoint is SampleControlPoint)
{
var existing = BinarySearch(SamplePoints, time);
return newPoint.IsRedundant(existing);
}
return base.CheckAlreadyExisting(time, newPoint);
}
protected override void GroupItemAdded(ControlPoint controlPoint)
{
if (controlPoint is SampleControlPoint typed)
samplePoints.Add(typed);
base.GroupItemAdded(controlPoint);
}
protected override void GroupItemRemoved(ControlPoint controlPoint)
{
if (controlPoint is SampleControlPoint typed)
samplePoints.Remove(typed);
base.GroupItemRemoved(controlPoint);
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using JetBrains.Annotations;
using Newtonsoft.Json;
using osu.Framework.Bindables;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Beatmaps.Legacy
{
public class LegacyControlPointInfo : ControlPointInfo
{
/// <summary>
/// All sound points.
/// </summary>
[JsonProperty]
public IBindableList<SampleControlPoint> SamplePoints => samplePoints;
private readonly BindableList<SampleControlPoint> samplePoints = new BindableList<SampleControlPoint>();
/// <summary>
/// Finds the sound control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the sound control point at.</param>
/// <returns>The sound control point.</returns>
[NotNull]
public SampleControlPoint SamplePointAt(double time) => BinarySearchWithFallback(SamplePoints, time, SamplePoints.Count > 0 ? SamplePoints[0] : SampleControlPoint.DEFAULT);
public override void Clear()
{
base.Clear();
samplePoints.Clear();
}
protected override bool CheckAlreadyExisting(double time, ControlPoint newPoint)
{
if (newPoint is SampleControlPoint _)
{
var existing = BinarySearch(SamplePoints, time);
return newPoint.IsRedundant(existing);
}
return base.CheckAlreadyExisting(time, newPoint);
}
protected override void GroupItemAdded(ControlPoint controlPoint)
{
if (controlPoint is SampleControlPoint typed)
samplePoints.Add(typed);
base.GroupItemAdded(controlPoint);
}
protected override void GroupItemRemoved(ControlPoint controlPoint)
{
if (controlPoint is SampleControlPoint typed)
samplePoints.Remove(typed);
base.GroupItemRemoved(controlPoint);
}
}
}
| mit | C# |
5d3afd828bd44f9d95b6b3535b622a58384ea89f | Update IQueryableBatchExtensions.cs | borisdj/EFCore.BulkExtensions | EFCore.BulkExtensions/IQueryableBatchExtensions.cs | EFCore.BulkExtensions/IQueryableBatchExtensions.cs | using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace EFCore.BulkExtensions
{
public static class IQueryableBatchExtensions
{
public static int BatchDelete<T>(this IQueryable<T> query) where T : class, new()
{
DbContext context = BatchUtil.GetDbContext(query);
string sql = BatchUtil.GetSqlDelete(query);
return context.Database.ExecuteSqlCommand(sql);
}
public static int BatchUpdate<T>(this IQueryable<T> query, T updateValues, List<string> updateColumns = null) where T : class, new()
{
DbContext context = BatchUtil.GetDbContext(query);
List<SqlParameter> parameters = new List<SqlParameter>();
string sql = BatchUtil.GetSqlUpdate(query, context, updateValues, updateColumns, parameters);
return context.Database.ExecuteSqlCommand(sql, parameters.ToArray());
}
public static int BatchUpdate<T>(this IQueryable<T> query, Expression<Func<T, bool>> updateExpression) where T : class, new()
{
var context = BatchUtil.GetDbContext(query);
var (sql, sp) = BatchUtil.GetSqlUpdate(query, updateExpression);
return context.Database.ExecuteSqlCommand(sql, sp);
}
// Async methods
public static async Task<int> BatchDeleteAsync<T>(this IQueryable<T> query) where T : class, new()
{
DbContext context = BatchUtil.GetDbContext(query);
string sql = BatchUtil.GetSqlDelete(query);
return await context.Database.ExecuteSqlCommandAsync(sql);
}
public static async Task<int> BatchUpdateAsync<T>(this IQueryable<T> query, T updateValues, List<string> updateColumns = null) where T : class, new()
{
DbContext context = BatchUtil.GetDbContext(query);
List<SqlParameter> parameters = new List<SqlParameter>();
string sql = BatchUtil.GetSqlUpdate(query, context, updateValues, updateColumns, parameters);
return await context.Database.ExecuteSqlCommandAsync(sql, parameters.ToArray());
}
public static async Task<int> BatchUpdateAsync<T>(this IQueryable<T> query, Expression<Func<T, bool>> updateExpression) where T : class, new()
{
var context = BatchUtil.GetDbContext(query);
var (sql, sp) = BatchUtil.GetSqlUpdate(query, updateExpression);
return await context.Database.ExecuteSqlCommandAsync(sql, sp);
}
}
}
| using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace EFCore.BulkExtensions
{
public static class IQueryableBatchExtensions
{
public static int BatchDelete<T>(this IQueryable<T> query) where T : class, new()
{
DbContext context = BatchUtil.GetDbContext(query);
string sql = BatchUtil.GetSqlDelete(query);
return context.Database.ExecuteSqlCommand(sql);
}
public static int BatchUpdate<T>(this IQueryable<T> query, T updateValues, List<string> updateColumns = null) where T : class, new()
{
DbContext context = BatchUtil.GetDbContext(query);
List<SqlParameter> parameters = new List<SqlParameter>();
string sql = BatchUtil.GetSqlUpdate(query, context, updateValues, updateColumns, parameters);
return context.Database.ExecuteSqlCommand(sql, parameters.ToArray());
}
// Async methods
public static async Task<int> BatchDeleteAsync<T>(this IQueryable<T> query) where T : class, new()
{
DbContext context = BatchUtil.GetDbContext(query);
string sql = BatchUtil.GetSqlDelete(query);
return await context.Database.ExecuteSqlCommandAsync(sql);
}
public static async Task<int> BatchUpdateAsync<T>(this IQueryable<T> query, T updateValues, List<string> updateColumns = null) where T : class, new()
{
DbContext context = BatchUtil.GetDbContext(query);
List<SqlParameter> parameters = new List<SqlParameter>();
string sql = BatchUtil.GetSqlUpdate(query, context, updateValues, updateColumns, parameters);
return await context.Database.ExecuteSqlCommandAsync(sql, parameters.ToArray());
}
}
} | mit | C# |
e8db9f0bc875cabe1893edd5f40a607ea8b9b477 | Use InvariantCulture in MathConverter | ButchersBoy/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit,tipunch74/MaterialDesignInXamlToolkit,DingpingZhang/MaterialDesignInXamlToolkit,tipunch74/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit,tipunch74/MaterialDesignInXamlToolkit | MaterialDesignThemes.Wpf/Converters/MathConverter.cs | MaterialDesignThemes.Wpf/Converters/MathConverter.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace MaterialDesignThemes.Wpf.Converters
{
public enum MathOperation
{
Add,
Subtract,
Multiply,
Divide
}
public sealed class MathConverter : IValueConverter
{
public MathOperation Operation { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double value1, value2;
if (Double.TryParse(value.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out value1)
&& Double.TryParse(parameter.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out value2))
{
switch (Operation)
{
default:
case MathOperation.Add:
return value1 + value2;
case MathOperation.Divide:
return value1 / value2;
case MathOperation.Multiply:
return value1 * value2;
case MathOperation.Subtract:
return value1 - value2;
}
}
return Binding.DoNothing;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace MaterialDesignThemes.Wpf.Converters
{
public enum MathOperation
{
Add,
Subtract,
Multiply,
Divide
}
public sealed class MathConverter : IValueConverter
{
public MathOperation Operation { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double value1, value2;
if (Double.TryParse(value.ToString(), out value1) && Double.TryParse(parameter.ToString(), out value2))
{
switch (Operation)
{
default:
case MathOperation.Add:
return value1 + value2;
case MathOperation.Divide:
return value1 / value2;
case MathOperation.Multiply:
return value1 * value2;
case MathOperation.Subtract:
return value1 - value2;
}
}
return Binding.DoNothing;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
}
| mit | C# |
189f037fbd1de3578df664dfafc886c0ca60d646 | Add new employment fields for change employer (Portable) | SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments | src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/Requests/CreateChangeOfPartyRequestRequest.cs | src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/Requests/CreateChangeOfPartyRequestRequest.cs | using System;
using SFA.DAS.CommitmentsV2.Types;
namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
public class CreateChangeOfPartyRequestRequest : SaveDataRequest
{
public ChangeOfPartyRequestType ChangeOfPartyRequestType { get; set; }
public long NewPartyId { get; set; }
public int? NewPrice { get; set; }
public DateTime? NewStartDate { get; set; }
public DateTime? NewEndDate { get; set; }
public DateTime? NewEmploymentEndDate { get; set; }
public int? NewEmploymentPrice { get; set; }
}
} | using System;
using SFA.DAS.CommitmentsV2.Types;
namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
public class CreateChangeOfPartyRequestRequest : SaveDataRequest
{
public ChangeOfPartyRequestType ChangeOfPartyRequestType { get; set; }
public long NewPartyId { get; set; }
public int? NewPrice { get; set; }
public DateTime? NewStartDate { get; set; }
public DateTime? NewEndDate { get; set; }
}
} | mit | C# |
971d690c18628c0e42f04c8b64ae2cb1cebf78a3 | Bump UpdateManager version to latest | Glurmo/LiveSplit,Glurmo/LiveSplit,LiveSplit/LiveSplit,Glurmo/LiveSplit | LiveSplit/UpdateManager/UpdateManagerUpdateable.cs | LiveSplit/UpdateManager/UpdateManagerUpdateable.cs | using System;
namespace UpdateManager
{
public class UpdateManagerUpdateable : IUpdateable
{
private UpdateManagerUpdateable() { }
private static UpdateManagerUpdateable _Instance { get; set; }
public static UpdateManagerUpdateable Instance
{
get
{
if (_Instance == null)
_Instance = new UpdateManagerUpdateable();
return _Instance;
}
}
public string UpdateName
{
get { return "Update Manager"; }
}
public string XMLURL
{
get { return "http://livesplit.org/update/update.updater.xml"; }
}
public string UpdateURL
{
get { return "http://livesplit.org/update/"; }
}
public Version Version
{
get { return Version.Parse("2.0.2"); }
}
}
}
| using System;
namespace UpdateManager
{
public class UpdateManagerUpdateable : IUpdateable
{
private UpdateManagerUpdateable() { }
private static UpdateManagerUpdateable _Instance { get; set; }
public static UpdateManagerUpdateable Instance
{
get
{
if (_Instance == null)
_Instance = new UpdateManagerUpdateable();
return _Instance;
}
}
public string UpdateName
{
get { return "Update Manager"; }
}
public string XMLURL
{
get { return "http://livesplit.org/update/update.updater.xml"; }
}
public string UpdateURL
{
get { return "http://livesplit.org/update/"; }
}
public Version Version
{
get { return Version.Parse("2.0.1"); }
}
}
}
| mit | C# |
48244d80de4d2db610745bcf024e8ad342953e15 | Change the UpdateManager's version to 2.0.1 | Fluzzarn/LiveSplit,ROMaster2/LiveSplit,Dalet/LiveSplit,Glurmo/LiveSplit,kugelrund/LiveSplit,kugelrund/LiveSplit,ROMaster2/LiveSplit,Dalet/LiveSplit,LiveSplit/LiveSplit,Glurmo/LiveSplit,kugelrund/LiveSplit,Fluzzarn/LiveSplit,Glurmo/LiveSplit,ROMaster2/LiveSplit,Fluzzarn/LiveSplit,Dalet/LiveSplit | LiveSplit/UpdateManager/UpdateManagerUpdateable.cs | LiveSplit/UpdateManager/UpdateManagerUpdateable.cs | using System;
namespace UpdateManager
{
public class UpdateManagerUpdateable : IUpdateable
{
private UpdateManagerUpdateable() { }
private static UpdateManagerUpdateable _Instance { get; set; }
public static UpdateManagerUpdateable Instance
{
get
{
if (_Instance == null)
_Instance = new UpdateManagerUpdateable();
return _Instance;
}
}
public string UpdateName
{
get { return "Update Manager"; }
}
public string XMLURL
{
get { return "http://livesplit.org/update/update.updater.xml"; }
}
public string UpdateURL
{
get { return "http://livesplit.org/update/"; }
}
public Version Version
{
get { return Version.Parse("2.0.1"); }
}
}
}
| using System;
namespace UpdateManager
{
public class UpdateManagerUpdateable : IUpdateable
{
private UpdateManagerUpdateable() { }
private static UpdateManagerUpdateable _Instance { get; set; }
public static UpdateManagerUpdateable Instance
{
get
{
if (_Instance == null)
_Instance = new UpdateManagerUpdateable();
return _Instance;
}
}
public string UpdateName
{
get { return "Update Manager"; }
}
public string XMLURL
{
get { return "http://livesplit.org/update/update.updater.xml"; }
}
public string UpdateURL
{
get { return "http://livesplit.org/update/"; }
}
public Version Version
{
get { return Version.Parse("2.0"); }
}
}
}
| mit | C# |
f722dcf98dbcb94283be8f67bdaae81ff3f8d900 | Fix PrerenderResult in Webpack sample | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | samples/misc/Webpack/ActionResults/PrerenderResult.cs | samples/misc/Webpack/ActionResults/PrerenderResult.cs | using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.NodeServices;
using Microsoft.AspNetCore.SpaServices.Prerendering;
using Microsoft.Extensions.DependencyInjection;
namespace Webpack.ActionResults
{
// This is an example of how you could invoke the prerendering API from an ActionResult, so as to
// prerender a SPA component as the entire response page (instead of injecting the SPA component
// into a Razor view's output)
public class PrerenderResult : ActionResult
{
private JavaScriptModuleExport _moduleExport;
private object _dataToSupply;
public PrerenderResult(JavaScriptModuleExport moduleExport, object dataToSupply = null)
{
_moduleExport = moduleExport;
_dataToSupply = dataToSupply;
}
public override async Task ExecuteResultAsync(ActionContext context)
{
var nodeServices = context.HttpContext.RequestServices.GetRequiredService<INodeServices>();
var hostEnv = context.HttpContext.RequestServices.GetRequiredService<IHostingEnvironment>();
var applicationBasePath = hostEnv.ContentRootPath;
var request = context.HttpContext.Request;
var response = context.HttpContext.Response;
var prerenderedHtml = await Prerenderer.RenderToString(
applicationBasePath,
nodeServices,
_moduleExport,
request.GetEncodedUrl(),
request.Path + request.QueryString.Value,
_dataToSupply,
/* timeoutMilliseconds */ 30000,
/* requestPathBase */ "/"
);
response.ContentType = "text/html";
await response.WriteAsync(prerenderedHtml.Html);
}
}
} | using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.NodeServices;
using Microsoft.AspNetCore.SpaServices.Prerendering;
using Microsoft.Extensions.DependencyInjection;
namespace Webpack.ActionResults
{
// This is an example of how you could invoke the prerendering API from an ActionResult, so as to
// prerender a SPA component as the entire response page (instead of injecting the SPA component
// into a Razor view's output)
public class PrerenderResult : ActionResult
{
private JavaScriptModuleExport _moduleExport;
private object _dataToSupply;
public PrerenderResult(JavaScriptModuleExport moduleExport, object dataToSupply = null)
{
_moduleExport = moduleExport;
_dataToSupply = dataToSupply;
}
public override async Task ExecuteResultAsync(ActionContext context)
{
var nodeServices = context.HttpContext.RequestServices.GetRequiredService<INodeServices>();
var hostEnv = context.HttpContext.RequestServices.GetRequiredService<IHostingEnvironment>();
var applicationBasePath = hostEnv.ContentRootPath;
var request = context.HttpContext.Request;
var response = context.HttpContext.Response;
var prerenderedHtml = await Prerenderer.RenderToString(
applicationBasePath,
nodeServices,
_moduleExport,
request.GetEncodedUrl(),
request.Path + request.QueryString.Value,
_dataToSupply,
/* timeoutMilliseconds */ 30000
);
response.ContentType = "text/html";
await response.WriteAsync(prerenderedHtml.Html);
}
}
} | apache-2.0 | C# |
9304ff4c0541adc79d43c91070d4a1b807c7cfc8 | Update WalletWasabi/Services/Terminate/TerminateService.cs | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Services/Terminate/TerminateService.cs | WalletWasabi/Services/Terminate/TerminateService.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Logging;
namespace WalletWasabi.Services.Terminate
{
public class TerminateService
{
private Func<Task> _terminateApplicationAsync;
private const long TerminateStatusIdle = 0;
private const long TerminateStatusInProgress = 1;
private const long TerminateFinished = 2;
private long _terminateStatus;
public TerminateService(Func<Task> terminateApplicationAsync)
{
_terminateApplicationAsync = terminateApplicationAsync;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
Console.CancelKeyPress += Console_CancelKeyPress;
}
private void CurrentDomain_ProcessExit(object? sender, EventArgs e)
{
Logger.LogDebug("ProcessExit was called.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
Terminate();
}
private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
Logger.LogWarning("Process was signaled for termination.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
// In some cases CurrentDomain_ProcessExit is called after this by the OS.
Terminate();
}
/// <summary>
/// Terminates the application.
/// </summary>
/// <remark>This is a blocking method. Note that program execution ends at the end of this method due to <see cref="Environment.Exit(int)"/> call.</remark>
public void Terminate(int exitCode = 0)
{
var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle);
Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}");
if (prevValue != TerminateStatusIdle)
{
// Secondary callers will be blocked until the end of the termination.
while (_terminateStatus != TerminateFinished)
{
}
return;
}
// First caller starts the terminate procedure.
Logger.LogDebug("Start shutting down the application.");
// Async termination has to be started on another thread otherwise there is a possibility of deadlock.
// We still need to block the caller so ManualResetEvent applied.
using ManualResetEvent resetEvent = new ManualResetEvent(false);
Task.Run(async () =>
{
try
{
await _terminateApplicationAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogWarning(ex.ToTypeMessageString());
}
resetEvent.Set();
});
resetEvent.WaitOne();
AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;
Console.CancelKeyPress -= Console_CancelKeyPress;
// Indicate that the termination procedure finished. So other callers can return.
Interlocked.Exchange(ref _terminateStatus, TerminateFinished);
Environment.Exit(exitCode);
}
public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle;
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Logging;
namespace WalletWasabi.Services.Terminate
{
public class TerminateService
{
private Func<Task> _terminateApplicationAsync;
private const long TerminateStatusIdle = 0;
private const long TerminateStatusInProgress = 1;
private const long TerminateFinished = 2;
private long _terminateStatus;
public TerminateService(Func<Task> terminateApplicationAsync)
{
_terminateApplicationAsync = terminateApplicationAsync;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
Console.CancelKeyPress += Console_CancelKeyPress;
}
private void CurrentDomain_ProcessExit(object? sender, EventArgs e)
{
Logger.LogDebug("ProcessExit was called.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
Terminate();
}
private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
Logger.LogWarning("Process was signaled for termination.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
// In some cases CurrentDomain_ProcessExit is called after this by the OS.
Terminate();
}
/// <summary>
/// Terminates the application.
/// </summary>
/// <remark>This is a blocking method. Note that program execution ends at the end of this method due to <see cref="Environment.Exit(int)"/> call.</remark>
public void Terminate(int exitCode = 0)
{
var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle);
Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}");
if (prevValue != TerminateStatusIdle)
{
// Secondary callers will be blocked until the end of the termination.
while (_terminateStatus != TerminateFinished)
{
}
return;
}
// First caller starts the terminate procedure.
Logger.LogDebug("Terminate application was started.");
// Async termination has to be started on another thread otherwise there is a possibility of deadlock.
// We still need to block the caller so ManualResetEvent applied.
using ManualResetEvent resetEvent = new ManualResetEvent(false);
Task.Run(async () =>
{
try
{
await _terminateApplicationAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogWarning(ex.ToTypeMessageString());
}
resetEvent.Set();
});
resetEvent.WaitOne();
AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;
Console.CancelKeyPress -= Console_CancelKeyPress;
// Indicate that the termination procedure finished. So other callers can return.
Interlocked.Exchange(ref _terminateStatus, TerminateFinished);
Environment.Exit(exitCode);
}
public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle;
}
}
| mit | C# |
8a62194acb0aef9462abc671aedc28e851ba16ef | Use autoproperties | arnovb-github/CmcLibNet | CmcLibNet.Database/CommencePreferences.cs | CmcLibNet.Database/CommencePreferences.cs | namespace Vovin.CmcLibNet.Database
{
/// <summary>
/// Class exposing some of Commence's preferences settings
/// </summary>
internal class Preferences
{
/// <summary>
/// Gets (-Me-) item.
/// </summary>
/// <remarks>Does NOT set this preference in Commence.</remarks>
internal string Me { get; set; } = "(-Me-) item not set.";
/// <summary>
/// Gets/Sets (-Me-) category.
/// </summary>
/// <remarks>Does NOT set this preference in Commence.</remarks>
internal string MeCategory { get; set; } = "(-Me-) category not set.";
/// <summary>
/// Gets/Sets Letter Log path
/// </summary>
/// <remarks>Does NOT set this preference in Commence.</remarks>
internal string LetterLogDir { get; set; } = "Letter Log Directory not set.";
/// <summary>
/// Gets/Sets External Data files path.
/// </summary>
/// <remarks>Does NOT set this preference in Commence.</remarks>
internal string ExternalDir { get; set; } = "Spool directory not set or not applicable.";
}
}
| namespace Vovin.CmcLibNet.Database
{
/// <summary>
/// Class exposing some of Commence's preferences settings
/// </summary>
internal class Preferences
{
string _me = "(-Me-) item not set.";
string _mecat = "(-Me-) category not set.";
string _letterlogdir = "Letter Log Directory not set.";
string _externaldir = "Spool directory not set or not applicable.";
/// <summary>
/// Gets (-Me-) item.
/// </summary>
/// <remarks>Does NOT set this preference in Commence.</remarks>
internal string Me
{
get
{
return _me;
}
set
{
_me = value;
}
}
/// <summary>
/// Gets/Sets (-Me-) category.
/// </summary>
/// <remarks>Does NOT set this preference in Commence.</remarks>
internal string MeCategory
{
get
{
return _mecat;
}
set
{
_mecat = value;
}
}
/// <summary>
/// Gets/Sets Letter Log path
/// </summary>
/// <remarks>Does NOT set this preference in Commence.</remarks>
internal string LetterLogDir
{
get
{
return _letterlogdir;
}
set
{
_letterlogdir = value;
}
}
/// <summary>
/// Gets/Sets External Data files path.
/// </summary>
/// <remarks>Does NOT set this preference in Commence.</remarks>
internal string ExternalDir
{
get
{
return _externaldir;
}
set
{
_externaldir = value;
}
}
}
}
| mit | C# |
949267fe88fd11440184d92a113cd88245453a4c | update assembly info | RapidScada/scada,RapidScada/scada,RapidScada/scada,RapidScada/scada | ScadaWeb/ScadaWebShell5/Properties/AssemblyInfo.cs | ScadaWeb/ScadaWebShell5/Properties/AssemblyInfo.cs | using Scada.Web;
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("ScadaWebShell5")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Rapid SCADA")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("868de826-356e-47a4-9de7-ea7168fca90a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion(WebUtils.AppVersion)]
[assembly: AssemblyFileVersion(WebUtils.AppVersion)]
| using Scada.Web;
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("ScadaWebShell5Beta")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Rapid SCADA")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("868de826-356e-47a4-9de7-ea7168fca90a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion(WebUtils.AppVersion)]
[assembly: AssemblyFileVersion(WebUtils.AppVersion)]
| apache-2.0 | C# |
c458758b8c209d931b4a45ec4f970e581ae1474f | Remove unused methods | arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5 | src/Arkivverket.Arkade.Core/Base/TestRun.cs | src/Arkivverket.Arkade.Core/Base/TestRun.cs | using System;
using Arkivverket.Arkade.Core.Testing;
using System.Collections.Generic;
using System.Linq;
using Arkivverket.Arkade.Core.Util;
namespace Arkivverket.Arkade.Core.Base
{
public class TestRun : IComparable
{
private readonly IArkadeTest _test;
public TestId TestId => _test.GetId();
public string TestName => ArkadeTestNameProvider.GetDisplayName(_test);
public TestType TestType => _test.GetTestType();
public string TestDescription => _test.GetDescription();
public List<TestResult> Results { get; set; }
public long TestDuration { get; set; }
public TestRun(IArkadeTest test)
{
_test = test;
Results = new List<TestResult>();
}
public bool IsSuccess()
{
return Results.TrueForAll(r => !r.IsError());
}
public int FindNumberOfErrors()
{
return Results.Count(r => r.IsError()) + Results.Where(r => r.IsErrorGroup()).Sum(r => r.GroupErrors);
}
public int CompareTo(object obj)
{
var testRun = (TestRun) obj;
return _test.CompareTo(testRun._test);
}
}
}
| using System;
using Arkivverket.Arkade.Core.Testing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Arkivverket.Arkade.Core.Util;
namespace Arkivverket.Arkade.Core.Base
{
public class TestRun : IComparable
{
private readonly IArkadeTest _test;
public TestId TestId => _test.GetId();
public string TestName => ArkadeTestNameProvider.GetDisplayName(_test);
public TestType TestType => _test.GetTestType();
public string TestDescription => _test.GetDescription();
public List<TestResult> Results { get; set; }
public long TestDuration { get; set; }
public TestRun(IArkadeTest test)
{
_test = test;
Results = new List<TestResult>();
}
public void Add(TestResult result)
{
Results.Add(result);
}
public bool IsSuccess()
{
return Results.TrueForAll(r => !r.IsError());
}
public override string ToString()
{
var builder = new StringBuilder();
builder.Append("Test: ").AppendLine(TestName);
builder.Append("Test type: ").AppendLine(TestType.ToString());
builder.Append("IsSuccess: ").AppendLine(IsSuccess().ToString());
builder.AppendLine("Results: ");
foreach (TestResult result in Results)
builder.AppendLine(result.ToString());
return builder.ToString();
}
public int FindNumberOfErrors()
{
return Results.Count(r => r.IsError()) + Results.Where(r => r.IsErrorGroup()).Sum(r => r.GroupErrors);
}
public int CompareTo(object obj)
{
var testRun = (TestRun) obj;
return _test.CompareTo(testRun._test);
}
}
}
| agpl-3.0 | C# |
57801767917c272f7d989f3e59aafc2691a8ac38 | mark props as virtual for EF | nexbit/IdentityManager.MembershipReboot | source/Host/MembershipRebootIdentityManagerFactory.cs | source/Host/MembershipRebootIdentityManagerFactory.cs | using BrockAllen.MembershipReboot;
using BrockAllen.MembershipReboot.Ef;
using BrockAllen.MembershipReboot.Relational;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Thinktecture.IdentityManager;
using Thinktecture.IdentityManager.MembershipReboot;
namespace Thinktecture.IdentityManager.Host
{
public class CustomUser : RelationalUserAccount
{
[Display(Name="First Name")]
public virtual string FirstName { get; set; }
[Display(Name = "Last Name")]
public virtual string LastName { get; set; }
public virtual int? Age { get; set; }
}
public class CustomDatabase : MembershipRebootDbContext<CustomUser>
{
public CustomDatabase()
: this("CustomMembershipReboot")
{
}
public CustomDatabase(string name)
:base(name)
{
}
}
public class MembershipRebootIdentityManagerFactory
{
static MembershipRebootConfiguration<CustomUser> config;
static MembershipRebootIdentityManagerFactory()
{
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<CustomDatabase>());
config = new MembershipRebootConfiguration<CustomUser>();
config.PasswordHashingIterationCount = 10000;
config.RequireAccountVerification = false;
}
string connString;
public MembershipRebootIdentityManagerFactory(string connString)
{
this.connString = connString;
}
public IIdentityManagerService Create()
{
var db = new CustomDatabase("CustomMembershipReboot");
var repo = new DbContextUserAccountRepository<CustomDatabase, CustomUser>(db);
repo.QueryFilter = RelationalUserAccountQuery<CustomUser>.Filter;
repo.QuerySort = RelationalUserAccountQuery<CustomUser>.Sort;
var svc = new UserAccountService<CustomUser>(config, repo);
var idMgr = new MembershipRebootIdentityManagerService<CustomUser>(svc, repo);
return new DisposableIdentityManagerService(idMgr, db);
}
}
} | using BrockAllen.MembershipReboot;
using BrockAllen.MembershipReboot.Ef;
using BrockAllen.MembershipReboot.Relational;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Thinktecture.IdentityManager;
using Thinktecture.IdentityManager.MembershipReboot;
namespace Thinktecture.IdentityManager.Host
{
public class CustomUser : RelationalUserAccount
{
[Display(Name="First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public int? Age { get; set; }
}
public class CustomDatabase : MembershipRebootDbContext<CustomUser>
{
public CustomDatabase()
: this("CustomMembershipReboot")
{
}
public CustomDatabase(string name)
:base(name)
{
}
}
public class MembershipRebootIdentityManagerFactory
{
static MembershipRebootConfiguration<CustomUser> config;
static MembershipRebootIdentityManagerFactory()
{
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<CustomDatabase>());
config = new MembershipRebootConfiguration<CustomUser>();
config.PasswordHashingIterationCount = 10000;
config.RequireAccountVerification = false;
}
string connString;
public MembershipRebootIdentityManagerFactory(string connString)
{
this.connString = connString;
}
public IIdentityManagerService Create()
{
var db = new CustomDatabase("CustomMembershipReboot");
var repo = new DbContextUserAccountRepository<CustomDatabase, CustomUser>(db);
repo.QueryFilter = RelationalUserAccountQuery<CustomUser>.Filter;
repo.QuerySort = RelationalUserAccountQuery<CustomUser>.Sort;
var svc = new UserAccountService<CustomUser>(config, repo);
var idMgr = new MembershipRebootIdentityManagerService<CustomUser>(svc, repo);
return new DisposableIdentityManagerService(idMgr, db);
}
}
} | apache-2.0 | C# |
6ea3c4c7c611344f540fe9e7e27fd67f6d5b16f9 | Change test strings | lpatalas/ExpressRunner | ExpressRunner.TestProject/ExampleTests.cs | ExpressRunner.TestProject/ExampleTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Extensions;
namespace ExpressRunner.TestProject
{
public class ExampleTests
{
[Fact]
public void Should_fail_always()
{
Assert.Equal("text", "wrong text");
}
[Fact]
public void Should_pass_always()
{
Assert.True(true);
}
[Fact]
public void Should_pass_also()
{
Assert.True(true);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
public void Should_support_theory(int input)
{
Assert.Equal(1, input);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Extensions;
namespace ExpressRunner.TestProject
{
public class ExampleTests
{
[Fact]
public void Should_fail_always()
{
Assert.Equal("napis", "wypis");
}
[Fact]
public void Should_pass_always()
{
Assert.True(true);
}
[Fact]
public void Should_pass_also()
{
Assert.True(true);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
public void Should_support_theory(int input)
{
Assert.Equal(1, input);
}
}
}
| mit | C# |
88281f6a90ee98f4e373d0c3c5d5c70d1428d1c8 | Fix build error | mmooney/Sriracha.Deploy,mmooney/Sriracha.Deploy,mmooney/Sriracha.Deploy,mmooney/Sriracha.Deploy | Sriracha.Deploy.Data/Deployment/DeploymentImpl/DeployComponentRunner.cs | Sriracha.Deploy.Data/Deployment/DeploymentImpl/DeployComponentRunner.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MMDB.Shared;
using Sriracha.Deploy.Data.Dto;
using Sriracha.Deploy.Data.Tasks;
using Sriracha.Deploy.Data.Credentials;
namespace Sriracha.Deploy.Data.Deployment.DeploymentImpl
{
public class DeployComponentRunner : IDeployComponentRunner
{
private readonly IDeployTaskFactory _deployTaskFactory;
private readonly IImpersonator _impersonator;
public DeployComponentRunner(IDeployTaskFactory deployTaskFactory, IImpersonator impersonator)
{
_deployTaskFactory = DIHelper.VerifyParameter(deployTaskFactory);
_impersonator = DIHelper.VerifyParameter(impersonator);
}
public void Run(string deployStateId, IDeployTaskStatusManager statusManager, List<IDeployTaskDefinition> taskDefinitionList, DeployComponent component, DeployEnvironmentConfiguration environmentComponent, DeployMachine machine, DeployBuild build, RuntimeSystemSettings runtimeSystemSettings)
{
int stepCounter = 0;
foreach(var taskDefinition in taskDefinitionList)
{
stepCounter++;
statusManager.Info(deployStateId, string.Format("Step {0}: Starting {1}", stepCounter, taskDefinition.TaskDefintionName));
DeployTaskExecutionResult result;
using (var impersontator = BeginImpersonation(deployStateId, statusManager, environmentComponent))
{
var executor = _deployTaskFactory.CreateTaskExecutor(taskDefinition.GetTaskExecutorType());
result = executor.Execute(deployStateId, statusManager, taskDefinition, component, environmentComponent, machine, build, runtimeSystemSettings);
}
switch(result.Status)
{
case EnumDeployTaskExecutionResultStatus.Success:
statusManager.Info(deployStateId, string.Format("Step {0}: End {1}, completed successfully", stepCounter, taskDefinition.TaskDefintionName));
break;
case EnumDeployTaskExecutionResultStatus.Error:
statusManager.Info(deployStateId, string.Format("Step {0}: End {1}, failed", stepCounter, taskDefinition.TaskDefintionName));
return; //error error eject!
//break;
case EnumDeployTaskExecutionResultStatus.Warning:
statusManager.Info(deployStateId, string.Format("Step {0}: End {1}, completed with warnings", stepCounter, taskDefinition.TaskDefintionName));
break;
default:
throw new UnknownEnumValueException(result.Status);
}
}
}
private ImpersonationContext BeginImpersonation(string deployStateId, IDeployTaskStatusManager statusManager, DeployEnvironmentConfiguration environmentComponent)
{
if(!string.IsNullOrEmpty(environmentComponent.DeployCredentialsId))
{
var context = _impersonator.BeginImpersonation(environmentComponent.DeployCredentialsId);
statusManager.Info(deployStateId, "Starting impersonation of " + context.Credentials.DisplayValue);
return context;
}
else
{
statusManager.Info(deployStateId, "No impersonation");
return null;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MMDB.Shared;
using Sriracha.Deploy.Data.Dto;
using Sriracha.Deploy.Data.Tasks;
using Sriracha.Deploy.Data.Credentials;
namespace Sriracha.Deploy.Data.Deployment.DeploymentImpl
{
public class DeployComponentRunner : IDeployComponentRunner
{
private readonly IDeployTaskFactory _deployTaskFactory;
private readonly IImpersonator _impersonator;
public DeployComponentRunner(IDeployTaskFactory deployTaskFactory, IImpersonator impersonator)
{
_deployTaskFactory = DIHelper.VerifyParameter(deployTaskFactory);
_impersonator = DIHelper.VerifyParameter(impersonator);
}
public void Run(string deployStateId, IDeployTaskStatusManager statusManager, List<IDeployTaskDefinition> taskDefinitionList, DeployComponent component, DeployEnvironmentConfiguration environmentComponent, DeployMachine machine, DeployBuild build, RuntimeSystemSettings runtimeSystemSettings)
{
int stepCounter = 0;
foreach(var taskDefinition in taskDefinitionList)
{
stepCounter++;
statusManager.Info(deployStateId, string.Format("Step {0}: Starting {1}", stepCounter, taskDefinition.TaskDefintionName));
DeployTaskExecutionResult result;
using (var impersontator = BeginImpersonation(deployStateId, statusManager, environmentComponent))
{
result = executor.Execute(deployStateId, statusManager, taskDefinition, component, environmentComponent, machine, build, runtimeSystemSettings);
}
switch(result.Status)
{
case EnumDeployTaskExecutionResultStatus.Success:
statusManager.Info(deployStateId, string.Format("Step {0}: End {1}, completed successfully", stepCounter, taskDefinition.TaskDefintionName));
break;
case EnumDeployTaskExecutionResultStatus.Error:
statusManager.Info(deployStateId, string.Format("Step {0}: End {1}, failed", stepCounter, taskDefinition.TaskDefintionName));
return; //error error eject!
//break;
case EnumDeployTaskExecutionResultStatus.Warning:
statusManager.Info(deployStateId, string.Format("Step {0}: End {1}, completed with warnings", stepCounter, taskDefinition.TaskDefintionName));
break;
default:
throw new UnknownEnumValueException(result.Status);
}
}
}
private ImpersonationContext BeginImpersonation(string deployStateId, IDeployTaskStatusManager statusManager, DeployEnvironmentConfiguration environmentComponent)
{
if(!string.IsNullOrEmpty(environmentComponent.DeployCredentialsId))
{
var context = _impersonator.BeginImpersonation(environmentComponent.DeployCredentialsId);
statusManager.Info(deployStateId, "Starting impersonation of " + context.Credentials.DisplayValue);
return context;
}
else
{
statusManager.Info(deployStateId, "No impersonation");
return null;
}
}
}
}
| mit | C# |
1d9354970ca9397253736e96cd3f546935250e46 | Update ServiceCollectionExtensions.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core/DependencyInjection/ServiceCollectionExtensions.cs | TIKSN.Framework.Core/DependencyInjection/ServiceCollectionExtensions.cs | using System;
using System.Collections.Generic;
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using TIKSN.Data;
using TIKSN.FileSystem;
namespace TIKSN.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddFrameworkPlatform(
this IServiceCollection services,
IReadOnlyList<MapperProfile> mapperProfiles = null,
Action<IMapperConfigurationExpression> autoMapperConfigurationAction = null)
{
_ = services.AddFrameworkCore();
services.TryAddSingleton<IKnownFolders, KnownFolders>();
mapperProfiles ??= Array.Empty<MapperProfile>();
_ = services.AddAutoMapper(config =>
{
foreach (var mapperProfile in mapperProfiles)
{
config.AddProfile(mapperProfile);
}
autoMapperConfigurationAction?.Invoke(config);
});
return services;
}
}
}
| using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using TIKSN.FileSystem;
namespace TIKSN.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddFrameworkPlatform(this IServiceCollection services)
{
_ = services.AddFrameworkCore();
services.TryAddSingleton<IKnownFolders, KnownFolders>();
return services;
}
}
}
| mit | C# |
8155eb24e540bed48169c8f88b49be85c88464da | add marginally less crappy resolution | anurse/ILspect,anurse/ILspect | src/ILspect.Core/DefaultAssemblyResolver.cs | src/ILspect.Core/DefaultAssemblyResolver.cs | using System;
using System.Collections.Generic;
using System.IO;
using Mono.Cecil;
namespace ILspect
{
public class DefaultAssemblyResolver : IAssemblyResolver
{
private readonly Dictionary<string, AssemblyDefinition> _cache = new Dictionary<string, AssemblyDefinition>();
public AssemblyDefinition Resolve(AssemblyNameReference name)
{
if (_cache.TryGetValue(name.FullName, out var asmDef))
{
return asmDef;
}
return LoadAssembly(name, new ReaderParameters(ReadingMode.Deferred));
}
public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
{
if (_cache.TryGetValue(name.FullName, out var asmDef))
{
return asmDef;
}
return LoadAssembly(name, parameters);
}
public void Register(AssemblyDefinition asmDef)
{
_cache[asmDef.FullName] = asmDef;
}
public void Dispose()
{
}
private AssemblyDefinition LoadAssembly(AssemblyNameReference name, ReaderParameters readerParameters)
{
var path = FindAssembly(name);
if (string.IsNullOrEmpty(path))
{
return null;
}
var asm = AssemblyDefinition.ReadAssembly(path, readerParameters);
Register(asm);
return asm;
}
private string FindAssembly(AssemblyNameReference name)
{
if (name.FullName.Equals("System.Runtime, Version=4.0.20.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"))
{
return Path.Combine(GetNuGetPackageDir(), "system.runtime", "4.3.0", "ref", "netstandard1.3", "System.Runtime.dll");
}
throw new NotSupportedException($"TODO: Find: {name.FullName}");
}
private string GetNuGetPackageDir()
{
var home = Environment.GetEnvironmentVariable("USERPROFILE");
if (string.IsNullOrEmpty(home))
{
home = Environment.GetEnvironmentVariable("HOME");
}
if (string.IsNullOrEmpty(home))
{
throw new NotImplementedException("TODO: Find NuGet Packages!");
}
return Path.Combine(home, ".nuget", "packages");
}
}
} | using System;
using System.Collections.Generic;
using Mono.Cecil;
namespace ILspect
{
public class DefaultAssemblyResolver : IAssemblyResolver
{
private readonly Dictionary<string, AssemblyDefinition> _cache = new Dictionary<string, AssemblyDefinition>();
public AssemblyDefinition Resolve(AssemblyNameReference name)
{
if (_cache.TryGetValue(name.FullName, out var asmDef))
{
return asmDef;
}
return LoadAssembly(name, new ReaderParameters(ReadingMode.Deferred));
}
public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
{
if (_cache.TryGetValue(name.FullName, out var asmDef))
{
return asmDef;
}
return LoadAssembly(name, parameters);
}
public void Register(AssemblyDefinition asmDef)
{
_cache[asmDef.FullName] = asmDef;
}
public void Dispose()
{
}
private AssemblyDefinition LoadAssembly(AssemblyNameReference name, ReaderParameters readerParameters)
{
var path = FindAssembly(name);
if (string.IsNullOrEmpty(path))
{
return null;
}
var asm = AssemblyDefinition.ReadAssembly(path, readerParameters);
Register(asm);
return asm;
}
private string FindAssembly(AssemblyNameReference name)
{
if (name.FullName.Equals("System.Runtime, Version=4.0.20.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"))
{
return @"C:\Users\anurse\.nuget\packages\system.runtime\4.3.0\ref\netstandard1.3\System.Runtime.dll";
}
return null;
}
}
} | apache-2.0 | C# |
ed50c8a94209e54eb7d3fb2de85d60eaf567ff20 | fix RIDER-71376, RIDER-71377, RIDER-71375 (#2224) | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/Rider/UnitTesting/UnityRiderUnitTestCoverageAvailabilityChecker.cs | resharper/resharper-unity/src/Rider/UnitTesting/UnityRiderUnitTestCoverageAvailabilityChecker.cs | using System;
using JetBrains.Application;
using JetBrains.Application.Components;
using JetBrains.RdBackend.Common.Features;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.UnitTestFramework.Elements;
using JetBrains.ReSharper.UnitTestFramework.Execution.Hosting;
using JetBrains.Rider.Backend.Features.UnitTesting;
using JetBrains.Rider.Model.Unity.FrontendBackend;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.UnitTesting
{
[ShellComponent]
public class UnityRiderUnitTestCoverageAvailabilityChecker : IRiderUnitTestCoverageAvailabilityChecker, IHideImplementation<DefaultRiderUnitTestCoverageAvailabilityChecker>
{
private static readonly Version ourMinSupportedUnityVersion = new(2018, 3);
// this method should be very fast as it gets called a lot
public HostProviderAvailability GetAvailability(IUnitTestElement element)
{
if (!element.Project.IsUnityProject())
return HostProviderAvailability.Available;
var solution = element.Project.GetSolution();
var frontendBackendModel = solution.GetProtocolSolution().GetFrontendBackendModel();
switch (frontendBackendModel.UnitTestPreference.Value)
{
case UnitTestLaunchPreference.NUnit:
return HostProviderAvailability.Available;
case UnitTestLaunchPreference.Both:
case UnitTestLaunchPreference.PlayMode:
case UnitTestLaunchPreference.EditMode:
{
var unityVersion = UnityVersion.Parse(frontendBackendModel.UnityApplicationData.Maybe.ValueOrDefault?.ApplicationVersion ?? string.Empty);
return unityVersion == null || unityVersion < ourMinSupportedUnityVersion
? HostProviderAvailability.Nonexistent
: HostProviderAvailability.Available;
}
default:
return HostProviderAvailability.Nonexistent;
}
}
}
} | using System;
using JetBrains.Application;
using JetBrains.Application.Components;
using JetBrains.Collections.Viewable;
using JetBrains.ProjectModel;
using JetBrains.RdBackend.Common.Features;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.UnitTestFramework.Elements;
using JetBrains.ReSharper.UnitTestFramework.Execution.Hosting;
using JetBrains.Rider.Backend.Features.UnitTesting;
using JetBrains.Rider.Model.Unity.FrontendBackend;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.UnitTesting
{
[ShellComponent]
public class UnityRiderUnitTestCoverageAvailabilityChecker : IRiderUnitTestCoverageAvailabilityChecker, IHideImplementation<DefaultRiderUnitTestCoverageAvailabilityChecker>
{
private static readonly Version ourMinSupportedUnityVersion = new(2018, 3);
// this method should be very fast as it gets called a lot
public HostProviderAvailability GetAvailability(IUnitTestElement element)
{
var solution = element.Project.GetSolution();
var tracker = solution.GetComponent<UnitySolutionTracker>();
if (tracker.IsUnityProject.HasValue() && !tracker.IsUnityProject.Value)
return HostProviderAvailability.Available;
var frontendBackendModel = solution.GetProtocolSolution().GetFrontendBackendModel();
switch (frontendBackendModel.UnitTestPreference.Value)
{
case UnitTestLaunchPreference.NUnit:
return HostProviderAvailability.Available;
case UnitTestLaunchPreference.Both:
case UnitTestLaunchPreference.PlayMode:
case UnitTestLaunchPreference.EditMode:
{
var unityVersion = UnityVersion.Parse(frontendBackendModel.UnityApplicationData.Maybe.ValueOrDefault?.ApplicationVersion ?? string.Empty);
return unityVersion == null || unityVersion < ourMinSupportedUnityVersion
? HostProviderAvailability.Nonexistent
: HostProviderAvailability.Available;
}
default:
return HostProviderAvailability.Nonexistent;
}
}
}
} | apache-2.0 | C# |
eef059fb4113b5db1495678c0b71f64dc295e160 | Repair famfamfam-flags | aspnetboilerplate/module-zero-template,aspnetboilerplate/module-zero-template,aspnetboilerplate/module-zero-template | src/AbpCompanyName.AbpProjectName.EntityFramework/Migrations/SeedData/DefaultLanguagesCreator.cs | src/AbpCompanyName.AbpProjectName.EntityFramework/Migrations/SeedData/DefaultLanguagesCreator.cs | using System.Collections.Generic;
using System.Linq;
using Abp.Localization;
using AbpCompanyName.AbpProjectName.EntityFramework;
namespace AbpCompanyName.AbpProjectName.Migrations.SeedData
{
public class DefaultLanguagesCreator
{
public static List<ApplicationLanguage> InitialLanguages { get; private set; }
private readonly AbpProjectNameDbContext _context;
static DefaultLanguagesCreator()
{
InitialLanguages = new List<ApplicationLanguage>
{
new ApplicationLanguage(null, "en", "English", "famfamfam-flags gb"),
new ApplicationLanguage(null, "tr", "Türkçe", "famfamfam-flags tr"),
new ApplicationLanguage(null, "zh-CN", "简体中文", "famfamfam-flags cn"),
new ApplicationLanguage(null, "pt-BR", "Português-BR", "famfamfam-flags br"),
new ApplicationLanguage(null, "es", "Español", "famfamfam-flags es"),
new ApplicationLanguage(null, "fr", "Français", "famfamfam-flags fr"),
new ApplicationLanguage(null, "it", "Italiano", "famfamfam-flags it"),
new ApplicationLanguage(null, "ja", "日本語", "famfamfam-flags jp"),
new ApplicationLanguage(null, "nl-NL", "Nederlands", "famfamfam-flags nl"),
new ApplicationLanguage(null, "lt", "Lietuvos", "famfamfam-flags lt")
};
}
public DefaultLanguagesCreator(AbpProjectNameDbContext context)
{
_context = context;
}
public void Create()
{
CreateLanguages();
}
private void CreateLanguages()
{
foreach (var language in InitialLanguages)
{
AddLanguageIfNotExists(language);
}
}
private void AddLanguageIfNotExists(ApplicationLanguage language)
{
if (_context.Languages.Any(l => l.TenantId == language.TenantId && l.Name == language.Name))
{
return;
}
_context.Languages.Add(language);
_context.SaveChanges();
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Abp.Localization;
using AbpCompanyName.AbpProjectName.EntityFramework;
namespace AbpCompanyName.AbpProjectName.Migrations.SeedData
{
public class DefaultLanguagesCreator
{
public static List<ApplicationLanguage> InitialLanguages { get; private set; }
private readonly AbpProjectNameDbContext _context;
static DefaultLanguagesCreator()
{
InitialLanguages = new List<ApplicationLanguage>
{
new ApplicationLanguage(null, "en", "English", "famfamfam-flag-gb"),
new ApplicationLanguage(null, "tr", "Türkçe", "famfamfam-flag-tr"),
new ApplicationLanguage(null, "zh-CN", "简体中文", "famfamfam-flag-cn"),
new ApplicationLanguage(null, "pt-BR", "Português-BR", "famfamfam-flag-br"),
new ApplicationLanguage(null, "es", "Español", "famfamfam-flag-es"),
new ApplicationLanguage(null, "fr", "Français", "famfamfam-flag-fr"),
new ApplicationLanguage(null, "it", "Italiano", "famfamfam-flag-it"),
new ApplicationLanguage(null, "ja", "日本語", "famfamfam-flag-jp"),
new ApplicationLanguage(null, "nl-NL", "Nederlands", "famfamfam-flag-nl"),
new ApplicationLanguage(null, "lt", "Lietuvos", "famfamfam-flag-lt")
};
}
public DefaultLanguagesCreator(AbpProjectNameDbContext context)
{
_context = context;
}
public void Create()
{
CreateLanguages();
}
private void CreateLanguages()
{
foreach (var language in InitialLanguages)
{
AddLanguageIfNotExists(language);
}
}
private void AddLanguageIfNotExists(ApplicationLanguage language)
{
if (_context.Languages.Any(l => l.TenantId == language.TenantId && l.Name == language.Name))
{
return;
}
_context.Languages.Add(language);
_context.SaveChanges();
}
}
}
| mit | C# |
21e40835e1de662ae0f36aa632632206d231c884 | Update AssemblyInfo.cs | BenVlodgi/VMFParser | VMFParser/Properties/AssemblyInfo.cs | VMFParser/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("VMFParser")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("VMFParser")]
[assembly: AssemblyCopyright("Copyright © Benjamin Thomas Blodgett 2016")]
[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("6140307b-779f-41bb-ae1a-ed009481cd9c")]
// 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")]
| 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("VMFParser")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("VMFParser")]
[assembly: AssemblyCopyright("Copyright © Benjamin Thomas Blodgett 2014")]
[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("6140307b-779f-41bb-ae1a-ed009481cd9c")]
// 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")]
| mit | C# |
0615015c1145af59539bd136d269500f7a914184 | Set obsolete | FlorianRappl/AngleSharp,Livven/AngleSharp,Livven/AngleSharp,FlorianRappl/AngleSharp,zedr0n/AngleSharp.Local,zedr0n/AngleSharp.Local,AngleSharp/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,Livven/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,zedr0n/AngleSharp.Local,FlorianRappl/AngleSharp | AngleSharp/DOM/Html/Head/HTMLBgsoundElement.cs | AngleSharp/DOM/Html/Head/HTMLBgsoundElement.cs | namespace AngleSharp.DOM.Html
{
using System;
/// <summary>
/// Represents the HTML bgsound element.
/// </summary>
[DomHistorical]
sealed class HTMLBgsoundElement : HTMLElement
{
internal HTMLBgsoundElement()
{
_name = Tags.Bgsound;
}
/// <summary>
/// Gets if the node is in the special category.
/// </summary>
protected internal override Boolean IsSpecial
{
get { return true; }
}
}
}
| namespace AngleSharp.DOM.Html
{
using System;
/// <summary>
/// Represents the HTML bgsound element.
/// </summary>
sealed class HTMLBgsoundElement : HTMLElement
{
internal HTMLBgsoundElement()
{
_name = Tags.Bgsound;
}
/// <summary>
/// Gets if the node is in the special category.
/// </summary>
protected internal override Boolean IsSpecial
{
get { return true; }
}
}
}
| mit | C# |
5a0ae0f4ad899aafa281a1e0e0d26824b9ad2b7b | Fix typo in test message. | arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5 | src/Arkivverket.Arkade/Tests/Noark5/NumberOfArchives.cs | src/Arkivverket.Arkade/Tests/Noark5/NumberOfArchives.cs | using System;
using System.Xml;
using Arkivverket.Arkade.Core;
namespace Arkivverket.Arkade.Tests.Noark5
{
public class NumberOfArchives : BaseTest
{
public const string AnalysisKeyArchives = "Archives";
public NumberOfArchives(IArchiveContentReader archiveReader) : base(TestType.Content, archiveReader)
{
}
protected override void Test(Archive archive)
{
using (var reader = XmlReader.Create(ArchiveReader.GetContentAsStream(archive)))
{
int counter = 0;
while (reader.ReadToFollowing("arkiv"))
{
counter++;
}
AddAnalysisResult(AnalysisKeyArchives, counter.ToString());
TestSuccess($"Antall arkiv: {counter}.");
}
}
}
}
| using System;
using System.Xml;
using Arkivverket.Arkade.Core;
namespace Arkivverket.Arkade.Tests.Noark5
{
public class NumberOfArchives : BaseTest
{
public const string AnalysisKeyArchives = "Archives";
public NumberOfArchives(IArchiveContentReader archiveReader) : base(TestType.Content, archiveReader)
{
}
protected override void Test(Archive archive)
{
using (var reader = XmlReader.Create(ArchiveReader.GetContentAsStream(archive)))
{
int counter = 0;
while (reader.ReadToFollowing("arkiv"))
{
counter++;
}
AddAnalysisResult(AnalysisKeyArchives, counter.ToString());
TestSuccess($"Antall arkiver: {counter}.");
}
}
}
}
| agpl-3.0 | C# |
10865457dd21fb95393ff617299b05b37484897c | Use guard statements to reduce deep nesting. | fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,ManufacturingIntelligence/nhibernate-core,lnu/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,lnu/nhibernate-core,nkreipke/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,alobakov/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core | src/NHibernate/Linq/Visitors/VisitorUtil.cs | src/NHibernate/Linq/Visitors/VisitorUtil.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Collections;
using NHibernate.Metadata;
using NHibernate.Type;
using System.Reflection;
using System.Collections.ObjectModel;
namespace NHibernate.Linq.Visitors
{
public class VisitorUtil
{
public static bool IsDynamicComponentDictionaryGetter(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, ISessionFactory sessionFactory, out string memberName)
{
memberName = null;
// A dynamic component must be an IDictionary with a string key.
if (method.Name != "get_Item" || !typeof(IDictionary).IsAssignableFrom(targetObject.Type))
return false;
var key = arguments.First().As<ConstantExpression>();
if (key == null || key.Type != typeof(string))
return false;
// The potential member name
memberName = (string)key.Value;
// Need the owning member (the dictionary).
var member = targetObject.As<MemberExpression>();
if (member == null)
return false;
var metaData = sessionFactory.GetClassMetadata(member.Expression.Type);
if (metaData == null)
return false;
// IDictionary can be mapped as collection or component - is it mapped as a component?
var propertyType = metaData.GetPropertyType(member.Member.Name);
return (propertyType != null && propertyType.IsComponentType);
}
public static bool IsDynamicComponentDictionaryGetter(MethodCallExpression expression, ISessionFactory sessionFactory, out string memberName)
{
return IsDynamicComponentDictionaryGetter(expression.Method, expression.Object, expression.Arguments, sessionFactory, out memberName);
}
public static bool IsDynamicComponentDictionaryGetter(MethodCallExpression expression, ISessionFactory sessionFactory)
{
string memberName;
return IsDynamicComponentDictionaryGetter(expression, sessionFactory, out memberName);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Collections;
using NHibernate.Metadata;
using NHibernate.Type;
using System.Reflection;
using System.Collections.ObjectModel;
namespace NHibernate.Linq.Visitors
{
public class VisitorUtil
{
public static bool IsDynamicComponentDictionaryGetter(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, ISessionFactory sessionFactory, out string memberName)
{
//an IDictionary item getter?
if (method.Name == "get_Item" && typeof(IDictionary).IsAssignableFrom(targetObject.Type))
{//a string constant expression as the argument?
ConstantExpression key = arguments.First().As<ConstantExpression>();
if (key != null && key.Type == typeof(string))
{
//The potential member name
memberName = (string)key.Value;
//need the owning member
MemberExpression member = targetObject.As<MemberExpression>();
if (member != null)
{
IClassMetadata metaData = sessionFactory.GetClassMetadata(member.Expression.Type);
if (metaData != null)
{
// is it mapped as a component?
IType propertyType = metaData.GetPropertyType(member.Member.Name);
return (propertyType != null && propertyType.IsComponentType);
}
}
}
}
memberName = null;
return false;
}
public static bool IsDynamicComponentDictionaryGetter(MethodCallExpression expression, ISessionFactory sessionFactory, out string memberName)
{
return IsDynamicComponentDictionaryGetter(expression.Method, expression.Object, expression.Arguments, sessionFactory, out memberName);
}
public static bool IsDynamicComponentDictionaryGetter(MethodCallExpression expression, ISessionFactory sessionFactory)
{
string memberName;
return IsDynamicComponentDictionaryGetter(expression, sessionFactory, out memberName);
}
}
}
| lgpl-2.1 | C# |
e7c1f4d738811976d76f8391877a135b906e4b36 | Use UIThreadNormalPriority with logging | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.InlineReviews/PullRequestStatusBarPackage.cs | src/GitHub.InlineReviews/PullRequestStatusBarPackage.cs | using System;
using System.Threading;
using System.Runtime.InteropServices;
using GitHub.Logging;
using GitHub.Services;
using GitHub.VisualStudio;
using GitHub.InlineReviews.Services;
using Microsoft.VisualStudio.Shell;
using Serilog;
using Task = System.Threading.Tasks.Task;
namespace GitHub.InlineReviews
{
[Guid(Guids.PullRequestStatusPackageId)]
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[ProvideAutoLoad(Guids.UIContext_Git, PackageAutoLoadFlags.BackgroundLoad)]
public class PullRequestStatusBarPackage : AsyncPackage
{
static readonly ILogger log = LogManager.ForContext<PullRequestStatusBarPackage>();
/// <summary>
/// Initialize the PR status UI on Visual Studio's status bar.
/// </summary>
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
var usageTracker = (IUsageTracker)await GetServiceAsync(typeof(IUsageTracker));
var serviceProvider = (IGitHubServiceProvider)await GetServiceAsync(typeof(IGitHubServiceProvider));
var barManager = new PullRequestStatusBarManager(usageTracker, serviceProvider);
log.Information("SwitchToMainThreadAsync");
await JoinableTaskFactory
.WithPriority(VsTaskRunContext.UIThreadNormalPriority)
.SwitchToMainThreadAsync();
log.Information("StartShowingStatus");
barManager.StartShowingStatus();
}
}
}
| using System;
using System.Threading;
using System.Runtime.InteropServices;
using GitHub.Helpers;
using GitHub.Services;
using GitHub.VisualStudio;
using GitHub.InlineReviews.Services;
using Microsoft.VisualStudio.Shell;
using Task = System.Threading.Tasks.Task;
namespace GitHub.InlineReviews
{
[Guid(Guids.PullRequestStatusPackageId)]
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[ProvideAutoLoad(Guids.UIContext_Git, PackageAutoLoadFlags.BackgroundLoad)]
public class PullRequestStatusBarPackage : AsyncPackage
{
/// <summary>
/// Initialize the PR status UI on Visual Studio's status bar.
/// </summary>
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
var usageTracker = (IUsageTracker)await GetServiceAsync(typeof(IUsageTracker));
var serviceProvider = (IGitHubServiceProvider)await GetServiceAsync(typeof(IGitHubServiceProvider));
var barManager = new PullRequestStatusBarManager(usageTracker, serviceProvider);
await ThreadingHelper.SwitchToMainThreadAsync();
barManager.StartShowingStatus();
}
}
}
| mit | C# |
1ef601f57bb65846bd6051e1e28b2e318526a820 | Store sender link name | ehelse/Helsenorge.Messaging | src/Helsenorge.Messaging/ServiceBus/ServiceBusSender.cs | src/Helsenorge.Messaging/ServiceBus/ServiceBusSender.cs | /*
* Copyright (c) 2020, Norsk Helsenett SF and contributors
* See the file CONTRIBUTORS for details.
*
* This file is licensed under the MIT license
* available at https://raw.githubusercontent.com/helsenorge/Helsenorge.Messaging/master/LICENSE
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Amqp;
using Helsenorge.Messaging.Abstractions;
using Microsoft.Extensions.Logging;
namespace Helsenorge.Messaging.ServiceBus
{
[ExcludeFromCodeCoverage]
internal class ServiceBusSender : CachedAmpqSessionEntity<SenderLink>, IMessagingSender
{
private readonly string _id;
private readonly ILogger _logger;
private readonly string _name;
public ServiceBusSender(ServiceBusConnection connection, string id, ILogger logger) : base(connection)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentException(nameof(id));
}
_id = id;
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_name = $"sender-link-{Guid.NewGuid()}";
}
public string Name => _name;
protected override SenderLink CreateLink(ISession session)
{
return session.CreateSender(Name, Connection.GetEntityName(_id)) as SenderLink;
}
public async Task SendAsync(IMessagingMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (!(message.OriginalObject is Message originalMessage))
{
throw new InvalidOperationException("OriginalObject is not a Message");
}
await new ServiceBusOperationBuilder(_logger, "Send").Build(async () =>
{
await EnsureOpen();
await _link.SendAsync(originalMessage);
}).PerformAsync().ConfigureAwait(false);
}
}
}
| /*
* Copyright (c) 2020, Norsk Helsenett SF and contributors
* See the file CONTRIBUTORS for details.
*
* This file is licensed under the MIT license
* available at https://raw.githubusercontent.com/helsenorge/Helsenorge.Messaging/master/LICENSE
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Amqp;
using Helsenorge.Messaging.Abstractions;
using Microsoft.Extensions.Logging;
namespace Helsenorge.Messaging.ServiceBus
{
[ExcludeFromCodeCoverage]
internal class ServiceBusSender : CachedAmpqSessionEntity<SenderLink>, IMessagingSender
{
private readonly string _id;
private readonly ILogger _logger;
public ServiceBusSender(ServiceBusConnection connection, string id, ILogger logger) : base(connection)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentException(nameof(id));
}
_id = id;
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
protected override SenderLink CreateLink(ISession session)
{
return session.CreateSender($"sender-link-{Guid.NewGuid()}", Connection.GetEntityName(_id)) as SenderLink;
}
public async Task SendAsync(IMessagingMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (!(message.OriginalObject is Message originalMessage))
{
throw new InvalidOperationException("OriginalObject is not a Message");
}
await new ServiceBusOperationBuilder(_logger, "Send").Build(async () =>
{
await EnsureOpen();
await _link.SendAsync(originalMessage);
}).PerformAsync().ConfigureAwait(false);
}
}
}
| mit | C# |
99d7572b8882d37785ae5f5b5375051b656c210e | remove saving of assembly | glenndierckx/RequestHandlers,Smartasses/RequestHandlers | src/RequestHandlers.WebApi.Core/ControllersBuilder.cs | src/RequestHandlers.WebApi.Core/ControllersBuilder.cs | using System;
using System.Reflection;
using System.Reflection.Emit;
namespace RequestHandlers.WebApi.Core
{
public class ControllersBuilder
{
public Assembly CreateControllers(Type webApiRequestProcessor, RequestHandlerDefinition[] requestHandlers, WebApiTypes webApiTypes)
{
var assemblyName = new AssemblyName("Generated");
var moduleName = $"{assemblyName.Name}.dll";
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
var moduleBuilder = assembly.DefineDynamicModule(moduleName, assemblyName.Name + ".dll", true);
var controllerBuilder = new ControllerBuilder(moduleBuilder, webApiRequestProcessor, webApiTypes);
foreach (var requestHandlerDefinition in requestHandlers)
{
controllerBuilder.CreateController(requestHandlerDefinition);
}
return moduleBuilder.Assembly;
}
}
}
| using System;
using System.Reflection;
using System.Reflection.Emit;
namespace RequestHandlers.WebApi.Core
{
public class ControllersBuilder
{
public Assembly CreateControllers(Type webApiRequestProcessor, RequestHandlerDefinition[] requestHandlers, WebApiTypes webApiTypes)
{
var assemblyName = new AssemblyName("Generated");
var moduleName = string.Format("{0}.dll", assemblyName.Name);
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, "c:\\");
var moduleBuilder = assembly.DefineDynamicModule(moduleName, assemblyName.Name + ".dll", true);
var controllerBuilder = new ControllerBuilder(moduleBuilder, webApiRequestProcessor, webApiTypes);
foreach (var requestHandlerDefinition in requestHandlers)
{
controllerBuilder.CreateController(requestHandlerDefinition);
}
assembly.Save(moduleName);
return moduleBuilder.Assembly;
}
}
}
| mit | C# |
0914f05be3d6aa4a4752c8c6c8ef343edde8af9e | Update version info | pveller/Sitecore.FakeDb,hermanussen/Sitecore.FakeDb,sergeyshushlyapin/Sitecore.FakeDb | src/Sitecore.FakeDb/Properties/AssemblyVersionInfo.cs | src/Sitecore.FakeDb/Properties/AssemblyVersionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("0.29.0.0")]
[assembly: AssemblyFileVersion("0.29.0.0")]
[assembly: AssemblyInformationalVersion("0.29.0")] | using System.Reflection;
[assembly: AssemblyVersion("0.28.1.0")]
[assembly: AssemblyFileVersion("0.28.1.0")]
[assembly: AssemblyInformationalVersion("0.28.1")] | mit | C# |
02a8871c8b9f83b5260f127a7a5aac515f188b59 | Fix identifier bug | occar421/OpenTKAnalyzer | src/OpenTKAnalyzer/OpenTKAnalyzer/Utility/Identifier.cs | src/OpenTKAnalyzer/OpenTKAnalyzer/Utility/Identifier.cs | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenTKAnalyzer.Utility
{
static public class Identifier
{
/// <summary>
/// Get identity string of variable.
/// </summary>
/// <param name="expression">expression node</param>
/// <param name="semanticModel">semantic Model</param>
/// <returns>indentity string</returns>
static public string GetVariableString(ExpressionSyntax expression, SemanticModel semanticModel)
{
if (expression == null)
{
return null;
}
if (expression is ElementAccessExpressionSyntax)
{
var identifierSymbol = semanticModel.GetSymbolInfo(expression.ChildNodes().First()).Symbol;
var index = expression.ChildNodes().Skip(1).FirstOrDefault()?.WithoutTrivia();
return identifierSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + index.ToFullString();
}
if (expression is BinaryExpressionSyntax)
{
return null;
}
if (expression is PostfixUnaryExpressionSyntax)
{
return null;
}
if (NumericValueParser.ParseFromExpressionDoubleOrNull(expression as ExpressionSyntax).HasValue) // constant
{
return null;
}
if (expression is PrefixUnaryExpressionSyntax)
{
return null;
}
else
{
return semanticModel.GetSymbolInfo(expression).Symbol?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
}
}
}
} | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenTKAnalyzer.Utility
{
static public class Identifier
{
/// <summary>
/// Get identity string of variable.
/// </summary>
/// <param name="expression">expression node</param>
/// <param name="semanticModel">semantic Model</param>
/// <returns>indentity string</returns>
static public string GetVariableString(ExpressionSyntax expression, SemanticModel semanticModel)
{
if (expression is ElementAccessExpressionSyntax)
{
var identifierSymbol = semanticModel.GetSymbolInfo(expression.ChildNodes().First()).Symbol;
var index = expression.ChildNodes().Skip(1).FirstOrDefault()?.WithoutTrivia();
return identifierSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + index.ToFullString();
}
if (expression is BinaryExpressionSyntax)
{
return null;
}
if (expression is PostfixUnaryExpressionSyntax)
{
return null;
}
if (NumericValueParser.ParseFromExpressionDoubleOrNull(expression as ExpressionSyntax).HasValue) // constant
{
return null;
}
if (expression is PrefixUnaryExpressionSyntax)
{
return null;
}
else
{
return semanticModel.GetSymbolInfo(expression).Symbol?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
}
}
}
} | mit | C# |
b487e00d8da5e2bb7d07697e039dd6c15f89968d | Update CreatedOn or MmodifiedOn properties of tracked entities when saving changes. | vasilvalkov/LanguageSchool,vasilvalkov/LanguageSchool,vasilvalkov/LanguageSchool | LanguageSchoolApp/LanguageSchoolApp.Data/MsSqlDbContext.cs | LanguageSchoolApp/LanguageSchoolApp.Data/MsSqlDbContext.cs | using LanguageSchoolApp.Data.Model;
using LanguageSchoolApp.Data.Model.Contracts;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LanguageSchoolApp.Data
{
public class MsSqlDbContext : IdentityDbContext<User>
{
public MsSqlDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public IDbSet<Course> Courses { get; set; }
public override int SaveChanges()
{
this.ApplyAuditInfoRules();
return base.SaveChanges();
}
private void ApplyAuditInfoRules()
{
foreach (var entry in
this.ChangeTracker.Entries()
.Where(e =>
e.Entity is IAuditable && ((e.State == EntityState.Added) || (e.State == EntityState.Modified))))
{
var entity = (IAuditable)entry.Entity;
if (entry.State == EntityState.Added && entity.CreatedOn == default(DateTime))
{
entity.CreatedOn = DateTime.Now;
}
else
{
entity.ModifiedOn = DateTime.Now;
}
}
}
public static MsSqlDbContext Create()
{
return new MsSqlDbContext();
}
}
}
| using LanguageSchoolApp.Data.Model;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LanguageSchoolApp.Data
{
public class MsSqlDbContext : IdentityDbContext<User>
{
public MsSqlDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public IDbSet<Course> Courses { get; set; }
public static MsSqlDbContext Create()
{
return new MsSqlDbContext();
}
}
}
| mit | C# |
6553d35620e2f7e12fc627ba49e02deb46c75782 | add short description to store app details data model | babelshift/Steam.Models | src/Steam.Models/SteamStore/StoreAppDetailsDataModel.cs | src/Steam.Models/SteamStore/StoreAppDetailsDataModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Steam.Models.SteamStore
{
public class StoreAppDetailsDataModel
{
public string Type { get; set; }
public string Name { get; set; }
public uint SteamAppId { get; set; }
public uint RequiredAge { get; set; }
public bool IsFree { get; set; }
public uint[] Dlc { get; set; }
public string DetailedDescription { get; set; }
public string AboutTheGame { get; set; }
public string ShortDescription { get; set; }
public string SupportedLanguages { get; set; }
public string HeaderImage { get; set; }
public string Website { get; set; }
public dynamic PcRequirements { get; set; }
public dynamic MacRequirements { get; set; }
public dynamic LinuxRequirements { get; set; }
public string[] Developers { get; set; }
public string[] Publishers { get; set; }
public StorePriceOverview PriceOverview { get; set; }
public string[] Packages { get; set; }
public StorePackageGroupModel[] PackageGroups { get; set; }
public StorePlatformsModel Platforms { get; set; }
public StoreMetacriticModel Metacritic { get; set; }
public StoreCategoryModel[] Categories { get; set; }
public StoreGenreModel[] Genres { get; set; }
public StoreScreenshotModel[] Screenshots { get; set; }
public StoreMovieModel[] Movies { get; set; }
public StoreRecommendationsModel Recommendations { get; set; }
public StoreReleaseDateModel ReleaseDate { get; set; }
public StoreSupportInfoModel SupportInfo { get; set; }
public string Background { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Steam.Models.SteamStore
{
public class StoreAppDetailsDataModel
{
public string Type { get; set; }
public string Name { get; set; }
public uint SteamAppId { get; set; }
public uint RequiredAge { get; set; }
public bool IsFree { get; set; }
public uint[] Dlc { get; set; }
public string DetailedDescription { get; set; }
public string AboutTheGame { get; set; }
public string SupportedLanguages { get; set; }
public string HeaderImage { get; set; }
public string Website { get; set; }
public dynamic PcRequirements { get; set; }
public dynamic MacRequirements { get; set; }
public dynamic LinuxRequirements { get; set; }
public string[] Developers { get; set; }
public string[] Publishers { get; set; }
public StorePriceOverview PriceOverview { get; set; }
public string[] Packages { get; set; }
public StorePackageGroupModel[] PackageGroups { get; set; }
public StorePlatformsModel Platforms { get; set; }
public StoreMetacriticModel Metacritic { get; set; }
public StoreCategoryModel[] Categories { get; set; }
public StoreGenreModel[] Genres { get; set; }
public StoreScreenshotModel[] Screenshots { get; set; }
public StoreMovieModel[] Movies { get; set; }
public StoreRecommendationsModel Recommendations { get; set; }
public StoreReleaseDateModel ReleaseDate { get; set; }
public StoreSupportInfoModel SupportInfo { get; set; }
public string Background { get; set; }
}
}
| mit | C# |
d792fb9948cb99a3a0341fac769c2b1cb488eda7 | add comment on removing app_config_detection | BrainCrumbz/NSpec.NetCore,BrainCrumbz/NSpec.NetCore | NSpec/test/Samples/SampleSpecs/Bug/app_config_detection.cs | NSpec/test/Samples/SampleSpecs/Bug/app_config_detection.cs | #if false
// TODO NETCORE appsettings - Probably we could remove this one
// together with appsettings.json: it seems a little bit out of scope
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NSpec;
using System.Configuration;
namespace SampleSpecs.Bug
{
class app_config_detection : nspec
{
void it_finds_app_config()
{
ConfigurationManager.AppSettings["SomeConfigEntry"].should_be("Worky");
}
}
}
#endif
| #if false
// TODO NETCORE appsettings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NSpec;
using System.Configuration;
namespace SampleSpecs.Bug
{
class app_config_detection : nspec
{
void it_finds_app_config()
{
ConfigurationManager.AppSettings["SomeConfigEntry"].should_be("Worky");
}
}
}
#endif
| mit | C# |
80f1fcbd7e7fd811a2cd089a24a4470641a6256c | Update LeControllerOpcode.cs | huysentruitw/win-beacon | src/WinBeacon.Stack/Hci/Opcodes/LeControllerOpcode.cs | src/WinBeacon.Stack/Hci/Opcodes/LeControllerOpcode.cs | /*
* Copyright 2015-2016 Huysentruit Wouter
*
* 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 WinBeacon.Stack.Hci.Opcodes
{
internal enum LeControllerOpcode : ushort
{
SetEventMask = 0x0001,
SetAdvertisingParameters = 0x0006, // http://stackoverflow.com/questions/21124993/is-there-a-way-to-increase-ble-advertisement-frequency-in-bluez
SetAdvertisingData = 0x0008,
SetAdvertisingEnable = 0x000A,
SetScanParameters = 0x000B,
SetScanEnable = 0x000C,
}
}
| /*
* Copyright 2015-2016 Huysentruit Wouter
*
* 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 WinBeacon.Stack.Hci.Opcodes
{
internal enum LeControllerOpcode : ushort
{
SetEventMask = 0x0001,
SetAdvertisingData = 0x0008,
SetAdvertisingEnable = 0x000A,
SetScanParameters = 0x000B,
SetScanEnable = 0x000C,
}
}
| mit | C# |
e6fe7d81406dfcebe37d748480b69b8d588f9d5d | Update version | Yonom/MultiplayerNom | MultiplayerNom/Properties/AssemblyInfo.cs | MultiplayerNom/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("MultiplayerNom")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MultiplayerNom")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("668508d7-b8f6-4050-91b9-c345fe2132fe")]
// 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.1.0")]
[assembly: AssemblyFileVersion("1.0.1.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("MultiplayerNom")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MultiplayerNom")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("668508d7-b8f6-4050-91b9-c345fe2132fe")]
// 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# |
1c2d213db4741dcfe50d62dbfc39ad17bb867411 | fix unit test | punker76/Markdown-Edit,dsuess/Markdown-Edit,chris84948/Markdown-Edit,mike-ward/Markdown-Edit,Tdue21/Markdown-Edit | src/UnitTests/Models/UtilityTests.cs | src/UnitTests/Models/UtilityTests.cs | using System;
using FluentAssertions;
using MarkdownEdit.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests.Models
{
[TestClass]
public class UtilityTests
{
[TestMethod]
public void MemoizeShouldReturnFunction()
{
Func<int, int> func = i => i;
var result = func.Memoize();
result.Should().NotBeNull();
}
[TestMethod]
public void DebouceShouldReturnFunction()
{
Action<int> func = i => { };
var result = func.Debounce();
result.Should().NotBeNull();
}
[TestMethod]
public void SeparateFrontMatterTest()
{
const string text =
@"---
layout: page
title: Downloads
---
### (a.k.a. The Goods)
A Windows Desktop Markdown Editor[Read more...](/ markdownedit)";
var tuple = Utility.SeperateFrontMatter(text);
tuple.Item1.Should().EndWith($"---{Environment.NewLine}{Environment.NewLine}");
tuple.Item2.Should().StartWith("###");
}
[TestMethod]
public void SuggestTitleTest()
{
const string text =
@"---
layout: page
title: ""Friday Links #357""
---
### (a.k.a. The Goods)
A Windows Desktop Markdown Editor[Read more...](/ markdownedit)";
var match = DateTime.Now.ToString("yyyy-MM-dd-") + "friday-links-357";
var title = Utility.SuggestFilenameFromTitle(text);
title.Should().Be(match);
}
}
} | using System;
using FluentAssertions;
using MarkdownEdit.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests.Models
{
[TestClass]
public class UtilityTests
{
[TestMethod]
public void MemoizeShouldReturnFunction()
{
Func<int, int> func = i => i;
var result = func.Memoize();
result.Should().NotBeNull();
}
[TestMethod]
public void DebouceShouldReturnFunction()
{
Action<int> func = i => { };
var result = func.Debounce();
result.Should().NotBeNull();
}
[TestMethod]
public void SeparateFrontMatterTest()
{
const string text =
@"---
layout: page
title: Downloads
---
### (a.k.a. The Goods)
A Windows Desktop Markdown Editor[Read more...](/ markdownedit)";
var tuple = Utility.SeperateFrontMatter(text);
tuple.Item1.Should().EndWith("---\r\n\r\n");
tuple.Item2.Should().StartWith("###");
}
[TestMethod]
public void SuggestTitleTest()
{
const string text =
@"---
layout: page
title: ""Friday Links #357""
---
### (a.k.a. The Goods)
A Windows Desktop Markdown Editor[Read more...](/ markdownedit)";
var match = DateTime.Now.ToString("yyyy-MM-dd-") + "friday-links-357";
var title = Utility.SuggestFilenameFromTitle(text);
title.Should().Be(match);
}
}
} | mit | C# |
0470f38fcbf39f532d3b8958b895a620c33055e3 | Update FieldGroupDescriptor.cs | CanadianBeaver/DataViewExtenders | Source/DataDescriptors/FieldGroupDescriptor.cs | Source/DataDescriptors/FieldGroupDescriptor.cs | using System;
using System.Data;
namespace CBComponents.DataDescriptors
{
/// <summary>
/// Width size of column or field
/// </summary>
public enum DataDescriptorSizeWidth : int
{
Smaller = 45,
Small = 90,
Medium = 135,
Normal = 225,
Large = 320,
Larger = 360
}
/// <summary>
/// DataDescriptor of groups on the Panel
/// </summary>
public class GroupDataDescriptor
{
public string CaptionText { get; set; }
public FieldDataDescriptor[] Fields { get; set; }
public HeaderTableLayoutPanel.HighlightCaptionStyle CaptionStyle { get; set; } = HeaderTableLayoutPanel.HighlightCaptionStyle.HighlightColor;
private const HeaderTableLayoutPanel.HighlightCaptionStyle _defaultHighlightCaptionStyle = HeaderTableLayoutPanel.HighlightCaptionStyle.HighlightColor;
private const int _defaultSizeWidth = (int)DataDescriptorSizeWidth.Smaller / 2;
public GroupDataDescriptor(string CaptionText, HeaderTableLayoutPanel.HighlightCaptionStyle CaptionStyle, int SizeWidth, params FieldDataDescriptor[] Fields)
{
this.CaptionText = CaptionText;
this.CaptionStyle = CaptionStyle;
if (SizeWidth > _defaultSizeWidth)
foreach (var field in Fields)
if (!field.SizeWidth.HasValue)
field.SizeWidth = SizeWidth;
this.Fields = Fields;
}
public GroupDataDescriptor(string CaptionText, HeaderTableLayoutPanel.HighlightCaptionStyle CaptionStyle, DataDescriptorSizeWidth SizeWidth, params FieldDataDescriptor[] Fields)
: this(CaptionText, CaptionStyle, (int)SizeWidth, Fields)
{
}
public GroupDataDescriptor(string CaptionText, params FieldDataDescriptor[] Fields)
: this(CaptionText, _defaultHighlightCaptionStyle, _defaultSizeWidth, Fields)
{
}
public GroupDataDescriptor(string CaptionText, HeaderTableLayoutPanel.HighlightCaptionStyle CaptionStyle, params FieldDataDescriptor[] Fields)
: this(CaptionText, CaptionStyle, _defaultSizeWidth, Fields)
{
}
public GroupDataDescriptor(string CaptionText, int SizeWidth, params FieldDataDescriptor[] Fields)
: this(CaptionText, _defaultHighlightCaptionStyle, SizeWidth, Fields)
{
}
public GroupDataDescriptor(string CaptionText, DataDescriptorSizeWidth SizeWidth, params FieldDataDescriptor[] Fields)
: this(CaptionText, _defaultHighlightCaptionStyle, (int)SizeWidth, Fields)
{
}
/// <summary>
/// Resulted Panel after generation
/// </summary>
public System.Windows.Forms.Panel GeneratedPanel = null;
}
}
| using System;
using System.Data;
namespace CBComponents.DataDescriptors
{
/// <summary>
/// Width size of column or field
/// </summary>
public enum DataDescriptorSizeWidth : int
{
Smaller = 45,
Small = 90,
Medium = 135,
Normal = 225,
Large = 320,
Larger = 360
}
/// <summary>
/// DataDescriptor of groups on the Panel
/// </summary>
public class GroupDataDescriptor
{
public string CaptionText { get; set; }
public FieldDataDescriptor[] Fields { get; set; }
public HeaderTableLayoutPanel.HighlightCaptionStyle CaptionStyle { get; set; } = HeaderTableLayoutPanel.HighlightCaptionStyle.HighlightColor;
private const HeaderTableLayoutPanel.HighlightCaptionStyle _defaultHighlightCaptionStyle = HeaderTableLayoutPanel.HighlightCaptionStyle.HighlightColor;
private const int _defaultSizeWidth = (int)DataDescriptorSizeWidth.Smaller / 2;
public GroupDataDescriptor(string CaptionText, HeaderTableLayoutPanel.HighlightCaptionStyle CaptionStyle, int SizeWidth, params FieldDataDescriptor[] Fields)
{
this.CaptionText = CaptionText;
this.CaptionStyle = CaptionStyle;
if (SizeWidth > _defaultSizeWidth)
foreach (var field in Fields)
if (!field.SizeWidth.HasValue)
field.SizeWidth = SizeWidth;
this.Fields = Fields;
}
public GroupDataDescriptor(string CaptionText, HeaderTableLayoutPanel.HighlightCaptionStyle CaptionStyle, DataDescriptorSizeWidth SizeWidth, params FieldDataDescriptor[] Fields)
: this(CaptionText, CaptionStyle, (int)SizeWidth, Fields)
{
}
public GroupDataDescriptor(string CaptionText, params FieldDataDescriptor[] Fields)
: this(CaptionText, _defaultHighlightCaptionStyle, _defaultSizeWidth, Fields)
{
}
public GroupDataDescriptor(string CaptionText, HeaderTableLayoutPanel.HighlightCaptionStyle CaptionStyle, params FieldDataDescriptor[] Fields)
: this(CaptionText, CaptionStyle, _defaultSizeWidth, Fields)
{
}
public GroupDataDescriptor(string CaptionText, int SizeWidth, params FieldDataDescriptor[] Fields)
: this(CaptionText, _defaultHighlightCaptionStyle, SizeWidth, Fields)
{
}
public GroupDataDescriptor(string CaptionText, DataDescriptorSizeWidth SizeWidth, params FieldDataDescriptor[] Fields)
: this(CaptionText, _defaultHighlightCaptionStyle, (int)SizeWidth, Fields)
{
}
/// <summary>
/// Resulted Panel after generation
/// </summary>
public System.Windows.Forms.Panel GeneratedPanel = null;
}
}
| mit | C# |
1861c69d0c77a8a16672af63bf1cc80da7a0982e | Update index.cshtml | Aleksandrovskaya/apmathclouddif | site/index.cshtml | site/index.cshtml | @{
double t_0 = 0;
double t_end = 150;
double step = 0.1;
int N = Convert.ToInt32((t_end-t_0)/step) + 1;
String data = "";
bool show_chart = false;
if (IsPost){
show_chart = true;
var number = Request["text1"];
double xd = number.AsInt();
double t = 0;
double x1 = 0;
double x2 = 0;
double x3 = 0;
double currentx1 = 0;
double currentx2 = 0;
double currentx3 = 0;
for (int i=0; i < N; ++i){
t = t_0 + step * i;
currentx1 = x1 + step* (-0.1252*x1 + -0.004637*(x2-xd)+-0.002198*x3);
currentx2 = x2 + step*x1 ;
currentx3= x3 + step*(10*x1 + -0.2*x3 +1*(x2-xd));
x1 = currentx1;
x2 = currentx2;
x3 = currentx3;
data += "[" +t+"," + x2+"]";
if( i < N - 1){
data += ",";
}
}
}
}
<html>
<head>
<meta charset="utf-8">
<title>MathBox</title>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={
'modules':[{
'name':'visualization',
'version':'1',
'packages':['corechart']
}]
}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Time', 'pitch'],
@data
]);
var options = {
title: 'pitch',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form action="" method="post" align="center">
<p><label for="text1">Input Angle</label><br>
<input type="text" name="text1" /></p>
<p><input type="submit" value=" Show " /></p>
</form>
@if (show_chart)
{
<div id="curve_chart" style="width: 900px; height: 500px" align="center"></div>
}
else
{
<p></p>
}
</body>
</html>
| @{
double t_0 = 0;
double t_end = 150;
double step = 0.1;
int N = Convert.ToInt32((t_end-t_0)/step) + 1;
String data = "";
bool show_chart = false;
if (IsPost){
show_chart = true;
var number = Request["text1"];
double xd = number.AsInt();
double t = 0;
double x1 = 0;
double x2 = 0;
double x3 = 0;
double currentx1 = 0;
double currentx2 = 0;
double currentx3 = 0;
for (int i=0; i < N; ++i){
t = t_0 + step * i;
currentx1 = x1 + step* (-0.1252*x1 + -0.004637*(x2-xd)+-0.002198*x3);
currentx2 = x2 + step*x1 ;
currentx3= x3 + step*(10*x1 + -0.2*x3 +1*(x2-xd));
x1 = currentx1;
x2 = currentx2;
x3 = currentx3;
data += "[" +t+"," + x2+"]";
if( i < N - 1){
data += ",";
}
}
}
}
<html>
<head>
<meta charset="utf-8">
<title>MathBox</title>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={
'modules':[{
'name':'visualization',
'version':'1',
'packages':['corechart']
}]
}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Time', 'pitch'],
@data
]);
var options = {
title: 'pitch',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form action="" method="post" align="center">
<p><label for="text1">Input Angle</label><br>
<input type="text" name="text1" /></p>
<p><input type="submit" value=" Show " /></p>
</form>
@if (show_chart)
{
<div id="curve_chart" style="width: 900px; height: 500px"></div>
}
else
{
<p></p>
}
</body>
</html>
| mit | C# |
35669b0853b7585fbcda040490f5b40be490abeb | Update TypeCachingKey.cs (#426) | elastacloud/parquet-dotnet | src/Parquet/Serialization/Values/TypeCachingKey.cs | src/Parquet/Serialization/Values/TypeCachingKey.cs | using System;
using System.Collections.Generic;
using System.Text;
using Parquet.Data;
namespace Parquet.Serialization.Values
{
class TypeCachingKey : IEquatable<TypeCachingKey>
{
public TypeCachingKey(Type classType, DataField field)
{
ClassType = classType ?? throw new ArgumentNullException(nameof(classType));
Field = field ?? throw new ArgumentNullException(nameof(field));
}
public Type ClassType { get; }
public DataField Field { get; }
public bool Equals(TypeCachingKey other)
{
if (ReferenceEquals(other, null)) return false;
if (ReferenceEquals(other, this)) return true;
return ClassType.Equals(other.ClassType) && Field.Equals(other.Field);
}
public override int GetHashCode()
{
return 31 * ClassType.GetHashCode() + Field.GetHashCode();
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Parquet.Data;
namespace Parquet.Serialization.Values
{
class TypeCachingKey : IEquatable<TypeCachingKey>
{
public TypeCachingKey(Type classType, DataField field)
{
ClassType = classType ?? throw new ArgumentNullException(nameof(classType));
Field = field ?? throw new ArgumentNullException(nameof(field));
}
public Type ClassType { get; }
public DataField Field { get; }
public bool Equals(TypeCachingKey other)
{
if (ReferenceEquals(other, null)) return false;
if (ReferenceEquals(other, this)) return true;
return ClassType.Equals(other.ClassType) && Field.Equals(other.Field);
}
}
}
| mit | C# |
3c0da09d0aff36a7047375fa50a6318226bb4139 | Add another subdir | genlu/roslyn,genlu/roslyn,bartdesmet/roslyn,weltkante/roslyn,brettfo/roslyn,agocke/roslyn,stephentoub/roslyn,weltkante/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,tmat/roslyn,diryboy/roslyn,KirillOsenkov/roslyn,tmat/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,dotnet/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,jmarolf/roslyn,eriawan/roslyn,brettfo/roslyn,heejaechang/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,dotnet/roslyn,eriawan/roslyn,gafter/roslyn,abock/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,abock/roslyn,tannergooding/roslyn,heejaechang/roslyn,aelij/roslyn,mavasani/roslyn,dotnet/roslyn,AmadeusW/roslyn,tannergooding/roslyn,gafter/roslyn,ErikSchierboom/roslyn,jmarolf/roslyn,davkean/roslyn,KirillOsenkov/roslyn,aelij/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,physhi/roslyn,agocke/roslyn,ErikSchierboom/roslyn,physhi/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,AmadeusW/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,reaction1989/roslyn,reaction1989/roslyn,KirillOsenkov/roslyn,aelij/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,reaction1989/roslyn,eriawan/roslyn,panopticoncentral/roslyn,panopticoncentral/roslyn,physhi/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,tmat/roslyn,davkean/roslyn,heejaechang/roslyn,mgoertz-msft/roslyn,genlu/roslyn,panopticoncentral/roslyn,davkean/roslyn,weltkante/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,agocke/roslyn,wvdd007/roslyn,abock/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,sharwell/roslyn,stephentoub/roslyn,KevinRansom/roslyn,jmarolf/roslyn | src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorageLocationService.cs | src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorageLocationService.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Host
{
interface IPersistentStorageLocationService : IWorkspaceService
{
string? TryGetStorageLocation(Solution solution);
}
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService
{
[ImportingConstructor]
public DefaultPersistentStorageLocationService()
{
}
public string? TryGetStorageLocation(Solution solution)
{
if (string.IsNullOrWhiteSpace(solution.FilePath))
return null;
// Ensure that each unique workspace kind for any given solution has a unique
// folder to store their data in.
// Store in the LocalApplicationData/Roslyn/hash folder (%appdatalocal%/... on Windows,
// ~/.local/share/... on unix). This will place the folder in a location we can trust
// to be able to get back to consistently as long as we're working with the same
// solution and the same workspace kind.
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create);
var kind = StripInvalidPathChars(solution.Workspace.Kind ?? "");
var hash = StripInvalidPathChars(Checksum.Create(solution.FilePath).ToString());
return Path.Combine(appDataFolder, "Roslyn", "Cache", kind, hash);
static string StripInvalidPathChars(string val)
{
var invalidPathChars = Path.GetInvalidPathChars();
val = new string(val.Where(c => !invalidPathChars.Contains(c)).ToArray());
return string.IsNullOrWhiteSpace(val) ? "None" : val;
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Host
{
interface IPersistentStorageLocationService : IWorkspaceService
{
string? TryGetStorageLocation(Solution solution);
}
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService
{
[ImportingConstructor]
public DefaultPersistentStorageLocationService()
{
}
public string? TryGetStorageLocation(Solution solution)
{
if (string.IsNullOrWhiteSpace(solution.FilePath))
return null;
// Ensure that each unique workspace kind for any given solution has a unique
// folder to store their data in.
// Store in the LocalApplicationData/Roslyn/hash folder (%appdatalocal%/... on Windows,
// ~/.local/share/... on unix). This will place the folder in a location we can trust
// to be able to get back to consistently as long as we're working with the same
// solution and the same workspace kind.
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create);
var kind = StripInvalidPathChars(solution.Workspace.Kind ?? "");
var hash = StripInvalidPathChars(Checksum.Create(solution.FilePath).ToString());
return Path.Combine(appDataFolder, "Roslyn", kind, hash);
static string StripInvalidPathChars(string val)
{
var invalidPathChars = Path.GetInvalidPathChars();
val = new string(val.Where(c => !invalidPathChars.Contains(c)).ToArray());
return string.IsNullOrWhiteSpace(val) ? "None" : val;
}
}
}
}
| mit | C# |
eb1a149d4027aa4f37a7c0f0dd5feccc6e1ff4dd | Revert "Removed Guid from iOS project" | cschwarz/AppShell,cschwarz/AppShell | src/AppShell.Mobile.iOS/Properties/AssemblyInfo.cs | src/AppShell.Mobile.iOS/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("AppShell.Mobile.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AppShell.Mobile.iOS")]
[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("ecceafc0-b15a-4932-99ec-36315a4e82e7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.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("AppShell.Mobile.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AppShell.Mobile.iOS")]
[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)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0.0")]
| mit | C# |
f7079974c45d1abdd64b6b3be8b865abb4f8acb1 | update TotpHelperTest | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | test/WeihanLi.Common.Test/HelpersTest/TotpHelperTest.cs | test/WeihanLi.Common.Test/HelpersTest/TotpHelperTest.cs | using System.Threading;
using WeihanLi.Common.Helpers;
using Xunit;
namespace WeihanLi.Common.Test.HelpersTest
{
public class TotpHelperTest
{
private readonly object _lock = new object();
[Fact]
public void Test()
{
lock (_lock)
{
TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = null;
options.ExpiresIn = 300;
});
var bizToken = "test_xxx";
var code = TotpHelper.GenerateCode(bizToken);
Thread.Sleep(2000);
Assert.NotEmpty(code);
Assert.True(TotpHelper.VerifyCode(bizToken, code));
}
}
[Fact]
public void SaltTest()
{
lock (_lock)
{
var bizToken = "test_xxx";
TotpHelper.ConfigureTotpOptions(options => options.Salt = null);
var code = TotpHelper.GenerateCode(bizToken);
TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = "amazing-dotnet";
options.ExpiresIn = 300;
});
var code1 = TotpHelper.GenerateCode(bizToken);
Thread.Sleep(2000);
Assert.NotEmpty(code);
Assert.False(TotpHelper.VerifyCode(bizToken, code));
Assert.NotEmpty(code1);
Assert.True(TotpHelper.VerifyCode(bizToken, code1));
}
}
}
}
| using System.Threading;
using WeihanLi.Common.Helpers;
using Xunit;
namespace WeihanLi.Common.Test.HelpersTest
{
public class TotpHelperTest
{
[Fact]
public void Test()
{
lock (TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = null;
options.ExpiresIn = 300;
}))
{
var bizToken = "test_xxx";
var code = TotpHelper.GenerateCode(bizToken);
Thread.Sleep(2000);
Assert.NotEmpty(code);
Assert.True(TotpHelper.VerifyCode(bizToken, code));
}
}
[Fact]
public void SaltTest()
{
var bizToken = "test_xxx";
string code;
lock (TotpHelper.ConfigureTotpOptions(options => options.Salt = null))
{
code = TotpHelper.GenerateCode(bizToken);
}
lock (TotpHelper.ConfigureTotpOptions(options =>
{
options.Salt = "amazing-dotnet";
options.ExpiresIn = 300;
}))
{
var code1 = TotpHelper.GenerateCode(bizToken);
Thread.Sleep(2000);
Assert.NotEmpty(code);
Assert.False(TotpHelper.VerifyCode(bizToken, code));
Assert.NotEmpty(code1);
Assert.True(TotpHelper.VerifyCode(bizToken, code1));
}
}
}
}
| mit | C# |
77915c933a58e28f1f7029c8a362683324f58261 | Remove not used code | jeffijoe/messageformat.net | src/Jeffijoe.MessageFormat/Formatting/Formatters/PluralRulesMetadata.cs | src/Jeffijoe.MessageFormat/Formatting/Formatters/PluralRulesMetadata.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Jeffijoe.MessageFormat.Formatting.Formatters
{
public static partial class PluralRulesMetadata
{
public static partial bool TryGetRuleByLocale(string locale, out Pluralizer pluralizer);
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Jeffijoe.MessageFormat.Formatting.Formatters
{
public static partial class PluralRulesMetadata
{
public static string DefaultPluralRule(double number)
{
if(number == 0)
{
return "zero";
}
if(number == 1)
{
return "one";
}
return "other";
}
public static partial bool TryGetRuleByLocale(string locale, out Pluralizer pluralizer);
}
}
| mit | C# |
02307143cae118cab71eec07899327caa8161e85 | Remove + cleanup warnings. Refactor pass. | drawcode/game-lib-engine | Engine/BaseEngine.cs | Engine/BaseEngine.cs | using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace Engine {
public class BaseEngine : BaseEngineObject {
public BaseEngine() {
}
public virtual void Tick(float deltaTime) {
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace Engine {
public class BaseEngine : BaseEngineObject {
public BaseEngine() {
}
public virtual void Tick(float deltaTime) {
}
}
} | mit | C# |
7e1c2f3d430779851bbdb9e719f39b52d269d5af | Add ToPlanetUpdate method to Planet class | andrii1812/galcon-server,andrii1812/galcon-server,andrii1812/galcon-server,andrii1812/galcon-server | src/Core/Planet.cs | src/Core/Planet.cs | using System;
namespace GalconServer.Core
{
public class Planet
{
public int ID { get; set; }
public Size Size { get; set; }
public double Population { get; set; }
public double X { get; set; }
public double Y { get; set; }
public int Owner { get; set; }
public Planet(int id, Size size, double population, double x, double y, int owner)
{
ID = id;
Size = size;
Population = population;
X = x;
Y = y;
Owner = owner;
}
public static Planet GenerateRandomPlanet(int id, Size size, int owner)
{
var rnd = new Random(DateTime.Now.Millisecond);
double population = rnd.Next(0, 100);
double x = rnd.NextDouble();
double y = rnd.NextDouble();
return new Planet(id, size, population, x, y, owner);
}
public PlanetUpdate ToPlanetUpdate()
{
return new PlanetUpdate(ID, Population, Owner);
}
}
}
| using System;
namespace GalconServer.Core
{
public class Planet
{
public int ID { get; set; }
public Size Size { get; set; }
public double Population { get; set; }
public double X { get; set; }
public double Y { get; set; }
public int Owner { get; set; }
public Planet(int id, Size size, double population, double x, double y, int owner)
{
ID = id;
Size = size;
Population = population;
X = x;
Y = y;
Owner = owner;
}
public static Planet GenerateRandomPlanet(int id, Size size, int owner)
{
var rnd = new Random(DateTime.Now.Millisecond);
double population = rnd.Next(0, 100);
double x = rnd.NextDouble();
double y = rnd.NextDouble();
return new Planet(id, size, population, x, y, owner);
}
}
}
| apache-2.0 | C# |
2f2ee85cdd366f64377835d3bcdd1b89b952996e | Update Maybe functionality | beardgame/utilities | src/Core/Maybe.cs | src/Core/Maybe.cs | using System;
namespace Bearded.Utilities
{
public struct Maybe<T>
{
private readonly bool hasValue;
private readonly T value;
private Maybe(T value)
{
hasValue = true;
this.value = value;
}
public static Maybe<T> Nothing() => new Maybe<T>();
public static Maybe<T> Just(T value) => new Maybe<T>(value);
public T ValueOrDefault(T @default) => hasValue ? value : @default;
public Maybe<TOut> Select<TOut>(Func<T, TOut> map) => hasValue ? Maybe.Just(map(value)) : Maybe<TOut>.Nothing();
public Maybe<TOut> SelectMany<TOut>(Func<T, Maybe<TOut>> map) => hasValue ? map(value) : Maybe<TOut>.Nothing();
public void Consume(Action<T> action)
{
Match(onValue: action, onNothing: () => { });
}
public void Match(Action<T> onValue, Action onNothing)
{
if (hasValue)
{
onValue(value);
}
else
{
onNothing();
}
}
}
public static class Maybe
{
public static Maybe<T> FromNullable<T>(T value) where T : class =>
value == null ? Maybe<T>.Nothing() : Maybe<T>.Just(value);
public static Maybe<T> FromNullable<T>(T? value) where T : struct =>
value.HasValue ? Maybe<T>.Just(value.Value) : Maybe<T>.Nothing();
public static Maybe<T> Just<T>(T value) => Maybe<T>.Just(value);
}
}
| using System;
namespace Bearded.Utilities
{
public struct Maybe<T>
{
private bool hasValue;
private T value;
private Maybe(T value)
{
hasValue = true;
this.value = value;
}
public static Maybe<T> Nothing() => new Maybe<T>();
public static Maybe<T> Just(T value) => new Maybe<T>(value);
public T OrElse(T @default) => hasValue ? value : @default;
public T OrThrow(Func<Exception> exceptionProvider) => hasValue ? value : throw exceptionProvider();
public Maybe<TOut> Map<TOut>(Func<T, TOut> map) =>
hasValue ? new Maybe<TOut>(map(value)) : Maybe<TOut>.Nothing();
public Maybe<TOut> FlatMap<TOut>(Func<T, Maybe<TOut>> map) => hasValue ? map(value) : Maybe<TOut>.Nothing();
}
}
| mit | C# |
41b0d13d4ad2dbe5db0140f4753d40bea995f453 | Remove unnecessary call to Trim | magicmonty/pickles,dirkrombauts/pickles,blorgbeard/pickles,magicmonty/pickles,picklesdoc/pickles,picklesdoc/pickles,dirkrombauts/pickles,magicmonty/pickles,blorgbeard/pickles,blorgbeard/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,blorgbeard/pickles,ludwigjossieaux/pickles,magicmonty/pickles,picklesdoc/pickles,dirkrombauts/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles | src/Pickles/Pickles/ObjectModel/KeywordResolver.cs | src/Pickles/Pickles/ObjectModel/KeywordResolver.cs | using System;
using System.Linq;
using AutoMapper;
namespace PicklesDoc.Pickles.ObjectModel
{
public class KeywordResolver : ITypeConverter<string, Keyword>
{
private readonly string language;
public KeywordResolver(string language)
{
this.language = language;
}
public Keyword Convert(ResolutionContext context)
{
string source = (string) context.SourceValue;
return this.MapToKeyword(source);
}
private Keyword MapToKeyword(string keyword)
{
keyword = keyword.Trim();
var gherkinDialect = new LanguageServices(new Configuration() { Language = this.language });
if (gherkinDialect.WhenStepKeywords.Contains(keyword))
{
return Keyword.When;
}
if (gherkinDialect.GivenStepKeywords.Contains(keyword))
{
return Keyword.Given;
}
if (gherkinDialect.ThenStepKeywords.Select(s => s.Trim()).Contains(keyword))
{
return Keyword.Then;
}
if (gherkinDialect.AndStepKeywords.Select(s => s.Trim()).Contains(keyword))
{
return Keyword.And;
}
if (gherkinDialect.ButStepKeywords.Select(s => s.Trim()).Contains(keyword))
{
return Keyword.But;
}
throw new ArgumentOutOfRangeException("keyword");
}
}
} | using System;
using System.Linq;
using AutoMapper;
namespace PicklesDoc.Pickles.ObjectModel
{
public class KeywordResolver : ITypeConverter<string, Keyword>
{
private readonly string language;
public KeywordResolver(string language)
{
this.language = language;
}
public Keyword Convert(ResolutionContext context)
{
string source = (string) context.SourceValue;
return this.MapToKeyword(source);
}
private Keyword MapToKeyword(string keyword)
{
keyword = keyword.Trim();
var gherkinDialect = new LanguageServices(new Configuration() { Language = this.language });
if (gherkinDialect.WhenStepKeywords.Select(s => s.Trim()).Contains(keyword))
{
return Keyword.When;
}
if (gherkinDialect.GivenStepKeywords.Select(s => s.Trim()).Contains(keyword))
{
return Keyword.Given;
}
if (gherkinDialect.ThenStepKeywords.Select(s => s.Trim()).Contains(keyword))
{
return Keyword.Then;
}
if (gherkinDialect.AndStepKeywords.Select(s => s.Trim()).Contains(keyword))
{
return Keyword.And;
}
if (gherkinDialect.ButStepKeywords.Select(s => s.Trim()).Contains(keyword))
{
return Keyword.But;
}
throw new ArgumentOutOfRangeException("keyword");
}
}
} | apache-2.0 | C# |
11a56e9e40770cc282f1ba4161cd11512e0a3745 | Make repository disposable | wilcommerce/Wilcommerce.Core | src/Wilcommerce.Core.Infrastructure/IRepository.cs | src/Wilcommerce.Core.Infrastructure/IRepository.cs | using System;
using System.Threading.Tasks;
namespace Wilcommerce.Core.Infrastructure
{
/// <summary>
/// Represents a generic repository for the aggregate's persistence
/// </summary>
public interface IRepository : IDisposable
{
/// <summary>
/// Add an aggregate to the repository
/// </summary>
/// <typeparam name="TModel">The aggregate's type</typeparam>
/// <param name="model">The aggregate to add</param>
void Add<TModel>(TModel model) where TModel : IAggregateRoot;
/// <summary>
/// Gets the aggregate based on the specified key
/// </summary>
/// <typeparam name="TModel">The aggregate's type</typeparam>
/// <param name="key">The key of the aggregate to search</param>
/// <returns>The aggregate found</returns>
TModel GetByKey<TModel>(Guid key) where TModel : IAggregateRoot;
/// <summary>
/// Async method. Gets the aggregate based on the specified key
/// </summary>
/// <typeparam name="TModel">The aggregate's type</typeparam>
/// <param name="key">The key of the aggregate to search</param>
/// <returns>The aggregate found</returns>
Task<TModel> GetByKeyAsync<TModel>(Guid key) where TModel : IAggregateRoot;
/// <summary>
/// Saves all the changes made on the aggregate
/// </summary>
void SaveChanges();
/// <summary>
/// Async method. Saves all the changes made on the aggregate
/// </summary>
/// <returns></returns>
Task SaveChangesAsyc();
}
}
| using System;
using System.Threading.Tasks;
namespace Wilcommerce.Core.Infrastructure
{
/// <summary>
/// Represents a generic repository for the aggregate's persistence
/// </summary>
public interface IRepository
{
/// <summary>
/// Add an aggregate to the repository
/// </summary>
/// <typeparam name="TModel">The aggregate's type</typeparam>
/// <param name="model">The aggregate to add</param>
void Add<TModel>(TModel model) where TModel : IAggregateRoot;
/// <summary>
/// Gets the aggregate based on the specified key
/// </summary>
/// <typeparam name="TModel">The aggregate's type</typeparam>
/// <param name="key">The key of the aggregate to search</param>
/// <returns>The aggregate found</returns>
TModel GetByKey<TModel>(Guid key) where TModel : IAggregateRoot;
/// <summary>
/// Async method. Gets the aggregate based on the specified key
/// </summary>
/// <typeparam name="TModel">The aggregate's type</typeparam>
/// <param name="key">The key of the aggregate to search</param>
/// <returns>The aggregate found</returns>
Task<TModel> GetByKeyAsync<TModel>(Guid key) where TModel : IAggregateRoot;
/// <summary>
/// Saves all the changes made on the aggregate
/// </summary>
void SaveChanges();
/// <summary>
/// Async method. Saves all the changes made on the aggregate
/// </summary>
/// <returns></returns>
Task SaveChangesAsyc();
}
}
| mit | C# |
c84a6b436f0c6c5496977b51cc33c1ca269830dc | Stop using context.Configuration. | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | samples/IdentitySample.Mvc/Models/SampleData.cs | samples/IdentitySample.Mvc/Models/SampleData.cs | using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.Data.Entity.SqlServer;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.OptionsModel;
namespace IdentitySample.Models
{
public static class SampleData
{
public static async Task InitializeIdentityDatabaseAsync(IServiceProvider serviceProvider)
{
using (var db = serviceProvider.GetRequiredService<ApplicationDbContext>())
{
var sqlServerDatabase = db.Database as SqlServerDatabase;
if (sqlServerDatabase != null)
{
if (await sqlServerDatabase.EnsureCreatedAsync())
{
await CreateAdminUser(serviceProvider);
}
}
else
{
await CreateAdminUser(serviceProvider);
}
}
}
/// <summary>
/// Creates a store manager user who can manage the inventory.
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
private static async Task CreateAdminUser(IServiceProvider serviceProvider)
{
var options = serviceProvider.GetRequiredService<IOptions<IdentityDbContextOptions>>().Options;
const string adminRole = "Administrator";
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
if (!await roleManager.RoleExistsAsync(adminRole))
{
await roleManager.CreateAsync(new IdentityRole(adminRole));
}
var user = await userManager.FindByNameAsync(options.DefaultAdminUserName);
if (user == null)
{
user = new ApplicationUser { UserName = options.DefaultAdminUserName };
await userManager.CreateAsync(user, options.DefaultAdminPassword);
await userManager.AddToRoleAsync(user, adminRole);
await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed"));
}
}
}
} | using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.Data.Entity.SqlServer;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.OptionsModel;
namespace IdentitySample.Models
{
public static class SampleData
{
public static async Task InitializeIdentityDatabaseAsync(IServiceProvider serviceProvider)
{
using (var db = serviceProvider.GetRequiredService<ApplicationDbContext>())
{
var sqlServerDataStore = db.Configuration.DataStore as SqlServerDataStore;
if (sqlServerDataStore != null)
{
if (await db.Database.EnsureCreatedAsync())
{
await CreateAdminUser(serviceProvider);
}
}
else
{
await CreateAdminUser(serviceProvider);
}
}
}
/// <summary>
/// Creates a store manager user who can manage the inventory.
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
private static async Task CreateAdminUser(IServiceProvider serviceProvider)
{
var options = serviceProvider.GetRequiredService<IOptions<IdentityDbContextOptions>>().Options;
const string adminRole = "Administrator";
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
if (!await roleManager.RoleExistsAsync(adminRole))
{
await roleManager.CreateAsync(new IdentityRole(adminRole));
}
var user = await userManager.FindByNameAsync(options.DefaultAdminUserName);
if (user == null)
{
user = new ApplicationUser { UserName = options.DefaultAdminUserName };
await userManager.CreateAsync(user, options.DefaultAdminPassword);
await userManager.AddToRoleAsync(user, adminRole);
await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed"));
}
}
}
} | apache-2.0 | C# |
7bd29e8de67ff1f973cbd372a8b7f76123b7b9f1 | Refactor ExceptionExtension wrap method | hossmi/qtfk | QTFK.Core/Extensions/Exceptions/ExceptionExtension.cs | QTFK.Core/Extensions/Exceptions/ExceptionExtension.cs | using System;
namespace QTFK.Extensions.Exceptions
{
public static class ExceptionExtension
{
//public static T wrap<T>(this Exception exception, Func<Exception, T> wrapperDelegate) where T : Exception
//{
// T wrappedException;
// Asserts.isNotNull(wrapperDelegate);
// wrappedException = wrapperDelegate(exception);
// Asserts.isNotNull(wrappedException);
// return wrappedException;
//}
public static TExOut wrap<TExOut, TExIn>(this TExIn exception, Func<TExIn, TExOut> wrapperDelegate)
where TExIn : Exception
where TExOut : Exception
{
TExOut wrappedException;
Asserts.isNotNull(wrapperDelegate);
wrappedException = wrapperDelegate(exception);
Asserts.isNotNull(wrappedException);
return wrappedException;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QTFK.Extensions.Exceptions
{
public static class ExceptionExtension
{
public static T wrap<T>(this Exception exception, Func<Exception, T> wrapperDelegate) where T : Exception
{
T wrappedException;
Asserts.isNotNull(wrapperDelegate);
wrappedException = wrapperDelegate(exception);
Asserts.isNotNull(wrappedException);
return wrappedException;
}
}
}
| mit | C# |
9ac14d6757af0a6b08fc30f69e82a6e384538e07 | Add company name to copyright in AssemblyInfo | GlobeBMG/GBMG.Monitoring | source/GBMG.Monitoring/Properties/AssemblyInfo.cs | source/GBMG.Monitoring/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("GBMG monitoring and telemetry abstraction")]
[assembly: AssemblyDescription("A generic interface for sending custom metrics and telemetry to the configured monitoring provider")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Globe Business Media Group")]
[assembly: AssemblyProduct("GBMG.Monitoring")]
[assembly: AssemblyCopyright("Copyright © Globe Business Media Group 2016")]
[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("e0eac5b4-d8e1-4060-9e37-4e1f25ccbd8e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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("GBMG monitoring and telemetry abstraction")]
[assembly: AssemblyDescription("A generic interface for sending custom metrics and telemetry to the configured monitoring provider")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Globe Business Media Group")]
[assembly: AssemblyProduct("GBMG.Monitoring")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("e0eac5b4-d8e1-4060-9e37-4e1f25ccbd8e")]
// 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# |
9b593eeaf51136920863e2340d99000ad223b93f | Remove the 'IgnoreHidden' parameter from ITorrentFileSource | dipeshc/BTDeploy | src/MonoTorrent/MonoTorrent.Common/IFileSource.cs | src/MonoTorrent/MonoTorrent.Common/IFileSource.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace MonoTorrent.Common
{
public interface ITorrentFileSource
{
IEnumerable<FileMapping> Files { get; }
string TorrentName { get; }
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace MonoTorrent.Common
{
public interface ITorrentFileSource
{
IEnumerable<FileMapping> Files { get; }
bool IgnoreHidden { get; }
string TorrentName { get; }
}
}
| mit | C# |
584568bceb1439e23b1a328f240a9e6c0b6ec850 | Change Remove function | CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,zarlo/Cosmos,zarlo/Cosmos,zarlo/Cosmos | source/Cosmos.System2/Network/Config/DNSConfig.cs | source/Cosmos.System2/Network/Config/DNSConfig.cs | using Cosmos.System.Network.IPv4;
using System;
using System.Collections.Generic;
using System.Text;
namespace Cosmos.System.Network.Config
{
/// <summary>
/// Contains DNS configuration
/// </summary>
public class DNSConfig
{
/// <summary>
/// DNS Addresses list.
/// </summary>
public static List<Address> DNSNameservers = new List<Address>();
/// <summary>
/// Add IPv4 configuration.
/// </summary>
/// <param name="config"></param>
public static void Add(Address nameserver)
{
foreach (var ns in DNSNameservers)
{
if (ns.address.ToString() == nameserver.address.ToString())
{
return;
}
}
DNSNameservers.Add(nameserver);
}
/// <summary>
/// Remove IPv4 configuration.
/// </summary>
/// <param name="config"></param>
public static void Remove(Address nameserver)
{
for (int i = 0; i < DNSNameservers.Count; i++)
{
if (DNSNameservers[i].address.Equals(nameserver))
{
DNSNameservers.RemoveAt(i);
return;
}
}
}
/// <summary>
/// Call this to get your adress to request your DNS server
/// </summary>
/// <param name="index">Which server you want to get</param>
/// <returns>DNS Server</returns>
public static Address Server(int index)
{
return DNSNameservers[index];
}
}
}
| using Cosmos.System.Network.IPv4;
using System;
using System.Collections.Generic;
using System.Text;
namespace Cosmos.System.Network.Config
{
/// <summary>
/// Contains DNS configuration
/// </summary>
public class DNSConfig
{
/// <summary>
/// DNS Addresses list.
/// </summary>
public static List<Address> DNSNameservers = new List<Address>();
/// <summary>
/// Add IPv4 configuration.
/// </summary>
/// <param name="config"></param>
public static void Add(Address nameserver)
{
foreach (var ns in DNSNameservers)
{
if (ns.address.ToString() == nameserver.address.ToString())
{
return;
}
}
DNSNameservers.Add(nameserver);
}
/// <summary>
/// Remove IPv4 configuration.
/// </summary>
/// <param name="config"></param>
public static void Remove(Address nameserver)
{
int counter = 0;
foreach (var ns in DNSNameservers)
{
if (ns.address.ToString() == nameserver.address.ToString())
{
DNSNameservers.RemoveAt(counter);
}
counter++;
}
}
/// <summary>
/// Call this to get your adress to request your DNS server
/// </summary>
/// <param name="index">Which server you want to get</param>
/// <returns>DNS Server</returns>
public static Address Server(int index)
{
return DNSNameservers[index];
}
}
}
| bsd-3-clause | C# |
26a1ea95f45107dd0b1902d652ca5dc64449b9ea | add more integration test for authors endpoint | hirohito-protagonist/dotnet-core-rest | test/BooksLibrary/Tests/Integration/AuthorsTest.cs | test/BooksLibrary/Tests/Integration/AuthorsTest.cs | using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using System.Text;
using Xunit;
using BooksLibrary.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.TestHost;
namespace BooksLibrary.Tests.Integration
{
public class AuthorsIntegrationTest : IntegrationTestsBase<Startup>
{
private void AddRequestIpLimitHeaders(HttpRequestMessage request)
{
var clientId = "cl-key-b";
var ip = "::1";
request.Headers.Add("X-ClientId", clientId);
request.Headers.Add("X-Real-IP", ip);
}
[Fact(DisplayName = "it should return collection of authors")]
public async void TestGetAuthors()
{
var request = new HttpRequestMessage(HttpMethod.Get, "api/authors");
this.AddRequestIpLimitHeaders(request);
var response = await this.Client.SendAsync(request);
response.EnsureSuccessStatusCode();
string raw = await response.Content.ReadAsStringAsync();
List<AuthorDto> outputModel = JsonConvert.DeserializeObject<List<AuthorDto>>(raw);
Assert.Equal(6, outputModel.Count);
}
[Fact(DisplayName = "it should return 404 not found status code when author could not be find by id")]
public async void TestGetAuthorWithInvalidId()
{
var request = new HttpRequestMessage(HttpMethod.Get, "api/authors/123test");
this.AddRequestIpLimitHeaders(request);
var response = await this.Client.SendAsync(request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact(DisplayName = "it should create author and return 201 status code on success")]
public async void TestAuthorCreation()
{
var content = new StringContent(JsonConvert.SerializeObject(new AuthorCreationDto()),
Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, "api/authors");
request.Content = content;
this.AddRequestIpLimitHeaders(request);
var response = await this.Client.SendAsync(request);
Assert.Equal(201, (int)response.StatusCode);
}
}
}
| using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using System.Text;
using Xunit;
using BooksLibrary.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.TestHost;
namespace BooksLibrary.Tests.Integration
{
public class AuthorsIntegrationTest : IntegrationTestsBase<Startup>
{
[Fact]
public async void TestGetAuthors()
{
// Arrange
var clientId = "cl-key-b";
var ip = "::1";
// Act
var request = new HttpRequestMessage(HttpMethod.Get, "api/authors");
request.Headers.Add("X-ClientId", clientId);
request.Headers.Add("X-Real-IP", ip);
var response = await this.Client.SendAsync(request);
response.EnsureSuccessStatusCode();
string raw = await response.Content.ReadAsStringAsync();
List<AuthorDto> outputModel = JsonConvert.DeserializeObject<List<AuthorDto>>(raw);
// Assert
Assert.Equal(6, outputModel.Count);
}
}
}
| unlicense | C# |
35f0c13b28367d344f547c60947c5029fd5794b8 | Fix infinity loop bug. | XJINE/Unity3D_ObjectController | Assets/ObjectController/Walker/RandomWalkerInBounds.cs | Assets/ObjectController/Walker/RandomWalkerInBounds.cs | using UnityEngine;
namespace ObjectController
{
/// <summary>
/// Bounds の中を移動する Walker.
/// </summary>
public class RandomWalkerInBounds : Walker
{
#region Field
/// <summary>
/// 移動できる Bounds.
/// </summary>
public BoundsBehaviour[] boundsBehaviours;
/// <summary>
/// 移動してはいけない Bounds.
/// </summary>
public BoundsBehaviour[] boundsBehaviourKeepout;
#endregion Field
#region Method
/// <summary>
/// 次のターゲットの座標を取得します。
/// </summary>
/// <returns>
/// 次のターゲットの座標。
/// </returns>
protected override Vector3 GetNextTarget()
{
int boundsBehaviourKeepoutLength = this.boundsBehaviourKeepout.Length;
Vector3 randomPoint = this.boundsBehaviours[Random.Range(0, this.boundsBehaviours.Length)].bounds.GetRandomPoint();
Ray ray = new Ray(this.transform.position, randomPoint - this.transform.position);
bool loop = true;
int count = 0;
int maxCount = 100;
while (loop)
{
loop = false;
for (int i = 0; i < boundsBehaviourKeepoutLength; i++)
{
if (this.boundsBehaviourKeepout[i].bounds.IntersectRay(ray))
{
randomPoint = this.boundsBehaviours[Random.Range(0, this.boundsBehaviours.Length)].bounds.GetRandomPoint();
ray = new Ray(this.transform.position, randomPoint - this.transform.position);
loop = true;
break;
}
}
count++;
if (count == maxCount)
{
break;
}
}
return randomPoint;
}
#endregion Method
}
} | using UnityEngine;
namespace ObjectController
{
/// <summary>
///
/// </summary>
public class RandomWalkerInBounds : Walker
{
#region Field
/// <summary>
/// 移動する Bounds.
/// </summary>
public BoundsBehaviour[] boundsBehaviours;
/// <summary>
/// 移動してはいけない Bounds.
/// </summary>
public BoundsBehaviour[] boundsBehaviourKeepout;
#endregion Field
#region Method
/// <summary>
/// 次のターゲットの座標を取得します。
/// </summary>
/// <returns>
/// 次のターゲットの座標。
/// </returns>
protected override Vector3 GetNextTarget()
{
int boundsBehaviourKeepoutLength = this.boundsBehaviourKeepout.Length;
Vector3 randomPoint = this.boundsBehaviours[Random.Range(0, this.boundsBehaviours.Length)].bounds.GetRandomPoint();
Ray ray = new Ray(this.transform.position, randomPoint - this.transform.position);
bool loop = true;
while (loop)
{
loop = false;
for (int i = 0; i < boundsBehaviourKeepoutLength; i++)
{
if (this.boundsBehaviourKeepout[i].bounds.IntersectRay(ray))
{
randomPoint = this.boundsBehaviours[Random.Range(0, this.boundsBehaviours.Length)].bounds.GetRandomPoint();
ray = new Ray(this.transform.position, randomPoint - this.transform.position);
loop = true;
break;
}
}
}
return randomPoint;
}
#endregion Method
}
} | bsd-3-clause | C# |
f9a8f568225747be12cdd8eb3c830661a80fbfc7 | Add revenue deduplication test in iOS app | adjust/xamarin_sdk,adjust/xamarin_sdk | iOS/Example/ViewController.cs | iOS/Example/ViewController.cs | using UIKit;
using System;
using AdjustBindingsiOS;
namespace Example
{
public partial class ViewController : UIViewController
{
partial void BtnTrackSimpleEvent_TouchUpInside(UIButton sender)
{
var adjustEvent = ADJEvent.EventWithEventToken("g3mfiw");
Adjust.TrackEvent(adjustEvent);
}
partial void BtnTrackRevenueEvent_TouchUpInside(UIButton sender)
{
var adjustEvent = ADJEvent.EventWithEventToken("a4fd35");
adjustEvent.SetRevenue(0.01, "EUR");
adjustEvent.SetTransactionId("dummy_id");
Adjust.TrackEvent(adjustEvent);
}
partial void BtnTrackCallbackEvent_TouchUpInside(UIButton sender)
{
var adjustEvent = ADJEvent.EventWithEventToken("34vgg9");
adjustEvent.AddCallbackParameter("a", "b");
adjustEvent.AddCallbackParameter("key", "value");
adjustEvent.AddCallbackParameter("a", "c");
Adjust.TrackEvent(adjustEvent);
}
partial void BtnTrackPartnerEvent_TouchUpInside(UIButton sender)
{
var adjustEvent = ADJEvent.EventWithEventToken("w788qs");
adjustEvent.AddPartnerParameter("x", "y");
adjustEvent.AddPartnerParameter("foo", "bar");
adjustEvent.AddPartnerParameter("x", "z");
Adjust.TrackEvent(adjustEvent);
}
partial void BtnEnableOfflineMode_TouchUpInside(UIButton sender)
{
Adjust.SetOfflineMode(true);
}
partial void BtnDisableOfflineMode_TouchUpInside(UIButton sender)
{
Adjust.SetOfflineMode(false);
}
partial void BtnEnableSdk_TouchUpInside(UIButton sender)
{
Adjust.SetEnabled(true);
}
partial void BtnDisableSdk_TouchUpInside(UIButton sender)
{
Adjust.SetEnabled(false);
}
partial void BtnIsSdkEnabled_TouchUpInside(UIButton sender)
{
String message = Adjust.IsEnabled ? "SDK is ENABLED" : "SDK is DISABLED";
UIAlertView alert = new UIAlertView()
{
Title = "Is SDK enabled?",
Message = message
};
alert.AddButton("OK");
alert.Show();
}
protected ViewController(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
}
}
| using UIKit;
using System;
using AdjustBindingsiOS;
namespace Example
{
public partial class ViewController : UIViewController
{
partial void BtnTrackSimpleEvent_TouchUpInside(UIButton sender)
{
var adjustEvent = ADJEvent.EventWithEventToken("g3mfiw");
Adjust.TrackEvent(adjustEvent);
}
partial void BtnTrackRevenueEvent_TouchUpInside(UIButton sender)
{
var adjustEvent = ADJEvent.EventWithEventToken("a4fd35");
adjustEvent.SetRevenue(0.01, "EUR");
Adjust.TrackEvent(adjustEvent);
}
partial void BtnTrackCallbackEvent_TouchUpInside(UIButton sender)
{
var adjustEvent = ADJEvent.EventWithEventToken("34vgg9");
adjustEvent.AddCallbackParameter("a", "b");
adjustEvent.AddCallbackParameter("key", "value");
adjustEvent.AddCallbackParameter("a", "c");
Adjust.TrackEvent(adjustEvent);
}
partial void BtnTrackPartnerEvent_TouchUpInside(UIButton sender)
{
var adjustEvent = ADJEvent.EventWithEventToken("w788qs");
adjustEvent.AddPartnerParameter("x", "y");
adjustEvent.AddPartnerParameter("foo", "bar");
adjustEvent.AddPartnerParameter("x", "z");
Adjust.TrackEvent(adjustEvent);
}
partial void BtnEnableOfflineMode_TouchUpInside(UIButton sender)
{
Adjust.SetOfflineMode(true);
}
partial void BtnDisableOfflineMode_TouchUpInside(UIButton sender)
{
Adjust.SetOfflineMode(false);
}
partial void BtnEnableSdk_TouchUpInside(UIButton sender)
{
Adjust.SetEnabled(true);
}
partial void BtnDisableSdk_TouchUpInside(UIButton sender)
{
Adjust.SetEnabled(false);
}
partial void BtnIsSdkEnabled_TouchUpInside(UIButton sender)
{
String message = Adjust.IsEnabled ? "SDK is ENABLED" : "SDK is DISABLED";
UIAlertView alert = new UIAlertView()
{
Title = "Is SDK enabled?",
Message = message
};
alert.AddButton("OK");
alert.Show();
}
protected ViewController(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
}
}
| mit | C# |
9ce60218c1e9ccc8f138241740396746c46a3221 | Make 'SessionDefaults' fields as Constants | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Session/SessionDefaults.cs | src/Microsoft.AspNet.Session/SessionDefaults.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;
namespace Microsoft.AspNet.Session
{
public static class SessionDefaults
{
public static readonly string CookieName = ".AspNet.Session";
public static readonly string CookiePath = "/";
}
} | // 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;
namespace Microsoft.AspNet.Session
{
public static class SessionDefaults
{
public static string CookieName = ".AspNet.Session";
public static string CookiePath = "/";
}
} | apache-2.0 | C# |
f9effecf77d942c38a5fd2eb3cdd8f4e1e13ca2e | Update server side API for single multiple answer question | Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist | Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs | Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs | using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
| mit | C# |
55752de18c731f0d9ff2ec1e8d7048835d23f629 | Remove an unused using | tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools,Cyberboss/tgstation-server,tgstation/tgstation-server | src/Tgstation.Server.Host/Core/RestartRegistration.cs | src/Tgstation.Server.Host/Core/RestartRegistration.cs | using System;
namespace Tgstation.Server.Host.Core
{
/// <inheritdoc />
sealed class RestartRegistration : IRestartRegistration
{
/// <summary>
/// The <see cref="Dispose"/> <see cref="Action"/>
/// </summary>
readonly Action onDispose;
/// <summary>
/// Construct a <see cref="RestartRegistration"/>
/// </summary>
/// <param name="onDispose">The value of <see cref="onDispose"/></param>
public RestartRegistration(Action onDispose)
{
this.onDispose = onDispose ?? throw new ArgumentNullException(nameof(onDispose));
}
/// <inheritdoc />
public void Dispose() => onDispose();
}
} | using System;
using Tgstation.Server.Host.Core;
namespace Tgstation.Server.Host.Core
{
/// <inheritdoc />
sealed class RestartRegistration : IRestartRegistration
{
/// <summary>
/// The <see cref="Dispose"/> <see cref="Action"/>
/// </summary>
readonly Action onDispose;
/// <summary>
/// Construct a <see cref="RestartRegistration"/>
/// </summary>
/// <param name="onDispose">The value of <see cref="onDispose"/></param>
public RestartRegistration(Action onDispose)
{
this.onDispose = onDispose ?? throw new ArgumentNullException(nameof(onDispose));
}
/// <inheritdoc />
public void Dispose() => onDispose();
}
} | agpl-3.0 | C# |
815180c7653a342214bfa644c6ad03bc8b1da8b4 | Add base64 SYSCALLs (#1717) | AntShares/AntShares | src/neo/SmartContract/ApplicationEngine.Binary.cs | src/neo/SmartContract/ApplicationEngine.Binary.cs | using Neo.VM.Types;
using static System.Convert;
namespace Neo.SmartContract
{
partial class ApplicationEngine
{
public static readonly InteropDescriptor System_Binary_Serialize = Register("System.Binary.Serialize", nameof(BinarySerialize), 0_00100000, TriggerType.All, CallFlags.None, true);
public static readonly InteropDescriptor System_Binary_Deserialize = Register("System.Binary.Deserialize", nameof(BinaryDeserialize), 0_00500000, TriggerType.All, CallFlags.None, true);
public static readonly InteropDescriptor System_Binary_Base64Encode = Register("System.Binary.Base64Encode", nameof(Base64Encode), 0_00100000, TriggerType.All, CallFlags.None, true);
public static readonly InteropDescriptor System_Binary_Base64Decode = Register("System.Binary.Base64Decode", nameof(Base64Decode), 0_00100000, TriggerType.All, CallFlags.None, true);
internal byte[] BinarySerialize(StackItem item)
{
return BinarySerializer.Serialize(item, MaxItemSize);
}
internal StackItem BinaryDeserialize(byte[] data)
{
return BinarySerializer.Deserialize(data, MaxStackSize, MaxItemSize, ReferenceCounter);
}
internal string Base64Encode(byte[] data)
{
return ToBase64String(data);
}
internal byte[] Base64Decode(string s)
{
return FromBase64String(s);
}
}
}
| using Neo.VM.Types;
namespace Neo.SmartContract
{
partial class ApplicationEngine
{
public static readonly InteropDescriptor System_Binary_Serialize = Register("System.Binary.Serialize", nameof(BinarySerialize), 0_00100000, TriggerType.All, CallFlags.None, true);
public static readonly InteropDescriptor System_Binary_Deserialize = Register("System.Binary.Deserialize", nameof(BinaryDeserialize), 0_00500000, TriggerType.All, CallFlags.None, true);
internal byte[] BinarySerialize(StackItem item)
{
return BinarySerializer.Serialize(item, MaxItemSize);
}
internal StackItem BinaryDeserialize(byte[] data)
{
return BinarySerializer.Deserialize(data, MaxStackSize, MaxItemSize, ReferenceCounter);
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.